From 7efd88a4e1f0101586af0c672670e39a329a135a Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 02:21:55 +0000 Subject: [PATCH 01/10] add an integration test for OIDC introspection --- tests/integration/oauth_test.go | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index e9b69f5f149b3..c20bd01016d8d 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -419,3 +419,40 @@ func TestRefreshTokenInvalidation(t *testing.T) { assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "token was already used", parsedError.ErrorDescription) } + +func TestOAuthIntrospection(t *testing.T) { + defer tests.PrepareTestEnv(t)() + req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{ + "grant_type": "authorization_code", + "client_id": "da7da3ba-9a13-4167-856f-3899de0b0138", + "client_secret": "4MK8Na6R55smdCY0WuCCumZ6hjRPnGY5saWVRHHjJiA=", + "redirect_uri": "a", + "code": "authcode", + "code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt", + }) + resp := MakeRequest(t, req, http.StatusOK) + type response struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + RefreshToken string `json:"refresh_token"` + } + parsed := new(response) + + assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + assert.True(t, len(parsed.AccessToken) > 10) + assert.True(t, len(parsed.RefreshToken) > 10) + + req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{ + "token": parsed.AccessToken, + }) + req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9") + resp = MakeRequest(t, req, http.StatusOK) + type introspectResponse struct { + Active bool `json:"active"` + Scope string `json:"scope,omitempty"` + } + introspectParsed := new(introspectResponse) + assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed)) + assert.True(t, introspectParsed.Active) +} From 3d6055e99d0ba6a8e1a677526f4129e09a589795 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 05:42:17 +0000 Subject: [PATCH 02/10] fix OIDC introspection authentication The introspect endpoint was using the OIDC token itself for authentication. This fixes it to use basic authentication with the client ID and secret instead: * Applications with a valid client ID and secret should be able to successfully introspect an invalid token, receiving a 200 response with JSON data that indicates the token is invalid * Requests with an invalid client ID and secret should not be able to introspect, even if the token itself is valid --- routers/web/auth/oauth.go | 82 +++++++++++++++++++++------------------ 1 file changed, 44 insertions(+), 38 deletions(-) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 50f0dff2b62df..3730e6ff519b5 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -5,7 +5,6 @@ package auth import ( go_context "context" - "encoding/base64" "errors" "fmt" "html" @@ -329,8 +328,16 @@ func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]str // IntrospectOAuth introspects an oauth token func IntrospectOAuth(ctx *context.Context) { - if ctx.Doer == nil { - ctx.Resp.Header().Set("WWW-Authenticate", `Bearer realm=""`) + clientIDValid := false + if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil { + if app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID); err == nil { + if app.ValidateClientSecret([]byte(clientSecret)) { + clientIDValid = true + } + } + } + if !clientIDValid { + ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm=""`) ctx.PlainText(http.StatusUnauthorized, "no valid authorization") return } @@ -634,47 +641,46 @@ func OIDCKeys(ctx *context.Context) { } } +func parseBasicAuth(ctx *context.Context) (username, password string, err error) { + authHeader := ctx.Req.Header.Get("Authorization") + authContent := strings.SplitN(authHeader, " ", 2) + if len(authContent) == 2 && authContent[0] == "Basic" { + return base.BasicAuthDecode(authContent[1]) + } + return "", "", errors.New("invalid basic authentication") +} + // AccessTokenOAuth manages all access token requests by the client func AccessTokenOAuth(ctx *context.Context) { form := *web.GetForm(ctx).(*forms.AccessTokenForm) // if there is no ClientID or ClientSecret in the request body, fill these fields by the Authorization header and ensure the provided field matches the Authorization header if form.ClientID == "" || form.ClientSecret == "" { - authHeader := ctx.Req.Header.Get("Authorization") - authContent := strings.SplitN(authHeader, " ", 2) - if len(authContent) == 2 && authContent[0] == "Basic" { - payload, err := base64.StdEncoding.DecodeString(authContent[1]) - if err != nil { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "cannot parse basic auth header", - }) - return - } - pair := strings.SplitN(string(payload), ":", 2) - if len(pair) != 2 { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "cannot parse basic auth header", - }) - return - } - if form.ClientID != "" && form.ClientID != pair[0] { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "client_id in request body inconsistent with Authorization header", - }) - return - } - form.ClientID = pair[0] - if form.ClientSecret != "" && form.ClientSecret != pair[1] { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "client_secret in request body inconsistent with Authorization header", - }) - return - } - form.ClientSecret = pair[1] + clientID, clientSecret, err := parseBasicAuth(ctx) + if err != nil { + // present and valid Basic auth header is required in this case: + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "cannot parse basic auth header", + }) + return + } + // validate that any fields present in the form match the Basic auth header + if form.ClientID != "" && form.ClientID != clientID { + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "client_id in request body inconsistent with Authorization header", + }) + return + } + form.ClientID = clientID + if form.ClientSecret != "" && form.ClientSecret != clientSecret { + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "client_secret in request body inconsistent with Authorization header", + }) + return } + form.ClientSecret = clientSecret } serverKey := oauth2.DefaultSigningKey From b9485476df0b5521627c2e9e1bee1298537abba0 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 06:32:05 +0000 Subject: [PATCH 03/10] review fix: use strings.Cut --- routers/web/auth/oauth.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 3730e6ff519b5..e914469e05815 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -643,9 +643,8 @@ func OIDCKeys(ctx *context.Context) { func parseBasicAuth(ctx *context.Context) (username, password string, err error) { authHeader := ctx.Req.Header.Get("Authorization") - authContent := strings.SplitN(authHeader, " ", 2) - if len(authContent) == 2 && authContent[0] == "Basic" { - return base.BasicAuthDecode(authContent[1]) + if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" { + return base.BasicAuthDecode(authData) } return "", "", errors.New("invalid basic authentication") } From 0dee9ce93757b3357134b0791466f0877414e0bb Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 07:10:03 +0000 Subject: [PATCH 04/10] fix non-confidential access_token flow --- routers/web/auth/oauth.go | 68 ++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index e914469e05815..a2bb1b983a6f0 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -326,6 +326,14 @@ func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]str return groups, nil } +func parseBasicAuth(ctx *context.Context) (username, password string, err error) { + authHeader := ctx.Req.Header.Get("Authorization") + if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" { + return base.BasicAuthDecode(authData) + } + return "", "", errors.New("invalid basic authentication") +} + // IntrospectOAuth introspects an oauth token func IntrospectOAuth(ctx *context.Context) { clientIDValid := false @@ -641,45 +649,39 @@ func OIDCKeys(ctx *context.Context) { } } -func parseBasicAuth(ctx *context.Context) (username, password string, err error) { - authHeader := ctx.Req.Header.Get("Authorization") - if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" { - return base.BasicAuthDecode(authData) - } - return "", "", errors.New("invalid basic authentication") -} - // AccessTokenOAuth manages all access token requests by the client func AccessTokenOAuth(ctx *context.Context) { form := *web.GetForm(ctx).(*forms.AccessTokenForm) // if there is no ClientID or ClientSecret in the request body, fill these fields by the Authorization header and ensure the provided field matches the Authorization header if form.ClientID == "" || form.ClientSecret == "" { - clientID, clientSecret, err := parseBasicAuth(ctx) - if err != nil { - // present and valid Basic auth header is required in this case: - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "cannot parse basic auth header", - }) - return - } - // validate that any fields present in the form match the Basic auth header - if form.ClientID != "" && form.ClientID != clientID { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "client_id in request body inconsistent with Authorization header", - }) - return - } - form.ClientID = clientID - if form.ClientSecret != "" && form.ClientSecret != clientSecret { - handleAccessTokenError(ctx, AccessTokenError{ - ErrorCode: AccessTokenErrorCodeInvalidRequest, - ErrorDescription: "client_secret in request body inconsistent with Authorization header", - }) - return + authHeader := ctx.Req.Header.Get("Authorization") + if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" { + clientID, clientSecret, err := base.BasicAuthDecode(authData) + if err != nil { + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "cannot parse basic auth header", + }) + return + } + // validate that any fields present in the form match the Basic auth header + if form.ClientID != "" && form.ClientID != clientID { + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "client_id in request body inconsistent with Authorization header", + }) + return + } + form.ClientID = clientID + if form.ClientSecret != "" && form.ClientSecret != clientSecret { + handleAccessTokenError(ctx, AccessTokenError{ + ErrorCode: AccessTokenErrorCodeInvalidRequest, + ErrorDescription: "client_secret in request body inconsistent with Authorization header", + }) + return + } + form.ClientSecret = clientSecret } - form.ClientSecret = clientSecret } serverKey := oauth2.DefaultSigningKey From a17da3e85792426d2d2afe77a599ce7992511a09 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 11:28:26 -0400 Subject: [PATCH 05/10] Update routers/web/auth/oauth.go Co-authored-by: Lauris BH --- routers/web/auth/oauth.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index a2bb1b983a6f0..3ee111fc624fd 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -339,9 +339,7 @@ func IntrospectOAuth(ctx *context.Context) { clientIDValid := false if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil { if app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID); err == nil { - if app.ValidateClientSecret([]byte(clientSecret)) { - clientIDValid = true - } + clientIDValid = app.ValidateClientSecret([]byte(clientSecret)) } } if !clientIDValid { From 6740a45882b435f4b66df034423520d574c72a82 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jul 2024 16:38:32 +0000 Subject: [PATCH 06/10] use strings.Cut for BasicAuthDecode as well --- modules/base/tool.go | 9 +++------ modules/base/tool_test.go | 3 +++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/base/tool.go b/modules/base/tool.go index 378eb7e3dd2ed..9e43030f40019 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -48,13 +48,10 @@ func BasicAuthDecode(encoded string) (string, string, error) { return "", "", err } - auth := strings.SplitN(string(s), ":", 2) - - if len(auth) != 2 { - return "", "", errors.New("invalid basic authentication") + if username, password, ok := strings.Cut(string(s), ":"); ok { + return username, password, nil } - - return auth[0], auth[1], nil + return "", "", errors.New("invalid basic authentication") } // VerifyTimeLimitCode verify time limit code diff --git a/modules/base/tool_test.go b/modules/base/tool_test.go index 62de7229acd4c..4af8b9bc4d528 100644 --- a/modules/base/tool_test.go +++ b/modules/base/tool_test.go @@ -41,6 +41,9 @@ func TestBasicAuthDecode(t *testing.T) { _, _, err = BasicAuthDecode("invalid") assert.Error(t, err) + + _, _, err = BasicAuthDecode("YWxpY2U=") // "alice", no colon + assert.Error(t, err) } func TestVerifyTimeLimitCode(t *testing.T) { From 6f8573f1a66fb8f82b235e91b31a4177f4096bb5 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 16 Jul 2024 03:16:07 +0000 Subject: [PATCH 07/10] review fix: return a 500 for database errors --- routers/web/auth/oauth.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 3ee111fc624fd..084a431c40358 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -340,6 +340,11 @@ func IntrospectOAuth(ctx *context.Context) { if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil { if app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID); err == nil { clientIDValid = app.ValidateClientSecret([]byte(clientSecret)) + } else if !auth.IsErrOauthClientIDInvalid(err) { + // this is likely a database error; log it and respond without details + log.Error("Error retrieving client_id: %v", err) + ctx.Error(http.StatusInternalServerError) + return } } if !clientIDValid { From f5a45c3377e2bde51046cf728350d5f4c8b84029 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 16 Jul 2024 03:20:20 +0000 Subject: [PATCH 08/10] review fix: add a test for invalid client secret --- tests/integration/oauth_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index c20bd01016d8d..5d15f9a29356d 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -443,6 +443,7 @@ func TestOAuthIntrospection(t *testing.T) { assert.True(t, len(parsed.AccessToken) > 10) assert.True(t, len(parsed.RefreshToken) > 10) + // successful request with a valid client_id/client_secret and a valid token req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{ "token": parsed.AccessToken, }) @@ -455,4 +456,12 @@ func TestOAuthIntrospection(t *testing.T) { introspectParsed := new(introspectResponse) assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed)) assert.True(t, introspectParsed.Active) + + // unsuccessful request with an invalid client_id/client_secret + req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{ + "token": parsed.AccessToken, + }) + req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpK") + resp = MakeRequest(t, req, http.StatusUnauthorized) + assert.Contains(t, resp.Body.String(), "no valid authorization") } From e160947350cad51777195ccb0d97bd4f66387847 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 16 Jul 2024 03:22:53 +0000 Subject: [PATCH 09/10] review fix: add a test for successfully introspecting an invalid token --- tests/integration/oauth_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index 5d15f9a29356d..c3f0abbe1dd49 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -457,6 +457,16 @@ func TestOAuthIntrospection(t *testing.T) { assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed)) assert.True(t, introspectParsed.Active) + // successful request with a valid client_id/client_secret, but an invalid token + req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{ + "token": "xyzzy", + }) + req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9") + resp = MakeRequest(t, req, http.StatusOK) + introspectParsed = new(introspectResponse) + assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed)) + assert.False(t, introspectParsed.Active) + // unsuccessful request with an invalid client_id/client_secret req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{ "token": parsed.AccessToken, From 21978a2455321fe2db522a96a6d3624313a85d63 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Wed, 17 Jul 2024 19:35:37 +0000 Subject: [PATCH 10/10] review fix: refactor error handling control flow --- routers/web/auth/oauth.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 084a431c40358..b4d0540453bdf 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -338,14 +338,14 @@ func parseBasicAuth(ctx *context.Context) (username, password string, err error) func IntrospectOAuth(ctx *context.Context) { clientIDValid := false if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil { - if app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID); err == nil { - clientIDValid = app.ValidateClientSecret([]byte(clientSecret)) - } else if !auth.IsErrOauthClientIDInvalid(err) { + app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID) + if err != nil && !auth.IsErrOauthClientIDInvalid(err) { // this is likely a database error; log it and respond without details log.Error("Error retrieving client_id: %v", err) ctx.Error(http.StatusInternalServerError) return } + clientIDValid = err == nil && app.ValidateClientSecret([]byte(clientSecret)) } if !clientIDValid { ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm=""`)