From d6135c6c57725a14e3a0c66fd94b70c825ca7c03 Mon Sep 17 00:00:00 2001 From: Matous Jobanek Date: Wed, 22 Jan 2025 11:00:03 +0100 Subject: [PATCH] use helper function for UserSignup creation in signup unit tests (#494) --- go.mod | 24 +- go.sum | 43 +++- pkg/controller/signup_test.go | 197 +++++--------- pkg/proxy/handlers/spacelister_get_test.go | 102 ++++---- pkg/proxy/handlers/spacelister_list_test.go | 24 +- pkg/proxy/handlers/spacelister_test.go | 34 ++- pkg/proxy/members_test.go | 76 ++---- pkg/proxy/proxy_community_test.go | 61 +++-- pkg/proxy/proxy_test.go | 52 ++-- pkg/signup/service/signup_service_test.go | 268 ++++++-------------- test/fake/proxy.go | 28 +- 11 files changed, 357 insertions(+), 552 deletions(-) diff --git a/go.mod b/go.mod index dc3b89ce..67f8782e 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,8 @@ go 1.20 require ( github.com/aws/aws-sdk-go v1.44.100 - github.com/codeready-toolchain/api v0.0.0-20250116110936-14cd9cc79fc6 - github.com/codeready-toolchain/toolchain-common v0.0.0-20250113092648-1078d683961b + github.com/codeready-toolchain/api v0.0.0-20250121053759-af12adf8e938 + github.com/codeready-toolchain/toolchain-common v0.0.0-20250121053752-f7e2c17c3c6b github.com/go-logr/logr v1.4.1 github.com/gofrs/uuid v4.2.0+incompatible github.com/pkg/errors v0.9.1 @@ -46,6 +46,10 @@ require ( cloud.google.com/go/auth v0.3.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect cloud.google.com/go/compute/metadata v0.3.0 // indirect + github.com/BurntSushi/toml v1.2.1 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.2.0 // indirect + github.com/Masterminds/sprig/v3 v3.2.3 // indirect github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bytedance/sonic v1.11.2 // indirect @@ -56,17 +60,21 @@ require ( github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/evanphx/json-patch/v5 v5.6.0 // indirect + github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/go-errors/errors v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/google/go-github/v52 v52.0.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/s2a-go v0.1.7 // indirect + github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.3 // indirect github.com/gorilla/mux v1.8.0 // indirect + github.com/huandu/xstrings v1.3.3 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect github.com/lestrrat-go/blackmagic v1.0.2 // indirect @@ -76,15 +84,23 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/migueleliasweb/go-github-mock v0.0.18 // indirect + github.com/mitchellh/copystructure v1.0.0 // indirect + github.com/mitchellh/reflectwalk v1.0.0 // indirect + github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/prometheus/procfs v0.9.0 // indirect + github.com/redhat-cop/operator-utils v1.3.6 // indirect + github.com/shopspring/decimal v1.2.0 // indirect + github.com/spf13/cast v1.3.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect + github.com/xlab/treeprint v1.1.0 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel/metric v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.24.0 // indirect + go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect golang.org/x/arch v0.7.0 // indirect gomodules.xyz/jsonpatch/v2 v2.3.0 // indirect google.golang.org/api v0.177.0 // indirect @@ -92,8 +108,12 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6 // indirect google.golang.org/grpc v1.63.2 // indirect k8s.io/apiextensions-apiserver v0.27.2 // indirect + k8s.io/cli-runtime v0.27.3 // indirect k8s.io/component-base v0.27.3 // indirect + k8s.io/kubectl v0.27.3 // indirect k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect + sigs.k8s.io/kustomize/api v0.13.2 // indirect + sigs.k8s.io/kustomize/kyaml v0.14.1 // indirect ) require ( diff --git a/go.sum b/go.sum index dd12d831..75fda8dc 100644 --- a/go.sum +++ b/go.sum @@ -10,9 +10,13 @@ cloud.google.com/go/recaptchaenterprise/v2 v2.13.0 h1:+QG02kE63W13vXI+rwAxFF3EhG cloud.google.com/go/recaptchaenterprise/v2 v2.13.0/go.mod h1:jNYyn2ScR4DTg+VNhjhv/vJQdaU8qz+NpmpIzEE7HFQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g= +github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= +github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8 h1:wPbRQzjjwFc0ih8puEVAOFGELsn1zoIIYdxvML7mDxA= github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8/go.mod h1:I0gYDMZ6Z5GRU7l58bNFSkPTFN6Yl12dsUlAZ8xy98g= github.com/aws/aws-sdk-go v1.44.100 h1:7I86bWNQB+HGDT5z/dJy61J7qgbgLoZ7O51C9eL6hrA= @@ -39,15 +43,18 @@ github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpV github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +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/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I= github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/codeready-toolchain/api v0.0.0-20250116110936-14cd9cc79fc6 h1:vr7dQouJ7J5MzAIemBVRVDHHFGM67+fMQSQxFSXIw+4= -github.com/codeready-toolchain/api v0.0.0-20250116110936-14cd9cc79fc6/go.mod h1:2KYfJlFwZtiKfa5QDhQfXTFh6RyALilURWBXyfKmKso= -github.com/codeready-toolchain/toolchain-common v0.0.0-20250113092648-1078d683961b h1:zlLUDN9ddogCX8hzuPrIdS/YpAF8siucA5b56zGUz00= -github.com/codeready-toolchain/toolchain-common v0.0.0-20250113092648-1078d683961b/go.mod h1:wLXGFyEan+RJHZEEMmvTxNa2BrlizIA+4+Lsi1cyuAk= +github.com/codeready-toolchain/api v0.0.0-20250121053759-af12adf8e938 h1:cj2H8bhNTjHVMUJnPEpLW8nLV9YMnG2nQ3oTgMJWsbI= +github.com/codeready-toolchain/api v0.0.0-20250121053759-af12adf8e938/go.mod h1:2KYfJlFwZtiKfa5QDhQfXTFh6RyALilURWBXyfKmKso= +github.com/codeready-toolchain/toolchain-common v0.0.0-20250121053752-f7e2c17c3c6b h1:AjguQB0pvRBaArWMs6pzdKu0IimYcfK4MIpM+vwf8us= +github.com/codeready-toolchain/toolchain-common v0.0.0-20250121053752-f7e2c17c3c6b/go.mod h1:YAvlMiumFFmUR8A3eF5TDjyn1KyhKbpdwCMdLKtupGA= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -67,6 +74,7 @@ github.com/evanphx/json-patch v5.6.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi github.com/evanphx/json-patch/v5 v5.6.0 h1:b91NhWfaz02IuVxO9faSllyAtNXHMPkC5J8sJCLunww= github.com/evanphx/json-patch/v5 v5.6.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2VvlbKOFpnXhI9Bw4= github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d h1:105gxyaGwCFad8crR9dcMQWvV9Hvulu6hwUh4tWPJnM= +github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= @@ -84,6 +92,7 @@ github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= @@ -173,6 +182,8 @@ github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJY github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -185,6 +196,8 @@ github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB7 github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4= +github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= @@ -257,7 +270,9 @@ github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfr github.com/migueleliasweb/go-github-mock v0.0.18 h1:0lWt9MYmZQGnQE2rFtjlft/YtD6hzxuN6JJRFpujzEI= github.com/migueleliasweb/go-github-mock v0.0.18/go.mod h1:CcgXcbMoRnf3rRVHqGssuBquZDIcaplxL2W6G+xs7kM= github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -265,12 +280,14 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= +github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= github.com/nyaruka/phonenumbers v1.1.1 h1:fyoZmpLN2VCmAnc51XcrNOUVP2wT1ZzQl348ggIaXII= github.com/nyaruka/phonenumbers v1.1.1/go.mod h1:cGaEsOrLjIL0iKGqJR5Rfywy86dSkbApEpXuM9KySNA= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q= github.com/onsi/gomega v1.27.7 h1:fVih9JD6ogIiHUN6ePK7HJidyEDpWGVB5mzM7cWNXoU= github.com/openshift/api v0.0.0-20241031180523-b1c90a6cf9a3 h1:QXptzhiO7WovLZSaXb4ig4Cd+ROctyyIJ2Tuw/Du4VI= @@ -295,18 +312,24 @@ github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI= github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= github.com/redhat-cop/operator-utils v1.3.6 h1:T+E/dxRMlFOIfqE1SAy1xFPXJXD8fKX4L7RL30N4D4w= +github.com/redhat-cop/operator-utils v1.3.6/go.mod h1:Qou2Sxm9iAdxz1ibUTm4nQGjHNv4bU7kz42fAvK1UuU= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= 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/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= 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/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 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= @@ -336,6 +359,7 @@ github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+ github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk= +github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= @@ -351,6 +375,7 @@ go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8p go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 h1:+FNtrFTmVw0YZGpBGX56XDee331t6JAXeK2bcyhLOOc= +go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0Hg7FvpRQsQh5OSqIylirxKC7o= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -368,6 +393,7 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= @@ -397,6 +423,7 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= @@ -422,6 +449,7 @@ golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191002063906-3421d5a6bb1c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/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= @@ -438,6 +466,7 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -448,6 +477,7 @@ golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= @@ -461,6 +491,7 @@ 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.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.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= @@ -557,6 +588,7 @@ k8s.io/apimachinery v0.27.7/go.mod h1:jBGQgTjkw99ef6q5hv1YurDd3BqKDk9YRxmX0Ozo0i k8s.io/apiserver v0.27.2 h1:p+tjwrcQEZDrEorCZV2/qE8osGTINPuS5ZNqWAvKm5E= k8s.io/apiserver v0.27.2/go.mod h1:EsOf39d75rMivgvvwjJ3OW/u9n1/BmUMK5otEOJrb1Y= k8s.io/cli-runtime v0.27.3 h1:h592I+2eJfXj/4jVYM+tu9Rv8FEc/dyCoD80UJlMW2Y= +k8s.io/cli-runtime v0.27.3/go.mod h1:LzXud3vFFuDFXn2LIrWnscPgUiEj7gQQcYZE2UPn9Kw= k8s.io/client-go v0.27.3 h1:7dnEGHZEJld3lYwxvLl7WoehK6lAq7GvgjxpA3nv1E8= k8s.io/client-go v0.27.3/go.mod h1:2MBEKuTo6V1lbKy3z1euEGnhPfGZLKTS9tiJ2xodM48= k8s.io/component-base v0.27.3 h1:g078YmdcdTfrCE4fFobt7qmVXwS8J/3cI1XxRi/2+6k= @@ -568,6 +600,7 @@ k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= k8s.io/kubectl v0.27.3 h1:HyC4o+8rCYheGDWrkcOQHGwDmyLKR5bxXFgpvF82BOw= +k8s.io/kubectl v0.27.3/go.mod h1:g9OQNCC2zxT+LT3FS09ZYqnDhlvsKAfFq76oyarBcq4= k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 h1:qY1Ad8PODbnymg2pRbkyMT/ylpTrCM8P2RJ0yroCyIk= k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= @@ -577,7 +610,9 @@ sigs.k8s.io/controller-runtime v0.15.0/go.mod h1:7ngYvp1MLT+9GeZ+6lH3LOlcHkp/+tz sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/kustomize/api v0.13.2 h1:kejWfLeJhUsTGioDoFNJET5LQe/ajzXhJGYoU+pJsiA= +sigs.k8s.io/kustomize/api v0.13.2/go.mod h1:DUp325VVMFVcQSq+ZxyDisA8wtldwHxLZbr1g94UHsw= sigs.k8s.io/kustomize/kyaml v0.14.1 h1:c8iibius7l24G2wVAGZn/Va2wNys03GXLjYVIcFVxKA= +sigs.k8s.io/kustomize/kyaml v0.14.1/go.mod h1:AN1/IpawKilWD7V+YvQwRGUvuUOOWpjsHu6uHwonSF4= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= diff --git a/pkg/controller/signup_test.go b/pkg/controller/signup_test.go index 9c7cfbc6..c557e930 100644 --- a/pkg/controller/signup_test.go +++ b/pkg/controller/signup_test.go @@ -28,6 +28,7 @@ import ( testconfig "github.com/codeready-toolchain/toolchain-common/pkg/test/config" testsocialevent "github.com/codeready-toolchain/toolchain-common/pkg/test/socialevent" testusersignup "github.com/codeready-toolchain/toolchain-common/pkg/test/usersignup" + apiv1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/gin-gonic/gin" @@ -36,9 +37,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "gopkg.in/h2non/gock.v1" - apiv1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) @@ -85,9 +84,6 @@ func (s *TestSignupSuite) TestSignupPostHandler() { signupCtrl := controller.NewSignup(application) handler := gin.HandlerFunc(signupCtrl.PostHandler) - userID, err := uuid.NewV4() - require.NoError(s.T(), err) - s.Run("signup created", func() { // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() @@ -99,32 +95,16 @@ func (s *TestSignupSuite) TestSignupPostHandler() { require.NoError(s.T(), err) expectedUserID := ob.String() ctx.Set(context.SubKey, expectedUserID) + ctx.Set(context.UsernameKey, "bill") ctx.Set(context.EmailKey, expectedUserID+"@test.com") - signup := &crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID.String(), - Namespace: "namespace-foo", - }, - Spec: crtapi.UserSignupSpec{ - IdentityClaims: crtapi.IdentityClaimsEmbedded{ - PreferredUsername: "bill", - }, - }, - Status: crtapi.UserSignupStatus{ - Conditions: []crtapi.Condition{ - { - Type: crtapi.UserSignupComplete, - Status: apiv1.ConditionFalse, - Reason: "test_reason", - Message: "test_message", - }, - }, - }, - } + signup := testusersignup.NewUserSignup( + testusersignup.WithName("bill"), + IncompleteUserSignupCondition(), + ) svc.MockSignup = func(ctx *gin.Context) (*crtapi.UserSignup, error) { assert.Equal(s.T(), expectedUserID, ctx.GetString(context.SubKey)) + assert.Equal(s.T(), "bill", ctx.GetString(context.UsernameKey)) assert.Equal(s.T(), expectedUserID+"@test.com", ctx.GetString(context.EmailKey)) return signup, nil } @@ -167,6 +147,19 @@ func (s *TestSignupSuite) TestSignupPostHandler() { }) } +func IncompleteUserSignupCondition() testusersignup.Modifier { + return func(userSignup *crtapi.UserSignup) { + userSignup.Status.Conditions = []crtapi.Condition{ + { + Type: crtapi.UserSignupComplete, + Status: apiv1.ConditionFalse, + Reason: "test_reason", + Message: "test_message", + }, + } + } +} + func (s *TestSignupSuite) TestSignupGetHandler() { // Create a request to pass to our handler. We don't have any query parameters for now, so we'll // pass 'nil' as the third parameter. @@ -267,25 +260,12 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { s.OverrideApplicationDefault() // Create UserSignup - ob, err := uuid.NewV4() - require.NoError(s.T(), err) - userID := ob.String() - - userSignup := &crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID, - Namespace: configuration.Namespace(), - Annotations: map[string]string{ - crtapi.UserSignupVerificationCounterAnnotationKey: "0", - crtapi.UserSignupVerificationCodeAnnotationKey: "", - }, - Labels: map[string]string{}, - }, - Spec: crtapi.UserSignupSpec{}, - Status: crtapi.UserSignupStatus{}, - } - states.SetVerificationRequired(userSignup, true) + userSignup := testusersignup.NewUserSignup( + testusersignup.WithName("johnny"), + testusersignup.WithAnnotation(crtapi.UserSignupVerificationCounterAnnotationKey, "0"), + testusersignup.WithAnnotation(crtapi.UserSignupVerificationCodeAnnotationKey, ""), + testusersignup.VerificationRequiredAgo(time.Second)) + userID := userSignup.Spec.IdentityClaims.UserID fakeClient, application := testutil.PrepareInClusterAppWithOption(s.T(), httpClientFactoryOption(), userSignup) defer gock.Off() @@ -300,11 +280,11 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { BodyString("") data := []byte(fmt.Sprintf(`{"phone_number": "%s", "country_code": "1"}`, phoneNumber)) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") require.Equal(s.T(), http.StatusNoContent, rr.Code) updatedUserSignup := &crtapi.UserSignup{} - err = fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(userSignup), updatedUserSignup) + err := fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(userSignup), updatedUserSignup) require.NoError(s.T(), err) require.NotEmpty(s.T(), updatedUserSignup.Annotations[crtapi.UserSignupVerificationCodeAnnotationKey]) @@ -334,11 +314,11 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { BodyString("") data := []byte(`{"phone_number": "2268213044", "country_code": "(1)"}`) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") require.Equal(s.T(), http.StatusBadRequest, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Bad Request", bodyParams["status"]) @@ -348,13 +328,13 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { }) s.Run("init verification request body could not be read", func() { data := []byte(`{"test_number": "2268213044", "test_code": "1"}`) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") // Check the status code is what we expect. assert.Equal(s.T(), http.StatusBadRequest, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) messageLines := strings.Split(bodyParams["message"].(string), "\n") @@ -369,11 +349,10 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { cfg := configuration.GetRegistrationServiceConfig() originalValue := cfg.Verification().DailyLimit() s.SetConfig(testconfig.RegistrationService().Verification().DailyLimit(0)) - require.NoError(s.T(), err) defer s.SetConfig(testconfig.RegistrationService().Verification().DailyLimit(originalValue)) data := []byte(`{"phone_number": "2268213044", "country_code": "1"}`) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") // Check the status code is what we expect. assert.Equal(s.T(), http.StatusForbidden, rr.Code, "handler returned wrong status code") @@ -381,20 +360,8 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { s.Run("init verification handler fails when verification not required", func() { // Create UserSignup - ob, err := uuid.NewV4() - require.NoError(s.T(), err) - userID := ob.String() - - userSignup := &crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID, - Namespace: configuration.Namespace(), - }, - Spec: crtapi.UserSignupSpec{}, - Status: crtapi.UserSignupStatus{}, - } - states.SetVerificationRequired(userSignup, false) + userSignup := testusersignup.NewUserSignup(testusersignup.WithName("johnny")) + userID := userSignup.Spec.IdentityClaims.UserID _, application := testutil.PrepareInClusterAppWithOption(s.T(), httpClientFactoryOption(), userSignup) @@ -403,13 +370,13 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { handler := gin.HandlerFunc(ctrl.InitVerificationHandler) data := []byte(`{"phone_number": "2268213044", "country_code": "1"}`) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") // Check the status code is what we expect. assert.Equal(s.T(), http.StatusBadRequest, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Bad Request", bodyParams["status"]) @@ -427,17 +394,9 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { // Create a mock SignupService svc := &FakeSignupService{ MockGetUserSignupFromIdentifier: func(_, _ string) (userSignup *crtapi.UserSignup, e error) { - us := crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID, - Labels: map[string]string{}, - }, - Spec: crtapi.UserSignupSpec{}, - Status: crtapi.UserSignupStatus{}, - } - states.SetVerificationRequired(&us, true) - return &us, nil + return testusersignup.NewUserSignup( + testusersignup.WithName("johnny"), + testusersignup.VerificationRequiredAgo(time.Second)), nil }, MockPhoneNumberAlreadyInUse: func(_, _, _ string) error { return nil @@ -454,7 +413,7 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. data := []byte(`{"phone_number": "!226%213044", "country_code": "1"}`) - rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "", http.MethodPut, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, gin.Param{}, data, userID, "johnny", http.MethodPut, "/api/v1/signup/verification") // Check the status code is what we expect. assert.Equal(s.T(), http.StatusBadRequest, rr.Code) @@ -463,24 +422,12 @@ func (s *TestSignupSuite) TestInitVerificationHandler() { func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { // Create UserSignup - ob, err := uuid.NewV4() - require.NoError(s.T(), err) - userID := ob.String() - - userSignup := &crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID, - Namespace: configuration.Namespace(), - Annotations: map[string]string{ - crtapi.UserVerificationAttemptsAnnotationKey: "0", - crtapi.UserSignupVerificationCodeAnnotationKey: "999888", - crtapi.UserVerificationExpiryAnnotationKey: time.Now().Add(10 * time.Second).Format(service.TimestampLayout), - }, - }, - Spec: crtapi.UserSignupSpec{}, - Status: crtapi.UserSignupStatus{}, - } + userSignup := testusersignup.NewUserSignup( + testusersignup.WithName("johnny"), + testusersignup.WithAnnotation(crtapi.UserVerificationAttemptsAnnotationKey, "0"), + testusersignup.WithAnnotation(crtapi.UserSignupVerificationCodeAnnotationKey, "999888"), + testusersignup.WithAnnotation(crtapi.UserVerificationExpiryAnnotationKey, time.Now().Add(10*time.Second).Format(service.TimestampLayout))) + userID := userSignup.Spec.IdentityClaims.UserID s.Run("verification successful", func() { // Create Signup controller instance. @@ -492,13 +439,13 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { Key: "code", Value: "999888", } - rr := initPhoneVerification(s.T(), handler, param, nil, userID, "", http.MethodGet, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, param, nil, userID, "johnny", http.MethodGet, "/api/v1/signup/verification") // Check the status code is what we expect. require.Equal(s.T(), http.StatusOK, rr.Code) updatedUserSignup := &crtapi.UserSignup{} - err = fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(userSignup), updatedUserSignup) + err := fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(userSignup), updatedUserSignup) require.NoError(s.T(), err) // Check that the correct UserSignup is passed into the FakeSignupService for update @@ -523,18 +470,18 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { Key: "code", Value: "111233", } - rr := initPhoneVerification(s.T(), handler, param, nil, userID, "", http.MethodGet, "/api/v1/signup/verification") + rr := initPhoneVerification(s.T(), handler, param, nil, userID, "johnny", http.MethodGet, "/api/v1/signup/verification") // Check the status code is what we expect. require.Equal(s.T(), http.StatusInternalServerError, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Internal Server Error", bodyParams["status"]) require.InDelta(s.T(), float64(500), bodyParams["code"], 0.01) - require.Equal(s.T(), fmt.Sprintf("no user: error retrieving usersignup: %s", userSignup.Name), bodyParams["message"]) + require.Equal(s.T(), fmt.Sprintf("no user: error retrieving usersignup: %s", userID), bodyParams["message"]) require.Equal(s.T(), "error while verifying phone code", bodyParams["details"]) }) @@ -555,7 +502,7 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { require.Equal(s.T(), http.StatusNotFound, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Not Found", bodyParams["status"]) @@ -577,14 +524,14 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { Key: "code", Value: "555555", } - rr := initPhoneVerification(s.T(), handler, param, nil, userID, "", http.MethodGet, + rr := initPhoneVerification(s.T(), handler, param, nil, userID, "johnny", http.MethodGet, "/api/v1/signup/verification/555555") // Check the status code is what we expect. require.Equal(s.T(), http.StatusInternalServerError, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Internal Server Error", bodyParams["status"]) @@ -611,13 +558,13 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { Key: "code", Value: "333333", } - rr := initPhoneVerification(s.T(), handler, param, nil, userID, "", http.MethodGet, "/api/v1/signup/verification/333333") + rr := initPhoneVerification(s.T(), handler, param, nil, userID, "johnny", http.MethodGet, "/api/v1/signup/verification/333333") // Check the status code is what we expect. require.Equal(s.T(), http.StatusTooManyRequests, rr.Code) bodyParams := make(map[string]interface{}) - err = json.Unmarshal(rr.Body.Bytes(), &bodyParams) + err := json.Unmarshal(rr.Body.Bytes(), &bodyParams) require.NoError(s.T(), err) require.Equal(s.T(), "Too Many Requests", bodyParams["status"]) @@ -644,29 +591,11 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { s.Run("usersignup stored by its username", func() { // Create another UserSignup - otherUserID := uuid.Must(uuid.NewV4()).String() - - otherUserSignup := &crtapi.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: "jsmith", - Namespace: configuration.Namespace(), - Annotations: map[string]string{ - crtapi.UserVerificationAttemptsAnnotationKey: "0", - crtapi.UserSignupVerificationCodeAnnotationKey: "999127", - crtapi.UserVerificationExpiryAnnotationKey: time.Now().Add(10 * time.Second).Format(service.TimestampLayout), - }, - }, - Spec: crtapi.UserSignupSpec{ - IdentityClaims: crtapi.IdentityClaimsEmbedded{ - PreferredUsername: "jsmith", - PropagatedClaims: crtapi.PropagatedClaims{ - Sub: otherUserID, - }, - }, - }, - Status: crtapi.UserSignupStatus{}, - } + otherUserSignup := testusersignup.NewUserSignup( + testusersignup.WithName("jsmith"), + testusersignup.WithAnnotation(crtapi.UserVerificationAttemptsAnnotationKey, "0"), + testusersignup.WithAnnotation(crtapi.UserSignupVerificationCodeAnnotationKey, "999127"), + testusersignup.WithAnnotation(crtapi.UserVerificationExpiryAnnotationKey, time.Now().Add(10*time.Second).Format(service.TimestampLayout))) fakeClient, application := testutil.PrepareInClusterApp(s.T(), otherUserSignup, userSignup) @@ -684,7 +613,7 @@ func (s *TestSignupSuite) TestVerifyPhoneCodeHandler() { require.Equal(s.T(), http.StatusOK, rr.Code) updatedUserSignup := &crtapi.UserSignup{} - err = fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(otherUserSignup), updatedUserSignup) + err := fakeClient.Get(gocontext.TODO(), client.ObjectKeyFromObject(otherUserSignup), updatedUserSignup) require.NoError(s.T(), err) // Check that the correct UserSignup is passed into the FakeSignupService for update diff --git a/pkg/proxy/handlers/spacelister_get_test.go b/pkg/proxy/handlers/spacelister_get_test.go index 56bece8c..bab33b32 100644 --- a/pkg/proxy/handlers/spacelister_get_test.go +++ b/pkg/proxy/handlers/spacelister_get_test.go @@ -82,7 +82,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { overrideMemberClient *test.FakeClient }{ "dancelover gets dancelover space": { - username: "dance.lover", + username: "dancelover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "dancelover", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -120,7 +120,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "dancelover", }, "dancelover gets movielover space": { - username: "dance.lover", + username: "dancelover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "other", false, commonproxy.WithAvailableRoles([]string{ @@ -153,7 +153,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "movielover", }, "dancelover gets foodlover space": { - username: "dance.lover", + username: "dancelover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "foodlover", "admin", false, commonproxy.WithAvailableRoles([]string{ @@ -177,7 +177,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "foodlover", }, "movielover gets movielover space": { - username: "movie.lover", + username: "movielover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -211,14 +211,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "movielover", }, "movielover cannot get dancelover space": { - username: "movie.lover", + username: "movielover", expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"dancelover\\\" not found\"", expectedWorkspace: "dancelover", expectedErrCode: 404, }, "signup not ready yet": { - username: "movie.lover", + username: "movielover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "movielover", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -251,7 +251,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "movielover", }, "get nstemplatetier error": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "nstemplatetier error", expectedErrCode: 500, @@ -266,7 +266,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "dancelover", }, "get signup error": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "signup error", expectedErrCode: 500, @@ -276,14 +276,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "dancelover", }, "signup has no compliant username set": { - username: "racing.lover", + username: "racinglover", expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"racinglover\\\" not found\"", expectedErrCode: 404, expectedWorkspace: "racinglover", }, "list spacebindings error": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "list spacebindings error", expectedErrCode: 500, @@ -298,7 +298,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "dancelover", }, "unable to get space": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"dancelover\\\" not found\"", expectedErrCode: 404, @@ -313,7 +313,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "dancelover", }, "unable to get parent-space": { - username: "food.lover", + username: "foodlover", expectedWs: nil, expectedErr: "Internal error occurred: unable to get parent-space: parent-space error", expectedErrCode: 500, @@ -328,7 +328,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "foodlover", }, "error spaceBinding request has no name": { - username: "anime.lover", + username: "animelover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "animelover", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -341,7 +341,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "animelover", }, "error spaceBinding request has no namespace set": { - username: "car.lover", + username: "carlover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "carlover", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -354,7 +354,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "carlover", }, "parent can list parentspace": { - username: "parent.space", + username: "parentspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "parentspace", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -372,7 +372,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "parentspace", }, "parent can list childspace": { - username: "parent.space", + username: "parentspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "childspace", "admin", false, commonproxy.WithAvailableRoles([]string{ @@ -395,7 +395,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "childspace", }, "parent can list grandchildspace": { - username: "parent.space", + username: "parentspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", false, commonproxy.WithAvailableRoles([]string{ @@ -423,14 +423,14 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "grandchildspace", }, "child cannot list parentspace": { - username: "child.space", + username: "childspace", expectedWs: nil, expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"parentspace\\\" not found\"", expectedErrCode: 404, expectedWorkspace: "parentspace", }, "child can list childspace": { - username: "child.space", + username: "childspace", expectedWorkspace: "childspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "childspace", "admin", true, @@ -453,7 +453,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, }, "child can list grandchildspace": { - username: "child.space", + username: "childspace", expectedWorkspace: "grandchildspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", false, @@ -481,7 +481,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, }, "grandchild can list grandchildspace": { - username: "grandchild.space", + username: "grandchildspace", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{workspaceFor(t, fakeClient, "grandchildspace", "admin", true, commonproxy.WithAvailableRoles([]string{ @@ -509,21 +509,21 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { expectedWorkspace: "grandchildspace", }, "grandchild cannot list parentspace": { - username: "grandchild.space", + username: "grandchildspace", expectedWorkspace: "parentspace", expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"parentspace\\\" not found\"", expectedErrCode: 404, expectedWs: nil, }, "grandchild cannot list childspace": { - username: "grandchild.space", + username: "grandchildspace", expectedWorkspace: "childspace", expectedErr: "\"workspaces.toolchain.dev.openshift.com \\\"childspace\\\" not found\"", expectedErrCode: 404, expectedWs: nil, }, "no member clusters found": { - username: "movie.lover", + username: "movielover", expectedWorkspace: "movielover", expectedErr: "no member clusters found", expectedErrCode: 500, @@ -532,7 +532,7 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { }, }, "error listing spacebinding requests": { - username: "movie.lover", + username: "movielover", expectedWorkspace: "movielover", expectedErr: "mock list error", expectedErrCode: 500, @@ -610,8 +610,8 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { func TestGetUserWorkspace(t *testing.T) { fakeSignupService := fake.NewSignupService( - newSignup("batman", "batman.space", true), - newSignup("robin", "robin.space", true), + newSignup("batman", true), + newSignup("robin", true), ) tests := map[string]struct { @@ -623,19 +623,19 @@ func TestGetUserWorkspace(t *testing.T) { overrideSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupComplete bool) (*signup.Signup, error) }{ "get robin workspace": { - username: "robin.space", + username: "robin", workspaceRequest: "robin", expectedWorkspace: func(t *testing.T, fakeClient *test.FakeClient) toolchainv1alpha1.Workspace { return workspaceFor(t, fakeClient, "robin", "admin", true) }, }, "invalid number of spacebindings": { - username: "batman.space", + username: "batman", expectedErr: "invalid number of SpaceBindings found for MUR:batman and Space:batman. Expected 1 got 2", workspaceRequest: "batman", }, "user is unauthorized": { - username: "robin.space", + username: "robin", workspaceRequest: "batman", }, "usersignup not found": { @@ -670,7 +670,7 @@ func TestGetUserWorkspace(t *testing.T) { expectedWorkspace: nil, // user is not authorized }, "get signup error": { - username: "batman.space", + username: "batman", workspaceRequest: "batman", expectedErr: "signup error", overrideSignupFunc: func(_ *gin.Context, _, _ string, _ bool) (*signup.Signup, error) { @@ -679,7 +679,7 @@ func TestGetUserWorkspace(t *testing.T) { expectedWorkspace: nil, }, "list spacebindings error": { - username: "robin.space", + username: "robin", workspaceRequest: "robin", expectedErr: "list spacebindings error", mockFakeClient: func(fakeClient *test.FakeClient) { @@ -699,7 +699,7 @@ func TestGetUserWorkspace(t *testing.T) { expectedWorkspace: nil, }, "batman can not get robin workspace": { // Because public viewer feature is NOT enabled - username: "batman.space", + username: "batman", workspaceRequest: "robin", expectedErr: "", expectedWorkspace: nil, @@ -768,9 +768,9 @@ func TestGetUserWorkspace(t *testing.T) { func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { fakeSignupService := fake.NewSignupService( - newSignup("batman", "batman.space", true), - newSignup("robin", "robin.space", true), - newSignup("gordon", "gordon.no-space", false), + newSignup("batman", true), + newSignup("robin", true), + newSignup("gordon", false), ) fakeClient := test.NewFakeClient(t, @@ -799,32 +799,32 @@ func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { expectedWorkspace *toolchainv1alpha1.Workspace }{ "robin can get robin workspace": { - username: "robin.space", + username: "robin", workspaceRequest: "robin", expectedWorkspace: &robinWS, }, "batman can get batman workspace": { - username: "batman.space", + username: "batman", workspaceRequest: "batman", expectedWorkspace: &batmanWS, }, "batman can get robin workspace as public-viewer": { - username: "batman.space", + username: "batman", workspaceRequest: "robin", expectedWorkspace: publicRobinWS, }, "robin can not get batman workspace": { - username: "robin.space", + username: "robin", workspaceRequest: "batman", expectedWorkspace: nil, }, "gordon can get robin workspace as public-viewer": { - username: "gordon.no-space", + username: "gordon", workspaceRequest: "robin", expectedWorkspace: publicRobinWS, }, "gordon can not get batman workspace": { - username: "gordon.no-space", + username: "gordon", workspaceRequest: "batman", expectedWorkspace: nil, }, @@ -871,9 +871,9 @@ func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { fakeSignupService := fake.NewSignupService( - newSignup("batman", "batman.space", true), - newSignup("robin", "robin.space", true), - newSignup("gordon", "gordon.no-space", false), + newSignup("batman", true), + newSignup("robin", true), + newSignup("gordon", false), ) fakeClient := test.NewFakeClient(t, @@ -924,17 +924,17 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { expectedWorkspace *toolchainv1alpha1.Workspace }{ "robin can get robin workspace": { - username: "robin.space", + username: "robin", workspaceRequest: "robin", expectedWorkspace: &robinWS, }, "batman can get batman workspace": { - username: "batman.space", + username: "batman", workspaceRequest: "batman", expectedWorkspace: &batmanWS, }, "batman can get robin workspace": { - username: "batman.space", + username: "batman", workspaceRequest: "robin", expectedWorkspace: func() *toolchainv1alpha1.Workspace { batmansRobinWS := robinWS.DeepCopy() @@ -944,17 +944,17 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { }(), }, "robin can not get batman workspace": { - username: "robin.space", + username: "robin", workspaceRequest: "batman", expectedWorkspace: nil, }, "gordon can not get batman workspace": { - username: "gordon.no-space", + username: "gordon", workspaceRequest: "batman", expectedWorkspace: nil, }, "gordon can get robin workspace": { - username: "gordon.no-space", + username: "gordon", workspaceRequest: "robin", expectedWorkspace: func() *toolchainv1alpha1.Workspace { batmansRobinWS := robinWS.DeepCopy() diff --git a/pkg/proxy/handlers/spacelister_list_test.go b/pkg/proxy/handlers/spacelister_list_test.go index 05fe4d4c..f0da39fb 100644 --- a/pkg/proxy/handlers/spacelister_list_test.go +++ b/pkg/proxy/handlers/spacelister_list_test.go @@ -30,15 +30,15 @@ import ( func TestListUserWorkspaces(t *testing.T) { tests := map[string]struct { username string - additionalSignups []fake.SignupDef + additionalSignups []*signup.Signup additionalObjects []runtimeclient.Object expectedWorkspaces func(*test.FakeClient) []toolchainv1alpha1.Workspace publicViewerEnabled bool }{ "dancelover lists spaces with public-viewer enabled": { - username: "dance.lover", - additionalSignups: []fake.SignupDef{ - newSignup("communitylover", "community.lover", true), + username: "dancelover", + additionalSignups: []*signup.Signup{ + newSignup("communitylover", true), }, additionalObjects: []runtimeclient.Object{ fake.NewSpace("communitylover", "member-1", "communitylover", space.WithTierName("appstudio")), @@ -54,7 +54,7 @@ func TestListUserWorkspaces(t *testing.T) { publicViewerEnabled: true, }, "dancelover lists spaces with public-viewer disabled": { - username: "dance.lover", + username: "dancelover", expectedWorkspaces: func(fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{ workspaceFor(t, fakeClient, "dancelover", "admin", true), @@ -126,7 +126,7 @@ func TestHandleSpaceListRequest(t *testing.T) { mockFakeClient func(fakeClient *test.FakeClient) }{ "dancelover lists spaces": { - username: "dance.lover", + username: "dancelover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{ workspaceFor(t, fakeClient, "dancelover", "admin", true), @@ -136,7 +136,7 @@ func TestHandleSpaceListRequest(t *testing.T) { expectedErr: "", }, "movielover lists spaces": { - username: "movie.lover", + username: "movielover", expectedWs: func(t *testing.T, fakeClient *test.FakeClient) []toolchainv1alpha1.Workspace { return []toolchainv1alpha1.Workspace{ workspaceFor(t, fakeClient, "movielover", "admin", true), @@ -145,25 +145,25 @@ func TestHandleSpaceListRequest(t *testing.T) { expectedErr: "", }, "signup has no compliant username set": { - username: "racing.lover", + username: "racinglover", expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "space not initialized yet": { - username: "panda.lover", + username: "pandalover", expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "no spaces found": { - username: "user.nospace", + username: "usernospace", expectedWs: nil, expectedErr: "", expectedErrCode: 200, }, "informer error": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "list spacebindings error", expectedErrCode: 500, @@ -177,7 +177,7 @@ func TestHandleSpaceListRequest(t *testing.T) { }, }, "get signup error": { - username: "dance.lover", + username: "dancelover", expectedWs: nil, expectedErr: "signup error", expectedErrCode: 500, diff --git a/pkg/proxy/handlers/spacelister_test.go b/pkg/proxy/handlers/spacelister_test.go index c5fc5cab..73824d2a 100644 --- a/pkg/proxy/handlers/spacelister_test.go +++ b/pkg/proxy/handlers/spacelister_test.go @@ -23,19 +23,19 @@ func buildSpaceListerFakes(t *testing.T) (*fake.SignupService, *test.FakeClient) return buildSpaceListerFakesWithResources(t, nil, nil) } -func buildSpaceListerFakesWithResources(t *testing.T, signups []fake.SignupDef, objs []client.Object) (*fake.SignupService, *test.FakeClient) { +func buildSpaceListerFakesWithResources(t *testing.T, signups []*signup.Signup, objs []client.Object) (*fake.SignupService, *test.FakeClient) { ss := append(signups, - newSignup("dancelover", "dance.lover", true), - newSignup("movielover", "movie.lover", true), - newSignup("pandalover", "panda.lover", true), - newSignup("usernospace", "user.nospace", true), - newSignup("foodlover", "food.lover", true), - newSignup("animelover", "anime.lover", true), - newSignup("carlover", "car.lover", true), - newSignup("racinglover", "racing.lover", false), - newSignup("parentspace", "parent.space", true), - newSignup("childspace", "child.space", true), - newSignup("grandchildspace", "grandchild.space", true), + newSignup("dancelover", true), + newSignup("movielover", true), + newSignup("pandalover", true), + newSignup("usernospace", true), + newSignup("foodlover", true), + newSignup("animelover", true), + newSignup("carlover", true), + newSignup("racinglover", false), + newSignup("parentspace", true), + newSignup("childspace", true), + newSignup("grandchildspace", true), ) fakeSignupService := fake.NewSignupService(ss...) @@ -103,22 +103,20 @@ func buildSpaceListerFakesWithResources(t *testing.T, signups []fake.SignupDef, return fakeSignupService, test.NewFakeClient(t, oo...) } -func newSignup(signupName, username string, ready bool) fake.SignupDef { +func newSignup(signupName string, ready bool) *signup.Signup { compliantUsername := signupName if !ready { // signup is not ready, let's set compliant username to blank compliantUsername = "" } - us := fake.Signup(signupName, &signup.Signup{ + return &signup.Signup{ Name: signupName, - Username: username, + Username: signupName, CompliantUsername: compliantUsername, Status: signup.Status{ Ready: ready, }, - }) - - return us + } } func decodeResponseToWorkspace(data []byte) (*toolchainv1alpha1.Workspace, error) { diff --git a/pkg/proxy/members_test.go b/pkg/proxy/members_test.go index 505daf18..5192920f 100644 --- a/pkg/proxy/members_test.go +++ b/pkg/proxy/members_test.go @@ -39,19 +39,22 @@ func TestRunMemberClustersSuite(t *testing.T) { func (s *TestMemberClustersSuite) TestGetClusterAccess() { // given - sc := fake.NewSignupService(fake.Signup("123-noise", &signup.Signup{ + sc := fake.NewSignupService(&signup.Signup{ + Name: "noise1", CompliantUsername: "noise1", Username: "noise1", Status: signup.Status{ Ready: true, }, - }), fake.Signup("456-not-ready", &signup.Signup{ + }, &signup.Signup{ + Name: "456-not-ready", CompliantUsername: "", Username: "john@", Status: signup.Status{ Ready: false, }, - }), fake.Signup("789-ready", &signup.Signup{ + }, &signup.Signup{ + Name: "789-ready", APIEndpoint: "https://api.endpoint.member-2.com:6443", ClusterName: "member-2", CompliantUsername: "smith2", @@ -59,7 +62,8 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { Status: signup.Status{ Ready: true, }, - }), fake.Signup("012-ready-unknown-cluster", &signup.Signup{ + }, &signup.Signup{ + Name: "012-ready-unknown-cluster", APIEndpoint: "https://api.endpoint.unknown.com:6443", ClusterName: "unknown", CompliantUsername: "doe", @@ -67,7 +71,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { Status: signup.Status{ Ready: true, }, - })) + }) pp := &toolchainv1alpha1.ProxyPlugin{ ObjectMeta: metav1.ObjectMeta{ @@ -117,7 +121,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { } // when - _, err := members.GetClusterAccess("789-ready", "", tc.workspace, "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "789-ready", tc.workspace, "", publicViewerEnabled) // then require.EqualError(s.T(), err, "oopsi woopsi") @@ -125,14 +129,6 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { sc.MockGetSignup = sc.DefaultMockGetSignup() // restore the default signup service, so it doesn't return an error anymore - s.Run("userid is not found", func() { - // when - _, err := members.GetClusterAccess("unknown_id", "", tc.workspace, "", publicViewerEnabled) - - // then - require.EqualError(s.T(), err, "user is not provisioned (yet)") - }) - s.Run("username is not found", func() { // when _, err := members.GetClusterAccess("", "unknown_username", tc.workspace, "", publicViewerEnabled) @@ -143,7 +139,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.Run("user is not provisioned yet", func() { // when - _, err := members.GetClusterAccess("456-not-ready", "", tc.workspace, "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "456-not-ready", tc.workspace, "", publicViewerEnabled) // then require.EqualError(s.T(), err, "user is not provisioned (yet)") @@ -169,7 +165,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { members := proxy.NewMemberClusters(nsClient, sc, commoncluster.GetMemberClusters) // when - _, err := members.GetClusterAccess("789-ready", "", "smith2", "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "789-ready", "smith2", "", publicViewerEnabled) // then // original error is only logged so that it doesn't reveal information about a space that may not belong to the requestor @@ -178,7 +174,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.Run("space not found", func() { // when - _, err := members.GetClusterAccess("789-ready", "", "unknown", "", publicViewerEnabled) // unknown workspace requested + _, err := members.GetClusterAccess("", "789-ready", "unknown", "", publicViewerEnabled) // unknown workspace requested // then require.EqualError(s.T(), err, "the requested space is not available") @@ -192,7 +188,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { }) s.Run("default workspace case", func() { // when - _, err := members.GetClusterAccess("789-ready", "", "", "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "789-ready", "", "", publicViewerEnabled) // then require.EqualError(s.T(), err, "no member clusters found") @@ -200,7 +196,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.Run("workspace context case", func() { // when - _, err := members.GetClusterAccess("789-ready", "", "smith2", "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "789-ready", "smith2", "", publicViewerEnabled) // then require.EqualError(s.T(), err, "no member clusters found") @@ -213,7 +209,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { }) s.Run("default workspace case", func() { // when - _, err := members.GetClusterAccess("012-ready-unknown-cluster", "", "", "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "012-ready-unknown-cluster", "", "", publicViewerEnabled) // then require.EqualError(s.T(), err, "no member cluster found for the user") @@ -221,7 +217,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.Run("workspace context case", func() { // when - _, err := members.GetClusterAccess("012-ready-unknown-cluster", "", "unknown-cluster", "", publicViewerEnabled) + _, err := members.GetClusterAccess("", "012-ready-unknown-cluster", "unknown-cluster", "", publicViewerEnabled) // then require.EqualError(s.T(), err, "no member cluster found for space 'unknown-cluster'") @@ -282,7 +278,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { expectedToken := "abc123" // should match member 2 bearer token // when - ca, err := members.GetClusterAccess("789-ready", "", "", "tekton-results", publicViewerEnabled) + ca, err := members.GetClusterAccess("", "789-ready", "", "tekton-results", publicViewerEnabled) // then require.NoError(s.T(), err) @@ -293,22 +289,9 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.assertClusterAccess(access.NewClusterAccess(*expectedURL, expectedToken, ""), ca) - s.Run("cluster access correct when username provided", func() { - // when - ca, err := members.GetClusterAccess("", "smith@", "", "tekton-results", publicViewerEnabled) - - // then - require.NoError(s.T(), err) - require.NotNil(s.T(), ca) - expectedURL, err := url.Parse("https://myservice.endpoint.member-2.com") - require.NoError(s.T(), err) - s.assertClusterAccess(access.NewClusterAccess(*expectedURL, expectedToken, "smith"), ca) - assert.Equal(s.T(), "smith2", ca.Username()) - }) - s.Run("cluster access correct when using workspace context", func() { // when - ca, err := members.GetClusterAccess("789-ready", "", "smith2", "tekton-results", publicViewerEnabled) // workspace-context specified + ca, err := members.GetClusterAccess("", "789-ready", "smith2", "tekton-results", publicViewerEnabled) // workspace-context specified // then require.NoError(s.T(), err) @@ -336,7 +319,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { return memberClient.Client.Get(ctx, key, obj, opts...) } memberArray[0].Client = mC - ca, err := members.GetClusterAccess("789-ready", "", "teamspace", "tekton-results", publicViewerEnabled) // workspace-context specified + ca, err := members.GetClusterAccess("", "789-ready", "teamspace", "tekton-results", publicViewerEnabled) // workspace-context specified // then require.NoError(s.T(), err) @@ -354,7 +337,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { expectedToken := "abc123" // should match member 2 bearer token // when - ca, err := members.GetClusterAccess("789-ready", "", "", "", publicViewerEnabled) + ca, err := members.GetClusterAccess("", "789-ready", "", "", publicViewerEnabled) // then require.NoError(s.T(), err) @@ -365,22 +348,9 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.assertClusterAccess(access.NewClusterAccess(*expectedURL, expectedToken, ""), ca) - s.Run("cluster access correct when username provided", func() { - // when - ca, err := members.GetClusterAccess("", "smith@", "", "", publicViewerEnabled) - - // then - require.NoError(s.T(), err) - require.NotNil(s.T(), ca) - expectedURL, err := url.Parse("https://api.endpoint.member-2.com:6443") - require.NoError(s.T(), err) - s.assertClusterAccess(access.NewClusterAccess(*expectedURL, expectedToken, "smith"), ca) - assert.Equal(s.T(), "smith2", ca.Username()) - }) - s.Run("cluster access correct when using workspace context", func() { // when - ca, err := members.GetClusterAccess("789-ready", "", "smith2", "", publicViewerEnabled) // workspace-context specified + ca, err := members.GetClusterAccess("", "789-ready", "smith2", "", publicViewerEnabled) // workspace-context specified // then require.NoError(s.T(), err) @@ -392,7 +362,7 @@ func (s *TestMemberClustersSuite) TestGetClusterAccess() { s.Run("another workspace on another cluster", func() { // when - ca, err := members.GetClusterAccess("789-ready", "", "teamspace", "", publicViewerEnabled) // workspace-context specified + ca, err := members.GetClusterAccess("", "789-ready", "teamspace", "", publicViewerEnabled) // workspace-context specified // then require.NoError(s.T(), err) diff --git a/pkg/proxy/proxy_community_test.go b/pkg/proxy/proxy_community_test.go index c2170d7a..159602da 100644 --- a/pkg/proxy/proxy_community_test.go +++ b/pkg/proxy/proxy_community_test.go @@ -12,7 +12,6 @@ import ( "github.com/codeready-toolchain/registration-service/test/fake" commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" authsupport "github.com/codeready-toolchain/toolchain-common/pkg/test/auth" - "github.com/google/uuid" "go.uber.org/atomic" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" @@ -72,15 +71,15 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { s.Run("successfully proxy", func() { // user with public workspace - smith := uuid.New() + smith := "smith" // user with private workspace - alice := uuid.New() + alice := "alice" // unsigned user - bob := uuid.New() + bob := "bob" // not ready - john := uuid.New() + john := "john" // banned user - eve, eveEmail := uuid.New(), "eve@somecorp.com" + eve, eveEmail := "eve", "eve@somecorp.com" // Start the member-2 API Server httpTestServerResponse := "my response" @@ -89,43 +88,43 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { // initialize SignupService signupService := fake.NewSignupService( - fake.Signup(smith.String(), &signup.Signup{ - Name: "smith", + &signup.Signup{ + Name: smith, APIEndpoint: testServer.URL, ClusterName: "member-2", - CompliantUsername: "smith", + CompliantUsername: smith, Username: "smith@", Status: signup.Status{ Ready: true, }, - }), - fake.Signup(alice.String(), &signup.Signup{ - Name: "alice", + }, + &signup.Signup{ + Name: alice, APIEndpoint: testServer.URL, ClusterName: "member-2", - CompliantUsername: "alice", + CompliantUsername: alice, Username: "alice@", Status: signup.Status{ Ready: true, }, - }), - fake.Signup(john.String(), &signup.Signup{ - Name: "john", - CompliantUsername: "john", + }, + &signup.Signup{ + Name: john, + CompliantUsername: john, Username: "john@", Status: signup.Status{ Ready: false, }, - }), - fake.Signup(eve.String(), &signup.Signup{ - Name: "eve", - CompliantUsername: "eve", + }, + &signup.Signup{ + Name: eve, + CompliantUsername: eve, Username: "eve@", Status: signup.Status{ Ready: false, Reason: toolchainv1alpha1.UserSignupUserBannedReason, }, - }), + }, ) // init fakeClient @@ -173,7 +172,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith"}, - "X-SSO-User": {"username-" + smith.String()}, + "X-SSO-User": {smith}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsRequestURL("smith-community"), @@ -191,7 +190,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + john.String()}, + "X-SSO-User": {john}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsRequestURL("smith-community"), @@ -209,7 +208,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + bob.String()}, + "X-SSO-User": {bob}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsRequestURL("smith-community"), @@ -230,7 +229,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + alice.String()}, + "X-SSO-User": {alice}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsRequestURL("smith-community"), @@ -288,7 +287,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"alice"}, - "X-SSO-User": {"username-" + alice.String()}, + "X-SSO-User": {alice}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsInNamespaceRequestURL("alice-private", "outside-of-workspace-namespace"), @@ -307,7 +306,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith"}, - "X-SSO-User": {"username-" + smith.String()}, + "X-SSO-User": {smith}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsInNamespaceRequestURL("smith-community", "outside-of-workspace-namespace"), @@ -326,7 +325,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + alice.String()}, + "X-SSO-User": {alice}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsInNamespaceRequestURL("smith-community", "outside-of-workspace-namespace"), @@ -344,7 +343,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + bob.String()}, + "X-SSO-User": {bob}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsInNamespaceRequestURL("smith-community", "outside-of-workspace-namespace"), @@ -363,7 +362,7 @@ func (s *TestProxySuite) checkProxyCommunityOK(proxy *Proxy, port string) { ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {toolchainv1alpha1.KubesawAuthenticatedUsername}, - "X-SSO-User": {"username-" + john.String()}, + "X-SSO-User": {john}, }, ExpectedProxyResponseStatus: http.StatusOK, RequestPath: podsInNamespaceRequestURL("smith-community", "outside-of-workspace-namespace"), diff --git a/pkg/proxy/proxy_test.go b/pkg/proxy/proxy_test.go index 27c3d111..2bed79a6 100644 --- a/pkg/proxy/proxy_test.go +++ b/pkg/proxy/proxy_test.go @@ -223,8 +223,7 @@ func (s *TestProxySuite) checkPlainHTTPErrors(proxy *Proxy) { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) require.NoError(s.T(), err) require.NotNil(s.T(), req) - userID := uuid.New() - req.Header.Set("Authorization", "Bearer "+s.token(userID, authsupport.WithSubClaim(""))) + req.Header.Set("Authorization", "Bearer "+s.token("unauthorized-user", authsupport.WithSubClaim(""))) resp, err := http.DefaultClient.Do(req) // then @@ -240,8 +239,7 @@ func (s *TestProxySuite) checkPlainHTTPErrors(proxy *Proxy) { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) require.NoError(s.T(), err) require.NotNil(s.T(), req) - userID := uuid.New() - req.Header.Set("Authorization", "Bearer "+s.token(userID, authsupport.WithEmailClaim(""))) + req.Header.Set("Authorization", "Bearer "+s.token("unauthorized-user", authsupport.WithEmailClaim(""))) resp, err := http.DefaultClient.Do(req) // then @@ -312,8 +310,7 @@ func (s *TestProxySuite) checkPlainHTTPErrors(proxy *Proxy) { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) require.NoError(s.T(), err) require.NotNil(s.T(), req) - userID := uuid.New() - token := s.token(userID, authsupport.WithSubClaim("alice"), authsupport.WithEmailClaim(bannedUser.Spec.Email)) + token := s.token("alice", authsupport.WithSubClaim("alice"), authsupport.WithEmailClaim(bannedUser.Spec.Email)) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) resp, err := http.DefaultClient.Do(req) @@ -330,8 +327,7 @@ func (s *TestProxySuite) checkPlainHTTPErrors(proxy *Proxy) { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) require.NoError(s.T(), err) require.NotNil(s.T(), req) - userID := uuid.New() - token := s.token(userID, authsupport.WithSubClaim("alice"), authsupport.WithEmailClaim(bannedUserListErrorEmailValue)) + token := s.token("alice", authsupport.WithSubClaim("alice"), authsupport.WithEmailClaim(bannedUserListErrorEmailValue)) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) resp, err := http.DefaultClient.Do(req) @@ -494,10 +490,10 @@ func (s *TestProxySuite) checkWebLogin() { func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { s.Run("successfully proxy", func() { - userID := uuid.New() + username := "smith2" encodedSAToken := base64.RawURLEncoding.EncodeToString([]byte("clusterSAToken")) - encodedSSOToken := base64.RawURLEncoding.EncodeToString([]byte(s.token(userID))) + encodedSSOToken := base64.RawURLEncoding.EncodeToString([]byte(s.token(username))) // Start the member-2 API Server testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -596,7 +592,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { }, "plain http actual request": { ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith2"}, @@ -611,7 +607,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { }, "proxy plain http actual request as not provisioned user": { ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(uuid.New())}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token("not-provisioned")}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith3"}, @@ -621,7 +617,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { }, "proxy plain http actual request": { ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith2"}, @@ -637,7 +633,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { "plain http upgrade POST request": { ProxyRequestMethod: "POST", ProxyRequestHeaders: map[string][]string{ - "Authorization": {"Bearer " + s.token(userID)}, + "Authorization": {"Bearer " + s.token(username)}, "Connection": {"Upgrade"}, "Upgrade": {"SPDY/3.1"}, }, @@ -679,7 +675,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { }, "error retrieving user workspaces": { ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, }, @@ -694,7 +690,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { "not existing workspace namespace": "http://localhost:8081/workspaces/not-existing-workspace/api/namespaces/not-existing-namespace/pods", }, ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, }, @@ -708,7 +704,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { "not existing namespace": "http://localhost:8081/api/namespaces/namespace-outside-of-workspace/pods", }, ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith2"}, @@ -726,7 +722,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { "not existing namespace": "http://localhost:8081/workspaces/mycoolworkspace/api/namespaces/namespace-outside-of-workspace/pods", }, ProxyRequestMethod: "GET", - ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(userID)}}, + ProxyRequestHeaders: map[string][]string{"Authorization": {"Bearer " + s.token(username)}}, ExpectedAPIServerRequestHeaders: map[string][]string{ "Authorization": {"Bearer clusterSAToken"}, "Impersonate-User": {"smith2"}, @@ -816,8 +812,8 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { } }) proxy.signupService = fake.NewSignupService( - fake.Signup("someUserID", &signup.Signup{ - Name: "smith1", + &signup.Signup{ + Name: "someUsername", APIEndpoint: "https://api.endpoint.member-1.com:6443", ClusterName: "member-1", CompliantUsername: "smith1", @@ -825,8 +821,8 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { Status: signup.Status{ Ready: true, }, - }), - fake.Signup(userID.String(), &signup.Signup{ + }, + &signup.Signup{ Name: "smith2", APIEndpoint: testServer.URL, ClusterName: "member-2", @@ -835,7 +831,7 @@ func (s *TestProxySuite) checkProxyOK(proxy *Proxy) { Status: signup.Status{ Ready: true, }, - }), + }, ) proxyPlugin := &toolchainv1alpha1.ProxyPlugin{ @@ -1288,16 +1284,16 @@ func (s *TestProxySuite) request() *http.Request { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) require.NoError(s.T(), err) require.NotNil(s.T(), req) - userID := uuid.New() - req.Header.Set("Authorization", "Bearer "+s.token(userID)) + username := uuid.New() + req.Header.Set("Authorization", "Bearer "+s.token(username.String())) return req } -func (s *TestProxySuite) token(userID uuid.UUID, extraClaims ...authsupport.ExtraClaim) string { +func (s *TestProxySuite) token(username string, extraClaims ...authsupport.ExtraClaim) string { userIdentity := &authsupport.Identity{ - ID: userID, - Username: "username-" + userID.String(), + ID: uuid.New(), + Username: username, } // if an email address is not explicitly set, someemail@comp.com is used diff --git a/pkg/signup/service/signup_service_test.go b/pkg/signup/service/signup_service_test.go index 8ff98002..91d98b42 100644 --- a/pkg/signup/service/signup_service_test.go +++ b/pkg/signup/service/signup_service_test.go @@ -20,7 +20,11 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/signup/service" "github.com/codeready-toolchain/registration-service/pkg/util" "github.com/codeready-toolchain/registration-service/test" + "github.com/codeready-toolchain/registration-service/test/fake" testutil "github.com/codeready-toolchain/registration-service/test/util" + "github.com/codeready-toolchain/toolchain-common/pkg/test/masteruserrecord" + "github.com/codeready-toolchain/toolchain-common/pkg/test/space" + testusersignup "github.com/codeready-toolchain/toolchain-common/pkg/test/usersignup" "sigs.k8s.io/controller-runtime/pkg/client" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" @@ -472,31 +476,21 @@ func (s *TestSignupServiceSuite) TestCRTAdminUserSignup() { func (s *TestSignupServiceSuite) TestFailsIfUserSignupNameAlreadyExists() { s.ServiceConfiguration(true, "", 5) - userID, err := uuid.NewV4() - require.NoError(s.T(), err) - signup := &toolchainv1alpha1.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID.String(), - Namespace: commontest.HostOperatorNs, - }, - Spec: toolchainv1alpha1.UserSignupSpec{}, - } - require.NoError(s.T(), err) + signup := testusersignup.NewUserSignup(testusersignup.WithName("jsmith")) rr := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(rr) ctx.Set(context.UsernameKey, "jsmith") - ctx.Set(context.SubKey, userID.String()) + ctx.Set(context.SubKey, "userid") ctx.Set(context.EmailKey, "jsmith@gmail.com") _, application := testutil.PrepareInClusterApp(s.T(), signup) // when - _, err = application.SignupService().Signup(ctx) + _, err := application.SignupService().Signup(ctx) // then - require.EqualError(s.T(), err, fmt.Sprintf("Operation cannot be fulfilled on \"\": UserSignup [id: %s; username: jsmith]. Unable to create UserSignup because there is already an active UserSignup with such ID", userID.String())) + require.EqualError(s.T(), err, "Operation cannot be fulfilled on \"\": UserSignup [id: userid; username: jsmith]. Unable to create UserSignup because there is already an active UserSignup with such ID") } func (s *TestSignupServiceSuite) TestFailsIfUserBanned() { @@ -930,7 +924,7 @@ func (s *TestSignupServiceSuite) TestGetSignupStatusOK() { require.NotNil(s.T(), response) require.Equal(s.T(), us.Name, response.Name) - require.Equal(s.T(), "jsmith", response.Username) + require.Equal(s.T(), "ted", response.Username) require.Equal(s.T(), "ted", response.CompliantUsername) require.Equal(s.T(), mur.Status.ProvisionedTime.UTC().Format(time.RFC3339), response.StartDate) @@ -990,7 +984,7 @@ func (s *TestSignupServiceSuite) TestGetSignupByUsernameOK() { require.Equal(s.T(), deactivationTimestamp, responseEndDate) require.Equal(s.T(), us.Name, response.Name) - require.Equal(s.T(), "jsmith", response.Username) + require.Equal(s.T(), "ted", response.Username) require.Equal(s.T(), "ted", response.CompliantUsername) assert.True(s.T(), response.Status.Ready) assert.Equal(s.T(), "mur_ready_reason", response.Status.Reason) @@ -1177,7 +1171,14 @@ func (s *TestSignupServiceSuite) TestGetSignupBannedUserEmail() { // given s.ServiceConfiguration(true, "", 5) - us := s.newBannedUserSignup() + us := testusersignup.NewUserSignup( + testusersignup.WithName("ted"), + testusersignup.WithAnnotation(toolchainv1alpha1.UserSignupUserEmailHashLabelKey, "a7b1b413c1cbddbcd19a51222ef8e20a"), + testusersignup.ApprovedAutomaticallyAgo(time.Second), + testusersignup.BannedAgo(time.Second), + func(signup *toolchainv1alpha1.UserSignup) { + signup.Status.CompliantUsername = "ted" + }) _, application := testutil.PrepareInClusterApp(s.T(), us) rr := httptest.NewRecorder() @@ -1485,16 +1486,16 @@ func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() require.NoError(s.T(), err) require.Equal(s.T(), "cocochanel", modified.Spec.IdentityClaims.PreferredUsername) - require.Equal(s.T(), "John", modified.Spec.IdentityClaims.GivenName) - require.Equal(s.T(), "Smith", modified.Spec.IdentityClaims.FamilyName) - require.Equal(s.T(), "Acme Inc", modified.Spec.IdentityClaims.Company) + require.Equal(s.T(), "Foo", modified.Spec.IdentityClaims.GivenName) + require.Equal(s.T(), "Bar", modified.Spec.IdentityClaims.FamilyName) + require.Equal(s.T(), "Red Hat", modified.Spec.IdentityClaims.Company) - require.Equal(s.T(), "65432111", modified.Spec.IdentityClaims.AccountID) - require.Equal(s.T(), "123456789", modified.Spec.IdentityClaims.Sub) - require.Equal(s.T(), "54321666", modified.Spec.IdentityClaims.UserID) - require.Equal(s.T(), "jsmith-original-sub", modified.Spec.IdentityClaims.OriginalSub) - require.Equal(s.T(), "jsmith@redhat.com", modified.Spec.IdentityClaims.Email) - require.Equal(s.T(), "90cb861692508c36933b85dfe43f5369", modified.Labels["toolchain.dev.openshift.com/email-hash"]) + require.Equal(s.T(), "5647382910", modified.Spec.IdentityClaims.AccountID) + require.Equal(s.T(), "UserID123", modified.Spec.IdentityClaims.Sub) + require.Equal(s.T(), "0192837465", modified.Spec.IdentityClaims.UserID) + require.Equal(s.T(), "original-sub-value", modified.Spec.IdentityClaims.OriginalSub) + require.Equal(s.T(), "foo@redhat.com", modified.Spec.IdentityClaims.Email) + require.Equal(s.T(), "fd2addbd8d82f0d2dc088fa122377eaa", modified.Labels["toolchain.dev.openshift.com/email-hash"]) s.Run("GivenName property updated when set in context", func() { c, _ := gin.CreateTestContext(httptest.NewRecorder()) @@ -1511,15 +1512,15 @@ func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() // Confirm that some other properties were not changed require.Equal(s.T(), "cocochanel", modified.Spec.IdentityClaims.PreferredUsername) - require.Equal(s.T(), "Smith", modified.Spec.IdentityClaims.FamilyName) - require.Equal(s.T(), "Acme Inc", modified.Spec.IdentityClaims.Company) + require.Equal(s.T(), "Bar", modified.Spec.IdentityClaims.FamilyName) + require.Equal(s.T(), "Red Hat", modified.Spec.IdentityClaims.Company) - require.Equal(s.T(), "65432111", modified.Spec.IdentityClaims.AccountID) - require.Equal(s.T(), "123456789", modified.Spec.IdentityClaims.Sub) - require.Equal(s.T(), "54321666", modified.Spec.IdentityClaims.UserID) - require.Equal(s.T(), "jsmith-original-sub", modified.Spec.IdentityClaims.OriginalSub) - require.Equal(s.T(), "jsmith@redhat.com", modified.Spec.IdentityClaims.Email) - require.Equal(s.T(), "90cb861692508c36933b85dfe43f5369", modified.Labels["toolchain.dev.openshift.com/email-hash"]) + require.Equal(s.T(), "5647382910", modified.Spec.IdentityClaims.AccountID) + require.Equal(s.T(), "UserID123", modified.Spec.IdentityClaims.Sub) + require.Equal(s.T(), "0192837465", modified.Spec.IdentityClaims.UserID) + require.Equal(s.T(), "original-sub-value", modified.Spec.IdentityClaims.OriginalSub) + require.Equal(s.T(), "foo@redhat.com", modified.Spec.IdentityClaims.Email) + require.Equal(s.T(), "fd2addbd8d82f0d2dc088fa122377eaa", modified.Labels["toolchain.dev.openshift.com/email-hash"]) s.Run("FamilyName and Company properties updated when set in context", func() { c, _ := gin.CreateTestContext(httptest.NewRecorder()) @@ -1539,12 +1540,12 @@ func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() require.Equal(s.T(), "Jonathan", modified.Spec.IdentityClaims.GivenName) require.Equal(s.T(), "cocochanel", modified.Spec.IdentityClaims.PreferredUsername) - require.Equal(s.T(), "65432111", modified.Spec.IdentityClaims.AccountID) - require.Equal(s.T(), "123456789", modified.Spec.IdentityClaims.Sub) - require.Equal(s.T(), "54321666", modified.Spec.IdentityClaims.UserID) - require.Equal(s.T(), "jsmith-original-sub", modified.Spec.IdentityClaims.OriginalSub) - require.Equal(s.T(), "jsmith@redhat.com", modified.Spec.IdentityClaims.Email) - require.Equal(s.T(), "90cb861692508c36933b85dfe43f5369", modified.Labels["toolchain.dev.openshift.com/email-hash"]) + require.Equal(s.T(), "5647382910", modified.Spec.IdentityClaims.AccountID) + require.Equal(s.T(), "UserID123", modified.Spec.IdentityClaims.Sub) + require.Equal(s.T(), "0192837465", modified.Spec.IdentityClaims.UserID) + require.Equal(s.T(), "original-sub-value", modified.Spec.IdentityClaims.OriginalSub) + require.Equal(s.T(), "foo@redhat.com", modified.Spec.IdentityClaims.Email) + require.Equal(s.T(), "fd2addbd8d82f0d2dc088fa122377eaa", modified.Labels["toolchain.dev.openshift.com/email-hash"]) s.Run("Remaining properties updated when set in context", func() { c, _ := gin.CreateTestContext(httptest.NewRecorder()) @@ -1579,175 +1580,50 @@ func (s *TestSignupServiceSuite) TestGetSignupUpdatesUserSignupIdentityClaims() } func (s *TestSignupServiceSuite) newUserSignupComplete() *toolchainv1alpha1.UserSignup { - return s.newUserSignupCompleteWithReason("") -} - -func (s *TestSignupServiceSuite) newUserSignupCompleteWithReason(reason string) *toolchainv1alpha1.UserSignup { - userID, err := uuid.NewV4() - require.NoError(s.T(), err) - return &toolchainv1alpha1.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID.String(), - Namespace: commontest.HostOperatorNs, - Annotations: map[string]string{ - toolchainv1alpha1.UserSignupUserEmailHashLabelKey: "90cb861692508c36933b85dfe43f5369", - }, - }, - Spec: toolchainv1alpha1.UserSignupSpec{ - IdentityClaims: toolchainv1alpha1.IdentityClaimsEmbedded{ - PropagatedClaims: toolchainv1alpha1.PropagatedClaims{ - Sub: "123456789", - UserID: "54321666", - AccountID: "65432111", - OriginalSub: "jsmith-original-sub", - Email: "jsmith@redhat.com", - }, - PreferredUsername: "jsmith", - GivenName: "John", - FamilyName: "Smith", - Company: "Acme Inc", - }, - }, - Status: toolchainv1alpha1.UserSignupStatus{ - ScheduledDeactivationTimestamp: util.Ptr(v1.NewTime(time.Now().Add(30 * time.Hour * 24))), - Conditions: []toolchainv1alpha1.Condition{ - { - Type: toolchainv1alpha1.UserSignupComplete, - Status: apiv1.ConditionTrue, - Reason: reason, - }, - { - Type: toolchainv1alpha1.UserSignupApproved, - Status: apiv1.ConditionTrue, - Reason: toolchainv1alpha1.UserSignupApprovedAutomaticallyReason, - }, - }, - CompliantUsername: "ted", - HomeSpace: "ted", - }, - } -} - -func (s *TestSignupServiceSuite) newBannedUserSignup() *toolchainv1alpha1.UserSignup { - userID, err := uuid.NewV4() - require.NoError(s.T(), err) - return &toolchainv1alpha1.UserSignup{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: userID.String(), - Namespace: commontest.HostOperatorNs, - Annotations: map[string]string{ - toolchainv1alpha1.UserSignupUserEmailHashLabelKey: "a7b1b413c1cbddbcd19a51222ef8e20a", - }, - }, - Spec: toolchainv1alpha1.UserSignupSpec{ - IdentityClaims: toolchainv1alpha1.IdentityClaimsEmbedded{ - PropagatedClaims: toolchainv1alpha1.PropagatedClaims{ - Sub: "123456789", - UserID: "54321666", - AccountID: "65432111", - OriginalSub: "jsmith-original-sub", - Email: "jsmith@gmail.com", - }, - PreferredUsername: "jsmith", - GivenName: "John", - FamilyName: "Smith", - Company: "Acme Inc", - }, - }, - Status: toolchainv1alpha1.UserSignupStatus{ - Conditions: []toolchainv1alpha1.Condition{ - { - Type: toolchainv1alpha1.UserSignupApproved, - Status: apiv1.ConditionTrue, - Reason: toolchainv1alpha1.UserSignupApprovedAutomaticallyReason, - }, - { - Type: toolchainv1alpha1.UserSignupComplete, - Status: apiv1.ConditionTrue, - Reason: toolchainv1alpha1.UserSignupUserBannedReason, - }, - }, - CompliantUsername: "jsmith", - }, - } + return testusersignup.NewUserSignup( + testusersignup.WithName("ted"), + testusersignup.WithAnnotation(toolchainv1alpha1.UserSignupUserEmailHashLabelKey, "90cb861692508c36933b85dfe43f5369"), + testusersignup.SignupComplete(""), + testusersignup.ApprovedAutomaticallyAgo(time.Second), + func(signup *toolchainv1alpha1.UserSignup) { + signup.Status.CompliantUsername = "ted" + signup.Status.HomeSpace = "ted" + signup.Status.ScheduledDeactivationTimestamp = util.Ptr(v1.NewTime(time.Now().Add(30 * time.Hour * 24))) + }) } func (s *TestSignupServiceSuite) newProvisionedMUR(name string) *toolchainv1alpha1.MasterUserRecord { - return &toolchainv1alpha1.MasterUserRecord{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: name, - Namespace: commontest.HostOperatorNs, - }, - Spec: toolchainv1alpha1.MasterUserRecordSpec{ - UserAccounts: []toolchainv1alpha1.UserAccountEmbedded{{TargetCluster: "member-123"}}, - }, - Status: toolchainv1alpha1.MasterUserRecordStatus{ - ProvisionedTime: util.Ptr(v1.NewTime(time.Now())), - Conditions: []toolchainv1alpha1.Condition{ - { - Type: toolchainv1alpha1.MasterUserRecordReady, - Status: apiv1.ConditionTrue, - Reason: "mur_ready_reason", - Message: "mur_ready_message", - }, - }, - UserAccounts: []toolchainv1alpha1.UserAccountStatusEmbedded{{Cluster: toolchainv1alpha1.Cluster{ - Name: "member-123", - }}}, - }, - } + return masteruserrecord.NewMasterUserRecord(s.T(), name, + masteruserrecord.ProvisionedMur(util.Ptr(v1.NewTime(time.Now()))), + masteruserrecord.StatusCondition(toolchainv1alpha1.Condition{ + Type: toolchainv1alpha1.MasterUserRecordReady, + Status: apiv1.ConditionTrue, + Reason: "mur_ready_reason", + Message: "mur_ready_message", + }), + masteruserrecord.StatusUserAccount("member-123")) } func (s *TestSignupServiceSuite) newSpace(name string) *toolchainv1alpha1.Space { - return &toolchainv1alpha1.Space{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: name, - Namespace: commontest.HostOperatorNs, - Labels: map[string]string{ - toolchainv1alpha1.SpaceCreatorLabelKey: name, - }, - }, - Spec: toolchainv1alpha1.SpaceSpec{ - TargetCluster: "member-123", - TargetClusterRoles: []string{"cluster-role.toolchain.dev.openshift.com/tenant"}, - TierName: "base1ns", - }, - Status: toolchainv1alpha1.SpaceStatus{ - TargetCluster: "member-123", - ProvisionedNamespaces: []toolchainv1alpha1.SpaceNamespace{ - { - Name: fmt.Sprintf("%s-dev", name), - Type: "default", - }, + return space.NewSpace(commontest.HostOperatorNs, name, + space.WithLabel(toolchainv1alpha1.SpaceCreatorLabelKey, name), + space.WithSpecTargetCluster("member-123"), + space.WithSpecTargetClusterRoles([]string{"cluster-role.toolchain.dev.openshift.com/tenant"}), + space.WithTierName("base1ns"), + space.WithStatusTargetCluster("member-123"), + space.WithStatusProvisionedNamespaces([]toolchainv1alpha1.SpaceNamespace{ + { + Name: fmt.Sprintf("%s-dev", name), + Type: "default", }, - }, - } + })) } func (s *TestSignupServiceSuite) newSpaceBinding(murName, spaceName string) *toolchainv1alpha1.SpaceBinding { name, err := uuid.NewV4() require.NoError(s.T(), err) - return &toolchainv1alpha1.SpaceBinding{ - TypeMeta: v1.TypeMeta{}, - ObjectMeta: v1.ObjectMeta{ - Name: name.String(), - Namespace: commontest.HostOperatorNs, - Labels: map[string]string{ - toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceName, - toolchainv1alpha1.SpaceBindingMasterUserRecordLabelKey: murName, - }, - }, - Spec: toolchainv1alpha1.SpaceBindingSpec{ - MasterUserRecord: murName, - Space: spaceName, - SpaceRole: "admin", - }, - } + return fake.NewSpaceBinding(name.String(), murName, spaceName, "admin") } func deactivated() []toolchainv1alpha1.Condition { diff --git a/test/fake/proxy.go b/test/fake/proxy.go index 2cfb95a5..f0698ef9 100644 --- a/test/fake/proxy.go +++ b/test/fake/proxy.go @@ -8,19 +8,10 @@ import ( // This whole service abstraction is such a huge pain. We have to get rid of it!!! -type SignupDef func() (string, *signup.Signup) - -func Signup(identifier string, userSignup *signup.Signup) SignupDef { - return func() (string, *signup.Signup) { - return identifier, userSignup - } -} - -func NewSignupService(signupDefs ...SignupDef) *SignupService { +func NewSignupService(signups ...*signup.Signup) *SignupService { sc := newFakeSignupService() - for _, signupDef := range signupDefs { - identifier, signup := signupDef() - sc.addSignup(identifier, signup) + for _, signup := range signups { + sc.addSignup(signup.Name, signup) } return sc } @@ -45,17 +36,8 @@ type SignupService struct { } func (m *SignupService) DefaultMockGetSignup() func(userID, username string) (*signup.Signup, error) { - return func(userID, username string) (userSignup *signup.Signup, e error) { - us := m.userSignups[userID] - if us != nil { - return us, nil - } - for _, v := range m.userSignups { - if v.Username == username { - return v, nil - } - } - return nil, nil + return func(_, username string) (userSignup *signup.Signup, e error) { + return m.userSignups[username], nil } }