X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/6bf9e1a4b5640f3cdd057810f0c9b8a945bb88bd..bcad695db9a1c3aac5807faa153086e653107f51:/lib/controller/localdb/login_oidc_test.go?ds=sidebyside diff --git a/lib/controller/localdb/login_oidc_test.go b/lib/controller/localdb/login_oidc_test.go index 9bc6f90ea9..b9f0f56e05 100644 --- a/lib/controller/localdb/login_oidc_test.go +++ b/lib/controller/localdb/login_oidc_test.go @@ -7,13 +7,17 @@ package localdb import ( "bytes" "context" + "crypto/hmac" + "crypto/sha256" "encoding/json" "fmt" + "io" "net/http" "net/http/httptest" "net/url" "sort" "strings" + "sync" "testing" "time" @@ -23,6 +27,7 @@ import ( "git.arvados.org/arvados.git/sdk/go/arvadostest" "git.arvados.org/arvados.git/sdk/go/auth" "git.arvados.org/arvados.git/sdk/go/ctxlog" + "github.com/jmoiron/sqlx" check "gopkg.in/check.v1" ) @@ -52,6 +57,8 @@ func (s *OIDCLoginSuite) SetUpTest(c *check.C) { s.fakeProvider.AuthEmail = "active-user@arvados.local" s.fakeProvider.AuthEmailVerified = true s.fakeProvider.AuthName = "Fake User Name" + s.fakeProvider.AuthGivenName = "Fake" + s.fakeProvider.AuthFamilyName = "User Name" s.fakeProvider.ValidCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix()) s.fakeProvider.PeopleAPIResponse = map[string]interface{}{} @@ -59,7 +66,7 @@ func (s *OIDCLoginSuite) SetUpTest(c *check.C) { c.Assert(err, check.IsNil) s.cluster, err = cfg.GetCluster("") c.Assert(err, check.IsNil) - s.cluster.Login.SSO.Enable = false + s.cluster.Login.Test.Enable = false s.cluster.Login.Google.Enable = true s.cluster.Login.Google.ClientID = "test%client$id" s.cluster.Login.Google.ClientSecret = "test#client/secret" @@ -161,12 +168,14 @@ func (s *OIDCLoginSuite) TestConfig(c *check.C) { s.cluster.Login.OpenIDConnect.Issuer = "https://accounts.example.com/" s.cluster.Login.OpenIDConnect.ClientID = "oidc-client-id" s.cluster.Login.OpenIDConnect.ClientSecret = "oidc-client-secret" + s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"} localdb := NewConn(s.cluster) ctrl := localdb.loginController.(*oidcLoginController) c.Check(ctrl.Issuer, check.Equals, "https://accounts.example.com/") c.Check(ctrl.ClientID, check.Equals, "oidc-client-id") c.Check(ctrl.ClientSecret, check.Equals, "oidc-client-secret") c.Check(ctrl.UseGooglePeopleAPI, check.Equals, false) + c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue") for _, enableAltEmails := range []bool{false, true} { s.cluster.Login.OpenIDConnect.Enable = false @@ -174,12 +183,14 @@ func (s *OIDCLoginSuite) TestConfig(c *check.C) { s.cluster.Login.Google.ClientID = "google-client-id" s.cluster.Login.Google.ClientSecret = "google-client-secret" s.cluster.Login.Google.AlternateEmailAddresses = enableAltEmails + s.cluster.Login.Google.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"} localdb = NewConn(s.cluster) ctrl = localdb.loginController.(*oidcLoginController) c.Check(ctrl.Issuer, check.Equals, "https://accounts.google.com") c.Check(ctrl.ClientID, check.Equals, "google-client-id") c.Check(ctrl.ClientSecret, check.Equals, "google-client-secret") c.Check(ctrl.UseGooglePeopleAPI, check.Equals, enableAltEmails) + c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue") } } @@ -194,12 +205,144 @@ func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) { c.Check(resp.RedirectLocation, check.Equals, "") } +func (s *OIDCLoginSuite) TestOIDCAuthorizer(c *check.C) { + s.cluster.Login.Google.Enable = false + s.cluster.Login.OpenIDConnect.Enable = true + json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer) + s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id" + s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret" + s.cluster.Login.OpenIDConnect.AcceptAccessToken = true + s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = "" + s.fakeProvider.ValidClientID = "oidc#client#id" + s.fakeProvider.ValidClientSecret = "oidc#client#secret" + db := arvadostest.DB(c, s.cluster) + + tokenCacheTTL = time.Millisecond + tokenCacheRaceWindow = time.Millisecond + tokenCacheNegativeTTL = time.Millisecond + + oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil }) + accessToken := s.fakeProvider.ValidAccessToken() + + mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken)) + io.WriteString(mac, accessToken) + apiToken := fmt.Sprintf("%x", mac.Sum(nil)) + + cleanup := func() { + _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken) + c.Check(err, check.IsNil) + } + cleanup() + defer cleanup() + + ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}}) + var exp1 time.Time + + concurrent := 4 + s.fakeProvider.HoldUserInfo = make(chan *http.Request) + s.fakeProvider.ReleaseUserInfo = make(chan struct{}) + go func() { + for i := 0; ; i++ { + if i == concurrent { + close(s.fakeProvider.ReleaseUserInfo) + } + <-s.fakeProvider.HoldUserInfo + } + }() + var wg sync.WaitGroup + for i := 0; i < concurrent; i++ { + i := i + wg.Add(1) + go func() { + defer wg.Done() + _, err := oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) { + c.Logf("concurrent req %d/%d", i, concurrent) + var exp time.Time + + creds, ok := auth.FromContext(ctx) + c.Assert(ok, check.Equals, true) + c.Assert(creds.Tokens, check.HasLen, 1) + c.Check(creds.Tokens[0], check.Equals, accessToken) + + err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp) + c.Check(err, check.IsNil) + c.Check(exp.Sub(time.Now()) > -time.Second, check.Equals, true) + c.Check(exp.Sub(time.Now()) < time.Second, check.Equals, true) + if i == 0 { + exp1 = exp + } + return nil, nil + })(ctx, nil) + c.Check(err, check.IsNil) + }() + } + wg.Wait() + if c.Failed() { + c.Fatal("giving up") + } + + // If the token is used again after the in-memory cache + // expires, oidcAuthorizer must re-check the token and update + // the expires_at value in the database. + time.Sleep(3 * time.Millisecond) + oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) { + var exp time.Time + err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp) + c.Check(err, check.IsNil) + c.Check(exp.Sub(exp1) > 0, check.Equals, true, check.Commentf("expect %v > 0", exp.Sub(exp1))) + c.Check(exp.Sub(exp1) < time.Second, check.Equals, true, check.Commentf("expect %v < 1s", exp.Sub(exp1))) + return nil, nil + })(ctx, nil) + + s.fakeProvider.AccessTokenPayload = map[string]interface{}{"scope": "openid profile foobar"} + accessToken = s.fakeProvider.ValidAccessToken() + ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}}) + + mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken)) + io.WriteString(mac, accessToken) + apiToken = fmt.Sprintf("%x", mac.Sum(nil)) + + for _, trial := range []struct { + configEnable bool + configScope string + acceptable bool + shouldRun bool + }{ + {true, "foobar", true, true}, + {true, "foo", false, false}, + {true, "", true, true}, + {false, "", false, true}, + {false, "foobar", false, true}, + } { + c.Logf("trial = %+v", trial) + cleanup() + s.cluster.Login.OpenIDConnect.AcceptAccessToken = trial.configEnable + s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = trial.configScope + oidcAuthorizer = OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil }) + checked := false + oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) { + var n int + err := db.QueryRowContext(ctx, `select count(*) from api_client_authorizations where api_token=$1`, apiToken).Scan(&n) + c.Check(err, check.IsNil) + if trial.acceptable { + c.Check(n, check.Equals, 1) + } else { + c.Check(n, check.Equals, 0) + } + checked = true + return nil, nil + })(ctx, nil) + c.Check(checked, check.Equals, trial.shouldRun) + } +} + func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) { s.cluster.Login.Google.Enable = false s.cluster.Login.OpenIDConnect.Enable = true json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer) s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id" s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret" + s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"} s.fakeProvider.ValidClientID = "oidc#client#id" s.fakeProvider.ValidClientSecret = "oidc#client#secret" for _, trial := range []struct { @@ -259,7 +402,9 @@ func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) { s.localdb = NewConn(s.cluster) *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider) - state := s.startLogin(c) + state := s.startLogin(c, func(form url.Values) { + c.Check(form.Get("testkey"), check.Equals, "testvalue") + }) resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ Code: s.fakeProvider.ValidCode, State: state, @@ -290,7 +435,12 @@ func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) { } func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) { - state := s.startLogin(c) + s.cluster.Login.Google.AuthenticationRequestParameters["prompt"] = "consent" + s.cluster.Login.Google.AuthenticationRequestParameters["foo"] = "bar" + state := s.startLogin(c, func(form url.Values) { + c.Check(form.Get("foo"), check.Equals, "bar") + c.Check(form.Get("prompt"), check.Equals, "consent") + }) resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ Code: s.fakeProvider.ValidCode, State: state, @@ -305,8 +455,8 @@ func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) { c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`) authinfo := getCallbackAuthInfo(c, s.railsSpy) - c.Check(authinfo.FirstName, check.Equals, "Fake User") - c.Check(authinfo.LastName, check.Equals, "Name") + c.Check(authinfo.FirstName, check.Equals, "Fake") + c.Check(authinfo.LastName, check.Equals, "User Name") c.Check(authinfo.Email, check.Equals, "active-user@arvados.local") c.Check(authinfo.AlternateEmails, check.HasLen, 0) @@ -330,6 +480,7 @@ func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) { func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) { s.fakeProvider.AuthEmail = "joe.smith@primary.example.com" + s.fakeProvider.AuthEmailVerified = true s.fakeProvider.PeopleAPIResponse = map[string]interface{}{ "names": []map[string]interface{}{ { @@ -355,8 +506,10 @@ func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) { c.Check(authinfo.LastName, check.Equals, "Psmith") } -func (s *OIDCLoginSuite) TestGoogleLogin_OIDCRealName(c *check.C) { +func (s *OIDCLoginSuite) TestGoogleLogin_OIDCNameWithoutGivenAndFamilyNames(c *check.C) { s.fakeProvider.AuthName = "Joe P. Smith" + s.fakeProvider.AuthGivenName = "" + s.fakeProvider.AuthFamilyName = "" s.fakeProvider.AuthEmail = "joe.smith@primary.example.com" state := s.startLogin(c) s.localdb.Login(context.Background(), arvados.LoginOptions{ @@ -455,7 +608,7 @@ func (s *OIDCLoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) { c.Check(authinfo.Username, check.Equals, "") } -func (s *OIDCLoginSuite) startLogin(c *check.C) (state string) { +func (s *OIDCLoginSuite) startLogin(c *check.C, checks ...func(url.Values)) (state string) { // Initiate login, but instead of following the redirect to // the provider, just grab state from the redirect URL. resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"}) @@ -464,6 +617,10 @@ func (s *OIDCLoginSuite) startLogin(c *check.C) (state string) { c.Check(err, check.IsNil) state = target.Query().Get("state") c.Check(state, check.Not(check.Equals), "") + for _, fn := range checks { + fn(target.Query()) + } + s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"} return }