Пример #1
0
/**
 * This creates a new OAuth configuration and synchronizes concurrent access
 * to that configuration.
 * This is expected since ServerHTTP run on their own goroutine
 * @param path is the path to retrieve CA certificates
 * @param c is the channel to write to
 * @see #PopulateCertPool(string)
 */
func OAuthConfigurationManager(clientid, clientsecret, redirecturl, authurl, tokenurl string, c chan *oauth2.Config) {

	var logger = NewPrefixed("security#OAuthConfigurationManager")

	oauthConfig := new(oauth2.Config)
	oauthConfig.ClientID = clientid
	oauthConfig.ClientSecret = clientsecret
	oauthConfig.Scopes = []string{"email"}
	oauthConfig.RedirectURL = redirecturl
	oauthConfig.Endpoint = oauth2.Endpoint{
		AuthURL:  authurl,
		TokenURL: tokenurl,
	}

	for {
		select {
		case c <- oauthConfig:
			logger.Finest("Written OAuthconf : %v", oauthConfig)
		}
	}
}
Пример #2
0
// TestOAuth2CodeFlow runs integration tests against a test server. The tests stand up a server
// which requires no interaction to login, logs in through a test client, then passes the client
// and returned token to the test.
func TestOAuth2CodeFlow(t *testing.T) {
	clientID := "testclient"
	clientSecret := "testclientsecret"
	requestedScopes := []string{oidc.ScopeOpenID, "email", "profile", "groups", "offline_access"}

	t0 := time.Now()

	// Always have the time function used by the server return the same time so
	// we can predict expected values of "expires_in" fields exactly.
	now := func() time.Time { return t0 }

	// Used later when configuring test servers to set how long id_tokens will be valid for.
	//
	// The actual value of 30s is completely arbitrary. We just need to set a value
	// so tests can compute the expected "expires_in" field.
	idTokensValidFor := time.Second * 30

	// Connector used by the tests.
	var conn *mock.Callback

	tests := []struct {
		name string
		// If specified these set of scopes will be used during the test case.
		scopes []string
		// handleToken provides the OAuth2 token response for the integration test.
		handleToken func(context.Context, *oidc.Provider, *oauth2.Config, *oauth2.Token) error
	}{
		{
			name: "verify ID Token",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				idToken, ok := token.Extra("id_token").(string)
				if !ok {
					return fmt.Errorf("no id token found")
				}
				if _, err := p.Verifier().Verify(ctx, idToken); err != nil {
					return fmt.Errorf("failed to verify id token: %v", err)
				}
				return nil
			},
		},
		{
			name: "verify id token and oauth2 token expiry",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				expectedExpiry := now().Add(idTokensValidFor)

				timeEq := func(t1, t2 time.Time, within time.Duration) bool {
					return t1.Sub(t2) < within
				}

				if !timeEq(token.Expiry, expectedExpiry, time.Second) {
					return fmt.Errorf("expected expired_in to be %s, got %s", expectedExpiry, token.Expiry)
				}

				rawIDToken, ok := token.Extra("id_token").(string)
				if !ok {
					return fmt.Errorf("no id token found")
				}
				idToken, err := p.Verifier().Verify(ctx, rawIDToken)
				if err != nil {
					return fmt.Errorf("failed to verify id token: %v", err)
				}
				if !timeEq(idToken.Expiry, expectedExpiry, time.Second) {
					return fmt.Errorf("expected id token expiry to be %s, got %s", expectedExpiry, token.Expiry)
				}
				return nil
			},
		},
		{
			name: "refresh token",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				// have to use time.Now because the OAuth2 package uses it.
				token.Expiry = time.Now().Add(time.Second * -10)
				if token.Valid() {
					return errors.New("token shouldn't be valid")
				}

				newToken, err := config.TokenSource(ctx, token).Token()
				if err != nil {
					return fmt.Errorf("failed to refresh token: %v", err)
				}
				if token.RefreshToken == newToken.RefreshToken {
					return fmt.Errorf("old refresh token was the same as the new token %q", token.RefreshToken)
				}
				return nil
			},
		},
		{
			name: "refresh with explicit scopes",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				v := url.Values{}
				v.Add("client_id", clientID)
				v.Add("client_secret", clientSecret)
				v.Add("grant_type", "refresh_token")
				v.Add("refresh_token", token.RefreshToken)
				v.Add("scope", strings.Join(requestedScopes, " "))
				resp, err := http.PostForm(p.Endpoint().TokenURL, v)
				if err != nil {
					return err
				}
				defer resp.Body.Close()
				if resp.StatusCode != http.StatusOK {
					dump, err := httputil.DumpResponse(resp, true)
					if err != nil {
						panic(err)
					}
					return fmt.Errorf("unexpected response: %s", dump)
				}
				return nil
			},
		},
		{
			name: "refresh with extra spaces",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				v := url.Values{}
				v.Add("client_id", clientID)
				v.Add("client_secret", clientSecret)
				v.Add("grant_type", "refresh_token")
				v.Add("refresh_token", token.RefreshToken)

				// go-oidc adds an additional space before scopes when refreshing.
				// Since we support that client we choose to be more relaxed about
				// scope parsing, disregarding extra whitespace.
				v.Add("scope", " "+strings.Join(requestedScopes, " "))
				resp, err := http.PostForm(p.Endpoint().TokenURL, v)
				if err != nil {
					return err
				}
				defer resp.Body.Close()
				if resp.StatusCode != http.StatusOK {
					dump, err := httputil.DumpResponse(resp, true)
					if err != nil {
						panic(err)
					}
					return fmt.Errorf("unexpected response: %s", dump)
				}
				return nil
			},
		},
		{
			name:   "refresh with unauthorized scopes",
			scopes: []string{"openid", "email"},
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				v := url.Values{}
				v.Add("client_id", clientID)
				v.Add("client_secret", clientSecret)
				v.Add("grant_type", "refresh_token")
				v.Add("refresh_token", token.RefreshToken)
				// Request a scope that wasn't requestd initially.
				v.Add("scope", "oidc email profile")
				resp, err := http.PostForm(p.Endpoint().TokenURL, v)
				if err != nil {
					return err
				}
				defer resp.Body.Close()
				if resp.StatusCode == http.StatusOK {
					dump, err := httputil.DumpResponse(resp, true)
					if err != nil {
						panic(err)
					}
					return fmt.Errorf("unexpected response: %s", dump)
				}
				return nil
			},
		},
		{
			// This test ensures that the connector.RefreshConnector interface is being
			// used when clients request a refresh token.
			name: "refresh with identity changes",
			handleToken: func(ctx context.Context, p *oidc.Provider, config *oauth2.Config, token *oauth2.Token) error {
				// have to use time.Now because the OAuth2 package uses it.
				token.Expiry = time.Now().Add(time.Second * -10)
				if token.Valid() {
					return errors.New("token shouldn't be valid")
				}

				ident := connector.Identity{
					UserID:        "fooid",
					Username:      "******",
					Email:         "*****@*****.**",
					EmailVerified: true,
					Groups:        []string{"foo", "bar"},
				}
				conn.Identity = ident

				type claims struct {
					Username      string   `json:"name"`
					Email         string   `json:"email"`
					EmailVerified bool     `json:"email_verified"`
					Groups        []string `json:"groups"`
				}
				want := claims{ident.Username, ident.Email, ident.EmailVerified, ident.Groups}

				newToken, err := config.TokenSource(ctx, token).Token()
				if err != nil {
					return fmt.Errorf("failed to refresh token: %v", err)
				}
				rawIDToken, ok := newToken.Extra("id_token").(string)
				if !ok {
					return fmt.Errorf("no id_token in refreshed token")
				}
				idToken, err := p.Verifier().Verify(ctx, rawIDToken)
				if err != nil {
					return fmt.Errorf("failed to verify id token: %v", err)
				}
				var got claims
				if err := idToken.Claims(&got); err != nil {
					return fmt.Errorf("failed to unmarshal claims: %v", err)
				}

				if diff := pretty.Compare(want, got); diff != "" {
					return fmt.Errorf("got identity != want identity: %s", diff)
				}
				return nil
			},
		},
	}

	for _, tc := range tests {
		func() {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			httpServer, s := newTestServer(ctx, t, func(c *Config) {
				c.Issuer = c.Issuer + "/non-root-path"
				c.Now = now
				c.IDTokensValidFor = idTokensValidFor
				// Create a new mock callback connector for each test case.
				conn = mock.NewCallbackConnector().(*mock.Callback)
				c.Connectors = []Connector{
					{
						ID:          "mock",
						DisplayName: "mock",
						Connector:   conn,
					},
				}
			})
			defer httpServer.Close()

			p, err := oidc.NewProvider(ctx, httpServer.URL)
			if err != nil {
				t.Fatalf("failed to get provider: %v", err)
			}

			var (
				reqDump, respDump []byte
				gotCode           bool
				state             = "a_state"
			)
			defer func() {
				if !gotCode {
					t.Errorf("never got a code in callback\n%s\n%s", reqDump, respDump)
				}
			}()

			var oauth2Config *oauth2.Config
			oauth2Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if r.URL.Path == "/callback" {
					q := r.URL.Query()
					if errType := q.Get("error"); errType != "" {
						if desc := q.Get("error_description"); desc != "" {
							t.Errorf("got error from server %s: %s", errType, desc)
						} else {
							t.Errorf("got error from server %s", errType)
						}
						w.WriteHeader(http.StatusInternalServerError)
						return
					}

					if code := q.Get("code"); code != "" {
						gotCode = true
						token, err := oauth2Config.Exchange(ctx, code)
						if err != nil {
							t.Errorf("failed to exchange code for token: %v", err)
							return
						}
						err = tc.handleToken(ctx, p, oauth2Config, token)
						if err != nil {
							t.Errorf("%s: %v", tc.name, err)
						}
						return

					}
					if gotState := q.Get("state"); gotState != state {
						t.Errorf("state did not match, want=%q got=%q", state, gotState)
					}
					w.WriteHeader(http.StatusOK)
					return
				}
				http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusSeeOther)
			}))

			defer oauth2Server.Close()

			redirectURL := oauth2Server.URL + "/callback"
			client := storage.Client{
				ID:           clientID,
				Secret:       clientSecret,
				RedirectURIs: []string{redirectURL},
			}
			if err := s.storage.CreateClient(client); err != nil {
				t.Fatalf("failed to create client: %v", err)
			}

			oauth2Config = &oauth2.Config{
				ClientID:     client.ID,
				ClientSecret: client.Secret,
				Endpoint:     p.Endpoint(),
				Scopes:       requestedScopes,
				RedirectURL:  redirectURL,
			}
			if len(tc.scopes) != 0 {
				oauth2Config.Scopes = tc.scopes
			}

			resp, err := http.Get(oauth2Server.URL + "/login")
			if err != nil {
				t.Fatalf("get failed: %v", err)
			}
			if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
				t.Fatal(err)
			}
			if respDump, err = httputil.DumpResponse(resp, true); err != nil {
				t.Fatal(err)
			}
		}()
	}
}