diff --git a/go.mod b/go.mod index 922f2aac..63195cb8 100644 --- a/go.mod +++ b/go.mod @@ -2,12 +2,55 @@ module github.com/stackitcloud/stackit-cli go 1.21.3 -require github.com/spf13/cobra v1.8.0 +require ( + github.com/golang-jwt/jwt/v5 v5.1.0 + github.com/google/go-cmp v0.6.0 + github.com/google/uuid v1.4.0 + github.com/jedib0t/go-pretty/v6 v6.4.9 + github.com/spf13/cobra v1.8.0 + github.com/spf13/pflag v1.0.5 + github.com/spf13/viper v1.17.0 + github.com/stackitcloud/stackit-sdk-go/core v0.7.3 + github.com/stackitcloud/stackit-sdk-go/services/dns v0.6.0 + github.com/stackitcloud/stackit-sdk-go/services/postgresql v0.7.0 + github.com/zalando/go-keyring v0.2.3 + golang.org/x/oauth2 v0.14.0 +) require ( + github.com/MicahParks/keyfunc/v2 v2.1.0 // indirect + github.com/alessio/shellescape v1.4.1 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect + github.com/danieljoos/wincred v1.2.0 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-logr/logr v1.2.4 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/rivo/uniseg v0.2.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect + github.com/sagikazarmark/locafero v0.3.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.10.0 // indirect + github.com/spf13/cast v1.5.1 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect + golang.org/x/net v0.18.0 // indirect + golang.org/x/sys v0.14.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/apimachinery v0.28.4 // indirect + k8s.io/klog/v2 v2.100.1 // indirect + k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect ) diff --git a/go.sum b/go.sum index 83cee7ac..8576f371 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,559 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k= +github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k= +github.com/alessio/shellescape v1.4.1 h1:V7yhSDDn8LP4lc4jS8pFkt0zCnzVJlG5JXy9BVKJUX0= +github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/danieljoos/wincred v1.2.0 h1:ozqKHaLK0W/ii4KVbbvluM91W2H3Sh0BncbUNPS7jLE= +github.com/danieljoos/wincred v1.2.0/go.mod h1:FzQLLMKBFdvu+osBrnFODiv32YGwCfx0SkRa/eYHgec= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= +github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang-jwt/jwt/v5 v5.1.0 h1:UGKbA/IPjtS6zLcdB7i5TyACMgSbOTiR8qzXgw8HWQU= +github.com/golang-jwt/jwt/v5 v5.1.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jedib0t/go-pretty/v6 v6.4.9 h1:vZ6bjGg2eBSrJn365qlxGcaWu09Id+LHtrfDWlB2Usc= +github.com/jedib0t/go-pretty/v6 v6.4.9/go.mod h1:Ndk3ase2CkQbXLLNf5QDHoYb6J9WtVfmHZu9n8rk2xs= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= +github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= +github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= +github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ= +github.com/sagikazarmark/locafero v0.3.0/go.mod h1:w+v7UsPNFwzF1cHuOajOOzoq4U7v/ig1mpRjqV+Bu1U= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY= +github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= +github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA= +github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48= github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.17.0 h1:I5txKw7MJasPL/BrfkbA0Jyo/oELqVmux4pR/UxOMfI= +github.com/spf13/viper v1.17.0/go.mod h1:BmMMMLQXSbcHK6KAOiFLz0l5JHrU89OdIRHvsk0+yVI= +github.com/stackitcloud/stackit-sdk-go/core v0.7.3 h1:oxLY44Vuyn7+lcKBZDFGbc2YSjnw43PbuiATBL3aq+I= +github.com/stackitcloud/stackit-sdk-go/core v0.7.3/go.mod h1:5hA/nSktcp/BiFaRyMIV6E/1d/i7cieLNE5XzWPrICo= +github.com/stackitcloud/stackit-sdk-go/services/dns v0.6.0 h1:n7ONZlfyWk/D10mWMT/j25kuV6ARgyFd3vIZB3kgrIo= +github.com/stackitcloud/stackit-sdk-go/services/dns v0.6.0/go.mod h1:1hRYJV33kFW/WaJuiFZWP7Z5FHhf6TnVc1equhFhMnA= +github.com/stackitcloud/stackit-sdk-go/services/postgresql v0.7.0 h1:JcXTG/WuiwXAIzjPCWbfnqq+5KLhnPokKNDyJEg3pT8= +github.com/stackitcloud/stackit-sdk-go/services/postgresql v0.7.0/go.mod h1:hopYdX5D+bBLRwmie84xMV5hXRyRQJ5oN3yQyJfnXwU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/zalando/go-keyring v0.2.3 h1:v9CUu9phlABObO4LPWycf+zwMG7nlbb3t/B5wa97yms= +github.com/zalando/go-keyring v0.2.3/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= +golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.14.0 h1:P0Vrf/2538nmC0H+pEQ3MNFRRnVR7RlqyVw+bvm26z0= +golang.org/x/oauth2 v0.14.0/go.mod h1:lAtNWgaWfL4cm7j2OV8TxGi9Qb7ECORx8DktCY74OwM= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= +golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +k8s.io/apimachinery v0.28.4 h1:zOSJe1mc+GxuMnFzD4Z/U1wst50X28ZNsn5bhgIIao8= +k8s.io/apimachinery v0.28.4/go.mod h1:wI37ncBvfAoswfq626yPTe6Bz1c22L7uaJ8dho83mgg= +k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= +k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/internal/cmd/auth/activate-service-account/activate_service_account.go b/internal/cmd/auth/activate-service-account/activate_service_account.go new file mode 100644 index 00000000..2585233b --- /dev/null +++ b/internal/cmd/auth/activate-service-account/activate_service_account.go @@ -0,0 +1,102 @@ +package activateserviceaccount + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/auth" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + sdkAuth "github.com/stackitcloud/stackit-sdk-go/core/auth" + sdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config" +) + +const ( + serviceAccountTokenFlag = "service-account-token" + serviceAccountKeyPathFlag = "service-account-key-path" + privateKeyPathFlag = "private-key-path" + tokenCustomEndpointFlag = "token-custom-endpoint" + jwksCustomEndpointFlag = "jwks-custom-endpoint" +) + +type flagModel struct { + ServiceAccountToken string + ServiceAccountKeyPath string + PrivateKeyPath string + TokenCustomEndpoint string + JwksCustomEndpoint string +} + +var Cmd = &cobra.Command{ + Use: "activate-service-account", + Short: "Activate service account authentication", + Long: "Activate authentication using service account credentials.\nFor more details on how to configure your service account, check the Authentication section on our documentation (LINK HERE README)", + Example: `$ stackit auth activate-service-account --service-account-key-path path/to/service_account_key.json --private-key-path path/to/private_key.pem`, + RunE: func(cmd *cobra.Command, args []string) error { + model := parseFlags(cmd) + + err := storeFlags(model) + if err != nil { + return err + } + + cfg := &sdkConfig.Configuration{ + Token: model.ServiceAccountToken, + ServiceAccountKeyPath: model.ServiceAccountKeyPath, + PrivateKeyPath: model.PrivateKeyPath, + TokenCustomUrl: model.TokenCustomEndpoint, + JWKSCustomUrl: model.JwksCustomEndpoint, + } + + // Setup authentication based on the provided credentials and the environment + // Initializes the authentication flow + rt, err := sdkAuth.SetupAuth(cfg) + if err != nil { + return fmt.Errorf("set up authentication: %w", err) + } + + // Authenticates the service account and stores credentials + email, err := auth.AuthenticateServiceAccount(rt) + if err != nil { + return fmt.Errorf("authenticate service account: %w", err) + } + + fmt.Printf("You have been successfully authenticated to the STACKIT CLI!\nService account email: %s\n", email) + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().String(serviceAccountTokenFlag, "", "Service account long-lived access token") + cmd.Flags().String(serviceAccountKeyPathFlag, "", "Service account key path") + cmd.Flags().String(privateKeyPathFlag, "", "RSA private key path") + cmd.Flags().String(tokenCustomEndpointFlag, "", "Custom endpoint for the token API, which is used to request access tokens when the service-account authentication is activated") + cmd.Flags().String(jwksCustomEndpointFlag, "", "Custom endpoint for the jwks API, which is used to get the json web key sets (jwks) to validate tokens when the service-account authentication is activated") +} + +func parseFlags(cmd *cobra.Command) *flagModel { + return &flagModel{ + ServiceAccountToken: utils.FlagToStringValue(cmd, serviceAccountTokenFlag), + ServiceAccountKeyPath: utils.FlagToStringValue(cmd, serviceAccountKeyPathFlag), + PrivateKeyPath: utils.FlagToStringValue(cmd, privateKeyPathFlag), + TokenCustomEndpoint: utils.FlagToStringValue(cmd, tokenCustomEndpointFlag), + JwksCustomEndpoint: utils.FlagToStringValue(cmd, jwksCustomEndpointFlag), + } +} + +func storeFlags(model *flagModel) error { + err := auth.SetAuthField(auth.TOKEN_CUSTOM_ENDPOINT, model.TokenCustomEndpoint) + if err != nil { + return fmt.Errorf("set %s: %w", auth.TOKEN_CUSTOM_ENDPOINT, err) + } + err = auth.SetAuthField(auth.JWKS_CUSTOM_ENDPOINT, model.JwksCustomEndpoint) + if err != nil { + return fmt.Errorf("set %s: %w", auth.JWKS_CUSTOM_ENDPOINT, err) + } + return nil +} diff --git a/internal/cmd/auth/activate-service-account/activate_service_account_test.go b/internal/cmd/auth/activate-service-account/activate_service_account_test.go new file mode 100644 index 00000000..433864d5 --- /dev/null +++ b/internal/cmd/auth/activate-service-account/activate_service_account_test.go @@ -0,0 +1,117 @@ +package activateserviceaccount + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/spf13/cobra" +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + serviceAccountTokenFlag: "token", + serviceAccountKeyPathFlag: "sa_key", + privateKeyPathFlag: "private_key", + tokenCustomEndpointFlag: "token_url", + jwksCustomEndpointFlag: "jwks_url", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ServiceAccountToken: "token", + ServiceAccountKeyPath: "sa_key", + PrivateKeyPath: "private_key", + TokenCustomEndpoint: "token_url", + JwksCustomEndpoint: "jwks_url", + } + for _, mod := range mods { + mod(model) + } + return model +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: true, + expectedModel: &flagModel{ + ServiceAccountToken: "", + ServiceAccountKeyPath: "", + PrivateKeyPath: "", + TokenCustomEndpoint: "", + JwksCustomEndpoint: "", + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + serviceAccountTokenFlag: "", + serviceAccountKeyPathFlag: "", + privateKeyPathFlag: "", + tokenCustomEndpointFlag: "", + jwksCustomEndpointFlag: "", + }, + isValid: true, + expectedModel: &flagModel{ + ServiceAccountToken: "", + ServiceAccountKeyPath: "", + PrivateKeyPath: "", + TokenCustomEndpoint: "", + JwksCustomEndpoint: "", + }, + }, + { + description: "invalid_flag", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues["test_flag"] = "test" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + model := parseFlags(cmd) + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/auth/auth.go b/internal/cmd/auth/auth.go new file mode 100644 index 00000000..951e52ef --- /dev/null +++ b/internal/cmd/auth/auth.go @@ -0,0 +1,21 @@ +package auth + +import ( + activateserviceaccount "github.com/stackitcloud/stackit-cli/internal/cmd/auth/activate-service-account" + "github.com/stackitcloud/stackit-cli/internal/cmd/auth/login" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "auth", + Short: "Provides authentication functionality", + Long: "Provides authentication functionality", + Example: `$ stackit auth login`, +} + +func init() { + // Add all direct child commands + Cmd.AddCommand(login.Cmd) + Cmd.AddCommand(activateserviceaccount.Cmd) +} diff --git a/internal/cmd/auth/login/login.go b/internal/cmd/auth/login/login.go new file mode 100644 index 00000000..e17b59ff --- /dev/null +++ b/internal/cmd/auth/login/login.go @@ -0,0 +1,29 @@ +package login + +import ( + "fmt" + "os" + + "github.com/stackitcloud/stackit-cli/internal/pkg/auth" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "login", + Short: "Login to the provider", + Long: "Login to the provider", + Example: `$ stackit auth login`, + Run: func(cmd *cobra.Command, args []string) { + err := auth.AuthorizeUser() + if err != nil { + fmt.Printf("Authorization failed: %s\n", err) + os.Exit(1) + } + + fmt.Println("Successfully logged into STACKIT CLI.") + }, +} + +func init() { +} diff --git a/internal/cmd/config/config.go b/internal/cmd/config/config.go new file mode 100644 index 00000000..b198b124 --- /dev/null +++ b/internal/cmd/config/config.go @@ -0,0 +1,24 @@ +package config + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/config/inspect" + "github.com/stackitcloud/stackit-cli/internal/cmd/config/set" + "github.com/stackitcloud/stackit-cli/internal/cmd/config/unset" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "config", + Short: "CLI configuration options", + Long: "CLI configuration options", + Example: fmt.Sprintf("%s\n%s\n%s", set.Cmd.Example, inspect.Cmd.Example, unset.Cmd.Example), +} + +func init() { + Cmd.AddCommand(inspect.Cmd) + Cmd.AddCommand(set.Cmd) + Cmd.AddCommand(unset.Cmd) +} diff --git a/internal/cmd/config/inspect/inspect.go b/internal/cmd/config/inspect/inspect.go new file mode 100644 index 00000000..d9eacca1 --- /dev/null +++ b/internal/cmd/config/inspect/inspect.go @@ -0,0 +1,32 @@ +package inspect + +import ( + "encoding/json" + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var Cmd = &cobra.Command{ + Use: "inspect", + Short: "Inspect the current CLI configuration values", + Long: "Inspect the current CLI configuration values", + Example: `$ stackit config inspect`, + RunE: func(cmd *cobra.Command, args []string) error { + err := viper.ReadInConfig() + if err != nil { + return fmt.Errorf("read config file: %w", err) + } + + configData := viper.AllSettings() + + configJSON, err := json.MarshalIndent(configData, "", " ") + if err != nil { + return fmt.Errorf("marshal config: %w", err) + } + fmt.Println(string(configJSON)) + + return nil + }, +} diff --git a/internal/cmd/config/set/set.go b/internal/cmd/config/set/set.go new file mode 100644 index 00000000..ebab801c --- /dev/null +++ b/internal/cmd/config/set/set.go @@ -0,0 +1,98 @@ +package set + +import ( + "fmt" + "time" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + sessionTimeLimitFlag = "session-time-limit" + projectIdFlag = "project-id" + dnsCustomEndpointFlag = "dns-custom-endpoint" + postgreSQLCustomEndpointFlag = "postgresql-custom-endpoint" +) + +type flagModel struct { + SessionTimeLimit *string +} + +var Cmd = &cobra.Command{ + Use: "set", + Short: "Set CLI configuration options", + Long: "Set CLI configuration options", + Example: `$ stackit config set --project-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + model, err := parseFlags(cmd) + if err != nil { + return err + } + + if model.SessionTimeLimit != nil { + cmd.Println("Authenticate again to apply changes to session time limit") + viper.Set(config.SessionTimeLimitKey, *model.SessionTimeLimit) + } + + err = viper.WriteConfig() + if err != nil { + return fmt.Errorf("write new config to file: %w", err) + } + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().String(sessionTimeLimitFlag, "", "Maximum time before authentication is required again. Can't be larger than 24h. Examples: 3h, 5h30m40s") + cmd.Flags().String(dnsCustomEndpointFlag, "", "DNS custom endpoint") + cmd.Flags().String(postgreSQLCustomEndpointFlag, "", "PostgreSQL custom endpoint") + + err := viper.BindPFlag(config.DNSCustomEndpointKey, cmd.Flags().Lookup(dnsCustomEndpointFlag)) + cobra.CheckErr(err) + err = viper.BindPFlag(config.PostgreSQLCustomEndpointKey, cmd.Flags().Lookup(postgreSQLCustomEndpointFlag)) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + sessionTimeLimit, err := parseSessionTimeLimit(cmd) + if err != nil { + return nil, fmt.Errorf("parse --%s: %w", sessionTimeLimitFlag, err) + } + + return &flagModel{ + SessionTimeLimit: sessionTimeLimit, + }, nil +} + +func parseSessionTimeLimit(cmd *cobra.Command) (*string, error) { + sessionTimeLimit := utils.FlagToStringPointer(cmd, sessionTimeLimitFlag) + if sessionTimeLimit == nil { + return nil, nil + } + + // time.ParseDuration doesn't recognize unit "d", for simplicity we allow the value "1d" + if *sessionTimeLimit == "1d" { + *sessionTimeLimit = "24h" + } + + duration, err := time.ParseDuration(*sessionTimeLimit) + if err != nil { + return nil, fmt.Errorf("parse value \"%s\": %w", *sessionTimeLimit, err) + } + if duration <= 0 { + return nil, fmt.Errorf("value must be positive") + } + if duration > time.Duration(24)*time.Hour { + return nil, fmt.Errorf("value can't be larger than 24h") + } + + return sessionTimeLimit, nil +} diff --git a/internal/cmd/config/set/set_test.go b/internal/cmd/config/set/set_test.go new file mode 100644 index 00000000..6083e1f1 --- /dev/null +++ b/internal/cmd/config/set/set_test.go @@ -0,0 +1,127 @@ +package set + +import ( + "testing" + + "github.com/spf13/cobra" +) + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + }{ + { + description: "valid session time limit 1", + flagValues: map[string]string{ + sessionTimeLimitFlag: "1h", + }, + isValid: true, + }, + { + description: "valid session time limit 2", + flagValues: map[string]string{ + sessionTimeLimitFlag: "5h30m40s", + }, + isValid: true, + }, + { + description: "valid session time limit 3", + flagValues: map[string]string{ + sessionTimeLimitFlag: "1h2m3s4ms5us6ns", + }, + isValid: true, + }, + { + description: "valid session time limit 4", + flagValues: map[string]string{ + sessionTimeLimitFlag: "1d", + }, + isValid: true, + }, + { + description: "invalid session time limit 1", + flagValues: map[string]string{ + sessionTimeLimitFlag: "foo", + }, + isValid: false, + }, + { + description: "invalid session time limit 2", + flagValues: map[string]string{ + sessionTimeLimitFlag: "", + }, + isValid: false, + }, + { + description: "invalid session time limit 3", + flagValues: map[string]string{ + sessionTimeLimitFlag: "1", + }, + isValid: false, + }, + { + description: "invalid session time limit 4", + flagValues: map[string]string{ + sessionTimeLimitFlag: "h", + }, + isValid: false, + }, + { + description: "invalid session time limit 5", + flagValues: map[string]string{ + sessionTimeLimitFlag: "0h", + }, + isValid: false, + }, + { + description: "invalid session time limit 6", + flagValues: map[string]string{ + sessionTimeLimitFlag: "-1h", + }, + isValid: false, + }, + { + description: "invalid session time limit 7", + flagValues: map[string]string{ + sessionTimeLimitFlag: "25h", + }, + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err := cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + _, err = parseFlags(cmd) + + if err != nil && tt.isValid { + t.Fatalf("error parsing flags: %v", err) + } + if err == nil && !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + }) + } +} diff --git a/internal/cmd/config/unset/unset.go b/internal/cmd/config/unset/unset.go new file mode 100644 index 00000000..0497f56b --- /dev/null +++ b/internal/cmd/config/unset/unset.go @@ -0,0 +1,67 @@ +package unset + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + projectIdFlag = "project-id" + dnsCustomEndpointFlag = "dns-custom-endpoint" + postgreSQLCustomEndpointFlag = "postgresql-custom-endpoint" +) + +type flagModel struct { + ProjectId bool + DNSCustomEndpoint bool + PostgreSQLCustomEndpoint bool +} + +var Cmd = &cobra.Command{ + Use: "unset", + Short: "Unset CLI configuration options", + Long: "Unset CLI configuration options", + Example: `$ stackit config unset --project-id`, + RunE: func(cmd *cobra.Command, args []string) error { + model := parseFlags(cmd) + + if model.ProjectId { + viper.Set(config.ProjectIdKey, "") + } + if model.DNSCustomEndpoint { + viper.Set(config.DNSCustomEndpointKey, "") + } + if model.PostgreSQLCustomEndpoint { + viper.Set(config.PostgreSQLCustomEndpointKey, "") + } + + err := viper.WriteConfig() + if err != nil { + return fmt.Errorf("write updated config to file: %w", err) + } + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Bool(projectIdFlag, false, "Project ID") + cmd.Flags().Bool(dnsCustomEndpointFlag, false, "DNS custom endpoint") + cmd.Flags().Bool(postgreSQLCustomEndpointFlag, false, "PostgreSQL custom endpoint") +} + +func parseFlags(cmd *cobra.Command) *flagModel { + return &flagModel{ + ProjectId: utils.FlagToBoolValue(cmd, projectIdFlag), + DNSCustomEndpoint: utils.FlagToBoolValue(cmd, dnsCustomEndpointFlag), + PostgreSQLCustomEndpoint: utils.FlagToBoolValue(cmd, postgreSQLCustomEndpointFlag), + } +} diff --git a/internal/cmd/config/unset/unset_test.go b/internal/cmd/config/unset/unset_test.go new file mode 100644 index 00000000..84290362 --- /dev/null +++ b/internal/cmd/config/unset/unset_test.go @@ -0,0 +1,125 @@ +package unset + +import ( + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/spf13/cobra" +) + +func fixtureFlagValues(mods ...func(flagValues map[string]bool)) map[string]bool { + flagValues := map[string]bool{ + projectIdFlag: true, + dnsCustomEndpointFlag: true, + postgreSQLCustomEndpointFlag: true, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: true, + DNSCustomEndpoint: true, + PostgreSQLCustomEndpoint: true, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]bool + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]bool{}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.ProjectId = false + model.DNSCustomEndpoint = false + model.PostgreSQLCustomEndpoint = false + }), + }, + { + description: "project id empty", + flagValues: fixtureFlagValues(func(flagValues map[string]bool) { + flagValues[projectIdFlag] = false + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.ProjectId = false + }), + }, + { + description: "dns custom endpoint empty", + flagValues: fixtureFlagValues(func(flagValues map[string]bool) { + flagValues[dnsCustomEndpointFlag] = false + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.DNSCustomEndpoint = false + }), + }, + { + description: "postgresql custom endpoint empty", + flagValues: fixtureFlagValues(func(flagValues map[string]bool) { + flagValues[postgreSQLCustomEndpointFlag] = false + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.PostgreSQLCustomEndpoint = false + }), + }, + } + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + stringBool := fmt.Sprintf("%v", value) + err := cmd.Flags().Set(flag, stringBool) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, stringBool, err) + } + } + + err := cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model := parseFlags(cmd) + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/dns.go b/internal/cmd/dns/dns.go new file mode 100644 index 00000000..8c911763 --- /dev/null +++ b/internal/cmd/dns/dns.go @@ -0,0 +1,22 @@ +package dns + +import ( + "fmt" + + recordset "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "dns", + Short: "Provides functionality for DNS", + Long: "Provides functionality for DNS", + Example: fmt.Sprintf("%s\n%s", zone.Cmd.Example, recordset.Cmd.Example), +} + +func init() { + Cmd.AddCommand(zone.Cmd) + Cmd.AddCommand(recordset.Cmd) +} diff --git a/internal/cmd/dns/record-set/create/create.go b/internal/cmd/dns/record-set/create/create.go new file mode 100644 index 00000000..ff0e2185 --- /dev/null +++ b/internal/cmd/dns/record-set/create/create.go @@ -0,0 +1,125 @@ +package create + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + commentFlag = "comment" + nameFlag = "name" + recordFlag = "record" + ttlFlag = "ttl" + typeFlag = "type" +) + +type flagModel struct { + ProjectId string + ZoneId string + Comment *string + Name *string + Records []string + TTL *int64 + Type *string +} + +var Cmd = &cobra.Command{ + Use: "create", + Short: "Creates a DNS record set", + Long: "Creates a DNS record set", + Example: `$ stackit dns record-set create --project-id xxx --zone-id xxx --name my-zone --type A --record 1.2.3.4 --record 5.6.7.8`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("create DNS record set: %w", err) + } + + // Wait for async operation + recordSetId := *resp.Rrset.Id + _, err = wait.CreateRecordSetWaitHandler(ctx, apiClient, model.ProjectId, model.ZoneId, recordSetId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS record set creation: %w", err) + } + + fmt.Printf("Created record set with ID %s\n", recordSetId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + typeFlagOptions := []string{"A", "AAAA", "SOA", "CNAME", "NS", "MX", "TXT", "SRV", "PTR", "ALIAS", "DNAME", "CAA"} + + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().String(commentFlag, "", "User comment") + cmd.Flags().String(nameFlag, "", "Name of the record, should be compliant with RFC1035, Section 2.3.4") + cmd.Flags().Int64(ttlFlag, 0, "Time to live, if not provided defaults to the zone's default TTL") + cmd.Flags().StringSlice(recordFlag, []string{}, "Records belonging to the record set") + cmd.Flags().Var(flags.EnumFlag(false, typeFlagOptions...), typeFlag, fmt.Sprintf("Zone type, one of %q", typeFlagOptions)) + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag, nameFlag, recordFlag, typeFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + Comment: utils.FlagToStringPointer(cmd, commentFlag), + Name: utils.FlagToStringPointer(cmd, nameFlag), + Records: utils.FlagToStringSliceValue(cmd, recordFlag), + TTL: utils.FlagToInt64Pointer(cmd, ttlFlag), + Type: utils.FlagToStringPointer(cmd, typeFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiCreateRecordSetRequest { + records := make([]dns.RecordPayload, 0) + for _, r := range model.Records { + records = append(records, dns.RecordPayload{Content: utils.Ptr(r)}) + } + + req := apiClient.CreateRecordSet(ctx, model.ProjectId, model.ZoneId) + req = req.CreateRecordSetPayload(dns.CreateRecordSetPayload{ + Comment: model.Comment, + Name: model.Name, + Records: &records, + Ttl: model.TTL, + Type: model.Type, + }) + return req +} diff --git a/internal/cmd/dns/record-set/create/create_test.go b/internal/cmd/dns/record-set/create/create_test.go new file mode 100644 index 00000000..c2543d12 --- /dev/null +++ b/internal/cmd/dns/record-set/create/create_test.go @@ -0,0 +1,333 @@ +package create + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + commentFlag: "comment", + nameFlag: "example.com", + recordFlag: "1.1.1.1", + ttlFlag: "3600", + typeFlag: "A", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr("example.com"), + Comment: utils.Ptr("comment"), + Records: []string{"1.1.1.1"}, + TTL: utils.Ptr(int64(3600)), + Type: utils.Ptr("A"), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiCreateRecordSetRequest)) dns.ApiCreateRecordSetRequest { + request := testClient.CreateRecordSet(testCtx, testProjectId, testZoneId) + request = request.CreateRecordSetPayload(dns.CreateRecordSetPayload{ + Name: utils.Ptr("example.com"), + Comment: utils.Ptr("comment"), + Records: &[]dns.RecordPayload{ + {Content: utils.Ptr("1.1.1.1")}, + }, + Ttl: utils.Ptr(int64(3600)), + Type: utils.Ptr("A"), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + recordFlagValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + nameFlag: "example.com", + recordFlag: "1.1.1.1", + typeFlag: "A", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr("example.com"), + Records: []string{"1.1.1.1"}, + Type: utils.Ptr("A"), + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + commentFlag: "", + nameFlag: "", + recordFlag: "1.1.1.1", + ttlFlag: "0", + typeFlag: "A", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr(""), + Comment: utils.Ptr(""), + Records: []string{"1.1.1.1"}, + TTL: utils.Ptr(int64(0)), + Type: utils.Ptr("A"), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "name missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, nameFlag) + }), + isValid: false, + }, + { + description: "records missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, recordFlag) + }), + isValid: false, + }, + { + description: "type missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, typeFlag) + }), + isValid: false, + }, + { + description: "type invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[typeFlag] = "" + }), + isValid: false, + }, + { + description: "type invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[typeFlag] = "a" + }), + isValid: false, + }, + { + description: "repeated primary flags", + flagValues: fixtureFlagValues(), + recordFlagValues: []string{"1.2.3.4", "5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Records = append(model.Records, "1.2.3.4", "5.6.7.8") + }), + }, + { + description: "repeated primary flags with list value", + flagValues: fixtureFlagValues(), + recordFlagValues: []string{"1.2.3.4,5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Records = append(model.Records, "1.2.3.4", "5.6.7.8") + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.recordFlagValues { + err := cmd.Flags().Set(recordFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", recordFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiCreateRecordSetRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr("example.com"), + Records: []string{"1.1.1.1"}, + Type: utils.Ptr("A"), + }, + expectedRequest: testClient.CreateRecordSet(testCtx, testProjectId, testZoneId). + CreateRecordSetPayload(dns.CreateRecordSetPayload{ + Name: utils.Ptr("example.com"), + Records: &[]dns.RecordPayload{ + {Content: utils.Ptr("1.1.1.1")}, + }, + Type: utils.Ptr("A"), + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/record-set/delete/delete.go b/internal/cmd/dns/record-set/delete/delete.go new file mode 100644 index 00000000..9c4c736c --- /dev/null +++ b/internal/cmd/dns/record-set/delete/delete.go @@ -0,0 +1,97 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + recordSetIdFlag = "record-set-id" +) + +type flagModel struct { + ProjectId string + ZoneId string + RecordSetId string +} + +var Cmd = &cobra.Command{ + Use: "delete", + Short: "Delete a DNS record set", + Long: "Delete a DNS record set", + Example: `$ stackit dns record-set delete --project-id xxx --zone-id xxx --record-set-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + if err != nil { + return err + } + _, err = req.Execute() + if err != nil { + return fmt.Errorf("delete DNS record set: %w", err) + } + + // Wait for async operation + _, err = wait.DeleteRecordSetWaitHandler(ctx, apiClient, model.ProjectId, model.ZoneId, model.RecordSetId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS record set deletion: %w", err) + } + + fmt.Println("Record set deleted") + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().Var(flags.UUIDFlag(), recordSetIdFlag, "Record set ID") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag, recordSetIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + RecordSetId: utils.FlagToStringValue(cmd, recordSetIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiDeleteRecordSetRequest { + req := apiClient.DeleteRecordSet(ctx, model.ProjectId, model.ZoneId, model.RecordSetId) + return req +} diff --git a/internal/cmd/dns/record-set/delete/delete_test.go b/internal/cmd/dns/record-set/delete/delete_test.go new file mode 100644 index 00000000..1c825190 --- /dev/null +++ b/internal/cmd/dns/record-set/delete/delete_test.go @@ -0,0 +1,217 @@ +package delete + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() +var testRecordSetId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + recordSetIdFlag: testRecordSetId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiDeleteRecordSetRequest)) dns.ApiDeleteRecordSetRequest { + request := testClient.DeleteRecordSet(testCtx, testProjectId, testZoneId, testRecordSetId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "record set id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, recordSetIdFlag) + }), + isValid: false, + }, + { + description: "record set id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "" + }), + isValid: false, + }, + { + description: "record set id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + isValid bool + expectedRequest dns.ApiDeleteRecordSetRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + isValid: true, + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/record-set/describe/describe.go b/internal/cmd/dns/record-set/describe/describe.go new file mode 100644 index 00000000..85fd3df1 --- /dev/null +++ b/internal/cmd/dns/record-set/describe/describe.go @@ -0,0 +1,95 @@ +package describe + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + recordSetIdFlag = "record-set-id" +) + +type flagModel struct { + ProjectId string + ZoneId string + RecordSetId string +} + +var Cmd = &cobra.Command{ + Use: "describe", + Short: "Get details of a DNS record set", + Long: "Get details of a DNS record set", + Example: `$ stackit dns record-set describe --project-id xxx --zone-id xxx --record-set-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("read DNS record set: %w", err) + } + recordSet := *resp.Rrset + + // Show details + details, err := json.MarshalIndent(recordSet, "", " ") + if err != nil { + return fmt.Errorf("marshal DNS record set: %w", err) + } + fmt.Println(string(details)) + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().Var(flags.UUIDFlag(), recordSetIdFlag, "Record Set ID") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag, recordSetIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + RecordSetId: utils.FlagToStringValue(cmd, recordSetIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiGetRecordSetRequest { + req := apiClient.GetRecordSet(ctx, model.ProjectId, model.ZoneId, model.RecordSetId) + return req +} diff --git a/internal/cmd/dns/record-set/describe/describe_test.go b/internal/cmd/dns/record-set/describe/describe_test.go new file mode 100644 index 00000000..cfde6e45 --- /dev/null +++ b/internal/cmd/dns/record-set/describe/describe_test.go @@ -0,0 +1,217 @@ +package describe + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() +var testRecordSetId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + recordSetIdFlag: testRecordSetId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiGetRecordSetRequest)) dns.ApiGetRecordSetRequest { + request := testClient.GetRecordSet(testCtx, testProjectId, testZoneId, testRecordSetId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "record set id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, recordSetIdFlag) + }), + isValid: false, + }, + { + description: "record set id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "" + }), + isValid: false, + }, + { + description: "record set id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + isValid bool + expectedRequest dns.ApiGetRecordSetRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + isValid: true, + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/record-set/list/list.go b/internal/cmd/dns/record-set/list/list.go new file mode 100644 index 00000000..f138e5ed --- /dev/null +++ b/internal/cmd/dns/record-set/list/list.go @@ -0,0 +1,121 @@ +package list + +import ( + "context" + "fmt" + "strings" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + nameLikeFlag = "name-like" + activeFlag = "is-active" + orderByNameFlag = "order-by-name" +) + +type flagModel struct { + ProjectId string + ZoneId string + NameLike *string + Active *bool + OrderByName *string +} + +var Cmd = &cobra.Command{ + Use: "list", + Short: "List all DNS record sets", + Long: "List all DNS record sets", + Example: `$ stackit dns record-set list --project-id xxx --zone-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("get DNS record sets: %w", err) + } + recordSets := *resp.RrSets + if len(recordSets) == 0 { + fmt.Printf("No record-sets found for zone with ID %s\n", model.ZoneId) + return nil + } + + // Show output as table + table := tables.NewTable() + table.SetHeader("ID", "Name", "Type", "State") + for _, recordSet := range recordSets { + table.AddRow(*recordSet.Id, *recordSet.Name, *recordSet.Type, *recordSet.State) + } + table.Render() + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + activeFlagOptions := []string{"true", "false"} + orderByNameFlagOptions := []string{"asc", "desc"} + + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().String(nameLikeFlag, "", "Filter by name") + cmd.Flags().Var(flags.EnumBoolFlag(), activeFlag, fmt.Sprintf("Filter by active status, one of %q", activeFlagOptions)) + cmd.Flags().Var(flags.EnumFlag(true, orderByNameFlagOptions...), orderByNameFlag, fmt.Sprintf("Order by name, one of %q", orderByNameFlagOptions)) + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + NameLike: utils.FlagToStringPointer(cmd, nameLikeFlag), + Active: utils.FlagToBoolPointer(cmd, activeFlag), + OrderByName: utils.FlagToStringPointer(cmd, orderByNameFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiGetRecordSetsRequest { + req := apiClient.GetRecordSets(ctx, model.ProjectId, model.ZoneId) + if model.NameLike != nil { + req = req.NameLike(*model.NameLike) + } + if model.Active != nil { + req = req.ActiveEq(*model.Active) + } + if model.OrderByName != nil { + req = req.OrderByName(strings.ToUpper(*model.OrderByName)) + } + return req +} diff --git a/internal/cmd/dns/record-set/list/list_test.go b/internal/cmd/dns/record-set/list/list_test.go new file mode 100644 index 00000000..e911a41e --- /dev/null +++ b/internal/cmd/dns/record-set/list/list_test.go @@ -0,0 +1,260 @@ +package list + +import ( + "context" + "fmt" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + nameLikeFlag: "some-pattern", + activeFlag: "true", + orderByNameFlag: "asc", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + NameLike: utils.Ptr("some-pattern"), + Active: utils.Ptr(true), + OrderByName: utils.Ptr("asc"), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiGetRecordSetsRequest)) dns.ApiGetRecordSetsRequest { + request := testClient.GetRecordSets(testCtx, testProjectId, testZoneId) + request = request.NameLike("some-pattern") + request = request.ActiveEq(true) + request = request.OrderByName("ASC") + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "name like empty", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameLikeFlag] = "" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.NameLike = utils.Ptr("") + }), + }, + { + description: "is active = false", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "false" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Active = utils.Ptr(false) + }), + }, + { + description: "is active invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "" + }), + isValid: false, + }, + { + description: "is active invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "invalid" + }), + isValid: false, + }, + { + description: "order by name desc", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "desc" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.OrderByName = utils.Ptr("desc") + }), + }, + { + description: "order by name invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "" + }), + isValid: false, + }, + { + description: "order by name invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "invalid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + fmt.Printf("setting flag --%s=%s: %v", flag, value, err) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiGetRecordSetsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + }, + expectedRequest: testClient.GetRecordSets(testCtx, testProjectId, testZoneId), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/record-set/record_set.go b/internal/cmd/dns/record-set/record_set.go new file mode 100644 index 00000000..8c946244 --- /dev/null +++ b/internal/cmd/dns/record-set/record_set.go @@ -0,0 +1,29 @@ +package recordset + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set/list" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/record-set/update" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "record-set", + Short: "Provides functionality for DNS record set", + Long: "Provides functionality for DNS record set", + Example: fmt.Sprintf("%s\n%s", list.Cmd.Example, create.Cmd.Example), +} + +func init() { + // Add all direct child commands + Cmd.AddCommand(list.Cmd) + Cmd.AddCommand(create.Cmd) + Cmd.AddCommand(describe.Cmd) + Cmd.AddCommand(delete.Cmd) + Cmd.AddCommand(update.Cmd) +} diff --git a/internal/cmd/dns/record-set/update/update.go b/internal/cmd/dns/record-set/update/update.go new file mode 100644 index 00000000..b9b6e7c0 --- /dev/null +++ b/internal/cmd/dns/record-set/update/update.go @@ -0,0 +1,124 @@ +package update + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + recordSetIdFlag = "record-set-id" + commentFlag = "comment" + nameFlag = "name" + recordFlag = "record" + ttlFlag = "ttl" +) + +type flagModel struct { + ProjectId string + ZoneId string + RecordSetId string + Comment *string + Name *string + Records *[]string + TTL *int64 +} + +var Cmd = &cobra.Command{ + Use: "update", + Short: "Updates a DNS record set", + Long: "Updates a DNS record set. Performs a partial update; fields not provided are kept unchanged", + Example: `$ stackit dns record-set update --project-id xxx --zone-id xxx --record-set-id xxx --name my-zone --type A --record 1.2.3.4 --record 5.6.7.8`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + _, err = req.Execute() + if err != nil { + return fmt.Errorf("update DNS record set: %w", err) + } + + // Wait for async operation + _, err = wait.UpdateRecordSetWaitHandler(ctx, apiClient, model.ProjectId, model.ZoneId, model.RecordSetId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS record set update: %w", err) + } + + fmt.Println("Record set updated") + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().Var(flags.UUIDFlag(), recordSetIdFlag, "Record set ID") + cmd.Flags().String(commentFlag, "", "User comment") + cmd.Flags().String(nameFlag, "", "Name of the record, should be compliant with RFC1035, Section 2.3.4") + cmd.Flags().Int64(ttlFlag, 0, "Time to live, if not provided defaults to the zone's default TTL") + cmd.Flags().StringSlice(recordFlag, []string{}, "Records belonging to the record set. If this flag is used, records already created that aren't set when running the command will be deleted") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag, recordSetIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + RecordSetId: utils.FlagToStringValue(cmd, recordSetIdFlag), + Comment: utils.FlagToStringPointer(cmd, commentFlag), + Name: utils.FlagToStringPointer(cmd, nameFlag), + Records: utils.FlagToStringSlicePointer(cmd, recordFlag), + TTL: utils.FlagToInt64Pointer(cmd, ttlFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiUpdateRecordSetRequest { + var records *[]dns.RecordPayload = nil + if model.Records != nil { + records = utils.Ptr(make([]dns.RecordPayload, 0)) + for _, r := range *model.Records { + records = utils.Ptr(append(*records, dns.RecordPayload{Content: utils.Ptr(r)})) + } + } + + req := apiClient.UpdateRecordSet(ctx, model.ProjectId, model.ZoneId, model.RecordSetId) + req = req.UpdateRecordSetPayload(dns.UpdateRecordSetPayload{ + Comment: model.Comment, + Name: model.Name, + Records: records, + Ttl: model.TTL, + }) + return req +} diff --git a/internal/cmd/dns/record-set/update/update_test.go b/internal/cmd/dns/record-set/update/update_test.go new file mode 100644 index 00000000..355a4a35 --- /dev/null +++ b/internal/cmd/dns/record-set/update/update_test.go @@ -0,0 +1,307 @@ +package update + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() +var testRecordSetId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + recordSetIdFlag: testRecordSetId, + commentFlag: "comment", + nameFlag: "example.com", + recordFlag: "1.1.1.1", + ttlFlag: "3600", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + Name: utils.Ptr("example.com"), + Comment: utils.Ptr("comment"), + Records: &[]string{"1.1.1.1"}, + TTL: utils.Ptr(int64(3600)), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiUpdateRecordSetRequest)) dns.ApiUpdateRecordSetRequest { + request := testClient.UpdateRecordSet(testCtx, testProjectId, testZoneId, testRecordSetId) + request = request.UpdateRecordSetPayload(dns.UpdateRecordSetPayload{ + Name: utils.Ptr("example.com"), + Comment: utils.Ptr("comment"), + Records: &[]dns.RecordPayload{ + {Content: utils.Ptr("1.1.1.1")}, + }, + Ttl: utils.Ptr(int64(3600)), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + recordFlagValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + recordSetIdFlag: testRecordSetId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + recordSetIdFlag: testRecordSetId, + commentFlag: "", + nameFlag: "", + recordFlag: "1.1.1.1", + ttlFlag: "0", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + Name: utils.Ptr(""), + Comment: utils.Ptr(""), + Records: &[]string{"1.1.1.1"}, + TTL: utils.Ptr(int64(0)), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "record set id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, recordSetIdFlag) + }), + isValid: false, + }, + { + description: "record set id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "" + }), + isValid: false, + }, + { + description: "record set id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[recordSetIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "repeated primary flags", + flagValues: fixtureFlagValues(), + recordFlagValues: []string{"1.2.3.4", "5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Records = utils.Ptr(append(*model.Records, "1.2.3.4", "5.6.7.8")) + }), + }, + { + description: "repeated primary flags with list value", + flagValues: fixtureFlagValues(), + recordFlagValues: []string{"1.2.3.4,5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Records = utils.Ptr(append(*model.Records, "1.2.3.4", "5.6.7.8")) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.recordFlagValues { + err := cmd.Flags().Set(recordFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", recordFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiUpdateRecordSetRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + RecordSetId: testRecordSetId, + }, + expectedRequest: testClient.UpdateRecordSet(testCtx, testProjectId, testZoneId, testRecordSetId). + UpdateRecordSetPayload(dns.UpdateRecordSetPayload{}), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/create/create.go b/internal/cmd/dns/zone/create/create.go new file mode 100644 index 00000000..0c7800f0 --- /dev/null +++ b/internal/cmd/dns/zone/create/create.go @@ -0,0 +1,153 @@ +package create + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +const ( + projectIdFlag = "project-id" + nameFlag = "name" + dnsNameFlag = "dns-name" + defaultTTLFlag = "default-ttl" + primaryFlag = "primary" + aclFlag = "acl" + typeFlag = "type" + retryTimeFlag = "retry-time" + refreshTimeFlag = "refresh-time" + negativeCacheFlag = "negative-cache" + isReverseZoneFlag = "is-reverse-zone" + expireTimeFlag = "expire-time" + descriptionFlag = "description" + contactEmailFlag = "contact-email" +) + +type flagModel struct { + ProjectId string + Name *string + DnsName *string + DefaultTTL *int64 + Primaries *[]string + Acl *string + Type *string + RetryTime *int64 + RefreshTime *int64 + NegativeCache *int64 + IsReverseZone *bool + ExpireTime *int64 + Description *string + ContactEmail *string +} + +var Cmd = &cobra.Command{ + Use: "create", + Short: "Creates a DNS zone", + Long: "Creates a DNS zone", + Example: `$ stackit dns zone create --project-id xxx --name my-zone --dns-name my-zone.com`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("create DNS zone: %w", err) + } + + // Wait for async operation + zoneId := *resp.Zone.Id + _, err = wait.CreateZoneWaitHandler(ctx, apiClient, model.ProjectId, zoneId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS zone creation: %w", err) + } + + fmt.Printf("Created zone with ID %s\n", zoneId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().String(nameFlag, "", "User given name of the zone") + cmd.Flags().String(dnsNameFlag, "", "DNS zone name") + cmd.Flags().Int64(defaultTTLFlag, 1000, "Default time to live") + cmd.Flags().StringSlice(primaryFlag, []string{}, "Primary name server for secondary zone") + cmd.Flags().String(aclFlag, "", "Access control list") + cmd.Flags().String(typeFlag, "", "Zone type") + cmd.Flags().Int64(retryTimeFlag, 0, "Retry time") + cmd.Flags().Int64(refreshTimeFlag, 0, "Refresh time") + cmd.Flags().Int64(negativeCacheFlag, 0, "Negative cache") + cmd.Flags().Bool(isReverseZoneFlag, false, "Is reverse zone") + cmd.Flags().Int64(expireTimeFlag, 0, "Expire time") + cmd.Flags().String(descriptionFlag, "", "Description of the zone") + cmd.Flags().String(contactEmailFlag, "", "Contact email for the zone") + + err := utils.MarkFlagsRequired(cmd, nameFlag, dnsNameFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + Name: utils.FlagToStringPointer(cmd, nameFlag), + DnsName: utils.FlagToStringPointer(cmd, dnsNameFlag), + DefaultTTL: utils.FlagToInt64Pointer(cmd, defaultTTLFlag), + Primaries: utils.FlagToStringSlicePointer(cmd, primaryFlag), + Acl: utils.FlagToStringPointer(cmd, aclFlag), + Type: utils.FlagToStringPointer(cmd, typeFlag), + RetryTime: utils.FlagToInt64Pointer(cmd, retryTimeFlag), + RefreshTime: utils.FlagToInt64Pointer(cmd, refreshTimeFlag), + NegativeCache: utils.FlagToInt64Pointer(cmd, negativeCacheFlag), + IsReverseZone: utils.FlagToBoolPointer(cmd, isReverseZoneFlag), + ExpireTime: utils.FlagToInt64Pointer(cmd, expireTimeFlag), + Description: utils.FlagToStringPointer(cmd, descriptionFlag), + ContactEmail: utils.FlagToStringPointer(cmd, contactEmailFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiCreateZoneRequest { + req := apiClient.CreateZone(ctx, model.ProjectId) + req = req.CreateZonePayload(dns.CreateZonePayload{ + Name: model.Name, + DnsName: model.DnsName, + DefaultTTL: model.DefaultTTL, + Primaries: model.Primaries, + Acl: model.Acl, + Type: model.Type, + RetryTime: model.RetryTime, + RefreshTime: model.RefreshTime, + NegativeCache: model.NegativeCache, + IsReverseZone: model.IsReverseZone, + ExpireTime: model.ExpireTime, + Description: model.Description, + ContactEmail: model.ContactEmail, + }) + return req +} diff --git a/internal/cmd/dns/zone/create/create_test.go b/internal/cmd/dns/zone/create/create_test.go new file mode 100644 index 00000000..775e718d --- /dev/null +++ b/internal/cmd/dns/zone/create/create_test.go @@ -0,0 +1,305 @@ +package create + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + nameFlag: "example", + dnsNameFlag: "example.com", + defaultTTLFlag: "3600", + aclFlag: "0.0.0.0/0", + typeFlag: "master", + primaryFlag: "1.1.1.1", + retryTimeFlag: "600", + refreshTimeFlag: "3600", + negativeCacheFlag: "60", + isReverseZoneFlag: "false", + expireTimeFlag: "36000000", + descriptionFlag: "Example", + contactEmailFlag: "example@example.com", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + Name: utils.Ptr("example"), + DnsName: utils.Ptr("example.com"), + DefaultTTL: utils.Ptr(int64(3600)), + Primaries: utils.Ptr([]string{"1.1.1.1"}), + Acl: utils.Ptr("0.0.0.0/0"), + Type: utils.Ptr("master"), + RetryTime: utils.Ptr(int64(600)), + RefreshTime: utils.Ptr(int64(3600)), + NegativeCache: utils.Ptr(int64(60)), + IsReverseZone: utils.Ptr(false), + ExpireTime: utils.Ptr(int64(36000000)), + Description: utils.Ptr("Example"), + ContactEmail: utils.Ptr("example@example.com"), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiCreateZoneRequest)) dns.ApiCreateZoneRequest { + request := testClient.CreateZone(testCtx, testProjectId) + request = request.CreateZonePayload(dns.CreateZonePayload{ + Name: utils.Ptr("example"), + DnsName: utils.Ptr("example.com"), + DefaultTTL: utils.Ptr(int64(3600)), + Primaries: utils.Ptr([]string{"1.1.1.1"}), + Acl: utils.Ptr("0.0.0.0/0"), + Type: utils.Ptr("master"), + RetryTime: utils.Ptr(int64(600)), + RefreshTime: utils.Ptr(int64(3600)), + NegativeCache: utils.Ptr(int64(60)), + IsReverseZone: utils.Ptr(false), + ExpireTime: utils.Ptr(int64(36000000)), + Description: utils.Ptr("Example"), + ContactEmail: utils.Ptr("example@example.com"), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + primaryFlagValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + nameFlag: "example", + dnsNameFlag: "example.com", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + Name: utils.Ptr("example"), + DnsName: utils.Ptr("example.com"), + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + nameFlag: "", + dnsNameFlag: "", + defaultTTLFlag: "0", + aclFlag: "", + typeFlag: "", + primaryFlag: "", + retryTimeFlag: "0", + refreshTimeFlag: "0", + negativeCacheFlag: "0", + isReverseZoneFlag: "false", + expireTimeFlag: "0", + descriptionFlag: "", + contactEmailFlag: "", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + Name: utils.Ptr(""), + DnsName: utils.Ptr(""), + DefaultTTL: utils.Ptr(int64(0)), + Primaries: utils.Ptr([]string{}), + Acl: utils.Ptr(""), + Type: utils.Ptr(""), + RetryTime: utils.Ptr(int64(0)), + RefreshTime: utils.Ptr(int64(0)), + NegativeCache: utils.Ptr(int64(0)), + IsReverseZone: utils.Ptr(false), + ExpireTime: utils.Ptr(int64(0)), + Description: utils.Ptr(""), + ContactEmail: utils.Ptr(""), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "repeated primary flags", + flagValues: fixtureFlagValues(), + primaryFlagValues: []string{"1.2.3.4", "5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Primaries = utils.Ptr( + append(*model.Primaries, "1.2.3.4", "5.6.7.8"), + ) + }), + }, + { + description: "repeated primary flags with list value", + flagValues: fixtureFlagValues(), + primaryFlagValues: []string{"1.2.3.4,5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Primaries = utils.Ptr( + append(*model.Primaries, "1.2.3.4", "5.6.7.8"), + ) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.primaryFlagValues { + err := cmd.Flags().Set(primaryFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", primaryFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiCreateZoneRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + Name: utils.Ptr("example"), + DnsName: utils.Ptr("example.com"), + }, + expectedRequest: testClient.CreateZone(testCtx, testProjectId). + CreateZonePayload(dns.CreateZonePayload{ + Name: utils.Ptr("example"), + DnsName: utils.Ptr("example.com"), + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/delete/delete.go b/internal/cmd/dns/zone/delete/delete.go new file mode 100644 index 00000000..843fd7f3 --- /dev/null +++ b/internal/cmd/dns/zone/delete/delete.go @@ -0,0 +1,93 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" +) + +type flagModel struct { + ProjectId string + ZoneId string +} + +var Cmd = &cobra.Command{ + Use: "delete", + Short: "Delete a DNS zone", + Long: "Delete a DNS zone", + Example: `$ stackit dns zone delete --project-id xxx --zone-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + if err != nil { + return err + } + _, err = req.Execute() + if err != nil { + return fmt.Errorf("delete DNS zone: %w", err) + } + + // Wait for async operation + _, err = wait.DeleteZoneWaitHandler(ctx, apiClient, model.ProjectId, model.ZoneId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS zone deletion: %w", err) + } + + fmt.Println("Zone deleted") + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiDeleteZoneRequest { + req := apiClient.DeleteZone(ctx, model.ProjectId, model.ZoneId) + return req +} diff --git a/internal/cmd/dns/zone/delete/delete_test.go b/internal/cmd/dns/zone/delete/delete_test.go new file mode 100644 index 00000000..87a75a9f --- /dev/null +++ b/internal/cmd/dns/zone/delete/delete_test.go @@ -0,0 +1,193 @@ +package delete + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiDeleteZoneRequest)) dns.ApiDeleteZoneRequest { + request := testClient.DeleteZone(testCtx, testProjectId, testZoneId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + isValid bool + expectedRequest dns.ApiDeleteZoneRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + isValid: true, + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/describe/describe.go b/internal/cmd/dns/zone/describe/describe.go new file mode 100644 index 00000000..fea57332 --- /dev/null +++ b/internal/cmd/dns/zone/describe/describe.go @@ -0,0 +1,90 @@ +package describe + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" +) + +type flagModel struct { + ProjectId string + ZoneId string +} + +var Cmd = &cobra.Command{ + Use: "describe", + Short: "Get details of a DNS zone", + Long: "Get details of a DNS zone", + Example: `$ stackit dns zone describe --project-id xxx --zone-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("read DNS zone: %w", err) + } + zone := *resp.Zone + + // Show details + details, err := json.MarshalIndent(zone, "", " ") + if err != nil { + return fmt.Errorf("marshal DNS zone: %w", err) + } + fmt.Println(string(details)) + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiGetZoneRequest { + req := apiClient.GetZone(ctx, model.ProjectId, model.ZoneId) + return req +} diff --git a/internal/cmd/dns/zone/describe/describe_test.go b/internal/cmd/dns/zone/describe/describe_test.go new file mode 100644 index 00000000..6023afcb --- /dev/null +++ b/internal/cmd/dns/zone/describe/describe_test.go @@ -0,0 +1,193 @@ +package describe + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiGetZoneRequest)) dns.ApiGetZoneRequest { + request := testClient.GetZone(testCtx, testProjectId, testZoneId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + isValid bool + expectedRequest dns.ApiGetZoneRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + isValid: true, + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/list/list.go b/internal/cmd/dns/zone/list/list.go new file mode 100644 index 00000000..eee92bcf --- /dev/null +++ b/internal/cmd/dns/zone/list/list.go @@ -0,0 +1,114 @@ +package list + +import ( + "context" + "fmt" + "strings" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +const ( + projectIdFlag = "project-id" + nameLikeFlag = "name-like" + activeFlag = "is-active" + orderByNameFlag = "order-by-name" +) + +type flagModel struct { + ProjectId string + NameLike *string + Active *bool + OrderByName *string +} + +var Cmd = &cobra.Command{ + Use: "list", + Short: "List all DNS zones", + Long: "List all DNS zones", + Example: `$ stackit dns zone list --project-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("get DNS zones: %w", err) + } + zones := *resp.Zones + if len(zones) == 0 { + fmt.Printf("No zones found for project with ID %s\n", model.ProjectId) + return nil + } + + // Show output as table + table := tables.NewTable() + table.SetHeader("ID", "NAME", "DNS_NAME", "STATE") + for _, zone := range zones { + table.AddRow(*zone.Id, *zone.Name, *zone.DnsName, *zone.State) + } + table.Render() + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + activeFlagOptions := []string{"true", "false"} + orderByNameFlagOptions := []string{"asc", "desc"} + + cmd.Flags().String(nameLikeFlag, "", "Filter by name") + cmd.Flags().Var(flags.EnumBoolFlag(), activeFlag, fmt.Sprintf("Filter by active status, one of %q", activeFlagOptions)) + cmd.Flags().Var(flags.EnumFlag(true, orderByNameFlagOptions...), orderByNameFlag, fmt.Sprintf("Order by name, one of %q", orderByNameFlagOptions)) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + NameLike: utils.FlagToStringPointer(cmd, nameLikeFlag), + Active: utils.FlagToBoolPointer(cmd, activeFlag), + OrderByName: utils.FlagToStringPointer(cmd, orderByNameFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiGetZonesRequest { + req := apiClient.GetZones(ctx, model.ProjectId) + if model.NameLike != nil { + req = req.NameLike(*model.NameLike) + } + if model.Active != nil { + req = req.ActiveEq(*model.Active) + } + if model.OrderByName != nil { + req = req.OrderByName(strings.ToUpper(*model.OrderByName)) + } + return req +} diff --git a/internal/cmd/dns/zone/list/list_test.go b/internal/cmd/dns/zone/list/list_test.go new file mode 100644 index 00000000..8992c872 --- /dev/null +++ b/internal/cmd/dns/zone/list/list_test.go @@ -0,0 +1,252 @@ +package list + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + nameLikeFlag: "some-pattern", + activeFlag: "true", + orderByNameFlag: "asc", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + NameLike: utils.Ptr("some-pattern"), + Active: utils.Ptr(true), + OrderByName: utils.Ptr("asc"), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiGetZonesRequest)) dns.ApiGetZonesRequest { + request := testClient.GetZones(testCtx, testProjectId) + request = request.NameLike("some-pattern") + request = request.ActiveEq(true) + request = request.OrderByName("ASC") + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "name like empty", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[nameLikeFlag] = "" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.NameLike = utils.Ptr("") + }), + }, + { + description: "is active = false", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "false" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Active = utils.Ptr(false) + }), + }, + { + description: "is active invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "" + }), + isValid: false, + }, + { + description: "is active invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[activeFlag] = "invalid" + }), + isValid: false, + }, + { + description: "order by name desc", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "desc" + }), + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.OrderByName = utils.Ptr("desc") + }), + }, + { + description: "order by name invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "" + }), + isValid: false, + }, + { + description: "order by name invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[orderByNameFlag] = "invalid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiGetZonesRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + }, + expectedRequest: testClient.GetZones(testCtx, testProjectId), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/update/update.go b/internal/cmd/dns/zone/update/update.go new file mode 100644 index 00000000..31bf2522 --- /dev/null +++ b/internal/cmd/dns/zone/update/update.go @@ -0,0 +1,145 @@ +package update + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/dns/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/dns" + "github.com/stackitcloud/stackit-sdk-go/services/dns/wait" +) + +type flagModel struct { + ProjectId string + ZoneId string + Name *string + DefaultTTL *int64 + Primaries *[]string + Acl *string + RetryTime *int64 + RefreshTime *int64 + NegativeCache *int64 + ExpireTime *int64 + Description *string + ContactEmail *string +} + +const ( + projectIdFlag = "project-id" + zoneIdFlag = "zone-id" + nameFlag = "name" + defaultTTLFlag = "default-ttl" + primaryFlag = "primary" + aclFlag = "acl" + retryTimeFlag = "retry-time" + refreshTimeFlag = "refresh-time" + negativeCacheFlag = "negative-cache" + expireTimeFlag = "expire-time" + descriptionFlag = "description" + contactEmailFlag = "contact-email" +) + +var Cmd = &cobra.Command{ + Use: "update", + Short: "Updates a DNS zone", + Long: "Updates a DNS zone. Performs a partial update; fields not provided are kept unchanged", + Example: `$ stackit dns zone update --project-id xxx --zone-id xxx --name my-zone --dns-name my-zone.com`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + if err != nil { + return err + } + _, err = req.Execute() + if err != nil { + return fmt.Errorf("update DNS zone: %w", err) + } + + // Wait for async operation + _, err = wait.UpdateZoneWaitHandler(ctx, apiClient, model.ProjectId, model.ZoneId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for DNS zone update: %w", err) + } + + fmt.Println("Zone updated") + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), zoneIdFlag, "Zone ID") + cmd.Flags().String(nameFlag, "", "User given name of the zone") + cmd.Flags().Int64(defaultTTLFlag, 1000, "Default time to live") + cmd.Flags().StringSlice(primaryFlag, []string{}, "Primary name server for secondary zone") + cmd.Flags().String(aclFlag, "", "Access control list") + cmd.Flags().Int64(retryTimeFlag, 0, "Retry time") + cmd.Flags().Int64(refreshTimeFlag, 0, "Refresh time") + cmd.Flags().Int64(negativeCacheFlag, 0, "Negative cache") + cmd.Flags().Int64(expireTimeFlag, 0, "Expire time") + cmd.Flags().String(descriptionFlag, "", "Description of the zone") + cmd.Flags().String(contactEmailFlag, "", "Contact email for the zone") + + err := utils.MarkFlagsRequired(cmd, zoneIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + ZoneId: utils.FlagToStringValue(cmd, zoneIdFlag), + Name: utils.FlagToStringPointer(cmd, nameFlag), + DefaultTTL: utils.FlagToInt64Pointer(cmd, defaultTTLFlag), + Primaries: utils.FlagToStringSlicePointer(cmd, primaryFlag), + Acl: utils.FlagToStringPointer(cmd, aclFlag), + RetryTime: utils.FlagToInt64Pointer(cmd, retryTimeFlag), + RefreshTime: utils.FlagToInt64Pointer(cmd, refreshTimeFlag), + NegativeCache: utils.FlagToInt64Pointer(cmd, negativeCacheFlag), + ExpireTime: utils.FlagToInt64Pointer(cmd, expireTimeFlag), + Description: utils.FlagToStringPointer(cmd, descriptionFlag), + ContactEmail: utils.FlagToStringPointer(cmd, contactEmailFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *dns.APIClient) dns.ApiUpdateZoneRequest { + req := apiClient.UpdateZone(ctx, model.ProjectId, model.ZoneId) + req = req.UpdateZonePayload(dns.UpdateZonePayload{ + Name: model.Name, + DefaultTTL: model.DefaultTTL, + Primaries: model.Primaries, + Acl: model.Acl, + RetryTime: model.RetryTime, + RefreshTime: model.RefreshTime, + NegativeCache: model.NegativeCache, + ExpireTime: model.ExpireTime, + Description: model.Description, + ContactEmail: model.ContactEmail, + }) + return req +} diff --git a/internal/cmd/dns/zone/update/update_test.go b/internal/cmd/dns/zone/update/update_test.go new file mode 100644 index 00000000..359a0f75 --- /dev/null +++ b/internal/cmd/dns/zone/update/update_test.go @@ -0,0 +1,310 @@ +package update + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/dns" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &dns.APIClient{} +var testProjectId = uuid.NewString() +var testZoneId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + nameFlag: "example", + defaultTTLFlag: "3600", + aclFlag: "0.0.0.0/0", + primaryFlag: "1.1.1.1", + retryTimeFlag: "600", + refreshTimeFlag: "3600", + negativeCacheFlag: "60", + expireTimeFlag: "36000000", + descriptionFlag: "Example", + contactEmailFlag: "example@example.com", + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr("example"), + DefaultTTL: utils.Ptr(int64(3600)), + Primaries: utils.Ptr([]string{"1.1.1.1"}), + Acl: utils.Ptr("0.0.0.0/0"), + RetryTime: utils.Ptr(int64(600)), + RefreshTime: utils.Ptr(int64(3600)), + NegativeCache: utils.Ptr(int64(60)), + ExpireTime: utils.Ptr(int64(36000000)), + Description: utils.Ptr("Example"), + ContactEmail: utils.Ptr("example@example.com"), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *dns.ApiUpdateZoneRequest)) dns.ApiUpdateZoneRequest { + request := testClient.UpdateZone(testCtx, testProjectId, testZoneId) + request = request.UpdateZonePayload(dns.UpdateZonePayload{ + Name: utils.Ptr("example"), + DefaultTTL: utils.Ptr(int64(3600)), + Primaries: utils.Ptr([]string{"1.1.1.1"}), + Acl: utils.Ptr("0.0.0.0/0"), + RetryTime: utils.Ptr(int64(600)), + RefreshTime: utils.Ptr(int64(3600)), + NegativeCache: utils.Ptr(int64(60)), + ExpireTime: utils.Ptr(int64(36000000)), + Description: utils.Ptr("Example"), + ContactEmail: utils.Ptr("example@example.com"), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + primaryFlagValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + zoneIdFlag: testZoneId, + nameFlag: "", + defaultTTLFlag: "0", + aclFlag: "", + primaryFlag: "", + retryTimeFlag: "0", + refreshTimeFlag: "0", + negativeCacheFlag: "0", + expireTimeFlag: "0", + descriptionFlag: "", + contactEmailFlag: "", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + Name: utils.Ptr(""), + DefaultTTL: utils.Ptr(int64(0)), + Primaries: utils.Ptr([]string{}), + Acl: utils.Ptr(""), + RetryTime: utils.Ptr(int64(0)), + RefreshTime: utils.Ptr(int64(0)), + NegativeCache: utils.Ptr(int64(0)), + ExpireTime: utils.Ptr(int64(0)), + Description: utils.Ptr(""), + ContactEmail: utils.Ptr(""), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "zone id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, zoneIdFlag) + }), + isValid: false, + }, + { + description: "zone id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "" + }), + isValid: false, + }, + { + description: "zone id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[zoneIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "repeated primary flags", + flagValues: fixtureFlagValues(), + primaryFlagValues: []string{"1.2.3.4", "5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Primaries = utils.Ptr( + append(*model.Primaries, "1.2.3.4", "5.6.7.8"), + ) + }), + }, + { + description: "repeated primary flags with list value", + flagValues: fixtureFlagValues(), + primaryFlagValues: []string{"1.2.3.4,5.6.7.8"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Primaries = utils.Ptr( + append(*model.Primaries, "1.2.3.4", "5.6.7.8"), + ) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.primaryFlagValues { + err := cmd.Flags().Set(primaryFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", primaryFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest dns.ApiUpdateZoneRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + ZoneId: testZoneId, + }, + expectedRequest: testClient.UpdateZone(testCtx, testProjectId, testZoneId). + UpdateZonePayload(dns.UpdateZonePayload{}), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/dns/zone/zone.go b/internal/cmd/dns/zone/zone.go new file mode 100644 index 00000000..385c97b5 --- /dev/null +++ b/internal/cmd/dns/zone/zone.go @@ -0,0 +1,29 @@ +package zone + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone/list" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns/zone/update" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "zone", + Short: "Provides functionality for DNS zone", + Long: "Provides functionality for DNS zone", + Example: fmt.Sprintf("%s\n%s", list.Cmd.Example, create.Cmd.Example), +} + +func init() { + // Add all direct child commands + Cmd.AddCommand(list.Cmd) + Cmd.AddCommand(create.Cmd) + Cmd.AddCommand(describe.Cmd) + Cmd.AddCommand(update.Cmd) + Cmd.AddCommand(delete.Cmd) +} diff --git a/internal/cmd/postgresql/credential/create/create.go b/internal/cmd/postgresql/credential/create/create.go new file mode 100644 index 00000000..dd59020a --- /dev/null +++ b/internal/cmd/postgresql/credential/create/create.go @@ -0,0 +1,83 @@ +package create + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" +) + +type flagModel struct { + ProjectId string + InstanceId string +} + +var Cmd = &cobra.Command{ + Use: "create", + Short: "Create credentials for a PostgreSQL instance", + Long: "Create credentials for a PostgreSQL instance", + Example: `$ stackit postgresql credential create --project-id xxx --instance-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("create PostgreSQL credentials: %w", err) + } + + fmt.Printf("Created credentials with ID %s\n", *resp.Id) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiCreateCredentialsRequest { + req := apiClient.CreateCredentials(ctx, model.ProjectId, model.InstanceId) + return req +} diff --git a/internal/cmd/postgresql/credential/create/create_test.go b/internal/cmd/postgresql/credential/create/create_test.go new file mode 100644 index 00000000..8a460f44 --- /dev/null +++ b/internal/cmd/postgresql/credential/create/create_test.go @@ -0,0 +1,191 @@ +package create + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiCreateCredentialsRequest)) postgresql.ApiCreateCredentialsRequest { + request := testClient.CreateCredentials(testCtx, testProjectId, testInstanceId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiCreateCredentialsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/credential/credential.go b/internal/cmd/postgresql/credential/credential.go new file mode 100644 index 00000000..70d02346 --- /dev/null +++ b/internal/cmd/postgresql/credential/credential.go @@ -0,0 +1,26 @@ +package credential + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/credential/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/credential/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/credential/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/credential/list" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "credential", + Short: "Provides functionality for PostgreSQL credentials", + Long: "Provides functionality for PostgreSQL credentials", + Example: fmt.Sprintf("%s\n%s", create.Cmd.Example, describe.Cmd.Example), +} + +func init() { + Cmd.AddCommand(create.Cmd) + Cmd.AddCommand(delete.Cmd) + Cmd.AddCommand(describe.Cmd) + Cmd.AddCommand(list.Cmd) +} diff --git a/internal/cmd/postgresql/credential/delete/delete.go b/internal/cmd/postgresql/credential/delete/delete.go new file mode 100644 index 00000000..ed645036 --- /dev/null +++ b/internal/cmd/postgresql/credential/delete/delete.go @@ -0,0 +1,89 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" + credentialsIdFlag = "credentials-id" +) + +type flagModel struct { + ProjectId string + InstanceId string + CredentialsId string +} + +var Cmd = &cobra.Command{ + Use: "delete", + Short: "Delete a PostgreSQL instance credential", + Long: "Delete a PostgreSQL instance credential", + Example: `$ stackit postgresql credential delete --project-id xxx --instance-id xxx --credentials-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + err = req.Execute() + if err != nil { + return fmt.Errorf("delete PostgreSQL credentials: %w", err) + } + + fmt.Printf("Deleted credentials with ID %s\n", model.CredentialsId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + cmd.Flags().Var(flags.UUIDFlag(), credentialsIdFlag, "Credentials ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) + err = utils.MarkFlagsRequired(cmd, credentialsIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + CredentialsId: utils.FlagToStringValue(cmd, credentialsIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiDeleteCredentialsRequest { + req := apiClient.DeleteCredentials(ctx, model.ProjectId, model.InstanceId, model.CredentialsId) + return req +} diff --git a/internal/cmd/postgresql/credential/delete/delete_test.go b/internal/cmd/postgresql/credential/delete/delete_test.go new file mode 100644 index 00000000..74517b1a --- /dev/null +++ b/internal/cmd/postgresql/credential/delete/delete_test.go @@ -0,0 +1,215 @@ +package delete + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() +var testCredentialsId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + credentialsIdFlag: testCredentialsId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + CredentialsId: testCredentialsId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiDeleteCredentialsRequest)) postgresql.ApiDeleteCredentialsRequest { + request := testClient.DeleteCredentials(testCtx, testProjectId, testInstanceId, testCredentialsId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "credentials id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, credentialsIdFlag) + }), + isValid: false, + }, + { + description: "credentials id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[credentialsIdFlag] = "" + }), + isValid: false, + }, + { + description: "credentials id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[credentialsIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiDeleteCredentialsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/credential/describe/describe.go b/internal/cmd/postgresql/credential/describe/describe.go new file mode 100644 index 00000000..ddd7dc09 --- /dev/null +++ b/internal/cmd/postgresql/credential/describe/describe.go @@ -0,0 +1,96 @@ +package describe + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" + credentialsIdFlag = "credentials-id" +) + +type flagModel struct { + ProjectId string + InstanceId string + CredentialsId string +} + +var Cmd = &cobra.Command{ + Use: "describe", + Short: "Get details of a PostgreSQL instance credential", + Long: "Get details of a PostgreSQL instance credential", + Example: `$ stackit postgresql credential describe --project-id xxx --instance-id xxx --credentials-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("describe PostgreSQL credentials: %w", err) + } + + // Show details + details, err := json.MarshalIndent(resp, "", " ") + if err != nil { + return fmt.Errorf("marshal PostgreSQL credentials: %w", err) + } + fmt.Println(string(details)) + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + cmd.Flags().Var(flags.UUIDFlag(), credentialsIdFlag, "Credentials ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) + err = utils.MarkFlagsRequired(cmd, credentialsIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + CredentialsId: utils.FlagToStringValue(cmd, credentialsIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiGetCredentialsRequest { + req := apiClient.GetCredentials(ctx, model.ProjectId, model.InstanceId, model.CredentialsId) + return req +} diff --git a/internal/cmd/postgresql/credential/describe/describe_test.go b/internal/cmd/postgresql/credential/describe/describe_test.go new file mode 100644 index 00000000..3ed48019 --- /dev/null +++ b/internal/cmd/postgresql/credential/describe/describe_test.go @@ -0,0 +1,215 @@ +package describe + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() +var testCredentialsId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + credentialsIdFlag: testCredentialsId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + CredentialsId: testCredentialsId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiGetCredentialsRequest)) postgresql.ApiGetCredentialsRequest { + request := testClient.GetCredentials(testCtx, testProjectId, testInstanceId, testCredentialsId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "credentials id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, credentialsIdFlag) + }), + isValid: false, + }, + { + description: "credentials id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[credentialsIdFlag] = "" + }), + isValid: false, + }, + { + description: "credentials id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[credentialsIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiGetCredentialsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/credential/list/list.go b/internal/cmd/postgresql/credential/list/list.go new file mode 100644 index 00000000..261fed45 --- /dev/null +++ b/internal/cmd/postgresql/credential/list/list.go @@ -0,0 +1,96 @@ +package list + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" +) + +type flagModel struct { + ProjectId string + InstanceId string +} + +var Cmd = &cobra.Command{ + Use: "list", + Short: "List all credentials IDs for a PostgreSQL instance", + Long: "List all credentials IDs for a PostgreSQL instance", + Example: `$ stackit postgresql credential list --project-id xxx --instance-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("list PostgreSQL credentials: %w", err) + } + credentials := *resp.CredentialsList + if len(credentials) == 0 { + fmt.Printf("No credentials found for instance with ID %s\n", model.InstanceId) + return nil + } + + // Show output as table + table := tables.NewTable() + table.SetHeader("ID") + for _, i := range credentials { + table.AddRow(*i.Id) + } + table.Render() + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiGetCredentialsIdsRequest { + req := apiClient.GetCredentialsIds(ctx, model.ProjectId, model.InstanceId) + return req +} diff --git a/internal/cmd/postgresql/credential/list/list_test.go b/internal/cmd/postgresql/credential/list/list_test.go new file mode 100644 index 00000000..867725ba --- /dev/null +++ b/internal/cmd/postgresql/credential/list/list_test.go @@ -0,0 +1,191 @@ +package list + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiGetCredentialsIdsRequest)) postgresql.ApiGetCredentialsIdsRequest { + request := testClient.GetCredentialsIds(testCtx, testProjectId, testInstanceId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiGetCredentialsIdsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/instance/create/create.go b/internal/cmd/postgresql/instance/create/create.go new file mode 100644 index 00000000..5e0fc290 --- /dev/null +++ b/internal/cmd/postgresql/instance/create/create.go @@ -0,0 +1,187 @@ +package create + +import ( + "context" + "fmt" + "strings" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + postgresqlUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql/wait" +) + +const ( + projectIdFlag = "project-id" + instanceNameFlag = "name" + enableMonitoringFlag = "enable-monitoring" + graphiteFlag = "graphite" + metricsFrequencyFlag = "metrics-frequency" + metricsPrefixFlag = "metrics-prefix" + monitoringInstanceIdFlag = "monitoring-instance-id" + pluginFlag = "plugin" + sgwAclFlag = "acl" + syslogFlag = "syslog" + planIdFlag = "plan-id" + planNameFlag = "plan-name" + versionFlag = "version" +) + +type flagModel struct { + ProjectId string + PlanName string + Version string + + InstanceName *string + EnableMonitoring *bool + Graphite *string + MetricsFrequency *int64 + MetricsPrefix *string + MonitoringInstanceId *string + Plugin *[]string + SgwAcl *[]string + Syslog *[]string + PlanId *string +} + +var Cmd = &cobra.Command{ + Use: "create", + Short: "Creates a PostgreSQL instance", + Long: "Creates a PostgreSQL instance", + Example: `$ stackit postgresql instance create --project-id xxx --name my-instance --plan-name plan-name --version version`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req, err := buildRequest(ctx, model, apiClient) + if err != nil { + return fmt.Errorf("build PostgreSQL instance creation request: %w", err) + } + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("create PostgreSQL instance: %w", err) + } + + // Wait for async operation + instanceId := *resp.InstanceId + _, err = wait.CreateInstanceWaitHandler(ctx, apiClient, model.ProjectId, instanceId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for PostgreSQL instance creation: %w", err) + } + + fmt.Printf("Created instance with ID %s\n", instanceId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().StringP(instanceNameFlag, "n", "", "Instance name") + cmd.Flags().Bool(enableMonitoringFlag, false, "Enable monitoring") + cmd.Flags().String(graphiteFlag, "", "Graphite host") + cmd.Flags().Int64(metricsFrequencyFlag, 0, "Metrics frequency") + cmd.Flags().String(metricsPrefixFlag, "", "Metrics prefix") + cmd.Flags().Var(flags.UUIDFlag(), monitoringInstanceIdFlag, "Monitoring instance ID") + cmd.Flags().StringSlice(pluginFlag, []string{}, "Plugin") + cmd.Flags().Var(flags.CIDRSliceFlag(), sgwAclFlag, "List of IP networks in CIDR notation which are allowed to access this instance") + cmd.Flags().StringSlice(syslogFlag, []string{}, "Syslog") + cmd.Flags().Var(flags.UUIDFlag(), planIdFlag, "Plan ID") + cmd.Flags().String(planNameFlag, "", "Plan name") + cmd.Flags().String(versionFlag, "", "Instance PostgreSQL version") + + cmd.MarkFlagsMutuallyExclusive(planIdFlag, planNameFlag) + cmd.MarkFlagsMutuallyExclusive(planIdFlag, versionFlag) + cmd.MarkFlagsRequiredTogether(planNameFlag, versionFlag) + + err := utils.MarkFlagsRequired(cmd, instanceNameFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + planId := utils.FlagToStringPointer(cmd, planIdFlag) + planName := utils.FlagToStringValue(cmd, planNameFlag) + version := utils.FlagToStringValue(cmd, versionFlag) + + if planId == nil && planName == "" && version == "" { + return nil, fmt.Errorf("either plan-id or plan-name and version must be set") + } + if planId != nil && (planName != "" || version != "") { + return nil, fmt.Errorf("please specify either plan-id or plan-name and version but not both") + } + + return &flagModel{ + ProjectId: projectId, + InstanceName: utils.FlagToStringPointer(cmd, instanceNameFlag), + EnableMonitoring: utils.FlagToBoolPointer(cmd, enableMonitoringFlag), + MonitoringInstanceId: utils.FlagToStringPointer(cmd, monitoringInstanceIdFlag), + Graphite: utils.FlagToStringPointer(cmd, graphiteFlag), + MetricsFrequency: utils.FlagToInt64Pointer(cmd, metricsFrequencyFlag), + MetricsPrefix: utils.FlagToStringPointer(cmd, metricsPrefixFlag), + Plugin: utils.FlagToStringSlicePointer(cmd, pluginFlag), + SgwAcl: utils.FlagToStringSlicePointer(cmd, sgwAclFlag), + Syslog: utils.FlagToStringSlicePointer(cmd, syslogFlag), + PlanId: planId, + PlanName: planName, + Version: version, + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient postgresqlUtils.PostgreSQLClient) (postgresql.ApiCreateInstanceRequest, error) { + req := apiClient.CreateInstance(ctx, model.ProjectId) + + var planId *string + var err error + if model.PlanId == nil { + planId, err = postgresqlUtils.LoadPlanId(ctx, apiClient, model.ProjectId, model.PlanName, model.Version) + if err != nil { + return req, fmt.Errorf("load plan ID: %w", err) + } + } else { + planId = model.PlanId + } + + var sgwAcl *string + if model.SgwAcl != nil { + sgwAcl = utils.Ptr(strings.Join(*model.SgwAcl, ",")) + } + + req = req.CreateInstancePayload(postgresql.CreateInstancePayload{ + InstanceName: model.InstanceName, + Parameters: &postgresql.InstanceParameters{ + EnableMonitoring: model.EnableMonitoring, + Graphite: model.Graphite, + MonitoringInstanceId: model.MonitoringInstanceId, + MetricsFrequency: model.MetricsFrequency, + MetricsPrefix: model.MetricsPrefix, + Plugins: model.Plugin, + SgwAcl: sgwAcl, + Syslog: model.Syslog, + }, + PlanId: planId, + }) + return req, nil +} diff --git a/internal/cmd/postgresql/instance/create/create_test.go b/internal/cmd/postgresql/instance/create/create_test.go new file mode 100644 index 00000000..0391b21d --- /dev/null +++ b/internal/cmd/postgresql/instance/create/create_test.go @@ -0,0 +1,421 @@ +package create + +import ( + "context" + "fmt" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} + +type postgreSQLClientMocked struct { + returnError bool + getOfferingsResp *postgresql.OfferingList +} + +func (c *postgreSQLClientMocked) CreateInstance(_ context.Context, _ string) postgresql.ApiCreateInstanceRequest { + return postgresql.ApiCreateInstanceRequest{} +} + +func (c *postgreSQLClientMocked) UpdateInstance(_ context.Context, _, _ string) postgresql.ApiUpdateInstanceRequest { + return postgresql.ApiUpdateInstanceRequest{} +} + +func (c *postgreSQLClientMocked) GetOfferingsExecute(_ context.Context, _ string) (*postgresql.OfferingList, error) { + if c.returnError { + return nil, fmt.Errorf("get flavors failed") + } + return c.getOfferingsResp, nil +} + +var testProjectId = uuid.NewString() +var testPlanId = uuid.NewString() +var testMonitoringInstanceId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceNameFlag: "example-name", + enableMonitoringFlag: "true", + graphiteFlag: "example-graphite", + metricsFrequencyFlag: "100", + metricsPrefixFlag: "example-prefix", + monitoringInstanceIdFlag: testMonitoringInstanceId, + pluginFlag: "example-plugin", + sgwAclFlag: "198.51.100.14/24", + syslogFlag: "example-syslog", + planIdFlag: testPlanId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceName: utils.Ptr("example-name"), + EnableMonitoring: utils.Ptr(true), + Graphite: utils.Ptr("example-graphite"), + MetricsFrequency: utils.Ptr(int64(100)), + MetricsPrefix: utils.Ptr("example-prefix"), + MonitoringInstanceId: utils.Ptr(testMonitoringInstanceId), + Plugin: utils.Ptr([]string{"example-plugin"}), + SgwAcl: utils.Ptr([]string{"198.51.100.14/24"}), + Syslog: utils.Ptr([]string{"example-syslog"}), + PlanId: utils.Ptr(testPlanId), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiCreateInstanceRequest)) postgresql.ApiCreateInstanceRequest { + request := testClient.CreateInstance(testCtx, testProjectId) + request = request.CreateInstancePayload(postgresql.CreateInstancePayload{ + InstanceName: utils.Ptr("example-name"), + Parameters: &postgresql.InstanceParameters{ + EnableMonitoring: utils.Ptr(true), + Graphite: utils.Ptr("example-graphite"), + MetricsFrequency: utils.Ptr(int64(100)), + MetricsPrefix: utils.Ptr("example-prefix"), + MonitoringInstanceId: utils.Ptr(testMonitoringInstanceId), + Plugins: utils.Ptr([]string{"example-plugin"}), + SgwAcl: utils.Ptr("198.51.100.14/24"), + Syslog: utils.Ptr([]string{"example-syslog"}), + }, + PlanId: utils.Ptr(testPlanId), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + sgwAclValues []string + pluginValues []string + syslogValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + instanceNameFlag: "example-name", + planIdFlag: testPlanId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + InstanceName: utils.Ptr("example-name"), + PlanId: utils.Ptr(testPlanId), + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + planIdFlag: testPlanId, + instanceNameFlag: "", + enableMonitoringFlag: "false", + graphiteFlag: "", + metricsFrequencyFlag: "0", + metricsPrefixFlag: "", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + PlanId: utils.Ptr(testPlanId), + InstanceName: utils.Ptr(""), + EnableMonitoring: utils.Ptr(false), + Graphite: utils.Ptr(""), + MetricsFrequency: utils.Ptr(int64(0)), + MetricsPrefix: utils.Ptr(""), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "repeated acl flags", + flagValues: fixtureFlagValues(), + sgwAclValues: []string{"198.51.100.14/24", "198.51.100.14/32"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.SgwAcl = utils.Ptr( + append(*model.SgwAcl, "198.51.100.14/24", "198.51.100.14/32"), + ) + }), + }, + { + description: "repeated acl flag with list value", + flagValues: fixtureFlagValues(), + sgwAclValues: []string{"198.51.100.14/24,198.51.100.14/32"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.SgwAcl = utils.Ptr( + append(*model.SgwAcl, "198.51.100.14/24", "198.51.100.14/32"), + ) + }), + }, + { + description: "repeated plugin flags", + flagValues: fixtureFlagValues(), + pluginValues: []string{"example-plugin-1", "example-plugin-2"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Plugin = utils.Ptr( + append(*model.Plugin, "example-plugin-1", "example-plugin-2"), + ) + }), + }, + { + description: "repeated syslog flags", + flagValues: fixtureFlagValues(), + syslogValues: []string{"example-syslog-1", "example-syslog-2"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Syslog = utils.Ptr( + append(*model.Syslog, "example-syslog-1", "example-syslog-2"), + ) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.sgwAclValues { + err := cmd.Flags().Set(sgwAclFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", sgwAclFlag, value, err) + } + } + + for _, value := range tt.pluginValues { + err := cmd.Flags().Set(pluginFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", pluginFlag, value, err) + } + } + + for _, value := range tt.syslogValues { + err := cmd.Flags().Set(syslogFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", syslogFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiCreateInstanceRequest + getOfferingsFails bool + getOfferingsResp *postgresql.OfferingList + isValid bool + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "use plan name and version", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + expectedRequest: fixtureRequest(), + getOfferingsResp: &postgresql.OfferingList{ + Offerings: &[]postgresql.Offering{ + { + Version: utils.Ptr("example-version"), + Plans: &[]postgresql.Plan{ + { + Name: utils.Ptr("example-plan-name"), + Id: utils.Ptr(testPlanId), + }, + }, + }, + }, + }, + }, + { + description: "get offering fails", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + getOfferingsFails: true, + isValid: false, + }, + { + description: "plan name not found", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + getOfferingsResp: &postgresql.OfferingList{ + Offerings: &[]postgresql.Offering{ + { + Version: utils.Ptr("example-version"), + Plans: &[]postgresql.Plan{ + { + Name: utils.Ptr("other-plan-name"), + Id: utils.Ptr(testPlanId), + }, + }, + }, + }, + }, + isValid: false, + }, + { + description: "required fields only", + model: &flagModel{ + ProjectId: testProjectId, + PlanId: utils.Ptr(testPlanId), + }, + expectedRequest: testClient.CreateInstance(testCtx, testProjectId). + CreateInstancePayload(postgresql.CreateInstancePayload{PlanId: utils.Ptr(testPlanId), Parameters: &postgresql.InstanceParameters{}}), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + client := &postgreSQLClientMocked{ + returnError: tt.getOfferingsFails, + getOfferingsResp: tt.getOfferingsResp, + } + request, err := buildRequest(testCtx, tt.model, client) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error building request: %v", err) + } + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.IgnoreFields(postgresql.ApiCreateInstanceRequest{}, "apiService", "ctx", "projectId"), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/instance/delete/delete.go b/internal/cmd/postgresql/instance/delete/delete.go new file mode 100644 index 00000000..ae5855a1 --- /dev/null +++ b/internal/cmd/postgresql/instance/delete/delete.go @@ -0,0 +1,89 @@ +package delete + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql/wait" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" +) + +type flagModel struct { + ProjectId string + InstanceId string +} + +var Cmd = &cobra.Command{ + Use: "delete", + Short: "Delete a PostgreSQL instance", + Long: "Delete a PostgreSQL instance", + Example: `$ stackit postgresql instance delete --project-id xxx --instance-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + err = req.Execute() + if err != nil { + return fmt.Errorf("delete PostgreSQL instance: %w", err) + } + + // Wait for async operation + _, err = wait.DeleteInstanceWaitHandler(ctx, apiClient, model.ProjectId, model.InstanceId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for PostgreSQL instance deletion: %w", err) + } + + fmt.Printf("Deleted instance with ID %s\n", model.InstanceId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiDeleteInstanceRequest { + req := apiClient.DeleteInstance(ctx, model.ProjectId, model.InstanceId) + return req +} diff --git a/internal/cmd/postgresql/instance/delete/delete_test.go b/internal/cmd/postgresql/instance/delete/delete_test.go new file mode 100644 index 00000000..a23296b7 --- /dev/null +++ b/internal/cmd/postgresql/instance/delete/delete_test.go @@ -0,0 +1,191 @@ +package delete + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiDeleteInstanceRequest)) postgresql.ApiDeleteInstanceRequest { + request := testClient.DeleteInstance(testCtx, testProjectId, testInstanceId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiDeleteInstanceRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/instance/describe/describe.go b/internal/cmd/postgresql/instance/describe/describe.go new file mode 100644 index 00000000..9b9ab88c --- /dev/null +++ b/internal/cmd/postgresql/instance/describe/describe.go @@ -0,0 +1,89 @@ +package describe + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" +) + +type flagModel struct { + ProjectId string + InstanceId string +} + +var Cmd = &cobra.Command{ + Use: "describe", + Short: "Get details of a PostgreSQL instance", + Long: "Get details of a PostgreSQL instance", + Example: `$ stackit postgresql instance describe --project-id xxx --instance-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("read PostgreSQL instance: %w", err) + } + + // Show details + details, err := json.MarshalIndent(resp, "", " ") + if err != nil { + return fmt.Errorf("marshal PostgreSQL instance: %w", err) + } + fmt.Println(string(details)) + + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().Var(flags.UUIDFlag(), instanceIdFlag, "Instance ID") + + err := utils.MarkFlagsRequired(cmd, instanceIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiGetInstanceRequest { + req := apiClient.GetInstance(ctx, model.ProjectId, model.InstanceId) + return req +} diff --git a/internal/cmd/postgresql/instance/describe/describe_test.go b/internal/cmd/postgresql/instance/describe/describe_test.go new file mode 100644 index 00000000..a28005e1 --- /dev/null +++ b/internal/cmd/postgresql/instance/describe/describe_test.go @@ -0,0 +1,191 @@ +package describe + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() +var testInstanceId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiGetInstanceRequest)) postgresql.ApiGetInstanceRequest { + request := testClient.GetInstance(testCtx, testProjectId, testInstanceId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "instance id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, instanceIdFlag) + }), + isValid: false, + }, + { + description: "instance id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "" + }), + isValid: false, + }, + { + description: "instance id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[instanceIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiGetInstanceRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/instance/instance.go b/internal/cmd/postgresql/instance/instance.go new file mode 100644 index 00000000..6bb9f5f3 --- /dev/null +++ b/internal/cmd/postgresql/instance/instance.go @@ -0,0 +1,28 @@ +package instance + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance/create" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance/delete" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance/describe" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance/list" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance/update" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "instance", + Short: "Provides functionality for PostgreSQL instance", + Long: "Provides functionality for PostgreSQL instance", + Example: fmt.Sprintf("%s\n%s", create.Cmd.Example, list.Cmd.Example), +} + +func init() { + Cmd.AddCommand(create.Cmd) + Cmd.AddCommand(delete.Cmd) + Cmd.AddCommand(describe.Cmd) + Cmd.AddCommand(list.Cmd) + Cmd.AddCommand(update.Cmd) +} diff --git a/internal/cmd/postgresql/instance/list/list.go b/internal/cmd/postgresql/instance/list/list.go new file mode 100644 index 00000000..60b79200 --- /dev/null +++ b/internal/cmd/postgresql/instance/list/list.go @@ -0,0 +1,76 @@ +package list + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type flagModel struct { + ProjectId string +} + +var Cmd = &cobra.Command{ + Use: "list", + Short: "List all PostgreSQL instances", + Long: "List all PostgreSQL instances", + Example: `$ stackit postgresql instance list --project-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("get PostgreSQL instances: %w", err) + } + instances := *resp.Instances + if len(instances) == 0 { + fmt.Printf("No instances found for product with ID %s\n", model.ProjectId) + return nil + } + + // Show output as table + table := tables.NewTable() + table.SetHeader("ID", "NAME", "LAST_OPERATION.TYPE", "LAST_OPERATION.STATE") + for _, i := range instances { + table.AddRow(*i.InstanceId, *i.Name, *i.LastOperation.Type, *i.LastOperation.State) + } + table.Render() + + return nil + }, +} + +func parseFlags(_ *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiGetInstancesRequest { + req := apiClient.GetInstances(ctx, model.ProjectId) + return req +} diff --git a/internal/cmd/postgresql/instance/list/list_test.go b/internal/cmd/postgresql/instance/list/list_test.go new file mode 100644 index 00000000..bc9bf61c --- /dev/null +++ b/internal/cmd/postgresql/instance/list/list_test.go @@ -0,0 +1,169 @@ +package list + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiGetInstancesRequest)) postgresql.ApiGetInstancesRequest { + request := testClient.GetInstances(testCtx, testProjectId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiGetInstancesRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/instance/update/update.go b/internal/cmd/postgresql/instance/update/update.go new file mode 100644 index 00000000..aa0db39b --- /dev/null +++ b/internal/cmd/postgresql/instance/update/update.go @@ -0,0 +1,293 @@ +package update + +import ( + "context" + "fmt" + "strings" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + postgresqlUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/utils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql/wait" +) + +const ( + projectIdFlag = "project-id" + instanceIdFlag = "instance-id" + instanceNameFlag = "name" + enableMonitoringFlag = "enable-monitoring" + graphiteFlag = "graphite" + metricsFrequencyFlag = "metrics-frequency" + metricsPrefixFlag = "metrics-prefix" + monitoringInstanceIdFlag = "monitoring-instance-id" + pluginFlag = "plugin" + sgwAclFlag = "acl" + syslogFlag = "syslog" + planIdFlag = "plan-id" + planNameFlag = "plan-name" + versionFlag = "version" +) + +type flagModel struct { + ProjectId string + InstanceId string + PlanName string + Version string + + EnableMonitoring *bool + Graphite *string + MetricsFrequency *int64 + MetricsPrefix *string + MonitoringInstanceId *string + Plugin *[]string + SgwAcl *[]string + Syslog *[]string + PlanId *string +} + +var Cmd = &cobra.Command{ + Use: "update", + Short: "Updates a PostgreSQL instance", + Long: "Updates a PostgreSQL instance", + Example: `$ stackit postgresql instance update --project-id xxx --instance-id xxx --plan-id xxx --acl xx.xx.xx.xx/xx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Get instance + instance, err := apiClient.GetInstanceExecute(ctx, model.ProjectId, model.InstanceId) + if err != nil { + return fmt.Errorf("get PostgreSQL instance: %w", err) + } + + // Call API + req, err := buildRequest(ctx, instance, model, apiClient) + if err != nil { + return fmt.Errorf("build PostgreSQL instance update request: %w", err) + } + err = req.Execute() + if err != nil { + return fmt.Errorf("update PostgreSQL instance: %w", err) + } + + // Wait for async operation + instanceId := model.InstanceId + _, err = wait.UpdateInstanceWaitHandler(ctx, apiClient, model.ProjectId, instanceId).WaitWithContext(ctx) + if err != nil { + return fmt.Errorf("wait for PostgreSQL instance update: %w", err) + } + + fmt.Printf("Updated instance with ID %s\n", instanceId) + return nil + }, +} + +func init() { + configureFlags(Cmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.Flags().StringP(instanceIdFlag, "i", "", "Instance ID") + cmd.Flags().Bool(enableMonitoringFlag, false, "Enable monitoring") + cmd.Flags().String(graphiteFlag, "", "Graphite host") + cmd.Flags().Int64(metricsFrequencyFlag, 0, "Metrics frequency") + cmd.Flags().String(metricsPrefixFlag, "", "Metrics prefix") + cmd.Flags().Var(flags.UUIDFlag(), monitoringInstanceIdFlag, "Monitoring instance ID") + cmd.Flags().StringSlice(pluginFlag, []string{}, "Plugin") + cmd.Flags().Var(flags.CIDRSliceFlag(), sgwAclFlag, "List of IP networks in CIDR notation which are allowed to access this instance") + cmd.Flags().StringSlice(syslogFlag, []string{}, "Syslog") + cmd.Flags().Var(flags.UUIDFlag(), planIdFlag, "Plan ID") + cmd.Flags().String(planNameFlag, "", "Plan name") + cmd.Flags().String(versionFlag, "", "Instance PostgreSQL version") + + cmd.MarkFlagsMutuallyExclusive(planIdFlag, planNameFlag) + cmd.MarkFlagsMutuallyExclusive(planIdFlag, versionFlag) + cmd.MarkFlagsRequiredTogether(planNameFlag, versionFlag) + + err := cmd.MarkFlagRequired(instanceIdFlag) + cobra.CheckErr(err) +} + +func parseFlags(cmd *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + planId := utils.FlagToStringPointer(cmd, planIdFlag) + planName := utils.FlagToStringValue(cmd, planNameFlag) + version := utils.FlagToStringValue(cmd, versionFlag) + + if planId != nil && (planName != "" || version != "") { + return nil, fmt.Errorf("please specify either plan-id or plan-name and version but not both") + } + + return &flagModel{ + ProjectId: projectId, + InstanceId: utils.FlagToStringValue(cmd, instanceIdFlag), + EnableMonitoring: utils.FlagToBoolPointer(cmd, enableMonitoringFlag), + MonitoringInstanceId: utils.FlagToStringPointer(cmd, monitoringInstanceIdFlag), + Graphite: utils.FlagToStringPointer(cmd, graphiteFlag), + MetricsFrequency: utils.FlagToInt64Pointer(cmd, metricsFrequencyFlag), + MetricsPrefix: utils.FlagToStringPointer(cmd, metricsPrefixFlag), + Plugin: utils.FlagToStringSlicePointer(cmd, pluginFlag), + SgwAcl: utils.FlagToStringSlicePointer(cmd, sgwAclFlag), + Syslog: utils.FlagToStringSlicePointer(cmd, syslogFlag), + PlanId: planId, + PlanName: planName, + Version: version, + }, nil +} + +func buildRequest(ctx context.Context, instance *postgresql.Instance, model *flagModel, apiClient postgresqlUtils.PostgreSQLClient) (postgresql.ApiUpdateInstanceRequest, error) { + req := apiClient.UpdateInstance(ctx, model.ProjectId, model.InstanceId) + + payload, err := buildCurrentPayload(instance) + if err != nil { + return req, fmt.Errorf("build payload from the current instance parameters: %w", err) + } + + // Override payload with the command parameters + var planId *string + if model.PlanId == nil && model.PlanName != "" && model.Version != "" { + planId, err = postgresqlUtils.LoadPlanId(ctx, apiClient, model.ProjectId, model.PlanName, model.Version) + if err != nil { + return req, fmt.Errorf("load plan ID: %w", err) + } + } else { + planId = model.PlanId + } + var sgwAcl *string + if model.SgwAcl != nil { + sgwAcl = utils.Ptr(strings.Join(*model.SgwAcl, ",")) + } + + if planId != nil { + payload.PlanId = planId + } + if model.EnableMonitoring != nil { + payload.Parameters.EnableMonitoring = model.EnableMonitoring + } + if model.Graphite != nil { + payload.Parameters.Graphite = model.Graphite + } + if model.MonitoringInstanceId != nil { + payload.Parameters.MonitoringInstanceId = model.MonitoringInstanceId + } + if model.MetricsFrequency != nil { + payload.Parameters.MetricsFrequency = model.MetricsFrequency + } + if model.MetricsPrefix != nil { + payload.Parameters.MetricsPrefix = model.MetricsPrefix + } + if model.Plugin != nil { + payload.Parameters.Plugins = model.Plugin + } + if model.SgwAcl != nil { + payload.Parameters.SgwAcl = sgwAcl + } + if model.Syslog != nil { + payload.Parameters.Syslog = model.Syslog + } + + req = req.UpdateInstancePayload(*payload) + return req, nil +} + +// Builds the payload from the current instance parameters +func buildCurrentPayload(instance *postgresql.Instance) (*postgresql.UpdateInstancePayload, error) { + if instance == nil { + return nil, fmt.Errorf("instance is nil") + } + + currentParameters := *instance.Parameters + var ok bool + var currentEnableMonitoring bool + var currentGraphite string + var currentMonitoringInstanceId string + var currentMetricsFrequency int64 + var currentMetricsPrefix string + var currentPlugins []string + var currentSyslog []string + var currentSgwAcl string + if currentParameters != nil { + if currentParameters["enable_monitoring"] != nil { + currentEnableMonitoring, ok = currentParameters["enable_monitoring"].(bool) + if !ok { + return nil, fmt.Errorf("parse enable_monitoring: type cannot be converted to bool") + } + } + if currentParameters["graphite"] != nil { + currentGraphite, ok = currentParameters["graphite"].(string) + if !ok { + return nil, fmt.Errorf("parse graphite: type cannot be converted to string") + } + } + if currentParameters["monitoring_instance_id"] != nil { + currentMonitoringInstanceId, ok = currentParameters["monitoring_instance_id"].(string) + if !ok { + return nil, fmt.Errorf("parse monitoring_instance_id: type cannot be converted to string") + } + } + if currentParameters["metrics_frequency"] != nil { + currentMetricsFrequency, ok = currentParameters["metrics_frequency"].(int64) + if !ok { + return nil, fmt.Errorf("parse metrics_frequency: type cannot be converted to int64") + } + } + if currentParameters["metrics_prefix"] != nil { + currentMetricsPrefix, ok = currentParameters["metrics_prefix"].(string) + if !ok { + return nil, fmt.Errorf("parse metrics_prefix: type cannot be converted to string") + } + } + if currentParameters["plugins"] != nil { + currentPlugins, ok = currentParameters["plugins"].([]string) + if !ok { + return nil, fmt.Errorf("parse plugins: type cannot be converted to []string") + } + } + if currentParameters["syslog"] != nil { + currentSyslog, ok = currentParameters["syslog"].([]string) + if !ok { + return nil, fmt.Errorf("parse syslog: type cannot be converted to []string") + } + } + if currentParameters["sgw_acl"] != nil { + currentSgwAcl, ok = currentParameters["sgw_acl"].(string) + if !ok { + return nil, fmt.Errorf("parse sgw_acl: type cannot be converted to string") + } + } + } + payload := &postgresql.UpdateInstancePayload{ + Parameters: &postgresql.InstanceParameters{ + EnableMonitoring: ¤tEnableMonitoring, + Graphite: ¤tGraphite, + MonitoringInstanceId: ¤tMonitoringInstanceId, + MetricsFrequency: ¤tMetricsFrequency, + MetricsPrefix: ¤tMetricsPrefix, + Plugins: ¤tPlugins, + Syslog: ¤tSyslog, + SgwAcl: ¤tSgwAcl, + }, + PlanId: instance.PlanId, + } + + return payload, nil +} diff --git a/internal/cmd/postgresql/instance/update/update_test.go b/internal/cmd/postgresql/instance/update/update_test.go new file mode 100644 index 00000000..20cad4fc --- /dev/null +++ b/internal/cmd/postgresql/instance/update/update_test.go @@ -0,0 +1,507 @@ +package update + +import ( + "context" + "fmt" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} + +type postgreSQLClientMocked struct { + returnError bool + getOfferingsResp *postgresql.OfferingList +} + +func (c *postgreSQLClientMocked) CreateInstance(_ context.Context, _ string) postgresql.ApiCreateInstanceRequest { + return postgresql.ApiCreateInstanceRequest{} +} + +func (c *postgreSQLClientMocked) UpdateInstance(_ context.Context, _, _ string) postgresql.ApiUpdateInstanceRequest { + return postgresql.ApiUpdateInstanceRequest{} +} + +func (c *postgreSQLClientMocked) GetOfferingsExecute(_ context.Context, _ string) (*postgresql.OfferingList, error) { + if c.returnError { + return nil, fmt.Errorf("get flavors failed") + } + return c.getOfferingsResp, nil +} + +var ( + testProjectId = uuid.NewString() + testInstanceId = uuid.NewString() + currentPlanId = uuid.NewString() + currentMonitoringInstanceIdValue = uuid.NewString() + updatedPlanIdValue = uuid.NewString() + updatedMonitoringInstanceIdValue = uuid.NewString() +) + +const ( + currentEnableMonitoringValue = false + currentGraphiteValue = "example-graphite" + currentMetricsFrequencyValue = int64(100) + currentMetricsPrefixValue = "example-prefix" + currentPluginValue = "example-plugin" + currentSgwAclValue = "198.51.100.14/24" + currentSyslogValue = "example-syslog" + updatedEnableMonitoringValue = true + updatedGraphiteValue = "example-graphite-updated" + updatedMetricsFrequencyValue = int64(101) + updatedMetricsPrefixValue = "example-prefix-updated" + updatedPluginValue = "example-plugin-updated" + updatedSgwAclValue = "0.0.0.0/0" + updatedSyslogValue = "example-syslog-updated" +) + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + enableMonitoringFlag: "true", + graphiteFlag: updatedGraphiteValue, + metricsFrequencyFlag: "101", + metricsPrefixFlag: updatedMetricsPrefixValue, + monitoringInstanceIdFlag: updatedMonitoringInstanceIdValue, + pluginFlag: updatedPluginValue, + sgwAclFlag: updatedSgwAclValue, + syslogFlag: updatedSyslogValue, + planIdFlag: updatedPlanIdValue, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + EnableMonitoring: utils.Ptr(updatedEnableMonitoringValue), + Graphite: utils.Ptr(updatedGraphiteValue), + MetricsFrequency: utils.Ptr(updatedMetricsFrequencyValue), + MetricsPrefix: utils.Ptr(updatedMetricsPrefixValue), + MonitoringInstanceId: utils.Ptr(updatedMonitoringInstanceIdValue), + Plugin: utils.Ptr([]string{updatedPluginValue}), + SgwAcl: utils.Ptr([]string{updatedSgwAclValue}), + Syslog: utils.Ptr([]string{updatedSyslogValue}), + PlanId: utils.Ptr(updatedPlanIdValue), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureInstance(mods ...func(instance *postgresql.Instance)) *postgresql.Instance { + instance := &postgresql.Instance{ + InstanceId: utils.Ptr(testInstanceId), + PlanId: utils.Ptr(currentPlanId), + Name: utils.Ptr("example-name"), + Parameters: utils.Ptr(map[string]interface{}{ + "enable_monitoring": currentEnableMonitoringValue, + "graphite": currentGraphiteValue, + "metrics_frequency": currentMetricsFrequencyValue, + "metrics_prefix": currentMetricsPrefixValue, + "monitoring_instance_id": currentMonitoringInstanceIdValue, + "plugins": []string{currentPluginValue}, + "sgw_acl": currentSgwAclValue, + "syslog": []string{currentSyslogValue}, + }), + } + for _, mod := range mods { + mod(instance) + } + return instance +} + +func fixtureRequest(mods ...func(request *postgresql.ApiUpdateInstanceRequest)) postgresql.ApiUpdateInstanceRequest { + request := testClient.UpdateInstance(testCtx, testProjectId, testInstanceId) + request = request.UpdateInstancePayload(postgresql.UpdateInstancePayload{ + Parameters: &postgresql.InstanceParameters{ + EnableMonitoring: utils.Ptr(updatedEnableMonitoringValue), + Graphite: utils.Ptr(updatedGraphiteValue), + MetricsFrequency: utils.Ptr(updatedMetricsFrequencyValue), + MetricsPrefix: utils.Ptr(updatedMetricsPrefixValue), + MonitoringInstanceId: utils.Ptr(updatedMonitoringInstanceIdValue), + Plugins: utils.Ptr([]string{updatedPluginValue}), + SgwAcl: utils.Ptr(updatedSgwAclValue), + Syslog: utils.Ptr([]string{updatedSyslogValue}), + }, + PlanId: utils.Ptr(updatedPlanIdValue), + }) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + sgwAclValues []string + pluginValues []string + syslogValues []string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "base with plan_name and version", + flagValues: fixtureFlagValues( + func(flagValues map[string]string) { + delete(flagValues, planIdFlag) + flagValues[planNameFlag] = "example-plan-name" + flagValues[versionFlag] = "example-version" + }, + ), + isValid: true, + expectedModel: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "required fields only", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + instanceIdFlag: testInstanceId, + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + }, + }, + { + description: "zero values", + flagValues: map[string]string{ + projectIdFlag: testProjectId, + planIdFlag: currentPlanId, + instanceIdFlag: testInstanceId, + enableMonitoringFlag: "false", + graphiteFlag: "", + metricsFrequencyFlag: "0", + metricsPrefixFlag: "", + }, + isValid: true, + expectedModel: &flagModel{ + ProjectId: testProjectId, + InstanceId: testInstanceId, + PlanId: utils.Ptr(currentPlanId), + EnableMonitoring: utils.Ptr(false), + Graphite: utils.Ptr(""), + MetricsFrequency: utils.Ptr(int64(0)), + MetricsPrefix: utils.Ptr(""), + }, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + { + description: "repeated acl flags", + flagValues: fixtureFlagValues(), + sgwAclValues: []string{currentSgwAclValue, "198.51.100.14/32"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.SgwAcl = utils.Ptr( + append(*model.SgwAcl, currentSgwAclValue, "198.51.100.14/32"), + ) + }), + }, + { + description: "repeated acl flag with list value", + flagValues: fixtureFlagValues(), + sgwAclValues: []string{"198.51.100.14/24,198.51.100.14/32"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.SgwAcl = utils.Ptr( + append(*model.SgwAcl, currentSgwAclValue, "198.51.100.14/32"), + ) + }), + }, + { + description: "repeated plugin flags", + flagValues: fixtureFlagValues(), + pluginValues: []string{"example-plugin-1", "example-plugin-2"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Plugin = utils.Ptr( + append(*model.Plugin, "example-plugin-1", "example-plugin-2"), + ) + }), + }, + { + description: "repeated syslog flags", + flagValues: fixtureFlagValues(), + syslogValues: []string{"example-syslog-1", "example-syslog-2"}, + isValid: true, + expectedModel: fixtureFlagModel(func(model *flagModel) { + model.Syslog = utils.Ptr( + append(*model.Syslog, "example-syslog-1", "example-syslog-2"), + ) + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + configureFlags(cmd) + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + for _, value := range tt.sgwAclValues { + err := cmd.Flags().Set(sgwAclFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", sgwAclFlag, value, err) + } + } + + for _, value := range tt.pluginValues { + err := cmd.Flags().Set(pluginFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", pluginFlag, value, err) + } + } + + for _, value := range tt.syslogValues { + err := cmd.Flags().Set(syslogFlag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", syslogFlag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + instance *postgresql.Instance + expectedRequest postgresql.ApiUpdateInstanceRequest + getOfferingsFails bool + getOfferingsResp *postgresql.OfferingList + isValid bool + }{ + { + description: "base", + instance: fixtureInstance(), + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + { + description: "do not update any field", + instance: fixtureInstance(), + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "" + model.Version = "" + model.EnableMonitoring = nil + model.Graphite = nil + model.MetricsFrequency = nil + model.MetricsPrefix = nil + model.MonitoringInstanceId = nil + model.Plugin = nil + model.SgwAcl = nil + model.Syslog = nil + }, + ), + expectedRequest: testClient.UpdateInstance(testCtx, testProjectId, testInstanceId). + UpdateInstancePayload(postgresql.UpdateInstancePayload{ + Parameters: &postgresql.InstanceParameters{ + EnableMonitoring: utils.Ptr(currentEnableMonitoringValue), + Graphite: utils.Ptr(currentGraphiteValue), + MetricsFrequency: utils.Ptr(currentMetricsFrequencyValue), + MetricsPrefix: utils.Ptr(currentMetricsPrefixValue), + MonitoringInstanceId: utils.Ptr(currentMonitoringInstanceIdValue), + Plugins: utils.Ptr([]string{currentPluginValue}), + SgwAcl: utils.Ptr(currentSgwAclValue), + Syslog: utils.Ptr([]string{currentSyslogValue}), + }, + PlanId: utils.Ptr(currentPlanId), + }), + }, + { + description: "use plan name and version", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + instance: fixtureInstance(), + expectedRequest: fixtureRequest(), + getOfferingsResp: &postgresql.OfferingList{ + Offerings: &[]postgresql.Offering{ + { + Version: utils.Ptr("example-version"), + Plans: &[]postgresql.Plan{ + { + Name: utils.Ptr("example-plan-name"), + Id: utils.Ptr(updatedPlanIdValue), + }, + }, + }, + }, + }, + }, + { + description: "get offering fails", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + getOfferingsFails: true, + isValid: false, + }, + { + description: "plan name not found", + model: fixtureFlagModel( + func(model *flagModel) { + model.PlanId = nil + model.PlanName = "example-plan-name" + model.Version = "example-version" + }, + ), + getOfferingsResp: &postgresql.OfferingList{ + Offerings: &[]postgresql.Offering{ + { + Version: utils.Ptr("example-version"), + Plans: &[]postgresql.Plan{ + { + Name: utils.Ptr("other-plan-name"), + Id: utils.Ptr(currentPlanId), + }, + }, + }, + }, + }, + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + client := &postgreSQLClientMocked{ + returnError: tt.getOfferingsFails, + getOfferingsResp: tt.getOfferingsResp, + } + request, err := buildRequest(testCtx, tt.instance, tt.model, client) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error building request: %v", err) + } + + diff := cmp.Diff(tt.expectedRequest, request, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.IgnoreFields(postgresql.ApiUpdateInstanceRequest{}, "apiService", "ctx", "projectId", "instanceId"), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/offerings/list/list.go b/internal/cmd/postgresql/offerings/list/list.go new file mode 100644 index 00000000..2ec5eba1 --- /dev/null +++ b/internal/cmd/postgresql/offerings/list/list.go @@ -0,0 +1,76 @@ +package list + +import ( + "context" + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresql/client" + "github.com/stackitcloud/stackit-cli/internal/pkg/tables" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +type flagModel struct { + ProjectId string +} + +var Cmd = &cobra.Command{ + Use: "list", + Short: "List all PostgreSQL service offerings", + Long: "List all PostgreSQL service offerings", + Example: `$ stackit postgresql offerings list --project-id xxx`, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() + model, err := parseFlags(cmd) + if err != nil { + return err + } + + // Configure API client + apiClient, err := client.ConfigureClient(cmd) + if err != nil { + return fmt.Errorf("authentication failed, please run \"stackit auth login\" or \"stackit auth activate-service-account\"") + } + + // Call API + req := buildRequest(ctx, model, apiClient) + resp, err := req.Execute() + if err != nil { + return fmt.Errorf("get PostgreSQL service offerings: %w", err) + } + offerings := *resp.Offerings + + // Show output as table + table := tables.NewTable() + table.SetHeader("NAME", "PLAN.ID", "PLAN.NAME", "PLAN.DESCRIPTION") + for _, o := range offerings { + for _, p := range *o.Plans { + table.AddRow(*o.Name, *p.Id, *p.Name, *p.Description) + } + table.AddSeparator() + } + table.EnableAutoMergeOnColumns(1) + table.Render() + + return nil + }, +} + +func parseFlags(_ *cobra.Command) (*flagModel, error) { + projectId := viper.GetString(config.ProjectIdKey) + if projectId == "" { + return nil, fmt.Errorf("project ID not set") + } + + return &flagModel{ + ProjectId: projectId, + }, nil +} + +func buildRequest(ctx context.Context, model *flagModel, apiClient *postgresql.APIClient) postgresql.ApiGetOfferingsRequest { + req := apiClient.GetOfferings(ctx, model.ProjectId) + return req +} diff --git a/internal/cmd/postgresql/offerings/list/list_test.go b/internal/cmd/postgresql/offerings/list/list_test.go new file mode 100644 index 00000000..dec9e1a2 --- /dev/null +++ b/internal/cmd/postgresql/offerings/list/list_test.go @@ -0,0 +1,169 @@ +package list + +import ( + "context" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/testutils" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/services/postgresql" +) + +const ( + projectIdFlag = "project-id" +) + +type testCtxKey struct{} + +var testCtx = context.WithValue(context.Background(), testCtxKey{}, "foo") +var testClient = &postgresql.APIClient{} +var testProjectId = uuid.NewString() + +func fixtureFlagValues(mods ...func(flagValues map[string]string)) map[string]string { + flagValues := map[string]string{ + projectIdFlag: testProjectId, + } + for _, mod := range mods { + mod(flagValues) + } + return flagValues +} + +func fixtureFlagModel(mods ...func(model *flagModel)) *flagModel { + model := &flagModel{ + ProjectId: testProjectId, + } + for _, mod := range mods { + mod(model) + } + return model +} + +func fixtureRequest(mods ...func(request *postgresql.ApiGetOfferingsRequest)) postgresql.ApiGetOfferingsRequest { + request := testClient.GetOfferings(testCtx, testProjectId) + for _, mod := range mods { + mod(&request) + } + return request +} + +func TestParseFlags(t *testing.T) { + tests := []struct { + description string + flagValues map[string]string + isValid bool + expectedModel *flagModel + }{ + { + description: "base", + flagValues: fixtureFlagValues(), + isValid: true, + expectedModel: fixtureFlagModel(), + }, + { + description: "no values", + flagValues: map[string]string{}, + isValid: false, + }, + { + description: "project id missing", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + delete(flagValues, projectIdFlag) + }), + isValid: false, + }, + { + description: "project id invalid 1", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "" + }), + isValid: false, + }, + { + description: "project id invalid 2", + flagValues: fixtureFlagValues(func(flagValues map[string]string) { + flagValues[projectIdFlag] = "invalid-uuid" + }), + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + cmd := &cobra.Command{} + + // Flag defined in root command + err := testutils.ConfigureBindUUIDFlag(cmd, projectIdFlag, config.ProjectIdKey) + if err != nil { + t.Fatalf("configure global flag --%s: %v", projectIdFlag, err) + } + + for flag, value := range tt.flagValues { + err := cmd.Flags().Set(flag, value) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("setting flag --%s=%s: %v", flag, value, err) + } + } + + err = cmd.ValidateRequiredFlags() + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error validating flags: %v", err) + } + + model, err := parseFlags(cmd) + if err != nil { + if !tt.isValid { + return + } + t.Fatalf("error parsing flags: %v", err) + } + + if !tt.isValid { + t.Fatalf("did not fail on invalid input") + } + diff := cmp.Diff(model, tt.expectedModel) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} + +func TestBuildRequest(t *testing.T) { + tests := []struct { + description string + model *flagModel + expectedRequest postgresql.ApiGetOfferingsRequest + }{ + { + description: "base", + model: fixtureFlagModel(), + expectedRequest: fixtureRequest(), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + request := buildRequest(testCtx, tt.model, testClient) + + diff := cmp.Diff(request, tt.expectedRequest, + cmp.AllowUnexported(tt.expectedRequest), + cmpopts.EquateComparable(testCtx), + ) + if diff != "" { + t.Fatalf("Data does not match: %s", diff) + } + }) + } +} diff --git a/internal/cmd/postgresql/offerings/offerings.go b/internal/cmd/postgresql/offerings/offerings.go new file mode 100644 index 00000000..23827e6b --- /dev/null +++ b/internal/cmd/postgresql/offerings/offerings.go @@ -0,0 +1,19 @@ +package offerings + +import ( + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/offerings/list" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "offerings", + Short: "Provides information regarding the PostgreSQL service offerings", + Long: "Provides information regarding the PostgreSQL service offerings", + Example: list.Cmd.Example, +} + +func init() { + // Add all direct child commands + Cmd.AddCommand(list.Cmd) +} diff --git a/internal/cmd/postgresql/postgresql.go b/internal/cmd/postgresql/postgresql.go new file mode 100644 index 00000000..06e46556 --- /dev/null +++ b/internal/cmd/postgresql/postgresql.go @@ -0,0 +1,24 @@ +package postgresql + +import ( + "fmt" + + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/credential" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/instance" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql/offerings" + + "github.com/spf13/cobra" +) + +var Cmd = &cobra.Command{ + Use: "postgresql", + Short: "Provides functionality for PostgreSQL", + Long: "Provides functionality for PostgreSQL", + Example: fmt.Sprintf("%s\n%s", instance.Cmd.Example, credential.Cmd.Example), +} + +func init() { + Cmd.AddCommand(instance.Cmd) + Cmd.AddCommand(offerings.Cmd) + Cmd.AddCommand(credential.Cmd) +} diff --git a/internal/cmd/root.go b/internal/cmd/root.go index c448c115..4e8dcaac 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -1,10 +1,21 @@ package cmd import ( - "fmt" "os" + "github.com/stackitcloud/stackit-cli/internal/cmd/auth" + "github.com/stackitcloud/stackit-cli/internal/cmd/config" + "github.com/stackitcloud/stackit-cli/internal/cmd/dns" + "github.com/stackitcloud/stackit-cli/internal/cmd/postgresql" + configPkg "github.com/stackitcloud/stackit-cli/internal/pkg/config" + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + projectIdFlag = "project-id" ) var RootCmd = &cobra.Command{ @@ -13,10 +24,6 @@ var RootCmd = &cobra.Command{ Long: "The root command of the STACKIT CLI", SilenceUsage: true, DisableAutoGenTag: true, - RunE: func(cmd *cobra.Command, args []string) error { - fmt.Println("Welcome to the STACKIT CLI! Functionality will be added soon.") - return nil - }, } func Execute() { @@ -25,3 +32,23 @@ func Execute() { os.Exit(1) } } + +func init() { + // Set up configuration files + configPkg.InitConfig() + + // Add all direct child commands + RootCmd.AddCommand(auth.Cmd) + RootCmd.AddCommand(config.Cmd) + RootCmd.AddCommand(dns.Cmd) + RootCmd.AddCommand(postgresql.Cmd) + + configureFlags(RootCmd) +} + +func configureFlags(cmd *cobra.Command) { + cmd.PersistentFlags().Var(flags.UUIDFlag(), projectIdFlag, "Project ID") + + err := viper.BindPFlag(configPkg.ProjectIdKey, cmd.PersistentFlags().Lookup(projectIdFlag)) + cobra.CheckErr(err) +} diff --git a/internal/pkg/auth/auth.go b/internal/pkg/auth/auth.go new file mode 100644 index 00000000..e5408888 --- /dev/null +++ b/internal/pkg/auth/auth.go @@ -0,0 +1,102 @@ +package auth + +import ( + "fmt" + "strconv" + "time" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + sdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config" +) + +// AuthenticationConfig reads the credentials from the storage and initializes the authentication flow. +// It returns the configuration option that can be used to create an authenticated SDK client. +// +// If the user was logged in and the user session expired, reauthorizeUserRoutine is called to reauthenticate the user again. +func AuthenticationConfig(cmd *cobra.Command, reauthorizeUserRoutine func() error) (authCfgOption sdkConfig.ConfigurationOption, err error) { + flow, err := GetAuthFlow() + if err != nil { + return nil, fmt.Errorf("get authentication flow: %w", err) + } + if flow == "" { + return nil, fmt.Errorf("authentication flow not set") + } + + userSessionExpired, err := userSessionExpired() + if err != nil { + return nil, fmt.Errorf("check if user session expired: %w", err) + } + + switch flow { + case AUTH_FLOW_SERVICE_ACCOUNT_TOKEN: + if userSessionExpired { + return nil, fmt.Errorf("session expired") + } + accessToken, err := getAccessToken() + if err != nil { + return nil, fmt.Errorf("get service account access token: %w", err) + } + authCfgOption = sdkConfig.WithToken(accessToken) + case AUTH_FLOW_SERVICE_ACCOUNT_KEY: + if userSessionExpired { + return nil, fmt.Errorf("session expired") + } + keyFlow, err := initKeyFlowWithStorage() + if err != nil { + return nil, fmt.Errorf("initialize service account key flow: %w", err) + } + authCfgOption = sdkConfig.WithCustomAuth(keyFlow) + case AUTH_FLOW_USER_TOKEN: + if userSessionExpired { + cmd.Println("Session expired, logging in again...") + err = reauthorizeUserRoutine() + if err != nil { + return nil, fmt.Errorf("user login: %w", err) + } + } + userTokenFlow := UserTokenFlow(cmd) + authCfgOption = sdkConfig.WithCustomAuth(userTokenFlow) + default: + return nil, fmt.Errorf("the provided authentication flow (%s) is not supported", flow) + } + return authCfgOption, nil +} + +func userSessionExpired() (bool, error) { + sessionExpiresAtString, err := GetAuthField(SESSION_EXPIRES_AT_UNIX) + if err != nil { + return false, fmt.Errorf("get %s: %w", SESSION_EXPIRES_AT_UNIX, err) + } + sessionExpiresAtInt, err := strconv.Atoi(sessionExpiresAtString) + if err != nil { + return false, fmt.Errorf("parse session expiration value \"%s\": %w", sessionExpiresAtString, err) + } + sessionExpiresAt := time.Unix(int64(sessionExpiresAtInt), 0) + now := time.Now() + return now.After(sessionExpiresAt), nil +} + +func getAccessToken() (string, error) { + accessToken, err := GetAuthField(ACCESS_TOKEN) + if err != nil { + return "", fmt.Errorf("get %s: %w", ACCESS_TOKEN, err) + } + if accessToken == "" { + return "", fmt.Errorf("%s not set", ACCESS_TOKEN) + } + return accessToken, nil +} + +func getStartingSessionExpiresAtUnix() (string, error) { + sessionStart := time.Now() + sessionTimeLimitString := viper.GetString(config.SessionTimeLimitKey) + sessionTimeLimit, err := time.ParseDuration(sessionTimeLimitString) + if err != nil { + return "", fmt.Errorf("parse session time limit \"%s\": %w", sessionTimeLimitString, err) + } + sessionExpiresAt := sessionStart.Add(sessionTimeLimit) + return strconv.FormatInt(sessionExpiresAt.Unix(), 10), nil +} diff --git a/internal/pkg/auth/auth_test.go b/internal/pkg/auth/auth_test.go new file mode 100644 index 00000000..ed6343ac --- /dev/null +++ b/internal/pkg/auth/auth_test.go @@ -0,0 +1,356 @@ +package auth + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "fmt" + "io" + "strconv" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/go-cmp/cmp" + "github.com/google/uuid" + "github.com/spf13/cobra" + "github.com/stackitcloud/stackit-sdk-go/core/clients" + sdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config" + "github.com/zalando/go-keyring" +) + +const saKeyStrPattern = `{ + "active": true, + "createdAt": "2023-03-23T18:26:20.335Z", + "credentials": { + "aud": "https://stackit-service-account-prod.apps.01.cf.eu01.stackit.cloud", + "iss": "stackit@sa.stackit.cloud", + "kid": "%s", + "sub": "%s" + }, + "id": "%s", + "keyAlgorithm": "RSA_2048", + "keyOrigin": "USER_PROVIDED", + "keyType": "USER_MANAGED", + "publicKey": "...", + "validUntil": "2024-03-22T18:05:41Z" +}` + +var ( + testSigningKey = []byte("Test") + testServiceAccountKey = fmt.Sprintf(saKeyStrPattern, uuid.New().String(), uuid.New().String(), uuid.New().String()) +) + +func generatePrivateKey() ([]byte, error) { + // Generate a new RSA key pair with a size of 2048 bits + privKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return nil, err + } + + // Encode the private key in PEM format + privKeyPEM := &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(privKey), + } + + // Print the private and public keys + return pem.EncodeToMemory(privKeyPEM), nil +} + +func TestAuthenticationConfig(t *testing.T) { + tests := []struct { + description string + flow authFlow + sessionExpiresAt time.Time + accessTokenSet bool + refreshToken string + saKey string + privateKeySet bool + tokenEndpoint string + jwksEndpoint string + isValid bool + expectedCustomAuthSet bool + expectedTokenSet bool + expectedReauthorizeUserCalled bool + }{ + { + description: "base_service_account_token", + flow: AUTH_FLOW_SERVICE_ACCOUNT_TOKEN, + sessionExpiresAt: time.Now().Add(time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + isValid: true, + expectedTokenSet: true, + }, + { + description: "service_account_token_session_expired", + flow: AUTH_FLOW_SERVICE_ACCOUNT_TOKEN, + sessionExpiresAt: time.Now().Add(-time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + isValid: false, + }, + { + description: "base_service_account_key", + flow: AUTH_FLOW_SERVICE_ACCOUNT_KEY, + sessionExpiresAt: time.Now().Add(time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + saKey: testServiceAccountKey, + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: true, + expectedCustomAuthSet: true, + }, + { + description: "service_account_key_session_expired", + flow: AUTH_FLOW_SERVICE_ACCOUNT_KEY, + sessionExpiresAt: time.Now().Add(-time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + saKey: testServiceAccountKey, + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: false, + }, + { + description: "base_user_token", + flow: AUTH_FLOW_USER_TOKEN, + sessionExpiresAt: time.Now().Add(time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + isValid: true, + }, + { + description: "user_token_session_expired", + flow: AUTH_FLOW_USER_TOKEN, + sessionExpiresAt: time.Now().Add(-time.Hour), + accessTokenSet: true, + refreshToken: "refresh_token", + isValid: true, + expectedReauthorizeUserCalled: true, + }, + { + description: "unsupported_flow", + flow: "test_flow", + isValid: false, + }, + { + description: "unset_access_token", + accessTokenSet: false, + isValid: false, + }, + { + description: "unset_flow", + flow: "", + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + keyring.MockInit() + timestamp := time.Now().Add(24 * time.Hour) + authFields := make(map[authFieldKey]string) + var accessToken string + var err error + if tt.accessTokenSet { + accessTokenJWT := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(timestamp)}) + accessToken, err = accessTokenJWT.SignedString(testSigningKey) + if err != nil { + t.Fatalf("Get test access token as string: %s", err) + } + } + + if tt.privateKeySet { + privateKey, err := generatePrivateKey() + if err != nil { + t.Fatalf("Generate private key: %s", err) + } + authFields[PRIVATE_KEY] = string(privateKey) + } + authFields[SESSION_EXPIRES_AT_UNIX] = strconv.FormatInt(tt.sessionExpiresAt.Unix(), 10) + authFields[ACCESS_TOKEN] = accessToken + authFields[REFRESH_TOKEN] = tt.refreshToken + authFields[SERVICE_ACCOUNT_KEY] = tt.saKey + authFields[TOKEN_CUSTOM_ENDPOINT] = tt.tokenEndpoint + authFields[JWKS_CUSTOM_ENDPOINT] = tt.jwksEndpoint + + err = SetAuthFlow(tt.flow) + if err != nil { + t.Fatalf("Failed to set auth flow: %s", err) + } + err = SetAuthFieldMap(authFields) + if err != nil { + t.Fatalf("Failed to set in auth storage: %v", err) + } + + reauthorizeUserCalled := false + reauthenticateUser := func() error { + if reauthorizeUserCalled { + t.Errorf("user reauthorized more than once") + } + reauthorizeUserCalled = true + return nil + } + + cmd := &cobra.Command{} + cmd.SetOut(io.Discard) // Suppresses console prints + + authCfgOption, err := AuthenticationConfig(cmd, reauthenticateUser) + + if !tt.isValid { + if err == nil { + t.Fatalf("Expected error but no error was returned") + } + } else { + if err != nil { + t.Fatalf("Expected no error but error was returned: %v", err) + } + + if reauthorizeUserCalled && !tt.expectedReauthorizeUserCalled { + t.Errorf("Unexpected user reauthentication") + } else if !reauthorizeUserCalled && tt.expectedReauthorizeUserCalled { + t.Errorf("User wasn't reauthenticated when it should've been") + } + + baseCfg := &sdkConfig.Configuration{} + err := authCfgOption(baseCfg) + if err != nil { + t.Fatalf("Applying returned auth config option: %v", err) + } + if tt.expectedCustomAuthSet && baseCfg.CustomAuth == nil { + t.Fatalf("The returned auth configuration option should set the CustomAuth field but it is nil") + } + if tt.expectedTokenSet && baseCfg.Token == "" { + t.Fatalf("The returned auth configuration option should set the Token field but it is empty") + } + } + }) + } +} + +func TestInitKeyFlow(t *testing.T) { + tests := []struct { + description string + accessTokenSet bool + refreshToken string + saKey string + privateKeySet bool + tokenEndpoint string + jwksEndpoint string + isValid bool + }{ + { + description: "base", + accessTokenSet: true, + refreshToken: "refresh_token", + saKey: testServiceAccountKey, + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: true, + }, + { + description: "invalid_service_account_key", + accessTokenSet: true, + refreshToken: "refresh_token", + saKey: "", + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: false, + }, + { + description: "invalid_private_key", + accessTokenSet: true, + refreshToken: "refresh_token", + saKey: testServiceAccountKey, + privateKeySet: false, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: false, + }, + { + description: "invalid_access_token", + accessTokenSet: false, + refreshToken: "refresh_token", + saKey: testServiceAccountKey, + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: false, + }, + { + description: "empty_refresh_token", + accessTokenSet: false, + refreshToken: "", + saKey: testServiceAccountKey, + privateKeySet: true, + tokenEndpoint: "token_url", + jwksEndpoint: "jwks_url", + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + keyring.MockInit() + timestamp := time.Now().Add(24 * time.Hour) + authFields := make(map[authFieldKey]string) + var accessToken string + var err error + if tt.accessTokenSet { + accessTokenJWT := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(timestamp)}) + accessToken, err = accessTokenJWT.SignedString(testSigningKey) + if err != nil { + t.Fatalf("Get test access token as string: %s", err) + } + } + if tt.privateKeySet { + privateKey, err := generatePrivateKey() + if err != nil { + t.Fatalf("Generate private key: %s", err) + } + authFields[PRIVATE_KEY] = string(privateKey) + } + authFields[ACCESS_TOKEN] = accessToken + authFields[REFRESH_TOKEN] = tt.refreshToken + authFields[SERVICE_ACCOUNT_KEY] = tt.saKey + authFields[TOKEN_CUSTOM_ENDPOINT] = tt.tokenEndpoint + authFields[JWKS_CUSTOM_ENDPOINT] = tt.jwksEndpoint + err = SetAuthFieldMap(authFields) + if err != nil { + t.Fatalf("Failed to set in auth storage: %v", err) + } + + keyFlowWithStorage, err := initKeyFlowWithStorage() + + if !tt.isValid { + if err == nil { + t.Fatalf("Expected error but no error was returned") + } + } else { + if err != nil { + t.Fatalf("Expected no error but error was returned: %v", err) + } + expectedToken := &clients.TokenResponseBody{ + AccessToken: accessToken, + ExpiresIn: int(timestamp.Unix()), + RefreshToken: tt.refreshToken, + Scope: "", + TokenType: "Bearer", + } + if !cmp.Equal(*expectedToken, keyFlowWithStorage.keyFlow.GetToken()) { + t.Errorf("The returned result is wrong. Expected %+v, got %+v", expectedToken, keyFlowWithStorage.keyFlow.GetToken()) + } + } + }) + } +} diff --git a/internal/pkg/auth/service_account.go b/internal/pkg/auth/service_account.go new file mode 100644 index 00000000..0b15eebc --- /dev/null +++ b/internal/pkg/auth/service_account.go @@ -0,0 +1,157 @@ +package auth + +import ( + "fmt" + "net/http" + + "github.com/golang-jwt/jwt/v5" + "github.com/stackitcloud/stackit-sdk-go/core/clients" +) + +type tokenClaims struct { + Email string `json:"email"` + jwt.RegisteredClaims +} + +type keyFlowInterface interface { + GetAccessToken() (string, error) + GetConfig() clients.KeyFlowConfig + GetToken() clients.TokenResponseBody + RoundTrip(*http.Request) (*http.Response, error) +} + +type tokenFlowInterface interface { + GetConfig() clients.TokenFlowConfig + RoundTrip(*http.Request) (*http.Response, error) +} + +type keyFlowWithStorage struct { + keyFlow *clients.KeyFlow +} + +// Ensure the implementation satisfies the expected interface +var _ http.RoundTripper = &keyFlowWithStorage{} + +// AuthenticateServiceAccount checks the type of the provided roundtripper, +// authenticates the CLI accordingly and store the credentials. +// For the key flow, it fetches an access and refresh token from the Service Account API. +// For the token flow, it just stores the provided token and doesn't check if it is valid. +// It returns the email associated with the service account +func AuthenticateServiceAccount(rt http.RoundTripper) (email string, err error) { + authFields := make(map[authFieldKey]string) + var authFlowType authFlow + switch flow := rt.(type) { + case keyFlowInterface: + authFlowType = AUTH_FLOW_SERVICE_ACCOUNT_KEY + + accessToken, err := flow.GetAccessToken() + if err != nil { + return "", fmt.Errorf("get access token: %w", err) + } + authFields[ACCESS_TOKEN] = accessToken + authFields[REFRESH_TOKEN] = flow.GetToken().RefreshToken + authFields[SERVICE_ACCOUNT_KEY] = flow.GetConfig().ServiceAccountKey + authFields[PRIVATE_KEY] = flow.GetConfig().PrivateKey + case tokenFlowInterface: + authFlowType = AUTH_FLOW_SERVICE_ACCOUNT_TOKEN + + authFields[ACCESS_TOKEN] = flow.GetConfig().ServiceAccountToken + default: + return "", fmt.Errorf("could not authenticate using any of the supported authentication flows (key and token): please report this issue") + } + + // We can safely use ParseUnverified because we are not authenticating the user at this point, + // We are parsing the token just to get the service account e-mail + parsedAccessToken, _, err := jwt.NewParser().ParseUnverified(authFields[ACCESS_TOKEN], &tokenClaims{}) + if err != nil { + return "", fmt.Errorf("parse access token to read service account email: %w", err) + } + claims, ok := parsedAccessToken.Claims.(*tokenClaims) + if !ok { + return "", fmt.Errorf("get claims from parsed access token: unknown claims type, please report this issue") + } + authFields[SERVICE_ACCOUNT_EMAIL] = claims.Email + + sessionExpiresAtUnix, err := getStartingSessionExpiresAtUnix() + if err != nil { + return "", fmt.Errorf("compute session expiration timestamp: %w", err) + } + authFields[SESSION_EXPIRES_AT_UNIX] = sessionExpiresAtUnix + + err = SetAuthFlow(authFlowType) + if err != nil { + return "", fmt.Errorf("set auth flow type: %w", err) + } + err = SetAuthFieldMap(authFields) + if err != nil { + return "", fmt.Errorf("set in auth storage: %w", err) + } + + return authFields[SERVICE_ACCOUNT_EMAIL], nil +} + +// initKeyFlowWithStorage initializes the keyFlow from the SDK and creates a keyFlowWithStorage struct that uses that keyFlow +func initKeyFlowWithStorage() (*keyFlowWithStorage, error) { + authFields := map[authFieldKey]string{ + ACCESS_TOKEN: "", + REFRESH_TOKEN: "", + SERVICE_ACCOUNT_KEY: "", + PRIVATE_KEY: "", + TOKEN_CUSTOM_ENDPOINT: "", + JWKS_CUSTOM_ENDPOINT: "", + } + err := GetAuthFieldMap(authFields) + if err != nil { + return nil, fmt.Errorf("get from auth storage: %w", err) + } + if authFields[ACCESS_TOKEN] == "" { + return nil, fmt.Errorf("access token not set") + } + if authFields[REFRESH_TOKEN] == "" { + return nil, fmt.Errorf("refresh token not set") + } + + cfg := &clients.KeyFlowConfig{ + ServiceAccountKey: authFields[SERVICE_ACCOUNT_KEY], + PrivateKey: authFields[PRIVATE_KEY], + ClientRetry: clients.NewRetryConfig(), + TokenUrl: authFields[TOKEN_CUSTOM_ENDPOINT], + JWKSUrl: authFields[JWKS_CUSTOM_ENDPOINT], + } + + keyFlow := &clients.KeyFlow{} + err = keyFlow.Init(cfg) + if err != nil { + return nil, fmt.Errorf("initialize key flow: %w", err) + } + err = keyFlow.SetToken(authFields[ACCESS_TOKEN], authFields[REFRESH_TOKEN]) + if err != nil { + return nil, fmt.Errorf("set access and refresh token: %w", err) + } + + // create keyFlowWithStorage roundtripper that stores the credentials after executing a request + keyFlowWithStorage := &keyFlowWithStorage{ + keyFlow: keyFlow, + } + return keyFlowWithStorage, nil +} + +// The keyFlowWithStorage Roundtrip executes the keyFlow roundtrip and then stores the access and refresh tokens +func (kf *keyFlowWithStorage) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := kf.keyFlow.RoundTrip(req) + + token := kf.keyFlow.GetToken() + accessToken := token.AccessToken + refreshToken := token.RefreshToken + tokenValues := map[authFieldKey]string{ + ACCESS_TOKEN: accessToken, + REFRESH_TOKEN: refreshToken, + } + + storageErr := SetAuthFieldMap(tokenValues) + if storageErr != nil { + return nil, fmt.Errorf("set access and refresh token in the storage: %w", err) + } + + return resp, err +} diff --git a/internal/pkg/auth/service_account_test.go b/internal/pkg/auth/service_account_test.go new file mode 100644 index 00000000..2a51d439 --- /dev/null +++ b/internal/pkg/auth/service_account_test.go @@ -0,0 +1,170 @@ +package auth + +import ( + "fmt" + "net/http" + "testing" + + "github.com/stackitcloud/stackit-cli/internal/pkg/config" + + "github.com/golang-jwt/jwt/v5" + "github.com/stackitcloud/stackit-sdk-go/core/clients" + "github.com/zalando/go-keyring" +) + +const ( + tokenFlow = "token" + keyFlow = "key" +) + +var accessTokenSigningKey = []byte("Test") + +type keyFlowMocked struct { + accessToken jwt.Token + config clients.KeyFlowConfig + tokenResponse clients.TokenResponseBody + getAccessTokenFail bool + tokenInvalid bool +} + +func (f *keyFlowMocked) GetAccessToken() (string, error) { + if f.getAccessTokenFail { + return "", fmt.Errorf("error") + } + if f.tokenInvalid { + return "", nil + } + raw, err := f.accessToken.SignedString(accessTokenSigningKey) + if err != nil { + return "", fmt.Errorf("sign string from token: %w", err) + } + return raw, nil +} + +func (f *keyFlowMocked) GetConfig() clients.KeyFlowConfig { + return f.config +} + +func (f *keyFlowMocked) GetToken() clients.TokenResponseBody { + return f.tokenResponse +} + +func (f *keyFlowMocked) RoundTrip(*http.Request) (*http.Response, error) { + return nil, nil +} + +type tokenFlowMocked struct { + config clients.TokenFlowConfig +} + +func (f *tokenFlowMocked) GetConfig() clients.TokenFlowConfig { + return f.config +} + +func (f *tokenFlowMocked) RoundTrip(*http.Request) (*http.Response, error) { + return nil, nil +} + +func TestAuthenticateServiceAccount(t *testing.T) { + tests := []struct { + description string + flowType string + getAccessTokenFail bool + tokenInvalid bool + accessToken jwt.Token + accessTokenRaw string + refreshToken string + expectedEmail string + isValid bool + }{ + { + description: "base_key_flow", + flowType: keyFlow, + accessToken: *jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{ + Email: "test_email", + RegisteredClaims: jwt.RegisteredClaims{}, + }), + refreshToken: "refresh_token", + expectedEmail: "test_email", + isValid: true, + }, + { + description: "base_token_flow", + flowType: tokenFlow, + accessToken: *jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{ + Email: "test_email", + }), + refreshToken: "refresh_token", + expectedEmail: "test_email", + isValid: true, + }, + { + description: "unsupported_flow", + flowType: "unsupported", + isValid: false, + }, + { + description: "key_flow_failed_get_access_token", + flowType: keyFlow, + getAccessTokenFail: true, + isValid: false, + }, + { + description: "invalid_token", + flowType: keyFlow, + tokenInvalid: true, + isValid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + keyring.MockInit() + config.InitConfig() // AuthenticateServiceAccount accesses the config + + var flow http.RoundTripper + switch tt.flowType { + case keyFlow: + flow = &keyFlowMocked{ + accessToken: tt.accessToken, + getAccessTokenFail: tt.getAccessTokenFail, + tokenInvalid: tt.tokenInvalid, + config: clients.KeyFlowConfig{ + ServiceAccountKey: "sa_key", + PrivateKey: "private_key", + }, + tokenResponse: clients.TokenResponseBody{ + RefreshToken: tt.refreshToken, + }, + } + case tokenFlow: + raw, err := tt.accessToken.SignedString(accessTokenSigningKey) + if err != nil { + t.Fatalf("signing string from token: %s", err) + } + flow = &tokenFlowMocked{ + config: clients.TokenFlowConfig{ + ServiceAccountToken: raw, + }, + } + default: + flow = &http.Transport{} + } + + email, err := AuthenticateServiceAccount(flow) + + if !tt.isValid { + if err == nil { + t.Fatalf("Expected error but no error was returned") + } + } else { + if err != nil { + t.Fatalf("Expected no error but error was returned: %v", err) + } + if tt.expectedEmail != email { + t.Fatalf("The returned email is wrong. Expected %s, got %s", tt.expectedEmail, email) + } + } + }) + } +} diff --git a/internal/pkg/auth/storage.go b/internal/pkg/auth/storage.go new file mode 100644 index 00000000..4d892c11 --- /dev/null +++ b/internal/pkg/auth/storage.go @@ -0,0 +1,208 @@ +package auth + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/zalando/go-keyring" +) + +// Name of an auth-related field +type authFieldKey string + +// Possible values of authentication flows +type authFlow string + +const ( + keyringService = "stackit-cli" + textFileFolderName = ".stackit" + textFileName = "cli-auth-storage.txt" +) + +const ( + SESSION_EXPIRES_AT_UNIX authFieldKey = "session_expires_at_unix" + ACCESS_TOKEN authFieldKey = "access_token" + REFRESH_TOKEN authFieldKey = "refresh_token" + SERVICE_ACCOUNT_TOKEN authFieldKey = "service_account_token" + SERVICE_ACCOUNT_EMAIL authFieldKey = "service_account_email" + SERVICE_ACCOUNT_KEY authFieldKey = "service_account_key" + PRIVATE_KEY authFieldKey = "private_key" + TOKEN_CUSTOM_ENDPOINT authFieldKey = "token_custom_endpoint" + JWKS_CUSTOM_ENDPOINT authFieldKey = "jwks_custom_endpoint" +) + +const ( + authFlowType authFieldKey = "auth_flow_type" + AUTH_FLOW_USER_TOKEN authFlow = "user_token" + AUTH_FLOW_SERVICE_ACCOUNT_TOKEN authFlow = "sa_token" + AUTH_FLOW_SERVICE_ACCOUNT_KEY authFlow = "sa_key" +) + +func SetAuthFlow(value authFlow) error { + return SetAuthField(authFlowType, string(value)) +} + +// Sets the values in the auth storage according to the given map +func SetAuthFieldMap(keyMap map[authFieldKey]string) error { + for key, value := range keyMap { + err := SetAuthField(key, value) + if err != nil { + return fmt.Errorf("set auth field \"%s\": %w", key, err) + } + } + return nil +} + +func SetAuthField(key authFieldKey, value string) error { + err := setAuthFieldInKeyring(key, value) + if err != nil { + errFallback := setAuthFieldInEncodedTextFile(key, value) + if errFallback != nil { + return fmt.Errorf("write to keyring failed (%w), try writing to encoded text file: %w", err, errFallback) + } + } + return nil +} + +func setAuthFieldInKeyring(key authFieldKey, value string) error { + return keyring.Set(keyringService, string(key), value) +} + +func setAuthFieldInEncodedTextFile(key authFieldKey, value string) error { + err := createEncodedTextFile() + if err != nil { + return err + } + + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("get home dir: %w", err) + } + textFileDir := filepath.Join(homeDir, textFileFolderName) + textFilePath := filepath.Join(textFileDir, textFileName) + + contentEncoded, err := os.ReadFile(textFilePath) + if err != nil { + return fmt.Errorf("read file: %w", err) + } + contentBytes, err := base64.StdEncoding.DecodeString(string(contentEncoded)) + if err != nil { + return fmt.Errorf("decode file: %w", err) + } + content := map[authFieldKey]string{} + err = json.Unmarshal(contentBytes, &content) + if err != nil { + return fmt.Errorf("unmarshal file: %w", err) + } + + content[key] = value + + contentBytes, err = json.Marshal(content) + if err != nil { + return fmt.Errorf("marshal file: %w", err) + } + contentEncoded = []byte(base64.StdEncoding.EncodeToString(contentBytes)) + err = os.WriteFile(textFilePath, contentEncoded, 0o600) + if err != nil { + return fmt.Errorf("write file: %w", err) + } + return nil +} + +// Populates the values in the given map according to the auth storage +func GetAuthFieldMap(keyMap map[authFieldKey]string) error { + for key := range keyMap { + value, err := GetAuthField(key) + if err != nil { + return fmt.Errorf("get auth field \"%s\": %w", key, err) + } + keyMap[key] = value + } + return nil +} + +func GetAuthFlow() (authFlow, error) { + value, err := GetAuthField(authFlowType) + return authFlow(value), err +} + +func GetAuthField(key authFieldKey) (string, error) { + value, err := getAuthFieldFromKeyring(key) + if err != nil { + var errFallback error + value, errFallback = getAuthFieldFromEncodedTextFile(key) + if errFallback != nil { + return "", fmt.Errorf("write to keyring failed (%w), tried write to encoded text file: %w", err, errFallback) + } + } + return value, nil +} + +func getAuthFieldFromKeyring(key authFieldKey) (string, error) { + return keyring.Get(keyringService, string(key)) +} + +func getAuthFieldFromEncodedTextFile(key authFieldKey) (string, error) { + err := createEncodedTextFile() + if err != nil { + return "", err + } + + homeDir, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("get home dir: %w", err) + } + textFileDir := filepath.Join(homeDir, textFileFolderName) + textFilePath := filepath.Join(textFileDir, textFileName) + + contentEncoded, err := os.ReadFile(textFilePath) + if err != nil { + return "", fmt.Errorf("read file: %w", err) + } + contentBytes, err := base64.StdEncoding.DecodeString(string(contentEncoded)) + if err != nil { + return "", fmt.Errorf("decode file: %w", err) + } + var content map[authFieldKey]string + err = json.Unmarshal(contentBytes, &content) + if err != nil { + return "", fmt.Errorf("unmarshal file: %w", err) + } + value, ok := content[key] + if !ok { + return "", fmt.Errorf("value not found") + } + return value, nil +} + +// Checks if the encoded text file exist. +// If it doesn't, creates it with the content "{}" encoded. +// If it does, does nothing (and returns nil). +func createEncodedTextFile() error { + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("get home dir: %w", err) + } + textFileDir := filepath.Join(homeDir, textFileFolderName) + textFilePath := filepath.Join(textFileDir, textFileName) + + err = os.MkdirAll(textFileDir, os.ModePerm) + if err != nil { + return fmt.Errorf("create file dir: %w", err) + } + _, err = os.Stat(textFilePath) + if !os.IsNotExist(err) { + return nil + } + + contentEncoded := base64.StdEncoding.EncodeToString([]byte("{}")) + err = os.WriteFile(textFilePath, []byte(contentEncoded), 0o600) + if err != nil { + return fmt.Errorf("create file: %w", err) + } + + return nil +} diff --git a/internal/pkg/auth/storage_test.go b/internal/pkg/auth/storage_test.go new file mode 100644 index 00000000..5b09c3c3 --- /dev/null +++ b/internal/pkg/auth/storage_test.go @@ -0,0 +1,381 @@ +package auth + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/zalando/go-keyring" +) + +func TestSetGetAuthField(t *testing.T) { + var testField1 authFieldKey = "test-field-1" + var testField2 authFieldKey = "test-field-2" + + testValue1 := fmt.Sprintf("value-1-%s", time.Now().Format(time.RFC3339)) + testValue2 := fmt.Sprintf("value-2-%s", time.Now().Format(time.RFC3339)) + testValue3 := fmt.Sprintf("value-3-%s", time.Now().Format(time.RFC3339)) + + type valueAssignment struct { + key authFieldKey + value string + } + + tests := []struct { + description string + keyringFails bool + valueAssignments []valueAssignment + expectedValues map[authFieldKey]string + }{ + { + description: "simple assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue1, + testField2: testValue2, + }, + }, + { + description: "simple assignments w/ keyring failing", + keyringFails: true, + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue1, + testField2: testValue2, + }, + }, + { + description: "overlapping assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + { + key: testField1, + value: testValue3, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue3, + testField2: testValue2, + }, + }, + { + description: "overlapping assignments w/ keyring failing", + keyringFails: true, + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + { + key: testField1, + value: testValue3, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue3, + testField2: testValue2, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + if !tt.keyringFails { + keyring.MockInit() + } else { + keyring.MockInitWithError(fmt.Errorf("keyring unavailable for testing")) + } + + for _, assignment := range tt.valueAssignments { + err := SetAuthField(assignment.key, assignment.value) + if err != nil { + t.Fatalf("Failed to set \"%s\" as \"%s\": %v", assignment.key, assignment.value, err) + } + // Check that this value will be checked + if _, ok := tt.expectedValues[assignment.key]; !ok { + t.Fatalf("Value \"%s\" set but not checked. Please add it to 'expectedValues'", assignment.key) + } + } + + for key, valueExpected := range tt.expectedValues { + value, err := GetAuthField(key) + if err != nil { + t.Errorf("Failed to get value of \"%s\": %v", key, err) + continue + } else if value != valueExpected { + t.Errorf("Value of field \"%s\" is wrong: expected \"%s\", got \"%s\"", key, valueExpected, value) + } + + if !tt.keyringFails { + err = deleteAuthFieldInKeyring(key) + if err != nil { + t.Errorf("Post-test cleanup failed: remove field \"%s\" from keyring: %v. Please remove it manually", key, err) + } + } else { + err = deleteAuthFieldInEncodedTextFile(key) + if err != nil { + t.Errorf("Post-test cleanup failed: remove field \"%s\" from text file: %v. Please remove it manually", key, err) + } + } + } + }) + } +} + +func TestSetGetAuthFieldKeyring(t *testing.T) { + var testField1 authFieldKey = "test-field-1" + var testField2 authFieldKey = "test-field-2" + + testValue1 := fmt.Sprintf("value-1-keyring-%s", time.Now().Format(time.RFC3339)) + testValue2 := fmt.Sprintf("value-2-keyring-%s", time.Now().Format(time.RFC3339)) + testValue3 := fmt.Sprintf("value-3-keyring-%s", time.Now().Format(time.RFC3339)) + + type valueAssignment struct { + key authFieldKey + value string + } + + tests := []struct { + description string + valueAssignments []valueAssignment + expectedValues map[authFieldKey]string + }{ + { + description: "simple assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue1, + testField2: testValue2, + }, + }, + { + description: "overlapping assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + { + key: testField1, + value: testValue3, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue3, + testField2: testValue2, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + keyring.MockInit() + + for _, assignment := range tt.valueAssignments { + err := setAuthFieldInKeyring(assignment.key, assignment.value) + if err != nil { + t.Fatalf("Failed to set \"%s\" as \"%s\": %v", assignment.key, assignment.value, err) + } + // Check that this value will be checked + if _, ok := tt.expectedValues[assignment.key]; !ok { + t.Fatalf("Value \"%s\" set but not checked. Please add it to 'expectedValues'", assignment.key) + } + } + + for key, valueExpected := range tt.expectedValues { + value, err := getAuthFieldFromKeyring(key) + if err != nil { + t.Errorf("Failed to get value of \"%s\": %v", key, err) + continue + } else if value != valueExpected { + t.Errorf("Value of field \"%s\" is wrong: expected \"%s\", got \"%s\"", key, valueExpected, value) + } + + err = deleteAuthFieldInKeyring(key) + if err != nil { + t.Errorf("Post-test cleanup failed: remove field \"%s\" from keyring: %v. Please remove it manually", key, err) + } + } + }) + } +} + +func TestSetGetAuthFieldEncodedTextFile(t *testing.T) { + var testField1 authFieldKey = "test-field-1" + var testField2 authFieldKey = "test-field-2" + + testValue1 := fmt.Sprintf("value-1-text-%s", time.Now().Format(time.RFC3339)) + testValue2 := fmt.Sprintf("value-2-text-%s", time.Now().Format(time.RFC3339)) + testValue3 := fmt.Sprintf("value-3-text-%s", time.Now().Format(time.RFC3339)) + + type valueAssignment struct { + key authFieldKey + value string + } + + tests := []struct { + description string + valueAssignments []valueAssignment + expectedValues map[authFieldKey]string + }{ + { + description: "simple assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue1, + testField2: testValue2, + }, + }, + { + description: "overlapping assignments", + valueAssignments: []valueAssignment{ + { + key: testField1, + value: testValue1, + }, + { + key: testField2, + value: testValue2, + }, + { + key: testField1, + value: testValue3, + }, + }, + expectedValues: map[authFieldKey]string{ + testField1: testValue3, + testField2: testValue2, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + for _, assignment := range tt.valueAssignments { + err := setAuthFieldInEncodedTextFile(assignment.key, assignment.value) + if err != nil { + t.Fatalf("Failed to set \"%s\" as \"%s\": %v", assignment.key, assignment.value, err) + } + // Check that this value will be checked + if _, ok := tt.expectedValues[assignment.key]; !ok { + t.Fatalf("Value \"%s\" set but not checked. Please add it to 'expectedValues'", assignment.key) + } + } + + for key, valueExpected := range tt.expectedValues { + value, err := getAuthFieldFromEncodedTextFile(key) + if err != nil { + t.Errorf("Failed to get value of \"%s\": %v", key, err) + continue + } else if value != valueExpected { + t.Errorf("Value of field \"%s\" is wrong: expected \"%s\", got \"%s\"", key, valueExpected, value) + } + + err = deleteAuthFieldInEncodedTextFile(key) + if err != nil { + t.Errorf("Post-test cleanup failed: remove field \"%s\" from text file: %v. Please remove it manually", key, err) + } + } + }) + } +} + +func deleteAuthFieldInKeyring(key authFieldKey) error { + return keyring.Delete(keyringService, string(key)) +} + +func deleteAuthFieldInEncodedTextFile(key authFieldKey) error { + err := createEncodedTextFile() + if err != nil { + return err + } + + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("get home dir: %w", err) + } + textFileDir := filepath.Join(homeDir, textFileFolderName) + textFilePath := filepath.Join(textFileDir, textFileName) + + contentEncoded, err := os.ReadFile(textFilePath) + if err != nil { + return fmt.Errorf("read file: %w", err) + } + contentBytes, err := base64.StdEncoding.DecodeString(string(contentEncoded)) + if err != nil { + return fmt.Errorf("decode file: %w", err) + } + content := map[authFieldKey]string{} + err = json.Unmarshal(contentBytes, &content) + if err != nil { + return fmt.Errorf("unmarshal file: %w", err) + } + + delete(content, key) + + contentBytes, err = json.Marshal(content) + if err != nil { + return fmt.Errorf("marshal file: %w", err) + } + contentEncoded = []byte(base64.StdEncoding.EncodeToString(contentBytes)) + err = os.WriteFile(textFilePath, contentEncoded, 0o600) + if err != nil { + return fmt.Errorf("write file: %w", err) + } + return nil +} diff --git a/internal/pkg/auth/user_login.go b/internal/pkg/auth/user_login.go new file mode 100644 index 00000000..7c7a1f7c --- /dev/null +++ b/internal/pkg/auth/user_login.go @@ -0,0 +1,215 @@ +package auth + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os/exec" + "runtime" + "strings" + "time" + + "golang.org/x/oauth2" +) + +const ( + authDomain = "auth.01.idp.eu01.stackit.cloud/oauth" + clientId = "stackit-cli-client-id" + redirectURL = "http://localhost:8000" +) + +// AuthorizeUser implements the PKCE OAuth2 flow. +func AuthorizeUser() error { + conf := &oauth2.Config{ + ClientID: clientId, + Endpoint: oauth2.Endpoint{ + AuthURL: fmt.Sprintf("https://%s/authorize", authDomain), + }, + Scopes: []string{"openid"}, + RedirectURL: redirectURL, + } + + // Initialize the code verifier + codeVerifier := oauth2.GenerateVerifier() + + // Construct the authorization URL + authorizationURL := conf.AuthCodeURL("", oauth2.S256ChallengeOption(codeVerifier)) + + // Start a web server to listen on a callback URL + mux := http.NewServeMux() + server := &http.Server{ + Addr: redirectURL, + Handler: mux, + ReadHeaderTimeout: 10 * time.Second, + } + + // Define a handler that will get the authorization code, call the token endpoint, and close the HTTP server + var errServer error + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + defer cleanup(server) + + // Get the authorization code + code := r.URL.Query().Get("code") + if code == "" { + errServer = fmt.Errorf("could not find 'code' URL parameter") + return + } + + // Trade the authorization code and the code verifier for access and refresh tokens + accessToken, refreshToken, err := getUserAccessAndRefreshTokens(authDomain, clientId, codeVerifier, code, redirectURL) + if err != nil { + errServer = fmt.Errorf("retrieve tokens: %w", err) + return + } + + sessionExpiresAtUnix, err := getStartingSessionExpiresAtUnix() + if err != nil { + errServer = fmt.Errorf("compute session expiration timestamp: %w", err) + return + } + + err = SetAuthFlow(AUTH_FLOW_USER_TOKEN) + if err != nil { + errServer = fmt.Errorf("set auth flow type: %w", err) + return + } + authFields := map[authFieldKey]string{ + SESSION_EXPIRES_AT_UNIX: sessionExpiresAtUnix, + ACCESS_TOKEN: accessToken, + REFRESH_TOKEN: refreshToken, + } + err = SetAuthFieldMap(authFields) + if err != nil { + errServer = fmt.Errorf("set in auth storage: %w", err) + } + + // Return an indication of success to the caller + _, _ = io.WriteString(w, ` + +
+