How to use NewConfig method of config Package

Best Selenoid code snippet using config.NewConfig

source.go

Source:source.go Github

copy

Full Screen

...15func main() {16 username := "admin"17 password := "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"18 fmt.Println("Doing something with: ", username, password)19}`}, 1, gosec.NewConfig()},20 {[]string{`21// Entropy check should not report this error by default22package main23import "fmt"24func main() {25 username := "admin"26 password := "secret"27 fmt.Println("Doing something with: ", username, password)28}`}, 0, gosec.NewConfig()},29 {[]string{`30package main31import "fmt"32var password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"33func main() {34 username := "admin"35 fmt.Println("Doing something with: ", username, password)36}`}, 1, gosec.NewConfig()},37 {[]string{`38package main39import "fmt"40const password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"41func main() {42 username := "admin"43 fmt.Println("Doing something with: ", username, password)44}`}, 1, gosec.NewConfig()},45 {[]string{`46package main47import "fmt"48const (49 username = "user"50 password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"51)52func main() {53 fmt.Println("Doing something with: ", username, password)54}`}, 1, gosec.NewConfig()},55 {[]string{`56package main57var password string58func init() {59 password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"60}`}, 1, gosec.NewConfig()},61 {[]string{`62package main63const (64 ATNStateSomethingElse = 165 ATNStateTokenStart = 4266)67func main() {68 println(ATNStateTokenStart)69}`}, 0, gosec.NewConfig()},70 {[]string{`71package main72const (73 ATNStateTokenStart = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"74)75func main() {76 println(ATNStateTokenStart)77}`}, 1, gosec.NewConfig()},78 {[]string{`79package main80import "fmt"81func main() {82 var password string83 if password == "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" {84 fmt.Println("password equality")85 }86}`}, 1, gosec.NewConfig()},87 {[]string{`88package main89import "fmt"90func main() {91 var password string92 if password != "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" {93 fmt.Println("password equality")94 }95}`}, 1, gosec.NewConfig()},96 {[]string{`97package main98import "fmt"99func main() {100 var p string101 if p != "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" {102 fmt.Println("password equality")103 }104}`}, 0, gosec.NewConfig()},105 {[]string{`106package main107import "fmt"108const (109 pw = "KjasdlkjapoIKLlka98098sdf012U/rL2sLdBqOHQUlt5Z6kCgKGDyCFA=="110)111func main() {112 fmt.Println(pw)113}`}, 1, gosec.NewConfig()},114 {[]string{`115package main116import "fmt"117var (118 pw string119)120func main() {121 pw = "KjasdlkjapoIKLlka98098sdf012U/rL2sLdBqOHQUlt5Z6kCgKGDyCFA=="122 fmt.Println(pw)123}`}, 1, gosec.NewConfig()},124 {[]string{`125package main126import "fmt"127const (128 cred = "KjasdlkjapoIKLlka98098sdf012U/rL2sLdBqOHQUlt5Z6kCgKGDyCFA=="129)130func main() {131 fmt.Println(cred)132}`}, 1, gosec.NewConfig()},133 {[]string{`134package main135import "fmt"136var (137 cred string138)139func main() {140 cred = "KjasdlkjapoIKLlka98098sdf012U/rL2sLdBqOHQUlt5Z6kCgKGDyCFA=="141 fmt.Println(cred)142}`}, 1, gosec.NewConfig()},143 {[]string{`144package main145import "fmt"146const (147 apiKey = "KjasdlkjapoIKLlka98098sdf012U"148)149func main() {150 fmt.Println(apiKey)151}`}, 1, gosec.NewConfig()},152 {[]string{`153package main154import "fmt"155var (156 apiKey string157)158func main() {159 apiKey = "KjasdlkjapoIKLlka98098sdf012U"160 fmt.Println(apiKey)161}`}, 1, gosec.NewConfig()},162 {[]string{`163package main164import "fmt"165const (166 bearer = "Bearer: 2lkjdfoiuwer092834kjdwf09"167)168func main() {169 fmt.Println(bearer)170}`}, 1, gosec.NewConfig()},171 {[]string{`172package main173import "fmt"174var (175 bearer string176)177func main() {178 bearer = "Bearer: 2lkjdfoiuwer092834kjdwf09"179 fmt.Println(bearer)180}`}, 1, gosec.NewConfig()},181 }182 // SampleCodeG102 code snippets for network binding183 SampleCodeG102 = []CodeSample{184 // Bind to all networks explicitly185 {[]string{`186package main187import (188 "log"189 "net"190)191func main() {192 l, err := net.Listen("tcp", "0.0.0.0:2000")193 if err != nil {194 log.Fatal(err)195 }196 defer l.Close()197}`}, 1, gosec.NewConfig()},198 // Bind to all networks implicitly (default if host omitted)199 {[]string{`200package main201import (202 "log"203 "net"204)205func main() {206 l, err := net.Listen("tcp", ":2000")207 if err != nil {208 log.Fatal(err)209 }210 defer l.Close()211}`}, 1, gosec.NewConfig()},212 // Bind to all networks indirectly through a parsing function213 {[]string{`214package main215import (216 "log"217 "net"218)219func parseListenAddr(listenAddr string) (network string, addr string) {220 return "", ""221}222func main() {223 addr := ":2000"224 l, err := net.Listen(parseListenAddr(addr))225 if err != nil {226 log.Fatal(err)227 }228 defer l.Close()229}`}, 1, gosec.NewConfig()},230 // Bind to all networks indirectly through a parsing function231 {[]string{`232package main233import (234 "log"235 "net"236)237const addr = ":2000"238func parseListenAddr(listenAddr string) (network string, addr string) {239 return "", ""240}241func main() {242 l, err := net.Listen(parseListenAddr(addr))243 if err != nil {244 log.Fatal(err)245 }246 defer l.Close()247}`}, 1, gosec.NewConfig()},248 {[]string{`249package main250import (251 "log"252 "net"253)254const addr = "0.0.0.0:2000"255func main() {256 l, err := net.Listen("tcp", addr)257 if err != nil {258 log.Fatal(err)259 }260 defer l.Close()261}`}, 1, gosec.NewConfig()},262 }263 // SampleCodeG103 find instances of unsafe blocks for auditing purposes264 SampleCodeG103 = []CodeSample{265 {[]string{`266package main267import (268 "fmt"269 "unsafe"270)271type Fake struct{}272func (Fake) Good() {}273func main() {274 unsafeM := Fake{}275 unsafeM.Good()276 intArray := [...]int{1, 2}277 fmt.Printf("\nintArray: %v\n", intArray)278 intPtr := &intArray[0]279 fmt.Printf("\nintPtr=%p, *intPtr=%d.\n", intPtr, *intPtr)280 addressHolder := uintptr(unsafe.Pointer(intPtr)) + unsafe.Sizeof(intArray[0])281 intPtr = (*int)(unsafe.Pointer(addressHolder))282 fmt.Printf("\nintPtr=%p, *intPtr=%d.\n\n", intPtr, *intPtr)283}`}, 3, gosec.NewConfig()},284 }285 // SampleCodeG104 finds errors that aren't being handled286 SampleCodeG104 = []CodeSample{287 {[]string{`288package main289import "fmt"290func test() (int,error) {291 return 0, nil292}293func main() {294 v, _ := test()295 fmt.Println(v)296}`}, 0, gosec.NewConfig()}, {[]string{`297package main298import (299 "io/ioutil"300 "os"301 "fmt"302)303func a() error {304 return fmt.Errorf("This is an error")305}306func b() {307 fmt.Println("b")308 ioutil.WriteFile("foo.txt", []byte("bar"), os.ModeExclusive)309}310func c() string {311 return fmt.Sprintf("This isn't anything")312}313func main() {314 _ = a()315 a()316 b()317 c()318}`}, 2, gosec.NewConfig()}, {[]string{`319package main320import "fmt"321func test() error {322 return nil323}324func main() {325 e := test()326 fmt.Println(e)327}`}, 0, gosec.NewConfig()}, {[]string{`328// +build go1.10329package main330import "strings"331func main() {332 var buf strings.Builder333 _, err := buf.WriteString("test string")334 if err != nil {335 panic(err)336 }337}`, `338package main339func dummy(){}340`}, 0, gosec.NewConfig()}, {[]string{`341package main342import (343 "bytes"344)345type a struct {346 buf *bytes.Buffer347}348func main() {349 a := &a{350 buf: new(bytes.Buffer),351 }352 a.buf.Write([]byte{0})353}354`}, 0, gosec.NewConfig()}, {[]string{`355package main356import (357 "io/ioutil"358 "os"359 "fmt"360)361func a() {362 fmt.Println("a")363 ioutil.WriteFile("foo.txt", []byte("bar"), os.ModeExclusive)364}365func main() {366 a()367}`}, 0, gosec.Config{"G104": map[string]interface{}{"ioutil": []interface{}{"WriteFile"}}}}, {[]string{`368package main369import (370 "bytes"371 "fmt"372 "io"373 "os"374 "strings"375)376func createBuffer() *bytes.Buffer {377 return new(bytes.Buffer)378}379func main() {380 new(bytes.Buffer).WriteString("*bytes.Buffer")381 fmt.Fprintln(os.Stderr, "fmt")382 new(strings.Builder).WriteString("*strings.Builder")383 _, pw := io.Pipe()384 pw.CloseWithError(io.EOF)385 createBuffer().WriteString("*bytes.Buffer")386 b := createBuffer()387 b.WriteString("*bytes.Buffer")388}`}, 0, gosec.NewConfig()},389 } // it shoudn't return any errors because all method calls are whitelisted by default390 // SampleCodeG104Audit finds errors that aren't being handled in audit mode391 SampleCodeG104Audit = []CodeSample{392 {[]string{`393package main394import "fmt"395func test() (int,error) {396 return 0, nil397}398func main() {399 v, _ := test()400 fmt.Println(v)401}`}, 1, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}}, {[]string{`402package main403import (404 "io/ioutil"405 "os"406 "fmt"407)408func a() error {409 return fmt.Errorf("This is an error")410}411func b() {412 fmt.Println("b")413 ioutil.WriteFile("foo.txt", []byte("bar"), os.ModeExclusive)414}415func c() string {416 return fmt.Sprintf("This isn't anything")417}418func main() {419 _ = a()420 a()421 b()422 c()423}`}, 3, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}}, {[]string{`424package main425import "fmt"426func test() error {427 return nil428}429func main() {430 e := test()431 fmt.Println(e)432}`}, 0, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}}, {[]string{`433// +build go1.10434package main435import "strings"436func main() {437 var buf strings.Builder438 _, err := buf.WriteString("test string")439 if err != nil {440 panic(err)441 }442}`, `443package main444func dummy(){}445`}, 0, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}},446 }447 // SampleCodeG106 - ssh InsecureIgnoreHostKey448 SampleCodeG106 = []CodeSample{{[]string{`449package main450import (451 "golang.org/x/crypto/ssh"452)453func main() {454 _ = ssh.InsecureIgnoreHostKey()455}`}, 1, gosec.NewConfig()}}456 // SampleCodeG107 - SSRF via http requests with variable url457 SampleCodeG107 = []CodeSample{{[]string{`458// Input from the std in is considered insecure459package main460import (461 "net/http"462 "io/ioutil"463 "fmt"464 "os"465 "bufio"466)467func main() {468 in := bufio.NewReader(os.Stdin)469 url, err := in.ReadString('\n')470 if err != nil {471 panic(err)472 }473 resp, err := http.Get(url)474 if err != nil {475 panic(err)476 }477 defer resp.Body.Close()478 body, err := ioutil.ReadAll(resp.Body)479 if err != nil {480 panic(err)481 }482 fmt.Printf("%s", body)483}`}, 1, gosec.NewConfig()}, {[]string{`484// Variable defined a package level can be changed at any time485// regardless of the initial value486package main487import (488 "fmt"489 "io/ioutil"490 "net/http"491)492var url string = "https://www.google.com"493func main() {494 resp, err := http.Get(url)495 if err != nil {496 panic(err)497 }498 defer resp.Body.Close()499 body, err := ioutil.ReadAll(resp.Body)500 if err != nil {501 panic(err)502 }503 fmt.Printf("%s", body)504}`}, 1, gosec.NewConfig()}, {[]string{`505// Environmental variables are not considered as secure source506package main507import (508 "net/http"509 "io/ioutil"510 "fmt"511 "os"512)513func main() {514 url := os.Getenv("tainted_url")515 resp, err := http.Get(url)516 if err != nil {517 panic(err)518 }519 defer resp.Body.Close()520 body, err := ioutil.ReadAll(resp.Body)521 if err != nil {522 panic(err)523 }524 fmt.Printf("%s", body)525}`}, 1, gosec.NewConfig()}, {[]string{`526// Constant variables or hard-coded strings are secure527package main528import (529 "fmt"530 "net/http"531)532const url = "http://127.0.0.1"533func main() {534 resp, err := http.Get(url)535 if err != nil {536 fmt.Println(err)537 }538 fmt.Println(resp.Status)539}`}, 0, gosec.NewConfig()}, {[]string{`540// A variable at function scope which is initialized to541// a constant string is secure (e.g. cannot be changed concurrently)542package main543import (544 "fmt"545 "net/http"546)547func main() {548 var url string = "http://127.0.0.1"549 resp, err := http.Get(url)550 if err != nil {551 fmt.Println(err)552 }553 fmt.Println(resp.Status)554}`}, 0, gosec.NewConfig()}, {[]string{`555// A variable at function scope which is initialized to556// a constant string is secure (e.g. cannot be changed concurrently)557package main558import (559 "fmt"560 "net/http"561)562func main() {563 url := "http://127.0.0.1"564 resp, err := http.Get(url)565 if err != nil {566 fmt.Println(err)567 }568 fmt.Println(resp.Status)569}`}, 0, gosec.NewConfig()}, {[]string{`570// A variable at function scope which is initialized to571// a constant string is secure (e.g. cannot be changed concurrently)572package main573import (574 "fmt"575 "net/http"576)577func main() {578 url1 := "test"579 var url2 string = "http://127.0.0.1"580 url2 = url1581 resp, err := http.Get(url2)582 if err != nil {583 fmt.Println(err)584 }585 fmt.Println(resp.Status)586}`}, 0, gosec.NewConfig()}, {[]string{`587// An exported variable declared a packaged scope is not secure588// because it can changed at any time589package main590import (591 "fmt"592 "net/http"593)594var Url string595func main() {596 resp, err := http.Get(Url)597 if err != nil {598 fmt.Println(err)599 }600 fmt.Println(resp.Status)601}`}, 1, gosec.NewConfig()}, {[]string{`602// An url provided as a function argument is not secure603package main604import (605 "fmt"606 "net/http"607)608func get(url string) {609 resp, err := http.Get(url)610 if err != nil {611 fmt.Println(err)612 }613 fmt.Println(resp.Status)614}615func main() {616 url := "http://127.0.0.1"617 get(url)618}`}, 1, gosec.NewConfig()}}619 // SampleCodeG108 - pprof endpoint automatically exposed620 SampleCodeG108 = []CodeSample{{[]string{`621package main622import (623 "fmt"624 "log"625 "net/http"626 _ "net/http/pprof"627)628func main() {629 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {630 fmt.Fprintf(w, "Hello World!")631 })632 log.Fatal(http.ListenAndServe(":8080", nil))633}`}, 1, gosec.NewConfig()}, {[]string{`634package main635import (636 "fmt"637 "log"638 "net/http"639)640func main() {641 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {642 fmt.Fprintf(w, "Hello World!")643 })644 log.Fatal(http.ListenAndServe(":8080", nil))645}`}, 0, gosec.NewConfig()}}646 // SampleCodeG109 - Potential Integer OverFlow647 SampleCodeG109 = []CodeSample{648 {[]string{`649package main650import (651 "fmt"652 "strconv"653)654func main() {655 bigValue, err := strconv.Atoi("2147483648")656 if err != nil {657 panic(err)658 }659 value := int32(bigValue)660 fmt.Println(value)661}`}, 1, gosec.NewConfig()}, {[]string{`662package main663import (664 "fmt"665 "strconv"666)667func main() {668 bigValue, err := strconv.Atoi("32768")669 if err != nil {670 panic(err)671 }672 if int16(bigValue) < 0 {673 fmt.Println(bigValue)674 }675}`}, 1, gosec.NewConfig()}, {[]string{`676package main677import (678 "fmt"679 "strconv"680)681func main() {682 bigValue, err := strconv.Atoi("2147483648")683 if err != nil {684 panic(err)685 }686 fmt.Println(bigValue)687}`}, 0, gosec.NewConfig()}, {[]string{`688package main689import (690 "fmt"691 "strconv"692)693func main() {694 bigValue, err := strconv.Atoi("2147483648")695 if err != nil {696 panic(err)697 }698 fmt.Println(bigValue)699 test()700}701func test() {702 bigValue := 30703 value := int32(bigValue)704 fmt.Println(value)705}`}, 0, gosec.NewConfig()}, {[]string{`706package main707import (708 "fmt"709 "strconv"710)711func main() {712 value := 10713 if value == 10 {714 value, _ := strconv.Atoi("2147483648")715 fmt.Println(value)716 }717 v := int32(value)718 fmt.Println(v)719}`}, 0, gosec.NewConfig()},720 }721 // SampleCodeG110 - potential DoS vulnerability via decompression bomb722 SampleCodeG110 = []CodeSample{723 {[]string{`724package main725import (726 "bytes"727 "compress/zlib"728 "io"729 "os"730)731func main() {732 buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,733 47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}734 b := bytes.NewReader(buff)735 r, err := zlib.NewReader(b)736 if err != nil {737 panic(err)738 }739 _, err = io.Copy(os.Stdout, r)740 if err != nil {741 panic(err)742 }743 r.Close()744}`}, 1, gosec.NewConfig()}, {[]string{`745package main746import (747 "bytes"748 "compress/zlib"749 "io"750 "os"751)752func main() {753 buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,754 47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}755 b := bytes.NewReader(buff)756 r, err := zlib.NewReader(b)757 if err != nil {758 panic(err)759 }760 buf := make([]byte, 8)761 _, err = io.CopyBuffer(os.Stdout, r, buf)762 if err != nil {763 panic(err)764 }765 r.Close()766}`}, 1, gosec.NewConfig()}, {[]string{`767package main768import (769 "archive/zip"770 "io"771 "os"772 "strconv"773)774func main() {775 r, err := zip.OpenReader("tmp.zip")776 if err != nil {777 panic(err)778 }779 defer r.Close()780 for i, f := range r.File {781 out, err := os.OpenFile("output" + strconv.Itoa(i), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())782 if err != nil {783 panic(err)784 }785 rc, err := f.Open()786 if err != nil {787 panic(err)788 }789 _, err = io.Copy(out, rc)790 out.Close()791 rc.Close()792 if err != nil {793 panic(err)794 }795 }796}`}, 1, gosec.NewConfig()}, {[]string{`797package main798import (799 "io"800 "os"801)802func main() {803 s, err := os.Open("src")804 if err != nil {805 panic(err)806 }807 defer s.Close()808 d, err := os.Create("dst")809 if err != nil {810 panic(err)811 }812 defer d.Close()813 _, err = io.Copy(d, s)814 if err != nil {815 panic(err)816 }817}`}, 0, gosec.NewConfig()},818 }819 // SampleCodeG201 - SQL injection via format string820 SampleCodeG201 = []CodeSample{821 {[]string{`822// Format string without proper quoting823package main824import (825 "database/sql"826 "fmt"827 "os"828)829func main(){830 db, err := sql.Open("sqlite3", ":memory:")831 if err != nil {832 panic(err)833 }834 q := fmt.Sprintf("SELECT * FROM foo where name = '%s'", os.Args[1])835 rows, err := db.Query(q)836 if err != nil {837 panic(err)838 }839 defer rows.Close()840}`}, 1, gosec.NewConfig()}, {[]string{`841// Format string without proper quoting case insensitive842package main843import (844 "database/sql"845 "fmt"846 "os"847)848func main(){849 db, err := sql.Open("sqlite3", ":memory:")850 if err != nil {851 panic(err)852 }853 q := fmt.Sprintf("select * from foo where name = '%s'", os.Args[1])854 rows, err := db.Query(q)855 if err != nil {856 panic(err)857 }858 defer rows.Close()859}`}, 1, gosec.NewConfig()}, {[]string{`860// Format string without proper quoting with context861package main862import (863 "context"864 "database/sql"865 "fmt"866 "os"867)868func main(){869 db, err := sql.Open("sqlite3", ":memory:")870 if err != nil {871 panic(err)872 }873 q := fmt.Sprintf("select * from foo where name = '%s'", os.Args[1])874 rows, err := db.QueryContext(context.Background(), q)875 if err != nil {876 panic(err)877 }878 defer rows.Close()879}`}, 1, gosec.NewConfig()}, {[]string{`880// Format string without proper quoting with transaction881package main882import (883 "context"884 "database/sql"885 "fmt"886 "os"887)888func main(){889 db, err := sql.Open("sqlite3", ":memory:")890 if err != nil {891 panic(err)892 }893 tx, err := db.Begin()894 if err != nil {895 panic(err)896 }897 defer tx.Rollback()898 q := fmt.Sprintf("select * from foo where name = '%s'", os.Args[1])899 rows, err := tx.QueryContext(context.Background(), q)900 if err != nil {901 panic(err)902 }903 defer rows.Close()904 if err := tx.Commit(); err != nil {905 panic(err)906 }907}`}, 1, gosec.NewConfig()}, {[]string{`908// Format string false positive, safe string spec.909package main910import (911 "database/sql"912 "fmt"913 "os"914)915func main(){916 db, err := sql.Open("sqlite3", ":memory:")917 if err != nil {918 panic(err)919 }920 q := fmt.Sprintf("SELECT * FROM foo where id = %d", os.Args[1])921 rows, err := db.Query(q)922 if err != nil {923 panic(err)924 }925 defer rows.Close()926}`}, 0, gosec.NewConfig()}, {[]string{`927// Format string false positive928package main929import (930 "database/sql"931)932const staticQuery = "SELECT * FROM foo WHERE age < 32"933func main(){934 db, err := sql.Open("sqlite3", ":memory:")935 if err != nil {936 panic(err)937 }938 rows, err := db.Query(staticQuery)939 if err != nil {940 panic(err)941 }942 defer rows.Close()943}`}, 0, gosec.NewConfig()}, {[]string{`944// Format string false positive, quoted formatter argument.945package main946import (947 "database/sql"948 "fmt"949 "os"950 "github.com/lib/pq"951)952func main(){953 db, err := sql.Open("postgres", "localhost")954 if err != nil {955 panic(err)956 }957 q := fmt.Sprintf("SELECT * FROM %s where id = 1", pq.QuoteIdentifier(os.Args[1]))958 rows, err := db.Query(q)959 if err != nil {960 panic(err)961 }962 defer rows.Close()963}`}, 0, gosec.NewConfig()}, {[]string{`964// false positive965package main966import (967 "database/sql"968 "fmt"969)970const Table = "foo"971func main(){972 db, err := sql.Open("sqlite3", ":memory:")973 if err != nil {974 panic(err)975 }976 q := fmt.Sprintf("SELECT * FROM %s where id = 1", Table)977 rows, err := db.Query(q)978 if err != nil {979 panic(err)980 }981 defer rows.Close()982}`}, 0, gosec.NewConfig()}, {[]string{`983package main984import (985 "fmt"986)987func main(){988 fmt.Sprintln()989}`}, 0, gosec.NewConfig()}, {[]string{`990// Format string with \n\r991package main992import (993 "database/sql"994 "fmt"995 "os"996)997func main(){998 db, err := sql.Open("sqlite3", ":memory:")999 if err != nil {1000 panic(err)1001 }1002 q := fmt.Sprintf("SELECT * FROM foo where\n name = '%s'", os.Args[1])1003 rows, err := db.Query(q)1004 if err != nil {1005 panic(err)1006 }1007 defer rows.Close()1008}`}, 1, gosec.NewConfig()}, {[]string{`1009// Format string with \n\r1010package main1011import (1012 "database/sql"1013 "fmt"1014 "os"1015)1016func main(){1017 db, err := sql.Open("sqlite3", ":memory:")1018 if err != nil {1019 panic(err)1020 }1021 q := fmt.Sprintf("SELECT * FROM foo where\nname = '%s'", os.Args[1])1022 rows, err := db.Query(q)1023 if err != nil {1024 panic(err)1025 }1026 defer rows.Close()1027}`}, 1, gosec.NewConfig()}, {[]string{`1028// SQLI by db.Query(some).Scan(&other)1029package main1030import (1031 "database/sql"1032 "fmt"1033 "os"1034)1035func main() {1036 var name string1037 db, err := sql.Open("sqlite3", ":memory:")1038 if err != nil {1039 panic(err)1040 }1041 q := fmt.Sprintf("SELECT name FROM users where id = '%s'", os.Args[1])1042 row := db.QueryRow(q)1043 err = row.Scan(&name)1044 if err != nil {1045 panic(err)1046 }1047 defer db.Close()1048}`}, 1, gosec.NewConfig()}, {[]string{`1049// SQLI by db.Query(some).Scan(&other)1050package main1051import (1052 "database/sql"1053 "fmt"1054 "os"1055)1056func main() {1057 var name string1058 db, err := sql.Open("sqlite3", ":memory:")1059 if err != nil {1060 panic(err)1061 }1062 q := fmt.Sprintf("SELECT name FROM users where id = '%s'", os.Args[1])1063 err = db.QueryRow(q).Scan(&name)1064 if err != nil {1065 panic(err)1066 }1067 defer db.Close()1068}`}, 1, gosec.NewConfig()},1069 }1070 // SampleCodeG202 - SQL query string building via string concatenation1071 SampleCodeG202 = []CodeSample{1072 {[]string{`1073package main1074import (1075 "database/sql"1076 "os"1077)1078func main(){1079 db, err := sql.Open("sqlite3", ":memory:")1080 if err != nil {1081 panic(err)1082 }1083 rows, err := db.Query("SELECT * FROM foo WHERE name = " + os.Args[1])1084 if err != nil {1085 panic(err)1086 }1087 defer rows.Close()1088}`}, 1, gosec.NewConfig()}, {[]string{`1089// case insensitive match1090package main1091import (1092 "database/sql"1093 "os"1094)1095func main(){1096 db, err := sql.Open("sqlite3", ":memory:")1097 if err != nil {1098 panic(err)1099 }1100 rows, err := db.Query("select * from foo where name = " + os.Args[1])1101 if err != nil {1102 panic(err)1103 }1104 defer rows.Close()1105}`}, 1, gosec.NewConfig()}, {[]string{`1106// context match1107package main1108import (1109 "context"1110 "database/sql"1111 "os"1112)1113func main(){1114 db, err := sql.Open("sqlite3", ":memory:")1115 if err != nil {1116 panic(err)1117 }1118 rows, err := db.QueryContext(context.Background(), "select * from foo where name = " + os.Args[1])1119 if err != nil {1120 panic(err)1121 }1122 defer rows.Close()1123}`}, 1, gosec.NewConfig()}, {[]string{`1124// DB transaction check1125package main1126import (1127 "context"1128 "database/sql"1129 "os"1130)1131func main(){1132 db, err := sql.Open("sqlite3", ":memory:")1133 if err != nil {1134 panic(err)1135 }1136 tx, err := db.Begin()1137 if err != nil {1138 panic(err)1139 }1140 defer tx.Rollback()1141 rows, err := tx.QueryContext(context.Background(), "select * from foo where name = " + os.Args[1])1142 if err != nil {1143 panic(err)1144 }1145 defer rows.Close()1146 if err := tx.Commit(); err != nil {1147 panic(err)1148 }1149}`}, 1, gosec.NewConfig()}, {[]string{`1150// multiple string concatenation1151package main1152import (1153 "database/sql"1154 "os"1155)1156func main(){1157 db, err := sql.Open("sqlite3", ":memory:")1158 if err != nil {1159 panic(err)1160 }1161 rows, err := db.Query("SELECT * FROM foo" + "WHERE name = " + os.Args[1])1162 if err != nil {1163 panic(err)1164 }1165 defer rows.Close()1166}`}, 1, gosec.NewConfig()}, {[]string{`1167// false positive1168package main1169import (1170 "database/sql"1171)1172var staticQuery = "SELECT * FROM foo WHERE age < "1173func main(){1174 db, err := sql.Open("sqlite3", ":memory:")1175 if err != nil {1176 panic(err)1177 }1178 rows, err := db.Query(staticQuery + "32")1179 if err != nil {1180 panic(err)1181 }1182 defer rows.Close()1183}`}, 0, gosec.NewConfig()}, {[]string{`1184package main1185import (1186 "database/sql"1187)1188const age = "32"1189var staticQuery = "SELECT * FROM foo WHERE age < "1190func main(){1191 db, err := sql.Open("sqlite3", ":memory:")1192 if err != nil {1193 panic(err)1194 }1195 rows, err := db.Query(staticQuery + age)1196 if err != nil {1197 panic(err)1198 }1199 defer rows.Close()1200}1201`}, 0, gosec.NewConfig()}, {[]string{`1202package main1203const gender = "M"1204`, `1205package main1206import (1207 "database/sql"1208)1209const age = "32"1210var staticQuery = "SELECT * FROM foo WHERE age < "1211func main(){1212 db, err := sql.Open("sqlite3", ":memory:")1213 if err != nil {1214 panic(err)1215 }1216 rows, err := db.Query("SELECT * FROM foo WHERE gender = " + gender)1217 if err != nil {1218 panic(err)1219 }1220 defer rows.Close()1221}1222`}, 0, gosec.NewConfig()},1223 }1224 // SampleCodeG203 - Template checks1225 SampleCodeG203 = []CodeSample{1226 {[]string{`1227// We assume that hardcoded template strings are safe as the programmer would1228// need to be explicitly shooting themselves in the foot (as below)1229package main1230import (1231 "html/template"1232 "os"1233)1234const tmpl = ""1235func main() {1236 t := template.Must(template.New("ex").Parse(tmpl))1237 v := map[string]interface{}{1238 "Title": "Test <b>World</b>",1239 "Body": template.HTML("<script>alert(1)</script>"),1240 }1241 t.Execute(os.Stdout, v)1242}`}, 0, gosec.NewConfig()}, {[]string{1243 `1244// Using a variable to initialize could potentially be dangerous. Under the1245// current model this will likely produce some false positives.1246package main1247import (1248 "html/template"1249 "os"1250)1251const tmpl = ""1252func main() {1253 a := "something from another place"1254 t := template.Must(template.New("ex").Parse(tmpl))1255 v := map[string]interface{}{1256 "Title": "Test <b>World</b>",1257 "Body": template.HTML(a),1258 }1259 t.Execute(os.Stdout, v)1260}`,1261 }, 1, gosec.NewConfig()}, {[]string{1262 `1263package main1264import (1265 "html/template"1266 "os"1267)1268const tmpl = ""1269func main() {1270 a := "something from another place"1271 t := template.Must(template.New("ex").Parse(tmpl))1272 v := map[string]interface{}{1273 "Title": "Test <b>World</b>",1274 "Body": template.JS(a),1275 }1276 t.Execute(os.Stdout, v)1277}`,1278 }, 1, gosec.NewConfig()}, {[]string{1279 `1280package main1281import (1282 "html/template"1283 "os"1284)1285const tmpl = ""1286func main() {1287 a := "something from another place"1288 t := template.Must(template.New("ex").Parse(tmpl))1289 v := map[string]interface{}{1290 "Title": "Test <b>World</b>",1291 "Body": template.URL(a),1292 }1293 t.Execute(os.Stdout, v)1294}`,1295 }, 1, gosec.NewConfig()},1296 }1297 // SampleCodeG204 - Subprocess auditing1298 SampleCodeG204 = []CodeSample{1299 {[]string{`1300package main1301import (1302 "log"1303 "os/exec"1304 "context"1305)1306func main() {1307 err := exec.CommandContext(context.Background(), "git", "rev-parse", "--show-toplavel").Run()1308 if err != nil {1309 log.Fatal(err)1310 }1311 log.Printf("Command finished with error: %v", err)1312}`}, 0, gosec.NewConfig()},1313 {[]string{`1314// Calling any function which starts a new process with using1315// command line arguments as it's arguments is considered dangerous1316package main1317import (1318 "context"1319 "log"1320 "os"1321 "os/exec"1322)1323func main() {1324 err := exec.CommandContext(context.Background(), os.Args[0], "5").Run()1325 if err != nil {1326 log.Fatal(err)1327 }1328 log.Printf("Command finished with error: %v", err)1329}`}, 1, gosec.NewConfig()},1330 {[]string{`1331// Initializing a local variable using a environmental1332// variable is consider as a dangerous user input1333package main1334import (1335 "log"1336 "os"1337 "os/exec"1338)1339func main() {1340 run := "sleep" + os.Getenv("SOMETHING")1341 cmd := exec.Command(run, "5")1342 err := cmd.Start()1343 if err != nil {1344 log.Fatal(err)1345 }1346 log.Printf("Waiting for command to finish...")1347 err = cmd.Wait()1348 log.Printf("Command finished with error: %v", err)1349}`}, 1, gosec.NewConfig()},1350 {[]string{`1351// gosec doesn't have enough context to decide that the1352// command argument of the RunCmd function is harcoded string1353// and that's why it's better to warn the user so he can audit it1354package main1355import (1356 "log"1357 "os/exec"1358)1359func RunCmd(command string) {1360 cmd := exec.Command(command, "5")1361 err := cmd.Start()1362 if err != nil {1363 log.Fatal(err)1364 }1365 log.Printf("Waiting for command to finish...")1366 err = cmd.Wait()1367}1368func main() {1369 RunCmd("sleep")1370}`}, 0, gosec.NewConfig()},1371 {[]string{`1372package main1373import (1374 "log"1375 "os/exec"1376)1377func RunCmd(a string, c string) {1378 cmd := exec.Command(c)1379 err := cmd.Start()1380 if err != nil {1381 log.Fatal(err)1382 }1383 log.Printf("Waiting for command to finish...")1384 err = cmd.Wait()1385 cmd = exec.Command(a)1386 err = cmd.Start()1387 if err != nil {1388 log.Fatal(err)1389 }1390 log.Printf("Waiting for command to finish...")1391 err = cmd.Wait()1392}1393func main() {1394 RunCmd("ll", "ls")1395}`}, 0, gosec.NewConfig()},1396 {[]string{`1397// syscall.Exec function called with harcoded arguments1398// shouldn't be consider as a command injection1399package main1400import (1401 "fmt"1402 "syscall"1403)1404func main() {1405 err := syscall.Exec("/bin/cat", []string{"/etc/passwd"}, nil)1406 if err != nil {1407 fmt.Printf("Error: %v\n", err)1408 }1409}`}, 0, gosec.NewConfig()},1410 {1411 []string{`1412package main1413import (1414 "fmt"1415 "syscall"1416)1417func RunCmd(command string) {1418 _, err := syscall.ForkExec(command, []string{}, nil)1419 if err != nil {1420 fmt.Printf("Error: %v\n", err)1421 }1422}1423func main() {1424 RunCmd("sleep")1425}`}, 1, gosec.NewConfig(),1426 },1427 {1428 []string{`1429package main1430import (1431 "fmt"1432 "syscall"1433)1434func RunCmd(command string) {1435 _, _, err := syscall.StartProcess(command, []string{}, nil)1436 if err != nil {1437 fmt.Printf("Error: %v\n", err)1438 }1439}1440func main() {1441 RunCmd("sleep")1442}`}, 1, gosec.NewConfig(),1443 },1444 {[]string{`1445// starting a process with a variable as an argument1446// even if not constant is not considered as dangerous1447// because it has harcoded value1448package main1449import (1450 "log"1451 "os/exec"1452)1453func main() {1454 run := "sleep"1455 cmd := exec.Command(run, "5")1456 err := cmd.Start()1457 if err != nil {1458 log.Fatal(err)1459 }1460 log.Printf("Waiting for command to finish...")1461 err = cmd.Wait()1462 log.Printf("Command finished with error: %v", err)1463}`}, 0, gosec.NewConfig()},1464 {[]string{`1465// exec.Command from supplemental package sys/execabs1466// using variable arguments1467package main1468import (1469 "context"1470 "log"1471 "os"1472 exec "golang.org/x/sys/execabs"1473)1474func main() {1475 err := exec.CommandContext(context.Background(), os.Args[0], "5").Run()1476 if err != nil {1477 log.Fatal(err)1478 }1479 log.Printf("Command finished with error: %v", err)1480}1481`}, 1, gosec.NewConfig()},1482 }1483 // SampleCodeG301 - mkdir permission check1484 SampleCodeG301 = []CodeSample{{[]string{`1485package main1486import (1487 "fmt"1488 "os"1489)1490func main() {1491 err := os.Mkdir("/tmp/mydir", 0777)1492 if err != nil {1493 fmt.Println("Error when creating a directory!")1494 return1495 }1496}`}, 1, gosec.NewConfig()}, {[]string{`1497package main1498import (1499 "fmt"1500 "os"1501)1502func main() {1503 err := os.MkdirAll("/tmp/mydir", 0777)1504 if err != nil {1505 fmt.Println("Error when creating a directory!")1506 return1507 }1508}`}, 1, gosec.NewConfig()}, {[]string{`1509package main1510import (1511 "fmt"1512 "os"1513)1514func main() {1515 err := os.Mkdir("/tmp/mydir", 0600)1516 if err != nil {1517 fmt.Println("Error when creating a directory!")1518 return1519 }1520}`}, 0, gosec.NewConfig()}}1521 // SampleCodeG302 - file create / chmod permissions check1522 SampleCodeG302 = []CodeSample{{[]string{`1523package main1524import (1525 "fmt"1526 "os"1527)1528func main() {1529 err := os.Chmod("/tmp/somefile", 0777)1530 if err != nil {1531 fmt.Println("Error when changing file permissions!")1532 return1533 }1534}`}, 1, gosec.NewConfig()}, {[]string{`1535package main1536import (1537 "fmt"1538 "os"1539)1540func main() {1541 _, err := os.OpenFile("/tmp/thing", os.O_CREATE|os.O_WRONLY, 0666)1542 if err != nil {1543 fmt.Println("Error opening a file!")1544 return1545 }1546}`}, 1, gosec.NewConfig()}, {[]string{`1547package main1548import (1549 "fmt"1550 "os"1551)1552func main() {1553 err := os.Chmod("/tmp/mydir", 0400)1554 if err != nil {1555 fmt.Println("Error")1556 return1557 }1558}`}, 0, gosec.NewConfig()}, {[]string{`1559package main1560import (1561 "fmt"1562 "os"1563)1564func main() {1565 _, err := os.OpenFile("/tmp/thing", os.O_CREATE|os.O_WRONLY, 0600)1566 if err != nil {1567 fmt.Println("Error opening a file!")1568 return1569 }1570}1571`}, 0, gosec.NewConfig()}}1572 // SampleCodeG303 - bad tempfile permissions & hardcoded shared path1573 SampleCodeG303 = []CodeSample{{[]string{`1574package samples1575import (1576 "fmt"1577 "io/ioutil"1578 "os"1579 "path"1580 "path/filepath"1581)1582func main() {1583 err := ioutil.WriteFile("/tmp/demo2", []byte("This is some data"), 0644)1584 if err != nil {1585 fmt.Println("Error while writing!")1586 }1587 f, err := os.Create("/tmp/demo2")1588 if err != nil {1589 fmt.Println("Error while writing!")1590 } else if err = f.Close(); err != nil {1591 fmt.Println("Error while closing!")1592 }1593 err = os.WriteFile("/tmp/demo2", []byte("This is some data"), 0644)1594 if err != nil {1595 fmt.Println("Error while writing!")1596 }1597 err = os.WriteFile("/usr/tmp/demo2", []byte("This is some data"), 0644)1598 if err != nil {1599 fmt.Println("Error while writing!")1600 }1601 err = os.WriteFile("/tmp/" + "demo2", []byte("This is some data"), 0644)1602 if err != nil {1603 fmt.Println("Error while writing!")1604 }1605 err = os.WriteFile(os.TempDir() + "/demo2", []byte("This is some data"), 0644)1606 if err != nil {1607 fmt.Println("Error while writing!")1608 }1609 err = os.WriteFile(path.Join("/var/tmp", "demo2"), []byte("This is some data"), 0644)1610 if err != nil {1611 fmt.Println("Error while writing!")1612 }1613 err = os.WriteFile(path.Join(os.TempDir(), "demo2"), []byte("This is some data"), 0644)1614 if err != nil {1615 fmt.Println("Error while writing!")1616 }1617 err = os.WriteFile(filepath.Join(os.TempDir(), "demo2"), []byte("This is some data"), 0644)1618 if err != nil {1619 fmt.Println("Error while writing!")1620 }1621}`}, 9, gosec.NewConfig()}}1622 // SampleCodeG304 - potential file inclusion vulnerability1623 SampleCodeG304 = []CodeSample{1624 {[]string{`1625package main1626import (1627"os"1628"io/ioutil"1629"log"1630)1631func main() {1632 f := os.Getenv("tainted_file")1633 body, err := ioutil.ReadFile(f)1634 if err != nil {1635 log.Printf("Error: %v\n", err)1636 }1637 log.Print(body)1638}`}, 1, gosec.NewConfig()}, {[]string{`1639package main1640import (1641"os"1642"log"1643)1644func main() {1645 f := os.Getenv("tainted_file")1646 body, err := os.ReadFile(f)1647 if err != nil {1648 log.Printf("Error: %v\n", err)1649 }1650 log.Print(body)1651}`}, 1, gosec.NewConfig()}, {[]string{`1652package main1653import (1654 "fmt"1655 "log"1656 "net/http"1657 "os"1658)1659func main() {1660 http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {1661 title := r.URL.Query().Get("title")1662 f, err := os.Open(title)1663 if err != nil {1664 fmt.Printf("Error: %v\n", err)1665 }1666 body := make([]byte, 5)1667 if _, err = f.Read(body); err != nil {1668 fmt.Printf("Error: %v\n", err)1669 }1670 fmt.Fprintf(w, "%s", body)1671 })1672 log.Fatal(http.ListenAndServe(":3000", nil))1673}`}, 1, gosec.NewConfig()}, {[]string{`1674package main1675import (1676 "fmt"1677 "log"1678 "net/http"1679 "os"1680)1681func main() {1682 http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {1683 title := r.URL.Query().Get("title")1684 f, err := os.OpenFile(title, os.O_RDWR|os.O_CREATE, 0755)1685 if err != nil {1686 fmt.Printf("Error: %v\n", err)1687 }1688 body := make([]byte, 5)1689 if _, err = f.Read(body); err != nil {1690 fmt.Printf("Error: %v\n", err)1691 }1692 fmt.Fprintf(w, "%s", body)1693 })1694 log.Fatal(http.ListenAndServe(":3000", nil))1695}`}, 1, gosec.NewConfig()}, {[]string{`1696package main1697import (1698 "log"1699 "os"1700 "io/ioutil"1701)1702 func main() {1703 f2 := os.Getenv("tainted_file2")1704 body, err := ioutil.ReadFile("/tmp/" + f2)1705 if err != nil {1706 log.Printf("Error: %v\n", err)1707 }1708 log.Print(body)1709 }`}, 1, gosec.NewConfig()}, {[]string{`1710 package main1711 import (1712 "bufio"1713 "fmt"1714 "os"1715 "path/filepath"1716 )1717func main() {1718 reader := bufio.NewReader(os.Stdin)1719 fmt.Print("Please enter file to read: ")1720 file, _ := reader.ReadString('\n')1721 file = file[:len(file)-1]1722 f, err := os.Open(filepath.Join("/tmp/service/", file))1723 if err != nil {1724 fmt.Printf("Error: %v\n", err)1725 }1726 contents := make([]byte, 15)1727 if _, err = f.Read(contents); err != nil {1728 fmt.Printf("Error: %v\n", err)1729 }1730 fmt.Println(string(contents))1731}`}, 1, gosec.NewConfig()}, {[]string{`1732package main1733import (1734 "log"1735 "os"1736 "io/ioutil"1737 "path/filepath"1738)1739func main() {1740 dir := os.Getenv("server_root")1741 f3 := os.Getenv("tainted_file3")1742 // edge case where both a binary expression and file Join are used.1743 body, err := ioutil.ReadFile(filepath.Join("/var/"+dir, f3))1744 if err != nil {1745 log.Printf("Error: %v\n", err)1746 }1747 log.Print(body)1748}`}, 1, gosec.NewConfig()}, {[]string{`1749package main1750import (1751 "os"1752 "path/filepath"1753)1754func main() {1755 repoFile := "path_of_file"1756 cleanRepoFile := filepath.Clean(repoFile)1757 _, err := os.OpenFile(cleanRepoFile, os.O_RDONLY, 0600)1758 if err != nil {1759 panic(err)1760 }1761}1762`}, 0, gosec.NewConfig()}, {[]string{`1763package main1764import (1765 "os"1766 "path/filepath"1767)1768func openFile(filePath string) {1769 _, err := os.OpenFile(filepath.Clean(filePath), os.O_RDONLY, 0600)1770 if err != nil {1771 panic(err)1772 }1773}1774func main() {1775 repoFile := "path_of_file"1776 openFile(repoFile)1777}1778`}, 0, gosec.NewConfig()}, {[]string{`1779package main1780import (1781 "os"1782 "path/filepath"1783)1784func main() {1785 repoFile := "path_of_file"1786 relFile, err := filepath.Rel("./", repoFile)1787 if err != nil {1788 panic(err)1789 }1790 _, err = os.OpenFile(relFile, os.O_RDONLY, 0600)1791 if err != nil {1792 panic(err)1793 }1794}1795`}, 0, gosec.NewConfig()}, {[]string{`1796package main1797import (1798 "io"1799 "os"1800)1801func createFile(file string) *os.File {1802 f, err := os.Create(file)1803 if err != nil {1804 panic(err)1805 }1806 return f1807}1808func main() {1809 s, err := os.Open("src")1810 if err != nil {1811 panic(err)1812 }1813 defer s.Close()1814 d := createFile("dst")1815 defer d.Close()1816 _, err = io.Copy(d, s)1817 if err != nil {1818 panic(err)1819 }1820}`}, 1, gosec.NewConfig()},1821 }1822 // SampleCodeG305 - File path traversal when extracting zip/tar archives1823 SampleCodeG305 = []CodeSample{{[]string{`1824package unzip1825import (1826 "archive/zip"1827 "io"1828 "os"1829 "path/filepath"1830)1831func unzip(archive, target string) error {1832 reader, err := zip.OpenReader(archive)1833 if err != nil {1834 return err1835 }1836 if err := os.MkdirAll(target, 0750); err != nil {1837 return err1838 }1839 for _, file := range reader.File {1840 path := filepath.Join(target, file.Name)1841 if file.FileInfo().IsDir() {1842 os.MkdirAll(path, file.Mode()) //#nosec1843 continue1844 }1845 fileReader, err := file.Open()1846 if err != nil {1847 return err1848 }1849 defer fileReader.Close()1850 targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())1851 if err != nil {1852 return err1853 }1854 defer targetFile.Close()1855 if _, err := io.Copy(targetFile, fileReader); err != nil {1856 return err1857 }1858 }1859 return nil1860}`}, 1, gosec.NewConfig()}, {[]string{`1861package unzip1862import (1863 "archive/zip"1864 "io"1865 "os"1866 "path/filepath"1867)1868func unzip(archive, target string) error {1869 reader, err := zip.OpenReader(archive)1870 if err != nil {1871 return err1872 }1873 if err := os.MkdirAll(target, 0750); err != nil {1874 return err1875 }1876 for _, file := range reader.File {1877 archiveFile := file.Name1878 path := filepath.Join(target, archiveFile)1879 if file.FileInfo().IsDir() {1880 os.MkdirAll(path, file.Mode()) //#nosec1881 continue1882 }1883 fileReader, err := file.Open()1884 if err != nil {1885 return err1886 }1887 defer fileReader.Close()1888 targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())1889 if err != nil {1890 return err1891 }1892 defer targetFile.Close()1893 if _, err := io.Copy(targetFile, fileReader); err != nil {1894 return err1895 }1896 }1897 return nil1898}`}, 1, gosec.NewConfig()}, {[]string{`1899package zip1900import (1901 "archive/zip"1902 "io"1903 "os"1904 "path"1905)1906func extractFile(f *zip.File, destPath string) error {1907 filePath := path.Join(destPath, f.Name)1908 os.MkdirAll(path.Dir(filePath), os.ModePerm)1909 rc, err := f.Open()1910 if err != nil {1911 return err1912 }1913 defer rc.Close()1914 fw, err := os.Create(filePath)1915 if err != nil {1916 return err1917 }1918 defer fw.Close()1919 if _, err = io.Copy(fw, rc); err != nil {1920 return err1921 }1922 if f.FileInfo().Mode()&os.ModeSymlink != 0 {1923 return nil1924 }1925 if err = os.Chtimes(filePath, f.ModTime(), f.ModTime()); err != nil {1926 return err1927 }1928 return os.Chmod(filePath, f.FileInfo().Mode())1929}`}, 1, gosec.NewConfig()}, {[]string{`1930package tz1931import (1932 "archive/tar"1933 "io"1934 "os"1935 "path"1936)1937func extractFile(f *tar.Header, tr *tar.Reader, destPath string) error {1938 filePath := path.Join(destPath, f.Name)1939 os.MkdirAll(path.Dir(filePath), os.ModePerm)1940 fw, err := os.Create(filePath)1941 if err != nil {1942 return err1943 }1944 defer fw.Close()1945 if _, err = io.Copy(fw, tr); err != nil {1946 return err1947 }1948 if f.FileInfo().Mode()&os.ModeSymlink != 0 {1949 return nil1950 }1951 if err = os.Chtimes(filePath, f.FileInfo().ModTime(), f.FileInfo().ModTime()); err != nil {1952 return err1953 }1954 return os.Chmod(filePath, f.FileInfo().Mode())1955}`}, 1, gosec.NewConfig()}}1956 // SampleCodeG306 - Poor permissions for WriteFile1957 SampleCodeG306 = []CodeSample{1958 {[]string{`package main1959import (1960 "bufio"1961 "fmt"1962 "io/ioutil"1963 "os"1964)1965func check(e error) {1966 if e != nil {1967 panic(e)1968 }1969}1970func main() {1971 d1 := []byte("hello\ngo\n")1972 err := ioutil.WriteFile("/tmp/dat1", d1, 0744)1973 check(err)1974 allowed := ioutil.WriteFile("/tmp/dat1", d1, 0600)1975 check(allowed)1976 f, err := os.Create("/tmp/dat2")1977 check(err)1978 defer f.Close()1979 d2 := []byte{115, 111, 109, 101, 10}1980 n2, err := f.Write(d2)1981 defer check(err)1982 fmt.Printf("wrote %d bytes\n", n2)1983 n3, err := f.WriteString("writes\n")1984 fmt.Printf("wrote %d bytes\n", n3)1985 f.Sync()1986 w := bufio.NewWriter(f)1987 n4, err := w.WriteString("buffered\n")1988 fmt.Printf("wrote %d bytes\n", n4)1989 w.Flush()1990}`}, 1, gosec.NewConfig()},1991 }1992 // SampleCodeG307 - Unsafe defer of os.Close1993 SampleCodeG307 = []CodeSample{1994 {[]string{`package main1995import (1996 "bufio"1997 "fmt"1998 "io/ioutil"1999 "os"2000)2001func check(e error) {2002 if e != nil {2003 panic(e)2004 }2005}2006func main() {2007 d1 := []byte("hello\ngo\n")2008 err := ioutil.WriteFile("/tmp/dat1", d1, 0744)2009 check(err)2010 allowed := ioutil.WriteFile("/tmp/dat1", d1, 0600)2011 check(allowed)2012 f, err := os.Create("/tmp/dat2")2013 check(err)2014 defer f.Close()2015 d2 := []byte{115, 111, 109, 101, 10}2016 n2, err := f.Write(d2)2017 defer check(err)2018 fmt.Printf("wrote %d bytes\n", n2)2019 n3, err := f.WriteString("writes\n")2020 fmt.Printf("wrote %d bytes\n", n3)2021 f.Sync()2022 w := bufio.NewWriter(f)2023 n4, err := w.WriteString("buffered\n")2024 fmt.Printf("wrote %d bytes\n", n4)2025 w.Flush()2026}`}, 1, gosec.NewConfig()},2027 }2028 // SampleCodeG401 - Use of weak crypto MD52029 SampleCodeG401 = []CodeSample{2030 {[]string{`2031package main2032import (2033 "crypto/md5"2034 "fmt"2035 "io"2036 "log"2037 "os"2038)2039func main() {2040 f, err := os.Open("file.txt")2041 if err != nil {2042 log.Fatal(err)2043 }2044 defer f.Close()2045 defer func() {2046 err := f.Close()2047 if err != nil {2048 log.Printf("error closing the file: %s", err)2049 }2050 }()2051 h := md5.New()2052 if _, err := io.Copy(h, f); err != nil {2053 log.Fatal(err)2054 }2055 fmt.Printf("%x", h.Sum(nil))2056}`}, 1, gosec.NewConfig()},2057 }2058 // SampleCodeG401b - Use of weak crypto SHA12059 SampleCodeG401b = []CodeSample{2060 {[]string{`2061package main2062import (2063 "crypto/sha1"2064 "fmt"2065 "io"2066 "log"2067 "os"2068)2069func main() {2070 f, err := os.Open("file.txt")2071 if err != nil {2072 log.Fatal(err)2073 }2074 defer f.Close()2075 h := sha1.New()2076 if _, err := io.Copy(h, f); err != nil {2077 log.Fatal(err)2078 }2079 fmt.Printf("%x", h.Sum(nil))2080}`}, 1, gosec.NewConfig()},2081 }2082 // SampleCodeG402 - TLS settings2083 SampleCodeG402 = []CodeSample{2084 {[]string{`2085// InsecureSkipVerify2086package main2087import (2088 "crypto/tls"2089 "fmt"2090 "net/http"2091)2092func main() {2093 tr := &http.Transport{2094 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},2095 }2096 client := &http.Client{Transport: tr}2097 _, err := client.Get("https://golang.org/")2098 if err != nil {2099 fmt.Println(err)2100 }2101}`}, 1, gosec.NewConfig()},2102 {[]string{2103 `2104// Insecure minimum version2105package main2106import (2107 "crypto/tls"2108 "fmt"2109 "net/http"2110)2111func main() {2112 tr := &http.Transport{2113 TLSClientConfig: &tls.Config{MinVersion: 0},2114 }2115 client := &http.Client{Transport: tr}2116 _, err := client.Get("https://golang.org/")2117 if err != nil {2118 fmt.Println(err)2119 }2120}`,2121 }, 1, gosec.NewConfig()},2122 {[]string{2123 `2124// Insecure minimum version2125package main2126import (2127 "crypto/tls"2128 "fmt"2129)2130func CaseNotError() *tls.Config {2131 var v uint16 = tls.VersionTLS132132 return &tls.Config{2133 MinVersion: v,2134 }2135}2136func main() {2137 a := CaseNotError()2138 fmt.Printf("Debug: %v\n", a.MinVersion)2139}`,2140 }, 0, gosec.NewConfig()},2141 {[]string{2142 `2143// Insecure minimum version2144package main2145import (2146 "crypto/tls"2147 "fmt"2148)2149func CaseNotError() *tls.Config {2150 return &tls.Config{2151 MinVersion: tls.VersionTLS13,2152 }2153}2154func main() {2155 a := CaseNotError()2156 fmt.Printf("Debug: %v\n", a.MinVersion)2157}`,2158 }, 0, gosec.NewConfig()},2159 {[]string{2160 `2161// Insecure minimum version2162package main2163import (2164 "crypto/tls"2165 "fmt"2166)2167func CaseError() *tls.Config {2168 var v = &tls.Config{2169 MinVersion: 0,2170 }2171 return v2172}2173func main() {2174 a := CaseError()2175 fmt.Printf("Debug: %v\n", a.MinVersion)2176}`,2177 }, 1, gosec.NewConfig()},2178 {[]string{2179 `2180// Insecure minimum version2181package main2182import (2183 "crypto/tls"2184 "fmt"2185)2186func CaseError() *tls.Config {2187 var v = &tls.Config{2188 MinVersion: getVersion(),2189 }2190 return v2191}2192func getVersion() uint16 {2193 return tls.VersionTLS122194}2195func main() {2196 a := CaseError()2197 fmt.Printf("Debug: %v\n", a.MinVersion)2198}`,2199 }, 1, gosec.NewConfig()},2200 {[]string{2201 `2202// Insecure minimum version2203package main2204import (2205 "crypto/tls"2206 "fmt"2207 "net/http"2208)2209var theValue uint16 = 0x03042210func main() {2211 tr := &http.Transport{2212 TLSClientConfig: &tls.Config{MinVersion: theValue},2213 }2214 client := &http.Client{Transport: tr}2215 _, err := client.Get("https://golang.org/")2216 if err != nil {2217 fmt.Println(err)2218 }2219}2220`,2221 }, 0, gosec.NewConfig()},2222 {[]string{`2223// Insecure max version2224package main2225import (2226 "crypto/tls"2227 "fmt"2228 "net/http"2229)2230func main() {2231 tr := &http.Transport{2232 TLSClientConfig: &tls.Config{MaxVersion: 0},2233 }2234 client := &http.Client{Transport: tr}2235 _, err := client.Get("https://golang.org/")2236 if err != nil {2237 fmt.Println(err)2238 }2239}2240`}, 1, gosec.NewConfig()},2241 {2242 []string{`2243// Insecure ciphersuite selection2244package main2245import (2246 "crypto/tls"2247 "fmt"2248 "net/http"2249)2250func main() {2251 tr := &http.Transport{2252 TLSClientConfig: &tls.Config{CipherSuites: []uint16{2253 tls.TLS_RSA_WITH_AES_128_GCM_SHA256,2254 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,2255 },},2256 }2257 client := &http.Client{Transport: tr}2258 _, err := client.Get("https://golang.org/")2259 if err != nil {2260 fmt.Println(err)2261 }2262}`}, 1, gosec.NewConfig(),2263 },2264 {[]string{`2265// secure max version when min version is specified2266package main2267import (2268 "crypto/tls"2269 "fmt"2270 "net/http"2271)2272func main() {2273 tr := &http.Transport{2274 TLSClientConfig: &tls.Config{MaxVersion: 0, MinVersion: tls.VersionTLS13},2275 }2276 client := &http.Client{Transport: tr}2277 _, err := client.Get("https://golang.org/")2278 if err != nil {2279 fmt.Println(err)2280 }2281}`}, 0, gosec.NewConfig()},2282 {[]string{`2283package p02284import "crypto/tls"2285func TlsConfig0() *tls.Config {2286 var v uint16 = 02287 return &tls.Config{MinVersion: v}2288}2289`, `2290package p02291import "crypto/tls"2292func TlsConfig1() *tls.Config {2293 return &tls.Config{MinVersion: 0x0304}2294}2295`}, 1, gosec.NewConfig()},2296 }2297 // SampleCodeG403 - weak key strength2298 SampleCodeG403 = []CodeSample{2299 {[]string{`2300package main2301import (2302 "crypto/rand"2303 "crypto/rsa"2304 "fmt"2305)2306func main() {2307 //Generate Private Key2308 pvk, err := rsa.GenerateKey(rand.Reader, 1024)2309 if err != nil {2310 fmt.Println(err)2311 }2312 fmt.Println(pvk)2313}`}, 1, gosec.NewConfig()},2314 }2315 // SampleCodeG404 - weak random number2316 SampleCodeG404 = []CodeSample{2317 {[]string{`2318package main2319import "crypto/rand"2320func main() {2321 good, _ := rand.Read(nil)2322 println(good)2323}`}, 0, gosec.NewConfig()},2324 {[]string{`2325package main2326import "math/rand"2327func main() {2328 bad := rand.Int()2329 println(bad)2330}`}, 1, gosec.NewConfig()},2331 {[]string{`2332package main2333import (2334 "crypto/rand"2335 mrand "math/rand"2336)2337func main() {2338 good, _ := rand.Read(nil)2339 println(good)2340 bad := mrand.Int31()2341 println(bad)2342}`}, 1, gosec.NewConfig()},2343 {[]string{`2344package main2345import (2346 "math/rand"2347)2348func main() {2349 gen := rand.New(rand.NewSource(10))2350 bad := gen.Int()2351 println(bad)2352}`}, 1, gosec.NewConfig()},2353 {[]string{`2354package main2355import (2356 "math/rand"2357)2358func main() {2359 bad := rand.Intn(10)2360 println(bad)2361}`}, 1, gosec.NewConfig()},2362 }2363 // SampleCodeG501 - Blocklisted import MD52364 SampleCodeG501 = []CodeSample{2365 {[]string{`2366package main2367import (2368 "crypto/md5"2369 "fmt"2370 "os"2371)2372func main() {2373 for _, arg := range os.Args {2374 fmt.Printf("%x - %s\n", md5.Sum([]byte(arg)), arg)2375 }2376}`}, 1, gosec.NewConfig()},2377 }2378 // SampleCodeG502 - Blocklisted import DES2379 SampleCodeG502 = []CodeSample{2380 {[]string{`2381package main2382import (2383 "crypto/cipher"2384 "crypto/des"2385 "crypto/rand"2386 "encoding/hex"2387 "fmt"2388 "io"2389)2390func main() {2391 block, err := des.NewCipher([]byte("sekritz"))2392 if err != nil {2393 panic(err)2394 }2395 plaintext := []byte("I CAN HAZ SEKRIT MSG PLZ")2396 ciphertext := make([]byte, des.BlockSize+len(plaintext))2397 iv := ciphertext[:des.BlockSize]2398 if _, err := io.ReadFull(rand.Reader, iv); err != nil {2399 panic(err)2400 }2401 stream := cipher.NewCFBEncrypter(block, iv)2402 stream.XORKeyStream(ciphertext[des.BlockSize:], plaintext)2403 fmt.Println("Secret message is: %s", hex.EncodeToString(ciphertext))2404}`}, 1, gosec.NewConfig()},2405 }2406 // SampleCodeG503 - Blocklisted import RC42407 SampleCodeG503 = []CodeSample{{[]string{`2408package main2409import (2410 "crypto/rc4"2411 "encoding/hex"2412 "fmt"2413)2414func main() {2415 cipher, err := rc4.NewCipher([]byte("sekritz"))2416 if err != nil {2417 panic(err)2418 }2419 plaintext := []byte("I CAN HAZ SEKRIT MSG PLZ")2420 ciphertext := make([]byte, len(plaintext))2421 cipher.XORKeyStream(ciphertext, plaintext)2422 fmt.Println("Secret message is: %s", hex.EncodeToString(ciphertext))2423}`}, 1, gosec.NewConfig()}}2424 // SampleCodeG504 - Blocklisted import CGI2425 SampleCodeG504 = []CodeSample{{[]string{`2426package main2427import (2428 "net/http/cgi"2429 "net/http"2430 )2431func main() {2432 cgi.Serve(http.FileServer(http.Dir("/usr/share/doc")))2433}`}, 1, gosec.NewConfig()}}2434 // SampleCodeG505 - Blocklisted import SHA12435 SampleCodeG505 = []CodeSample{2436 {[]string{`2437package main2438import (2439 "crypto/sha1"2440 "fmt"2441 "os"2442)2443func main() {2444 for _, arg := range os.Args {2445 fmt.Printf("%x - %s\n", sha1.Sum([]byte(arg)), arg)2446 }2447}`}, 1, gosec.NewConfig()},2448 }2449 // SampleCodeG601 - Implicit aliasing over range statement2450 SampleCodeG601 = []CodeSample{2451 {[]string{2452 `2453package main2454import "fmt"2455var vector []*string2456func appendVector(s *string) {2457 vector = append(vector, s)2458}2459func printVector() {2460 for _, item := range vector {2461 fmt.Printf("%s", *item)2462 }2463 fmt.Println()2464}2465func foo() (int, **string, *string) {2466 for _, item := range vector {2467 return 0, &item, item2468 }2469 return 0, nil, nil2470}2471func main() {2472 for _, item := range []string{"A", "B", "C"} {2473 appendVector(&item)2474 }2475 printVector()2476 zero, c_star, c := foo()2477 fmt.Printf("%d %v %s", zero, c_star, c)2478}`,2479 }, 1, gosec.NewConfig()},2480 {[]string{`2481// see: github.com/securego/gosec/issues/4752482package main2483import (2484 "fmt"2485)2486func main() {2487 sampleMap := map[string]string{}2488 sampleString := "A string"2489 for sampleString, _ = range sampleMap {2490 fmt.Println(sampleString)2491 }2492}`}, 0, gosec.NewConfig()},2493 }2494 // SampleCodeBuildTag - G601 build tags2495 SampleCodeBuildTag = []CodeSample{{[]string{`2496// +build tag2497package main2498func main() {2499 fmt.Println("no package imported error")2500}`}, 1, gosec.NewConfig()}}2501 // SampleCodeCgo - Cgo file sample2502 SampleCodeCgo = []CodeSample{{[]string{`2503package main2504import (2505 "fmt"2506 "unsafe"2507)2508/*2509#include <stdlib.h>2510#include <stdio.h>2511#include <string.h>2512int printData(unsigned char *data) {2513 return printf("cData: %lu \"%s\"\n", (long unsigned int)strlen(data), data);2514}2515*/2516import "C"2517func main() {2518 // Allocate C data buffer.2519 width, height := 8, 22520 lenData := width * height2521 // add string terminating null byte2522 cData := (*C.uchar)(C.calloc(C.size_t(lenData+1), C.sizeof_uchar))2523 // When no longer in use, free C allocations.2524 defer C.free(unsafe.Pointer(cData))2525 // Go slice reference to C data buffer,2526 // minus string terminating null byte2527 gData := (*[1 << 30]byte)(unsafe.Pointer(cData))[:lenData:lenData]2528 // Write and read cData via gData.2529 for i := range gData {2530 gData[i] = '.'2531 }2532 copy(gData[0:], "Data")2533 gData[len(gData)-1] = 'X'2534 fmt.Printf("gData: %d %q\n", len(gData), gData)2535 C.printData(cData)2536}2537`}, 0, gosec.NewConfig()}}2538)...

Full Screen

Full Screen

config_storage.go

Source:config_storage.go Github

copy

Full Screen

...298 return299 }300 var currentConfig *ConfigStorage301 if exists {302 currentConfig, err = NewConfigStorageFromApi(id, client)303 if err != nil{304 return305 }306 err = ValidateStringsEqual(newConfig.Type, currentConfig.Type, "type")307 if err != nil{308 return309 }310 }311 switch newConfig.Type {312 case "directory":313 if exists && newConfig.Directory != nil{314 err = ValidateStringsEqual(newConfig.Directory.Path, currentConfig.Directory.Path, "path")315 if err != nil{316 return317 }318 } else if !exists {319 if newConfig.Directory == nil {320 return ErrorKeyEmpty("directory")321 } else {322 err = ValidateFilePath(newConfig.Directory.Path, "path")323 if err != nil{324 return325 }326 }327 }328 case "lvm":329 if exists && newConfig.LVM != nil{330 err = ValidateStringsEqual(newConfig.LVM.VGname, currentConfig.LVM.VGname, "lvm:{ vgname }")331 if err != nil{332 return333 }334 } else if !exists {335 if newConfig.LVM == nil {336 return ErrorKeyEmpty("lvm")337 } else {338 if newConfig.LVM.VGname == "" {339 return ErrorKeyEmpty("lvm:{ vgname }")340 }341 }342 }343 case "lvm-thin":344 if exists && newConfig.LVMThin != nil{345 err = ValidateStringsEqual(newConfig.LVMThin.VGname, currentConfig.LVMThin.VGname, "lvm-thin:{ vgname }")346 if err != nil{347 return348 }349 err = ValidateStringsEqual(newConfig.LVMThin.Thinpool, currentConfig.LVMThin.Thinpool, "lvm-thin:{ thinpool }")350 if err != nil{351 return352 }353 } else if !exists {354 if newConfig.LVMThin == nil {355 return ErrorKeyEmpty("lvm-thin")356 } else {357 if newConfig.LVMThin.VGname == "" {358 return ErrorKeyEmpty("lvm-thin:{ vgname }")359 }360 if newConfig.LVMThin.Thinpool == "" {361 return ErrorKeyEmpty("lvm-thin:{ thinpool }")362 }363 }364 }365 case "nfs":366 if exists && newConfig.NFS != nil{367 err = ValidateStringsEqual(newConfig.NFS.Export, currentConfig.NFS.Export, "nfs:{ export }")368 if err != nil{369 return370 }371 err = ValidateStringsEqual(newConfig.NFS.Server, currentConfig.NFS.Server, "nfs:{ server }")372 if err != nil{373 return374 }375 } else if !exists {376 if newConfig.NFS == nil{377 return ErrorKeyEmpty("nfs")378 } else {379 err = ValidateStringNotEmpty(newConfig.NFS.Server, "nfs:{ server }")380 if err != nil{381 return382 }383 err = ValidateFilePath(newConfig.NFS.Export, "nfs:{ export }")384 if err != nil{385 return386 } 387 }388 }389 if newConfig.NFS != nil {390 if newConfig.NFS.Version != nil {391 err = ValidateStringInArray([]string{"3", "4","4.1","4.2"}, *newConfig.NFS.Version, "nfs:{ version }")392 if err != nil{393 return394 }395 }396 if newConfig.NFS.Preallocation != nil {397 err = ValidateStringNotEmpty(*newConfig.NFS.Preallocation, "nfs:{ preallocation }")398 if err != nil{399 return400 }401 }402 }403 case "smb":404 if exists && newConfig.SMB != nil{405 err = ValidateStringsEqual(newConfig.SMB.Server, currentConfig.SMB.Server, "smb:{ server }")406 if err != nil{407 return408 }409 err = ValidateStringsEqual(newConfig.SMB.Share, currentConfig.SMB.Share, "smb:{ share }")410 if err != nil{411 return412 }413 } else if !exists {414 if newConfig.SMB == nil{415 return ErrorKeyEmpty("smb")416 } else {417 err = ValidateStringNotEmpty(newConfig.SMB.Server, "smb:{ server }")418 if err != nil{419 return420 }421 err = ValidateStringNotEmpty(newConfig.SMB.Share, "smb:{ share }")422 if err != nil{423 return424 }425 }426 }427 if newConfig.SMB != nil {428 if newConfig.SMB.Version != nil {429 err = ValidateStringInArray([]string{"2.0","2.1","3","3.0","3.11"}, *newConfig.SMB.Version, "smb:{ version }")430 if err != nil{431 return432 }433 }434 if newConfig.SMB.Preallocation != nil {435 err = ValidateStringNotEmpty(*newConfig.SMB.Preallocation, "smb:{ preallocation }")436 if err != nil{437 return438 }439 }440 }441 case "glusterfs":442 if exists && newConfig.GlusterFS != nil{443 err = ValidateStringsEqual(newConfig.GlusterFS.Volume, currentConfig.GlusterFS.Volume, "glusterfs:{ volume }")444 if err != nil{445 return446 }447 } else if !exists {448 if newConfig.GlusterFS == nil{449 return ErrorKeyEmpty("glusterfs")450 } else {451 err = ValidateStringNotEmpty(newConfig.GlusterFS.Server1, "glusterfs:{ server1 }")452 if err != nil{453 return454 }455 err = ValidateStringNotEmpty(newConfig.GlusterFS.Volume, "glusterfs:{ volume }")456 if err != nil{457 return458 }459 }460 }461 if newConfig.GlusterFS != nil {462 err = ValidateStringNotEmpty(newConfig.GlusterFS.Server1, "glusterfs:{ server1 }")463 if err != nil{464 return465 }466 if newConfig.GlusterFS.Preallocation != nil {467 err = ValidateStringNotEmpty(*newConfig.GlusterFS.Preallocation, "glusterfs:{ preallocation }")468 if err != nil{469 return470 }471 }472 }473 case "iscsi":474 if exists && newConfig.ISCSI != nil{475 err = ValidateStringsEqual(newConfig.ISCSI.Portal, currentConfig.ISCSI.Portal, "iscsi:{ portal }")476 if err != nil{477 return478 }479 err = ValidateStringsEqual(newConfig.ISCSI.Target, currentConfig.ISCSI.Target, "iscsi:{ target }")480 if err != nil{481 return482 }483 } else if !exists {484 if newConfig.ISCSI == nil{485 return ErrorKeyEmpty("iscsi")486 } else {487 err = ValidateStringNotEmpty(newConfig.ISCSI.Portal, "iscsi:{ portal }")488 if err != nil{489 return490 }491 err = ValidateStringNotEmpty(newConfig.ISCSI.Target, "iscsi:{ target }")492 if err != nil{493 return494 }495 }496 }497 case "cephfs":498 if !exists && newConfig.CephFS == nil{499 return ErrorKeyEmpty("cephfs")500 }501 if newConfig.CephFS != nil {502 err = ValidateArrayNotEmpty(newConfig.CephFS.Monitors, "cephfs:{ monitors }")503 if err != nil{504 return505 }506 }507 case "rbd":508 if !exists && newConfig.RBD == nil{509 return ErrorKeyEmpty("rbd")510 }511 if newConfig.RBD != nil {512 err = ValidateArrayNotEmpty(newConfig.RBD.Monitors, "rbd:{ monitors }")513 if err != nil{514 return515 }516 }517 case "zfs-over-iscsi":518 if exists && newConfig.ZFSoverISCSI != nil{519 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.ISCSIprovider, currentConfig.ZFSoverISCSI.ISCSIprovider, "zfs-over-iscsi:{ iscsiprovider }")520 if err != nil{521 return522 }523 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.Portal, currentConfig.ZFSoverISCSI.Portal, "zfs-over-iscsi:{ portal }")524 if err != nil{525 return526 }527 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.Target, currentConfig.ZFSoverISCSI.Target, "zfs-over-iscsi:{ target }")528 if err != nil{529 return530 }531 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.Pool, currentConfig.ZFSoverISCSI.Pool, "zfs-over-iscsi:{ pool }")532 if err != nil{533 return534 }535 err = ValidateStringsEqual(*newConfig.ZFSoverISCSI.Blocksize, *currentConfig.ZFSoverISCSI.Blocksize, "zfs-over-iscsi:{ blocksize }")536 if err != nil{537 return538 }539 } else if !exists {540 if newConfig.ZFSoverISCSI == nil{541 return ErrorKeyEmpty("zfs-over-iscsi")542 } else {543 err = ValidateStringInArray([]string{"comstar","istgt","lio","iet"}, newConfig.ZFSoverISCSI.ISCSIprovider, "zfs-over-iscsi:{ iscsiprovider }")544 if err != nil{545 return546 }547 err = ValidateStringNotEmpty(newConfig.ZFSoverISCSI.Portal, "zfs-over-iscsi:{ portal }")548 if err != nil{549 return550 }551 err = ValidateStringNotEmpty(newConfig.ZFSoverISCSI.Pool, "zfs-over-iscsi:{ pool }")552 if err != nil{553 return554 }555 err = ValidateStringNotEmpty(newConfig.ZFSoverISCSI.Target, "zfs-over-iscsi:{ target }")556 if err != nil{557 return558 }559 }560 }561 switch newConfig.ZFSoverISCSI.ISCSIprovider{562 case "comstar":563 if exists && newConfig.ZFSoverISCSI.Comstar != nil{564 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.Comstar.HostGroup, currentConfig.ZFSoverISCSI.Comstar.HostGroup, "zfs-over-iscsi:{ comstar:{ host-group } }")565 if err != nil{566 return567 }568 err = ValidateStringsEqual(newConfig.ZFSoverISCSI.Comstar.TargetGroup, currentConfig.ZFSoverISCSI.Comstar.TargetGroup, "zfs-over-iscsi:{ comstar:{ target-group } }")569 if err != nil{570 return571 }572 } else if !exists && newConfig.ZFSoverISCSI.Comstar == nil{573 return ErrorKeyEmpty("zfs-over-iscsi:{ comstar }")574 }575 case "istgt":576 if !exists && newConfig.ZFSoverISCSI.Istgt == nil {577 return ErrorKeyEmpty("zfs-over-iscsi:{ istgt }")578 }579 case "lio":580 if !exists && newConfig.ZFSoverISCSI.LIO == nil {581 return ErrorKeyEmpty("zfs-over-iscsi:{ lio }")582 } else {583 err = ValidateStringNotEmpty(newConfig.ZFSoverISCSI.LIO.TargetPortalGroup, "zfs-over-iscsi:{ lio:{ targetportal-group } }")584 if err != nil{585 return586 }587 }588 }589 case "zfs":590 if exists && newConfig.ZFS != nil{591 err = ValidateStringsEqual(newConfig.ZFS.Pool, currentConfig.ZFS.Pool, "zfs:{ pool }")592 if err != nil{593 return594 }595 } else if !exists {596 if newConfig.ZFS == nil{597 return ErrorKeyEmpty("zfs")598 } else {599 err = ValidateStringNotEmpty(newConfig.ZFS.Pool, "zfs:{ pool }")600 if err != nil{601 return602 }603 }604 }605 if newConfig.ZFS != nil {606 if newConfig.ZFS.Blocksize != nil{607 err = ValidateStringNotEmpty(*newConfig.ZFS.Blocksize, "zfs:{ blocksize }")608 if err != nil{609 return610 }611 }612 }613 case "pbs":614 if exists && newConfig.PBS != nil{615 err = ValidateStringsEqual(newConfig.PBS.Server, currentConfig.PBS.Server, "pbs:{ server }")616 if err != nil{617 return618 }619 err = ValidateStringsEqual(newConfig.PBS.Datastore, currentConfig.PBS.Datastore, "pbs:{ datastore }")620 if err != nil{621 return622 }623 } else if !exists {624 if newConfig.PBS == nil{625 return ErrorKeyEmpty("pbs")626 } else {627 err = ValidateStringNotEmpty(newConfig.PBS.Server, "pbs:{ server }")628 if err != nil{629 return630 }631 err = ValidateStringNotEmpty(newConfig.PBS.Datastore, "pbs:{ datastore }")632 if err != nil{633 return634 }635 if newConfig.PBS.Password == nil {636 return ErrorKeyNotSet("pbs:{ password }")637 }638 }639 }640 if newConfig.PBS != nil {641 if newConfig.PBS.Port != nil {642 err = ValidateIntInRange(1, 65536, *newConfig.PBS.Port, "pbs:{ port }")643 if err != nil{644 return645 }646 }647 err = ValidateStringNotEmpty(newConfig.PBS.Username, "pbs:{ username }")648 if err != nil{649 return650 }651 }652 }653 654 if exists && newConfig.Content != nil{655 err = newConfig.Content.Validate(storageContentTypes[newConfig.Type].([]bool))656 if err != nil {657 return658 }659 } else if !exists {660 if newConfig.Content == nil {661 return ErrorKeyEmpty("content")662 } else {663 err = newConfig.Content.Validate(storageContentTypes[newConfig.Type].([]bool))664 if err != nil {665 return666 }667 }668 }669 err = newConfig.BackupRetention.Validate()670 return671}672func (config *ConfigStorage) MapToApiValues(create bool) (params map[string]interface{}) {673 var deletions string674 params = map[string]interface{}{675 "storage": config.ID,676 "disable": BoolInvert(config.Enable),677 }678 params["content"] = config.Content.MapStorageContent(storageContentTypes[config.Type].([]bool))679 switch config.Type {680 case "directory":681 if config.Directory != nil {682 config.Directory.SetDefaults()683 params["shared"] = config.Directory.Shared684 params["preallocation"] = *config.Directory.Preallocation685 if create {686 params["path"] = config.Directory.Path687 }688 }689 case "lvm":690 if config.LVM != nil {691 params["shared"] = config.LVM.Shared692 if create {693 params["vgname"] = config.LVM.VGname694 }695 }696 case "lvm-thin":697 if config.LVMThin != nil{698 if create {699 params["thinpool"] = config.LVMThin.Thinpool700 params["vgname"] = config.LVMThin.VGname701 }702 }703 case "nfs":704 if config.NFS != nil {705 config.NFS.SetDefaults()706 if config.NFS.Version != nil {707 params["options"] = "vers=" + *config.NFS.Version708 } else {709 deletions = AddToList(deletions, "options")710 }711 if create {712 params["server"] = config.NFS.Server713 params["export"] = config.NFS.Export714 }715 params["preallocation"] = *config.NFS.Preallocation716 }717 case "smb":718 if config.SMB != nil {719 config.SMB.SetDefaults()720 params["domain"] = config.SMB.Domain721 params["username"] = config.SMB.Username722 if create {723 params["share"] = config.SMB.Share724 params["server"] = config.SMB.Server725 }726 if config.SMB.Password != nil{727 params["password"] = *config.SMB.Password728 }729 if config.SMB.Version != nil {730 params["smbversion"] = *config.SMB.Version731 } else {732 deletions = AddToList(deletions, "smbversion")733 }734 params["preallocation"] = *config.SMB.Preallocation735 }736 case "glusterfs":737 if config.GlusterFS != nil{738 config.GlusterFS.SetDefaults()739 params["server"] = config.GlusterFS.Server1 740 if config.GlusterFS.Server2 != "" {741 params["server2"] = config.GlusterFS.Server2742 } else if !create {743 deletions = AddToList(deletions, "server2")744 }745 if create {746 params["volume"] = config.GlusterFS.Volume747 }748 params["preallocation"] = *config.GlusterFS.Preallocation749 }750 case "iscsi":751 if create {752 params["portal"] = config.ISCSI.Portal753 params["target"] = config.ISCSI.Target754 }755 content := config.Content.MapStorageContent(storageContentTypes[config.Type].([]bool))756 if content == "" {757 content = "none"758 }759 params["content"] = content760 case "cephfs":761 if config.CephFS != nil {762 params["monhost"] = ArrayToCSV(config.CephFS.Monitors)763 params["fs-name"] = config.CephFS.FSname764 params["username"] = config.CephFS.Username765 if config.CephFS.SecretKey != nil{766 // not sure if this is the right api parameter767 params["keyring"] = *config.CephFS.SecretKey768 }769 }770 case "rbd":771 if config.RBD != nil {772 params["krbd"] = config.RBD.KRBD773 params["monhost"] = ArrayToCSV(config.RBD.Monitors)774 params["pool"] = config.RBD.Pool775 params["namespace"] = config.RBD.Namespace776 params["username"] = config.RBD.Username777 if config.RBD.Keyring != nil {778 params["keyring"] = *config.RBD.Keyring779 }780 }781 case "zfs-over-iscsi":782 if config.ZFSoverISCSI != nil {783 config.ZFSoverISCSI.SetDefaults()784 params["sparse"] = config.ZFSoverISCSI.Thinprovision785 switch config.ZFSoverISCSI.ISCSIprovider {786 case "comstar":787 if config.ZFSoverISCSI.Comstar != nil {788 params["nowritecache"] = BoolInvert(config.ZFSoverISCSI.Comstar.Writecache)789 if create {790 params["comstar_hg"] = config.ZFSoverISCSI.Comstar.HostGroup791 params["comstar_tg"] = config.ZFSoverISCSI.Comstar.TargetGroup792 }793 }794 case "istgt":795 if config.ZFSoverISCSI.Istgt != nil {796 params["nowritecache"] = BoolInvert(config.ZFSoverISCSI.Istgt.Writecache)797 }798 case "lio":799 if config.ZFSoverISCSI.LIO != nil {800 params["lio_tpg"] = config.ZFSoverISCSI.LIO.TargetPortalGroup801 }802 }803 config.ZFSoverISCSI.RemapToAPI()804 if create {805 params["iscsiprovider"] = config.ZFSoverISCSI.ISCSIprovider806 params["portal"] = config.ZFSoverISCSI.Portal807 params["target"] = config.ZFSoverISCSI.Target808 params["pool"] = config.ZFSoverISCSI.Pool809 params["blocksize"] = *config.ZFSoverISCSI.Blocksize810 }811 }812 params["content"] = "images"813 case "zfs":814 if config.ZFS != nil {815 config.ZFS.SetDefaults()816 params["sparse"] = config.ZFS.Thinprovision817 params["blocksize"] = *config.ZFS.Blocksize818 if create {819 params["pool"] = config.ZFS.Pool820 }821 }822 case "pbs":823 if config.PBS != nil {824 config.PBS.SetDefaults()825 params["username"] = config.PBS.Username826 params["fingerprint"] = config.PBS.Fingerprint827 params["port"] = *config.PBS.Port828 if create {829 params["server"] = config.PBS.Server830 params["datastore"] = config.PBS.Datastore831 }832 if config.PBS.Password != nil {833 params["password"] = *config.PBS.Password834 }835 }836 params["content"] = "backup"837 }838 if config.BackupRetention != nil {839 if storageContentTypes[config.Type].([]bool)[0] {840 params["prune-backups"] = config.BackupRetention.MapStorageBackupRetention()841 }842 }843 if create {844 config.RemapToAPI()845 params["type"] = config.Type846 } else if deletions != "" {847 params["delete"] = deletions848 }849 return850}851func (config *ConfigStorage) CreateWithValidate(id string, client *Client) (err error) {852 err = config.Validate(id, true, client)853 if err != nil{854 return855 }856 return config.Create(id, true, client)857}858func (config *ConfigStorage) Create(id string, errorSupression bool, client *Client) (err error) {859 var enableStorage bool860 if errorSupression && config.Enable{861 config.Enable = false862 enableStorage = true863 }864 config.ID = id865 params := config.MapToApiValues(true)866 err = client.CreateStorage(id, params)867 if err != nil {868 params, _ := json.Marshal(&params)869 return fmt.Errorf("error creating Metrics Server: %v, (params: %v)", err, string(params))870 }871 // if it gets enabled after it has been configured proxmox wont give the error that it can't connect to the storage backend872 if enableStorage {873 err = client.EnableStorage(id)874 } 875 return876}877func (config *ConfigStorage) UpdateWithValidate(id string, client *Client) (err error) {878 err = config.Validate(id, false, client)879 if err != nil{880 return881 }882 return config.Update(id, client)883}884func (config *ConfigStorage) Update(id string, client *Client) (err error) {885 config.ID = id886 params := config.MapToApiValues(false)887 err = client.UpdateStorage(id, params)888 if err != nil {889 params, _ := json.Marshal(&params)890 return fmt.Errorf("error creating Metrics Server: %v, (params: %v)", err, string(params))891 }892 return893}894func NewConfigStorageFromApi(storageid string, client *Client) (config *ConfigStorage, err error) {895 // prepare json map to receive the information from the api896 var rawConfig map[string]interface{}897 rawConfig, err = client.GetStorageConfig(storageid)898 if err != nil {899 return nil, err900 }901 config = new(ConfigStorage)902 config.ID = storageid903 config.Type = rawConfig["type"].(string)904 config.RemapFromAPI()905 if _, isSet := rawConfig["disable"]; isSet {906 config.Enable = BoolInvert(Itob(int(rawConfig["disable"].(float64))))907 } else {908 config.Enable = true909 }910 switch config.Type {911 case "directory":912 config.Directory = new(ConfigStorageDirectory)913 config.Directory.Path = rawConfig["path"].(string)914 config.Directory.Shared = Itob(int(rawConfig["shared"].(float64)))915 if _, isSet := rawConfig["preallocation"]; isSet {config.Directory.Preallocation = PointerString(rawConfig["preallocation"].(string))}916 config.Directory.SetDefaults()917 case "lvm":918 config.LVM = new(ConfigStorageLVM)919 config.LVM.VGname = rawConfig["vgname"].(string)920 config.LVM.Shared = Itob(int(rawConfig["shared"].(float64)))921 case "lvmt-hin":922 config.LVMThin = new(ConfigStorageLVMThin)923 config.LVMThin.Thinpool = rawConfig["thinpool"].(string)924 config.LVMThin.VGname = rawConfig["vgname"].(string)925 case "nfs":926 config.NFS = new(ConfigStorageNFS)927 config.NFS.Server = rawConfig["server"].(string)928 config.NFS.Export = rawConfig["export"].(string)929 if _, isSet := rawConfig["options"]; isSet {930 version := strings.Split(rawConfig["options"].(string), "=")931 config.NFS.Version = PointerString(version[1])932 }933 if _, isSet := rawConfig["preallocation"]; isSet {config.NFS.Preallocation = PointerString(rawConfig["preallocation"].(string))}934 config.NFS.SetDefaults()935 case "smb":936 config.SMB = new(ConfigStorageSMB)937 config.SMB.Server = rawConfig["server"].(string)938 config.SMB.Share = rawConfig["share"].(string)939 if _, isSet := rawConfig["smbversion"]; isSet {940 smbVersion := rawConfig["smbversion"].(string)941 if smbVersion == "default" {942 config.SMB.Version = nil943 } else {944 config.SMB.Version = PointerString(smbVersion)945 }946 }947 if _, isSet := rawConfig["domain"]; isSet {config.SMB.Domain = rawConfig["domain"].(string)}948 if _, isSet := rawConfig["username"]; isSet {config.SMB.Username = rawConfig["username"].(string)}949 if _, isSet := rawConfig["preallocation"]; isSet {config.SMB.Preallocation = PointerString(rawConfig["preallocation"].(string))}950 config.SMB.SetDefaults()951 case "glusterfs":952 config.GlusterFS = new(ConfigStorageGlusterFS)953 config.GlusterFS.Server1 = rawConfig["server"].(string)954 config.GlusterFS.Volume = rawConfig["volume"].(string)955 if _, isSet := rawConfig["server2"]; isSet {config.GlusterFS.Server2 = rawConfig["server2"].(string)}956 if _, isSet := rawConfig["preallocation"]; isSet {config.GlusterFS.Preallocation = PointerString(rawConfig["preallocation"].(string))}957 config.GlusterFS.SetDefaults()958 case "iscsi":959 config.ISCSI = new(ConfigStorageISCSI)960 config.ISCSI.Portal = rawConfig["portal"].(string)961 config.ISCSI.Target = rawConfig["target"].(string)962 case "cephfs":963 config.CephFS = new(ConfigStorageCephFS)964 config.CephFS.Monitors = CSVtoArray(rawConfig["monhost"].(string))965 if _, isSet := rawConfig["fs-name"]; isSet {config.CephFS.FSname = rawConfig["fs-name"].(string)}966 if _, isSet := rawConfig["username"]; isSet {config.CephFS.Username = rawConfig["username"].(string)}967 case "rbd":968 config.RBD = new(ConfigStorageRBD)969 config.RBD.KRBD = Itob(int(rawConfig["krbd"].(float64)))970 config.RBD.Monitors = CSVtoArray(rawConfig["monhost"].(string))971 config.RBD.Pool = rawConfig["pool"].(string)972 if _, isSet := rawConfig["namespace"]; isSet {config.RBD.Namespace = rawConfig["namespace"].(string)}973 if _, isSet := rawConfig["username"]; isSet {config.RBD.Username = rawConfig["username"].(string)}974 case "zfs-over-iscsi":975 config.ZFSoverISCSI = new(ConfigStorageZFSoverISCSI)976 config.ZFSoverISCSI.Blocksize = PointerString(rawConfig["blocksize"].(string))977 config.ZFSoverISCSI.ISCSIprovider = rawConfig["iscsiprovider"].(string)978 config.ZFSoverISCSI.RemapFromAPI()979 switch config.ZFSoverISCSI.ISCSIprovider{980 case "comstar":981 config.ZFSoverISCSI.Comstar = new(ConfigStorageZFSoverISCSI_Comstar)982 if _, isSet := rawConfig["comstar_hg"]; isSet {983 config.ZFSoverISCSI.Comstar.Writecache = BoolInvert(Itob(int(rawConfig["nowritecache"].(float64))))984 } else {985 config.ZFSoverISCSI.Comstar.Writecache = true986 }987 if _, isSet := rawConfig["comstar_hg"]; isSet {config.ZFSoverISCSI.Comstar.HostGroup = rawConfig["comstar_hg"].(string)}988 if _, isSet := rawConfig["comstar_tg"]; isSet {config.ZFSoverISCSI.Comstar.TargetGroup = rawConfig["comstar_tg"].(string)}989 case "istgt":990 config.ZFSoverISCSI.Istgt = new(ConfigStorageZFSoverISCSI_istgt)991 config.ZFSoverISCSI.Istgt.Writecache = BoolInvert(Itob(int(rawConfig["nowritecache"].(float64))))992 case "lio":993 config.ZFSoverISCSI.LIO = new(ConfigStorageZFSoverISCSI_LIO)994 config.ZFSoverISCSI.LIO.TargetPortalGroup = rawConfig["lio_tpg"].(string)995 }996 config.ZFSoverISCSI.Pool = rawConfig["pool"].(string)997 config.ZFSoverISCSI.Portal = rawConfig["portal"].(string)998 config.ZFSoverISCSI.Target = rawConfig["target"].(string)999 config.ZFSoverISCSI.Thinprovision = Itob(int(rawConfig["sparse"].(float64)))1000 config.ZFSoverISCSI.SetDefaults()1001 case "zfs":1002 config.ZFS = new(ConfigStorageZFS)1003 config.ZFS.Pool = rawConfig["pool"].(string)1004 config.ZFS.Thinprovision = Itob(int(rawConfig["sparse"].(float64)))1005 if _, isSet := rawConfig["blocksize"]; isSet {config.ZFS.Blocksize = PointerString(rawConfig["blocksize"].(string))}1006 config.ZFS.SetDefaults()1007 case "pbs":1008 config.PBS = new(ConfigStoragePBS)1009 config.PBS.Datastore = rawConfig["datastore"].(string)1010 config.PBS.Server = rawConfig["server"].(string)1011 config.PBS.Username = rawConfig["username"].(string)1012 if _, isSet := rawConfig["port"]; isSet {config.PBS.Port = PointerInt(int(rawConfig["port"].(float64)))}1013 if _, isSet := rawConfig["fingerprint"]; isSet {config.PBS.Fingerprint = rawConfig["fingerprint"].(string)}1014 config.PBS.SetDefaults()1015 }1016 if _, isSet := rawConfig["content"]; isSet {1017 content := rawConfig["content"].(string)1018 if content != "none"{1019 contentArray := CSVtoArray(content)1020 config.Content = new(ConfigStorageContent)1021 if storageContentTypes[config.Type].([]bool)[0]{1022 config.Content.Backup = PointerBool(inArray(contentArray, strorageContentTypesAPI[0]))1023 }1024 if storageContentTypes[config.Type].([]bool)[1]{1025 config.Content.Container = PointerBool(inArray(contentArray, strorageContentTypesAPI[1]))1026 }1027 if storageContentTypes[config.Type].([]bool)[2]{1028 config.Content.DiskImage = PointerBool(inArray(contentArray, strorageContentTypesAPI[2]))1029 }1030 if storageContentTypes[config.Type].([]bool)[3]{1031 config.Content.Iso = PointerBool(inArray(contentArray, strorageContentTypesAPI[3]))1032 }1033 if storageContentTypes[config.Type].([]bool)[4]{1034 config.Content.Snippets = PointerBool(inArray(contentArray, strorageContentTypesAPI[4]))1035 }1036 if storageContentTypes[config.Type].([]bool)[5]{1037 config.Content.Template = PointerBool(inArray(contentArray, strorageContentTypesAPI[5]))1038 }1039 }1040 }1041 if _, isSet := rawConfig["prune-backups"]; isSet {1042 prune := CSVtoArray(rawConfig["prune-backups"].(string))1043 if !inArray(prune, "keep-all=1"){1044 retentionSettings := make(map[string]int)1045 for _, e := range prune{1046 a := strings.Split(e, "=")1047 retentionSettings[a[0]], _ = strconv.Atoi(a[1])1048 }1049 config.BackupRetention = new(ConfigStorageBackupRetention)1050 config.BackupRetention.Daily = PointerInt(retentionSettings["keep-daily"])1051 config.BackupRetention.Hourly = PointerInt(retentionSettings["keep-hourly"])1052 config.BackupRetention.Last = PointerInt(retentionSettings["keep-last"])1053 config.BackupRetention.Monthly = PointerInt(retentionSettings["keep-monthly"])1054 config.BackupRetention.Weekly = PointerInt(retentionSettings["keep-weekly"])1055 config.BackupRetention.Yearly = PointerInt(retentionSettings["keep-yearly"])1056 }1057 }1058 return1059}1060func NewConfigStorageFromJson(input []byte) (config *ConfigStorage, err error) {1061 config = &ConfigStorage{}1062 err = json.Unmarshal([]byte(input), config)1063 if err != nil {1064 log.Fatal(err)1065 }1066 return1067}...

Full Screen

Full Screen

authorization_test.go

Source:authorization_test.go Github

copy

Full Screen

1// Copyright 2018 Istio Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package model15import (16 "fmt"17 "reflect"18 "testing"19 "github.com/gogo/protobuf/proto"20 "github.com/google/go-cmp/cmp"21 "github.com/google/go-cmp/cmp/cmpopts"22 meshconfig "istio.io/api/mesh/v1alpha1"23 rbacproto "istio.io/api/rbac/v1alpha1"24 authpb "istio.io/api/security/v1beta1"25 selectorpb "istio.io/api/type/v1beta1"26 "istio.io/istio/pkg/config/labels"27 "istio.io/istio/pkg/config/mesh"28 "istio.io/istio/pkg/config/schema"29 "istio.io/istio/pkg/config/schemas"30)31func TestGetAuthorizationPolicies(t *testing.T) {32 testNS := "test-ns"33 roleCfg := Config{34 ConfigMeta: ConfigMeta{35 Type: schemas.ServiceRole.Type, Name: "test-role-1", Namespace: testNS},36 Spec: &rbacproto.ServiceRole{37 Rules: []*rbacproto.AccessRule{{Services: []string{"test-svc-1"}}},38 },39 }40 bindingCfg := Config{41 ConfigMeta: ConfigMeta{42 Type: schemas.ServiceRoleBinding.Type, Name: "test-binding-1", Namespace: testNS},43 Spec: &rbacproto.ServiceRoleBinding{44 Subjects: []*rbacproto.Subject{{User: "test-user-1"}},45 RoleRef: &rbacproto.RoleRef{Kind: "ServiceRole", Name: "test-role-1"},46 },47 }48 invalidateBindingCfg := Config{49 ConfigMeta: ConfigMeta{50 Type: schemas.ServiceRoleBinding.Type, Name: "test-binding-1", Namespace: testNS},51 Spec: &rbacproto.ServiceRoleBinding{52 Subjects: []*rbacproto.Subject{{User: "test-user-1"}},53 RoleRef: &rbacproto.RoleRef{Kind: "ServiceRole", Name: ""},54 },55 }56 cases := []struct {57 name string58 config []Config59 want *RolesAndBindings60 }{61 {62 name: "add ServiceRole",63 config: []Config{roleCfg},64 want: &RolesAndBindings{65 Roles: []ServiceRoleConfig{66 {67 Name: roleCfg.Name,68 ServiceRole: roleCfg.Spec.(*rbacproto.ServiceRole),69 },70 },71 Bindings: map[string][]*rbacproto.ServiceRoleBinding{}},72 },73 {74 name: "add invalidate ServiceRoleBinding",75 config: []Config{invalidateBindingCfg},76 want: nil,77 },78 {79 name: "add ServiceRoleBinding",80 config: []Config{bindingCfg},81 want: &RolesAndBindings{82 Bindings: map[string][]*rbacproto.ServiceRoleBinding{83 "test-role-1": {&rbacproto.ServiceRoleBinding{84 Subjects: []*rbacproto.Subject{{User: "test-user-1"}},85 RoleRef: &rbacproto.RoleRef{Kind: "ServiceRole", Name: "test-role-1"},86 }},87 },88 },89 },90 {91 name: "add ServiceRoleBinding and ServiceRole",92 config: []Config{roleCfg, bindingCfg},93 want: &RolesAndBindings{94 Roles: []ServiceRoleConfig{95 {96 Name: roleCfg.Name,97 ServiceRole: roleCfg.Spec.(*rbacproto.ServiceRole),98 },99 },100 Bindings: map[string][]*rbacproto.ServiceRoleBinding{101 "test-role-1": {bindingCfg.Spec.(*rbacproto.ServiceRoleBinding)},102 },103 },104 },105 }106 for _, c := range cases {107 t.Run(c.name, func(t *testing.T) {108 authzPolicies := createFakeAuthorizationPolicies(c.config, t)109 got := authzPolicies.NamespaceToV1alpha1Policies[testNS]110 if !reflect.DeepEqual(c.want, got) {111 t.Errorf("want:\n%s\n, got:\n%s\n", c.want, got)112 }113 })114 }115}116func TestAuthorizationPolicies_ListNamespacesOfServiceRoles(t *testing.T) {117 role := &rbacproto.ServiceRole{}118 binding := &rbacproto.ServiceRoleBinding{119 Subjects: []*rbacproto.Subject{120 {121 User: "user-1",122 },123 },124 RoleRef: &rbacproto.RoleRef{125 Kind: "ServiceRole",126 Name: "role-1",127 },128 }129 cases := []struct {130 name string131 ns string132 configs []Config133 want []string134 }{135 {136 name: "no roles",137 ns: "foo",138 want: []string{},139 },140 {141 name: "role and binding same namespace",142 ns: "bar",143 configs: []Config{144 newConfig("role", "bar", role),145 newConfig("binding", "bar", binding),146 },147 want: []string{"bar"},148 },149 {150 name: "two roles different namespaces",151 ns: "bar",152 configs: []Config{153 newConfig("role-1", "foo", role),154 newConfig("role-2", "bar", role),155 },156 want: []string{"foo", "bar"},157 },158 }159 for _, tc := range cases {160 t.Run(tc.name, func(t *testing.T) {161 authzPolicies := createFakeAuthorizationPolicies(tc.configs, t)162 got := authzPolicies.ListV1alpha1Namespaces()163 if diff := cmp.Diff(tc.want, got, cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" {164 t.Errorf("want:%v\n got: %v diff %v\n", tc.want, got, diff)165 }166 })167 }168}169func TestAuthorizationPolicies_ListServiceRolesRoles(t *testing.T) {170 role := &rbacproto.ServiceRole{}171 binding := &rbacproto.ServiceRoleBinding{172 Subjects: []*rbacproto.Subject{173 {174 User: "user-1",175 },176 },177 RoleRef: &rbacproto.RoleRef{178 Kind: "ServiceRole",179 Name: "role-1",180 },181 }182 cases := []struct {183 name string184 ns string185 configs []Config186 want []ServiceRoleConfig187 }{188 {189 name: "no roles",190 ns: "foo",191 want: nil,192 },193 {194 name: "only binding",195 ns: "foo",196 configs: []Config{197 newConfig("binding", "foo", binding),198 },199 want: nil,200 },201 {202 name: "no roles in namespace foo",203 ns: "foo",204 configs: []Config{205 newConfig("role", "bar", role),206 newConfig("binding", "bar", binding),207 },208 want: nil,209 },210 {211 name: "one role",212 ns: "bar",213 configs: []Config{214 newConfig("role", "bar", role),215 newConfig("binding", "bar", binding),216 },217 want: []ServiceRoleConfig{218 {219 Name: "role",220 ServiceRole: role,221 },222 },223 },224 {225 name: "two roles",226 ns: "bar",227 configs: []Config{228 newConfig("role-1", "foo", role),229 newConfig("role-1", "bar", role),230 newConfig("role-2", "bar", role),231 },232 want: []ServiceRoleConfig{233 {234 Name: "role-1",235 ServiceRole: role,236 },237 {238 Name: "role-2",239 ServiceRole: role,240 },241 },242 },243 }244 for _, tc := range cases {245 t.Run(tc.name, func(t *testing.T) {246 authzPolicies := createFakeAuthorizationPolicies(tc.configs, t)247 got := authzPolicies.ListServiceRoles(tc.ns)248 if !reflect.DeepEqual(tc.want, got) {249 t.Errorf("want:%v\n but got: %v\n", tc.want, got)250 }251 })252 }253}254func TestAuthorizationPolicies_ListServiceRoleBindings(t *testing.T) {255 role := &rbacproto.ServiceRole{}256 binding := &rbacproto.ServiceRoleBinding{257 Subjects: []*rbacproto.Subject{258 {259 User: "user-1",260 },261 },262 RoleRef: &rbacproto.RoleRef{263 Kind: "ServiceRole",264 Name: "role-1",265 },266 }267 binding2 := &rbacproto.ServiceRoleBinding{268 Subjects: []*rbacproto.Subject{269 {270 User: "user-2",271 },272 },273 RoleRef: &rbacproto.RoleRef{274 Kind: "ServiceRole",275 Name: "role-2",276 },277 }278 cases := []struct {279 name string280 ns string281 configs []Config282 want map[string][]*rbacproto.ServiceRoleBinding283 }{284 {285 name: "no configs",286 ns: "foo",287 want: map[string][]*rbacproto.ServiceRoleBinding{},288 },289 {290 name: "no configs in namespace foo",291 ns: "foo",292 configs: []Config{293 newConfig("role-1", "bar", role),294 newConfig("binding-1", "bar", binding),295 },296 want: map[string][]*rbacproto.ServiceRoleBinding{},297 },298 {299 name: "no bindings in namespace foo",300 ns: "foo",301 configs: []Config{302 newConfig("role-1", "foo", role),303 newConfig("role-1", "bar", role),304 newConfig("binding-1", "bar", binding),305 },306 want: map[string][]*rbacproto.ServiceRoleBinding{},307 },308 {309 name: "one binding",310 ns: "bar",311 configs: []Config{312 newConfig("role-1", "bar", role),313 newConfig("binding-1", "bar", binding),314 newConfig("role-2", "foo", role),315 newConfig("binding-2", "foo", binding2),316 },317 want: map[string][]*rbacproto.ServiceRoleBinding{318 "role-1": {319 binding,320 },321 },322 },323 {324 name: "two bindings",325 ns: "foo",326 configs: []Config{327 newConfig("role-1", "foo", role),328 newConfig("binding-1", "foo", binding),329 newConfig("role-2", "foo", role),330 newConfig("binding-2", "foo", binding2),331 },332 want: map[string][]*rbacproto.ServiceRoleBinding{333 "role-1": {334 binding,335 },336 "role-2": {337 binding2,338 },339 },340 },341 {342 name: "multiple bindings for same role",343 ns: "foo",344 configs: []Config{345 newConfig("role-1", "foo", role),346 newConfig("binding-1", "foo", binding),347 newConfig("binding-2", "foo", binding),348 newConfig("binding-3", "foo", binding),349 },350 want: map[string][]*rbacproto.ServiceRoleBinding{351 "role-1": {352 binding,353 binding,354 binding,355 },356 },357 },358 }359 for _, tc := range cases {360 t.Run(tc.name, func(t *testing.T) {361 authzPolicies := createFakeAuthorizationPolicies(tc.configs, t)362 got := authzPolicies.ListServiceRoleBindings(tc.ns)363 if !reflect.DeepEqual(tc.want, got) {364 t.Errorf("want: %v\n but got: %v", tc.want, got)365 }366 })367 }368}369func TestAuthorizationPolicies_ListAuthorizationPolicies(t *testing.T) {370 policy := &authpb.AuthorizationPolicy{371 Rules: []*authpb.Rule{372 {373 From: []*authpb.Rule_From{374 {375 Source: &authpb.Source{376 Principals: []string{"sleep"},377 },378 },379 },380 To: []*authpb.Rule_To{381 {382 Operation: &authpb.Operation{383 Methods: []string{"GET"},384 },385 },386 },387 },388 },389 }390 policyWithSelector := proto.Clone(policy).(*authpb.AuthorizationPolicy)391 policyWithSelector.Selector = &selectorpb.WorkloadSelector{392 MatchLabels: map[string]string{393 "app": "httpbin",394 "version": "v1",395 },396 }397 cases := []struct {398 name string399 ns string400 workloadLabels map[string]string401 configs []Config402 want []AuthorizationPolicyConfig403 }{404 {405 name: "no policies",406 ns: "foo",407 want: nil,408 },409 {410 name: "no policies in namespace foo",411 ns: "foo",412 configs: []Config{413 newConfig("authz-1", "bar", policy),414 newConfig("authz-2", "bar", policy),415 },416 want: nil,417 },418 {419 name: "one policy",420 ns: "bar",421 configs: []Config{422 newConfig("authz-1", "bar", policy),423 },424 want: []AuthorizationPolicyConfig{425 {426 Name: "authz-1",427 Namespace: "bar",428 AuthorizationPolicy: policy,429 },430 },431 },432 {433 name: "two policies",434 ns: "bar",435 configs: []Config{436 newConfig("authz-1", "foo", policy),437 newConfig("authz-1", "bar", policy),438 newConfig("authz-2", "bar", policy),439 },440 want: []AuthorizationPolicyConfig{441 {442 Name: "authz-1",443 Namespace: "bar",444 AuthorizationPolicy: policy,445 },446 {447 Name: "authz-2",448 Namespace: "bar",449 AuthorizationPolicy: policy,450 },451 },452 },453 {454 name: "selector exact match",455 ns: "bar",456 workloadLabels: map[string]string{457 "app": "httpbin",458 "version": "v1",459 },460 configs: []Config{461 newConfig("authz-1", "bar", policyWithSelector),462 },463 want: []AuthorizationPolicyConfig{464 {465 Name: "authz-1",466 Namespace: "bar",467 AuthorizationPolicy: policyWithSelector,468 },469 },470 },471 {472 name: "selector subset match",473 ns: "bar",474 workloadLabels: map[string]string{475 "app": "httpbin",476 "version": "v1",477 "env": "dev",478 },479 configs: []Config{480 newConfig("authz-1", "bar", policyWithSelector),481 },482 want: []AuthorizationPolicyConfig{483 {484 Name: "authz-1",485 Namespace: "bar",486 AuthorizationPolicy: policyWithSelector,487 },488 },489 },490 {491 name: "selector not match",492 ns: "bar",493 workloadLabels: map[string]string{494 "app": "httpbin",495 "version": "v2",496 },497 configs: []Config{498 newConfig("authz-1", "bar", policyWithSelector),499 },500 want: nil,501 },502 {503 name: "namespace not match",504 ns: "foo",505 workloadLabels: map[string]string{506 "app": "httpbin",507 "version": "v1",508 },509 configs: []Config{510 newConfig("authz-1", "bar", policyWithSelector),511 },512 want: nil,513 },514 {515 name: "root namespace",516 ns: "bar",517 configs: []Config{518 newConfig("authz-1", "istio-config", policy),519 },520 want: []AuthorizationPolicyConfig{521 {522 Name: "authz-1",523 Namespace: "istio-config",524 AuthorizationPolicy: policy,525 },526 },527 },528 {529 name: "root namespace equals config namespace",530 ns: "istio-config",531 configs: []Config{532 newConfig("authz-1", "istio-config", policy),533 },534 want: []AuthorizationPolicyConfig{535 {536 Name: "authz-1",537 Namespace: "istio-config",538 AuthorizationPolicy: policy,539 },540 },541 },542 {543 name: "root namespace and config namespace",544 ns: "bar",545 configs: []Config{546 newConfig("authz-1", "istio-config", policy),547 newConfig("authz-2", "bar", policy),548 },549 want: []AuthorizationPolicyConfig{550 {551 Name: "authz-1",552 Namespace: "istio-config",553 AuthorizationPolicy: policy,554 },555 {556 Name: "authz-2",557 Namespace: "bar",558 AuthorizationPolicy: policy,559 },560 },561 },562 }563 for _, tc := range cases {564 t.Run(tc.name, func(t *testing.T) {565 authzPolicies := createFakeAuthorizationPolicies(tc.configs, t)566 got := authzPolicies.ListAuthorizationPolicies(567 tc.ns, []labels.Instance{labels.Instance(tc.workloadLabels)})568 if !reflect.DeepEqual(tc.want, got) {569 t.Errorf("want:%v\n but got: %v\n", tc.want, got)570 }571 })572 }573}574func TestAuthorizationPolicies_IsRBACEnabled(t *testing.T) {575 target := &rbacproto.RbacConfig_Target{576 Services: []string{"review.default.svc", "product.default.svc"},577 Namespaces: []string{"special"},578 }579 testCases := []struct {580 name string581 config []Config582 service string583 namespace string584 want bool585 }{586 {587 name: "enabled",588 config: []Config{589 newConfig("default", "",590 &rbacproto.RbacConfig{591 Mode: rbacproto.RbacConfig_ON,592 }),593 },594 service: "product.default.svc",595 namespace: "default",596 want: true,597 },598 {599 name: "enabled with permissive",600 config: []Config{601 newConfig("default", "",602 &rbacproto.RbacConfig{603 Mode: rbacproto.RbacConfig_ON,604 EnforcementMode: rbacproto.EnforcementMode_PERMISSIVE,605 }),606 },607 service: "product.default.svc",608 namespace: "default",609 want: true,610 },611 {612 name: "enabled by inclusion.service",613 config: []Config{614 newConfig("default", "",615 &rbacproto.RbacConfig{616 Mode: rbacproto.RbacConfig_ON_WITH_INCLUSION,617 Inclusion: target,618 }),619 },620 service: "product.default.svc",621 namespace: "default",622 want: true,623 },624 {625 name: "enabled by inclusion.namespace",626 config: []Config{627 newConfig("default", "",628 &rbacproto.RbacConfig{629 Mode: rbacproto.RbacConfig_ON,630 Inclusion: target,631 }),632 },633 service: "other.special.svc",634 namespace: "special",635 want: true,636 },637 {638 name: "enabled by ClusterRbacConfig overriding RbacConfig",639 config: []Config{640 {641 ConfigMeta: ConfigMeta{642 Type: schemas.RbacConfig.Type,643 Name: "default",644 Namespace: "",645 },646 Spec: &rbacproto.RbacConfig{647 Mode: rbacproto.RbacConfig_OFF,648 },649 },650 newConfig("default", "",651 &rbacproto.RbacConfig{652 Mode: rbacproto.RbacConfig_ON,653 }),654 },655 service: "override.svc",656 namespace: "ns",657 want: true,658 },659 {660 name: "disabled by default",661 },662 {663 name: "disabled",664 config: []Config{665 newConfig("default", "",666 &rbacproto.RbacConfig{667 Mode: rbacproto.RbacConfig_OFF,668 }),669 },670 },671 {672 name: "disabled-if-service-empty",673 config: []Config{674 newConfig("default", "",675 &rbacproto.RbacConfig{676 Mode: rbacproto.RbacConfig_ON,677 }),678 },679 service: "",680 namespace: "default",681 want: false,682 },683 {684 name: "disabled-if-ns-empty",685 config: []Config{686 newConfig("default", "",687 &rbacproto.RbacConfig{688 Mode: rbacproto.RbacConfig_ON,689 }),690 },691 service: "product.default.svc",692 want: false,693 },694 {695 name: "disabled by exclusion.service",696 config: []Config{697 newConfig("default", "",698 &rbacproto.RbacConfig{699 Mode: rbacproto.RbacConfig_ON_WITH_EXCLUSION,700 Exclusion: target,701 }),702 },703 service: "product.default.svc",704 namespace: "default",705 },706 {707 name: "disabled by exclusion.namespace",708 config: []Config{709 newConfig("default", "",710 &rbacproto.RbacConfig{711 Mode: rbacproto.RbacConfig_ON_WITH_EXCLUSION,712 Exclusion: target,713 }),714 },715 service: "other.special.svc",716 namespace: "special",717 },718 }719 for _, tc := range testCases {720 t.Run(tc.name, func(t *testing.T) {721 authzPolicies := createFakeAuthorizationPolicies(tc.config, t)722 got := authzPolicies.IsRBACEnabled(tc.service, tc.namespace)723 if tc.want != got {724 t.Errorf("want %v but got %v", tc.want, got)725 }726 })727 }728}729func createFakeAuthorizationPolicies(configs []Config, t *testing.T) *AuthorizationPolicies {730 store := &authzFakeStore{}731 for _, cfg := range configs {732 store.add(cfg)733 }734 environment := &Environment{735 IstioConfigStore: MakeIstioStore(store),736 Watcher: mesh.NewFixedWatcher(&meshconfig.MeshConfig{RootNamespace: "istio-config"}),737 }738 authzPolicies, err := GetAuthorizationPolicies(environment)739 if err != nil {740 t.Fatalf("GetAuthorizationPolicies failed: %v", err)741 }742 return authzPolicies743}744func newConfig(name, ns string, spec proto.Message) Config {745 var typ string746 switch spec.(type) {747 case *rbacproto.RbacConfig:748 typ = schemas.ClusterRbacConfig.Type749 case *rbacproto.ServiceRole:750 typ = schemas.ServiceRole.Type751 case *rbacproto.ServiceRoleBinding:752 typ = schemas.ServiceRoleBinding.Type753 case *authpb.AuthorizationPolicy:754 typ = schemas.AuthorizationPolicy.Type755 }756 return Config{757 ConfigMeta: ConfigMeta{758 Type: typ,759 Name: name,760 Namespace: ns,761 },762 Spec: spec,763 }764}765type authzFakeStore struct {766 data []struct {767 typ string768 ns string769 cfg Config770 }771}772func (fs *authzFakeStore) add(config Config) {773 fs.data = append(fs.data, struct {774 typ string775 ns string776 cfg Config777 }{778 typ: config.Type,779 ns: config.Namespace,780 cfg: config,781 })782}783func (fs *authzFakeStore) ConfigDescriptor() schema.Set {784 return nil785}786func (fs *authzFakeStore) Get(typ, name, namespace string) *Config {787 return nil788}789func (fs *authzFakeStore) List(typ, namespace string) ([]Config, error) {790 var configs []Config791 for _, data := range fs.data {792 if data.typ == typ {793 if namespace != "" && data.ns == namespace {794 continue795 }796 configs = append(configs, data.cfg)797 }798 }799 return configs, nil800}801func (fs *authzFakeStore) Delete(typ, name, namespace string) error {802 return fmt.Errorf("not implemented")803}804func (fs *authzFakeStore) Create(config Config) (string, error) {805 return "not implemented", nil806}807func (fs *authzFakeStore) Update(config Config) (string, error) {808 return "not implemented", nil809}810func (fs *authzFakeStore) Version() string {811 return "not implemented"812}813func (fs *authzFakeStore) GetResourceAtVersion(version string, key string) (resourceVersion string, err error) {814 return "not implemented", nil815}...

Full Screen

Full Screen

NewConfig

Using AI Code Generation

copy

Full Screen

1config := config.NewConfig()2config.SetConfigName("config")3config.SetConfigType("yaml")4config.AddConfigPath(".")5config := config.NewConfig()6config.SetConfigName("config")7config.SetConfigType("yaml")8config.AddConfigPath(".")9config.ReadInConfig()10value := config.Get("key")11fmt.Println(value)12value := config.GetString("key")13fmt.Println(value)14value := config.GetInt("key")15fmt.Println(value)16value := config.GetBool("key")17fmt.Println(value)18value := config.GetFloat64("key")19fmt.Println(value)20value := config.GetStringSlice("key")21fmt.Println(value)22value := config.GetIntSlice("key")23fmt.Println(value)24value := config.GetBoolSlice("key")25fmt.Println(value)26value := config.GetFloat64Slice("key")27fmt.Println(value)28value := config.GetTime("key")29fmt.Println(value)30value := config.GetDuration("key")31fmt.Println(value)32value := config.GetSizeInBytes("key")33fmt.Println(value)34value := config.Get("key")35fmt.Println(value)36value := config.GetString("key")37fmt.Println(value)38value := config.GetInt("key")39fmt.Println(value)40value := config.GetBool("key")41fmt.Println(value)42value := config.GetFloat64("key")43fmt.Println(value)44value := config.GetStringSlice("key")45fmt.Println(value)

Full Screen

Full Screen

NewConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := config.NewConfig("ini", "conf/app.conf")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(c.String("appname"))8 fmt.Println(c.String("httpport"))9 fmt.Println(c.String("runmode"))10 fmt.Println(c.String("autorender"))11 fmt.Println(c.String("copyrequestbody"))12 fmt.Println(c.String("appname::"))13 fmt.Println(c.String("httpport::"))14 fmt.Println(c.String("runmode::"))15 fmt.Println(c.String("autorender::"))16 fmt.Println(c.String("copyrequestbody::"))17}

Full Screen

Full Screen

NewConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(strutil.Reverse("Hello, world"))4}5import (6func main() {7 fmt.Println(strutil.Reverse("Hello, world"))8}9import (10func main() {11 fmt.Println(strutil.Reverse("Hello, world"))12}13import (14func main() {15 fmt.Println(strutil.Reverse("Hello, world"))16}17import (18func main() {19 fmt.Println(strutil.Reverse("Hello, world"))20}21import (22func main() {23 fmt.Println(strutil.Reverse("Hello, world"))24}25import (26func main() {27 fmt.Println(strutil.Reverse("Hello, world

Full Screen

Full Screen

NewConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cfg, err := goconfig.LoadConfigFile("config.ini")4 if err != nil {5 fmt.Println(err)6 }7 err = cfg.LoadConfigFile("config.ini")8 if err != nil {9 fmt.Println(err)10 }11 value, err := cfg.GetValue("server", "port")12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(value)16 err = cfg.SetValue("server", "port", "8080")17 if err != nil {18 fmt.Println(err)19 }20 err = cfg.SaveConfigFile("config.ini")21 if err != nil {22 fmt.Println(err)23 }24}25import (26func main() {27 cfg, err := goconfig.LoadConfigFile("config.ini")28 if err != nil {29 fmt.Println(err)30 }31 err = cfg.SetValue("server", "port", "8080")32 if err != nil {33 fmt.Println(err)34 }35 err = cfg.SaveConfigFile("config.ini")36 if err != nil {37 fmt.Println(err)38 }39}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selenoid automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful