Skip to content

Commit 2f1cb1d

Browse files
authored
fix OIDC introspection authentication (go-gitea#31632)
See discussion on go-gitea#31561 for some background. 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 Unlike go-gitea#31561 (which just future-proofed the current behavior against future changes to `DISABLE_QUERY_AUTH_TOKEN`), this is a potential compatibility break (some introspection requests without valid client IDs that would previously succeed will now fail). Affected deployments must begin sending a valid HTTP basic authentication header with their introspection requests, with the username set to a valid client ID and the password set to the corresponding client secret.
1 parent 24f9390 commit 2f1cb1d

File tree

4 files changed

+90
-24
lines changed

4 files changed

+90
-24
lines changed

modules/base/tool.go

+3-6
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,10 @@ func BasicAuthDecode(encoded string) (string, string, error) {
4848
return "", "", err
4949
}
5050

51-
auth := strings.SplitN(string(s), ":", 2)
52-
53-
if len(auth) != 2 {
54-
return "", "", errors.New("invalid basic authentication")
51+
if username, password, ok := strings.Cut(string(s), ":"); ok {
52+
return username, password, nil
5553
}
56-
57-
return auth[0], auth[1], nil
54+
return "", "", errors.New("invalid basic authentication")
5855
}
5956

6057
// VerifyTimeLimitCode verify time limit code

modules/base/tool_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ func TestBasicAuthDecode(t *testing.T) {
4141

4242
_, _, err = BasicAuthDecode("invalid")
4343
assert.Error(t, err)
44+
45+
_, _, err = BasicAuthDecode("YWxpY2U=") // "alice", no colon
46+
assert.Error(t, err)
4447
}
4548

4649
func TestVerifyTimeLimitCode(t *testing.T) {

routers/web/auth/oauth.go

+28-18
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ package auth
55

66
import (
77
go_context "context"
8-
"encoding/base64"
98
"errors"
109
"fmt"
1110
"html"
@@ -326,10 +325,29 @@ func getOAuthGroupsForUser(ctx go_context.Context, user *user_model.User) ([]str
326325
return groups, nil
327326
}
328327

328+
func parseBasicAuth(ctx *context.Context) (username, password string, err error) {
329+
authHeader := ctx.Req.Header.Get("Authorization")
330+
if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" {
331+
return base.BasicAuthDecode(authData)
332+
}
333+
return "", "", errors.New("invalid basic authentication")
334+
}
335+
329336
// IntrospectOAuth introspects an oauth token
330337
func IntrospectOAuth(ctx *context.Context) {
331-
if ctx.Doer == nil {
332-
ctx.Resp.Header().Set("WWW-Authenticate", `Bearer realm=""`)
338+
clientIDValid := false
339+
if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil {
340+
app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID)
341+
if err != nil && !auth.IsErrOauthClientIDInvalid(err) {
342+
// this is likely a database error; log it and respond without details
343+
log.Error("Error retrieving client_id: %v", err)
344+
ctx.Error(http.StatusInternalServerError)
345+
return
346+
}
347+
clientIDValid = err == nil && app.ValidateClientSecret([]byte(clientSecret))
348+
}
349+
if !clientIDValid {
350+
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm=""`)
333351
ctx.PlainText(http.StatusUnauthorized, "no valid authorization")
334352
return
335353
}
@@ -639,40 +657,32 @@ func AccessTokenOAuth(ctx *context.Context) {
639657
// 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
640658
if form.ClientID == "" || form.ClientSecret == "" {
641659
authHeader := ctx.Req.Header.Get("Authorization")
642-
authContent := strings.SplitN(authHeader, " ", 2)
643-
if len(authContent) == 2 && authContent[0] == "Basic" {
644-
payload, err := base64.StdEncoding.DecodeString(authContent[1])
660+
if authType, authData, ok := strings.Cut(authHeader, " "); ok && authType == "Basic" {
661+
clientID, clientSecret, err := base.BasicAuthDecode(authData)
645662
if err != nil {
646663
handleAccessTokenError(ctx, AccessTokenError{
647664
ErrorCode: AccessTokenErrorCodeInvalidRequest,
648665
ErrorDescription: "cannot parse basic auth header",
649666
})
650667
return
651668
}
652-
pair := strings.SplitN(string(payload), ":", 2)
653-
if len(pair) != 2 {
654-
handleAccessTokenError(ctx, AccessTokenError{
655-
ErrorCode: AccessTokenErrorCodeInvalidRequest,
656-
ErrorDescription: "cannot parse basic auth header",
657-
})
658-
return
659-
}
660-
if form.ClientID != "" && form.ClientID != pair[0] {
669+
// validate that any fields present in the form match the Basic auth header
670+
if form.ClientID != "" && form.ClientID != clientID {
661671
handleAccessTokenError(ctx, AccessTokenError{
662672
ErrorCode: AccessTokenErrorCodeInvalidRequest,
663673
ErrorDescription: "client_id in request body inconsistent with Authorization header",
664674
})
665675
return
666676
}
667-
form.ClientID = pair[0]
668-
if form.ClientSecret != "" && form.ClientSecret != pair[1] {
677+
form.ClientID = clientID
678+
if form.ClientSecret != "" && form.ClientSecret != clientSecret {
669679
handleAccessTokenError(ctx, AccessTokenError{
670680
ErrorCode: AccessTokenErrorCodeInvalidRequest,
671681
ErrorDescription: "client_secret in request body inconsistent with Authorization header",
672682
})
673683
return
674684
}
675-
form.ClientSecret = pair[1]
685+
form.ClientSecret = clientSecret
676686
}
677687
}
678688

tests/integration/oauth_test.go

+56
Original file line numberDiff line numberDiff line change
@@ -419,3 +419,59 @@ func TestRefreshTokenInvalidation(t *testing.T) {
419419
assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode))
420420
assert.Equal(t, "token was already used", parsedError.ErrorDescription)
421421
}
422+
423+
func TestOAuthIntrospection(t *testing.T) {
424+
defer tests.PrepareTestEnv(t)()
425+
req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
426+
"grant_type": "authorization_code",
427+
"client_id": "da7da3ba-9a13-4167-856f-3899de0b0138",
428+
"client_secret": "4MK8Na6R55smdCY0WuCCumZ6hjRPnGY5saWVRHHjJiA=",
429+
"redirect_uri": "a",
430+
"code": "authcode",
431+
"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
432+
})
433+
resp := MakeRequest(t, req, http.StatusOK)
434+
type response struct {
435+
AccessToken string `json:"access_token"`
436+
TokenType string `json:"token_type"`
437+
ExpiresIn int64 `json:"expires_in"`
438+
RefreshToken string `json:"refresh_token"`
439+
}
440+
parsed := new(response)
441+
442+
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed))
443+
assert.True(t, len(parsed.AccessToken) > 10)
444+
assert.True(t, len(parsed.RefreshToken) > 10)
445+
446+
// successful request with a valid client_id/client_secret and a valid token
447+
req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{
448+
"token": parsed.AccessToken,
449+
})
450+
req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9")
451+
resp = MakeRequest(t, req, http.StatusOK)
452+
type introspectResponse struct {
453+
Active bool `json:"active"`
454+
Scope string `json:"scope,omitempty"`
455+
}
456+
introspectParsed := new(introspectResponse)
457+
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed))
458+
assert.True(t, introspectParsed.Active)
459+
460+
// successful request with a valid client_id/client_secret, but an invalid token
461+
req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{
462+
"token": "xyzzy",
463+
})
464+
req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9")
465+
resp = MakeRequest(t, req, http.StatusOK)
466+
introspectParsed = new(introspectResponse)
467+
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), introspectParsed))
468+
assert.False(t, introspectParsed.Active)
469+
470+
// unsuccessful request with an invalid client_id/client_secret
471+
req = NewRequestWithValues(t, "POST", "/login/oauth/introspect", map[string]string{
472+
"token": parsed.AccessToken,
473+
})
474+
req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpK")
475+
resp = MakeRequest(t, req, http.StatusUnauthorized)
476+
assert.Contains(t, resp.Body.String(), "no valid authorization")
477+
}

0 commit comments

Comments
 (0)