Skip to content

Commit 3533263

Browse files
authored
Improve OAuth2 provider (correct Issuer, respect ENABLED) (#34966)
1. Make "Issuer" strictly follow the spec (see comment) 2. Make "/.well-known/openid-configuration" respond 404 if the OAuth2 provider is not enabled. Then by the way, remove the JSEscape template helper because it is not needed any more.
1 parent 429efc8 commit 3533263

File tree

10 files changed

+80
-41
lines changed

10 files changed

+80
-41
lines changed

modules/templates/helper.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ func NewFuncMap() template.FuncMap {
4040
"HTMLFormat": htmlFormat,
4141
"QueryEscape": queryEscape,
4242
"QueryBuild": QueryBuild,
43-
"JSEscape": jsEscapeSafe,
4443
"SanitizeHTML": SanitizeHTML,
4544
"URLJoin": util.URLJoin,
4645
"DotEscape": dotEscape,
@@ -181,10 +180,6 @@ func htmlFormat(s any, args ...any) template.HTML {
181180
panic(fmt.Sprintf("unexpected type %T", s))
182181
}
183182

184-
func jsEscapeSafe(s string) template.HTML {
185-
return template.HTML(template.JSEscapeString(s))
186-
}
187-
188183
func queryEscape(s string) template.URL {
189184
return template.URL(url.QueryEscape(s))
190185
}

modules/templates/helper_test.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,6 @@ func TestSubjectBodySeparator(t *testing.T) {
5757
"Insufficient\n--\nSeparators")
5858
}
5959

60-
func TestJSEscapeSafe(t *testing.T) {
61-
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, jsEscapeSafe(`&<>'"`))
62-
}
63-
6460
func TestSanitizeHTML(t *testing.T) {
6561
assert.Equal(t, template.HTML(`<a href="/" rel="nofollow">link</a> xss <div>inline</div>`), SanitizeHTML(`<a href="/">link</a> <a href="javascript:">xss</a> <div style="dangerous">inline</div>`))
6662
}

routers/web/auth/oauth2_provider.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"net/url"
1212
"strconv"
13+
"strings"
1314

1415
"code.gitea.io/gitea/models/auth"
1516
user_model "code.gitea.io/gitea/models/user"
@@ -161,9 +162,7 @@ func IntrospectOAuth(ctx *context.Context) {
161162
if err == nil && app != nil {
162163
response.Active = true
163164
response.Scope = grant.Scope
164-
response.Issuer = setting.AppURL
165-
response.Audience = []string{app.ClientID}
166-
response.Subject = strconv.FormatInt(grant.UserID, 10)
165+
response.RegisteredClaims = oauth2_provider.NewJwtRegisteredClaimsFromUser(app.ClientID, grant.UserID, nil /*exp*/)
167166
}
168167
if user, err := user_model.GetUserByID(ctx, grant.UserID); err == nil {
169168
response.Username = user.Name
@@ -423,7 +422,14 @@ func GrantApplicationOAuth(ctx *context.Context) {
423422

424423
// OIDCWellKnown generates JSON so OIDC clients know Gitea's capabilities
425424
func OIDCWellKnown(ctx *context.Context) {
426-
ctx.Data["SigningKey"] = oauth2_provider.DefaultSigningKey
425+
if !setting.OAuth2.Enabled {
426+
http.NotFound(ctx.Resp, ctx.Req)
427+
return
428+
}
429+
jwtRegisteredClaims := oauth2_provider.NewJwtRegisteredClaimsFromUser("well-known", 0, nil)
430+
ctx.Data["OidcIssuer"] = jwtRegisteredClaims.Issuer // use the consistent issuer from the JWT registered claims
431+
ctx.Data["OidcBaseUrl"] = strings.TrimSuffix(setting.AppURL, "/")
432+
ctx.Data["SigningKeyMethodAlg"] = oauth2_provider.DefaultSigningKey.SigningMethod().Alg()
427433
ctx.JSONTemplate("user/auth/oidc_wellknown")
428434
}
429435

routers/web/swagger_json.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,15 @@
44
package web
55

66
import (
7+
"html/template"
8+
9+
"code.gitea.io/gitea/modules/setting"
710
"code.gitea.io/gitea/services/context"
811
)
912

1013
// SwaggerV1Json render swagger v1 json
1114
func SwaggerV1Json(ctx *context.Context) {
15+
ctx.Data["SwaggerAppVer"] = template.HTML(template.JSEscapeString(setting.AppVer))
16+
ctx.Data["SwaggerAppSubUrl"] = setting.AppSubURL // it is JS-safe
1217
ctx.JSONTemplate("swagger/v1_json")
1318
}

services/context/context_response.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ func (ctx *Context) HTML(status int, name templates.TplName) {
9292
}
9393

9494
// JSONTemplate renders the template as JSON response
95-
// keep in mind that the template is processed in HTML context, so JSON-things should be handled carefully, eg: by JSEscape
95+
// keep in mind that the template is processed in HTML context, so JSON things should be handled carefully, e.g.: use JSEscape
9696
func (ctx *Context) JSONTemplate(tmpl templates.TplName) {
9797
t, err := ctx.Render.TemplateLookup(string(tmpl), nil)
9898
if err != nil {

services/oauth2_provider/access_token.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,20 @@ func GrantAdditionalScopes(grantScopes string) auth.AccessTokenScope {
106106
return auth.AccessTokenScopeAll
107107
}
108108

109+
func NewJwtRegisteredClaimsFromUser(clientID string, grantUserID int64, exp *jwt.NumericDate) jwt.RegisteredClaims {
110+
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
111+
// The issuer value returned MUST be identical to the Issuer URL that was used as the prefix to /.well-known/openid-configuration
112+
// to retrieve the configuration information. This MUST also be identical to the "iss" Claim value in ID Tokens issued from this Issuer.
113+
// * https://accounts.google.com/.well-known/openid-configuration
114+
// * https://github.com/login/oauth/.well-known/openid-configuration
115+
return jwt.RegisteredClaims{
116+
Issuer: strings.TrimSuffix(setting.AppURL, "/"),
117+
Audience: []string{clientID},
118+
Subject: strconv.FormatInt(grantUserID, 10),
119+
ExpiresAt: exp,
120+
}
121+
}
122+
109123
func NewAccessTokenResponse(ctx context.Context, grant *auth.OAuth2Grant, serverKey, clientKey JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) {
110124
if setting.OAuth2.InvalidateRefreshTokens {
111125
if err := grant.IncreaseCounter(ctx); err != nil {
@@ -176,13 +190,8 @@ func NewAccessTokenResponse(ctx context.Context, grant *auth.OAuth2Grant, server
176190
}
177191

178192
idToken := &OIDCToken{
179-
RegisteredClaims: jwt.RegisteredClaims{
180-
ExpiresAt: jwt.NewNumericDate(expirationDate.AsTime()),
181-
Issuer: setting.AppURL,
182-
Audience: []string{app.ClientID},
183-
Subject: strconv.FormatInt(grant.UserID, 10),
184-
},
185-
Nonce: grant.Nonce,
193+
RegisteredClaims: NewJwtRegisteredClaimsFromUser(app.ClientID, grant.UserID, jwt.NewNumericDate(expirationDate.AsTime())),
194+
Nonce: grant.Nonce,
186195
}
187196
if grant.ScopeContains("profile") {
188197
idToken.Name = user.DisplayName()

templates/swagger/v1_input.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"info": {
3-
"version": "{{AppVer | JSEscape}}"
3+
"version": "{{.SwaggerAppVer}}"
44
},
5-
"basePath": "{{AppSubUrl | JSEscape}}/api/v1"
5+
"basePath": "{{.SwaggerAppSubUrl}}/api/v1"
66
}

templates/swagger/v1_json.tmpl

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

templates/user/auth/oidc_wellknown.tmpl

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
{
2-
"issuer": "{{AppUrl | JSEscape}}",
3-
"authorization_endpoint": "{{AppUrl | JSEscape}}login/oauth/authorize",
4-
"token_endpoint": "{{AppUrl | JSEscape}}login/oauth/access_token",
5-
"jwks_uri": "{{AppUrl | JSEscape}}login/oauth/keys",
6-
"userinfo_endpoint": "{{AppUrl | JSEscape}}login/oauth/userinfo",
7-
"introspection_endpoint": "{{AppUrl | JSEscape}}login/oauth/introspect",
2+
"issuer": "{{.OidcIssuer}}",
3+
"authorization_endpoint": "{{.OidcBaseUrl}}/login/oauth/authorize",
4+
"token_endpoint": "{{.OidcBaseUrl}}/login/oauth/access_token",
5+
"jwks_uri": "{{.OidcBaseUrl}}/login/oauth/keys",
6+
"userinfo_endpoint": "{{.OidcBaseUrl}}/login/oauth/userinfo",
7+
"introspection_endpoint": "{{.OidcBaseUrl}}/login/oauth/introspect",
88
"response_types_supported": [
99
"code",
1010
"id_token"
1111
],
1212
"id_token_signing_alg_values_supported": [
13-
"{{.SigningKey.SigningMethod.Alg | JSEscape}}"
13+
"{{.SigningKeyMethodAlg}}"
1414
],
1515
"subject_types_supported": [
1616
"public"

tests/integration/oauth_test.go

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,41 @@ import (
1919
"code.gitea.io/gitea/modules/json"
2020
"code.gitea.io/gitea/modules/setting"
2121
api "code.gitea.io/gitea/modules/structs"
22+
"code.gitea.io/gitea/modules/test"
2223
"code.gitea.io/gitea/services/oauth2_provider"
2324
"code.gitea.io/gitea/tests"
2425

2526
"github.com/stretchr/testify/assert"
2627
"github.com/stretchr/testify/require"
2728
)
2829

29-
func TestAuthorizeNoClientID(t *testing.T) {
30+
func TestOAuth2Provider(t *testing.T) {
3031
defer tests.PrepareTestEnv(t)()
32+
33+
t.Run("AuthorizeNoClientID", testAuthorizeNoClientID)
34+
t.Run("AuthorizeUnregisteredRedirect", testAuthorizeUnregisteredRedirect)
35+
t.Run("AuthorizeUnsupportedResponseType", testAuthorizeUnsupportedResponseType)
36+
t.Run("AuthorizeUnsupportedCodeChallengeMethod", testAuthorizeUnsupportedCodeChallengeMethod)
37+
t.Run("AuthorizeLoginRedirect", testAuthorizeLoginRedirect)
38+
39+
t.Run("OAuth2WellKnown", testOAuth2WellKnown)
40+
}
41+
42+
func testAuthorizeNoClientID(t *testing.T) {
3143
req := NewRequest(t, "GET", "/login/oauth/authorize")
3244
ctx := loginUser(t, "user2")
3345
resp := ctx.MakeRequest(t, req, http.StatusBadRequest)
3446
assert.Contains(t, resp.Body.String(), "Client ID not registered")
3547
}
3648

37-
func TestAuthorizeUnregisteredRedirect(t *testing.T) {
38-
defer tests.PrepareTestEnv(t)()
49+
func testAuthorizeUnregisteredRedirect(t *testing.T) {
3950
req := NewRequest(t, "GET", "/login/oauth/authorize?client_id=da7da3ba-9a13-4167-856f-3899de0b0138&redirect_uri=UNREGISTERED&response_type=code&state=thestate")
4051
ctx := loginUser(t, "user1")
4152
resp := ctx.MakeRequest(t, req, http.StatusBadRequest)
4253
assert.Contains(t, resp.Body.String(), "Unregistered Redirect URI")
4354
}
4455

45-
func TestAuthorizeUnsupportedResponseType(t *testing.T) {
46-
defer tests.PrepareTestEnv(t)()
56+
func testAuthorizeUnsupportedResponseType(t *testing.T) {
4757
req := NewRequest(t, "GET", "/login/oauth/authorize?client_id=da7da3ba-9a13-4167-856f-3899de0b0138&redirect_uri=a&response_type=UNEXPECTED&state=thestate")
4858
ctx := loginUser(t, "user1")
4959
resp := ctx.MakeRequest(t, req, http.StatusSeeOther)
@@ -53,8 +63,7 @@ func TestAuthorizeUnsupportedResponseType(t *testing.T) {
5363
assert.Equal(t, "Only code response type is supported.", u.Query().Get("error_description"))
5464
}
5565

56-
func TestAuthorizeUnsupportedCodeChallengeMethod(t *testing.T) {
57-
defer tests.PrepareTestEnv(t)()
66+
func testAuthorizeUnsupportedCodeChallengeMethod(t *testing.T) {
5867
req := NewRequest(t, "GET", "/login/oauth/authorize?client_id=da7da3ba-9a13-4167-856f-3899de0b0138&redirect_uri=a&response_type=code&state=thestate&code_challenge_method=UNEXPECTED")
5968
ctx := loginUser(t, "user1")
6069
resp := ctx.MakeRequest(t, req, http.StatusSeeOther)
@@ -64,8 +73,7 @@ func TestAuthorizeUnsupportedCodeChallengeMethod(t *testing.T) {
6473
assert.Equal(t, "unsupported code challenge method", u.Query().Get("error_description"))
6574
}
6675

67-
func TestAuthorizeLoginRedirect(t *testing.T) {
68-
defer tests.PrepareTestEnv(t)()
76+
func testAuthorizeLoginRedirect(t *testing.T) {
6977
req := NewRequest(t, "GET", "/login/oauth/authorize")
7078
assert.Contains(t, MakeRequest(t, req, http.StatusSeeOther).Body.String(), "/user/login")
7179
}
@@ -903,3 +911,23 @@ func TestOAuth_GrantScopesClaimAllGroups(t *testing.T) {
903911
assert.Contains(t, userinfoParsed.Groups, group)
904912
}
905913
}
914+
915+
func testOAuth2WellKnown(t *testing.T) {
916+
urlOpenidConfiguration := "/.well-known/openid-configuration"
917+
918+
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/")()
919+
req := NewRequest(t, "GET", urlOpenidConfiguration)
920+
resp := MakeRequest(t, req, http.StatusOK)
921+
var respMap map[string]any
922+
DecodeJSON(t, resp, &respMap)
923+
assert.Equal(t, "https://try.gitea.io", respMap["issuer"])
924+
assert.Equal(t, "https://try.gitea.io/login/oauth/authorize", respMap["authorization_endpoint"])
925+
assert.Equal(t, "https://try.gitea.io/login/oauth/access_token", respMap["token_endpoint"])
926+
assert.Equal(t, "https://try.gitea.io/login/oauth/keys", respMap["jwks_uri"])
927+
assert.Equal(t, "https://try.gitea.io/login/oauth/userinfo", respMap["userinfo_endpoint"])
928+
assert.Equal(t, "https://try.gitea.io/login/oauth/introspect", respMap["introspection_endpoint"])
929+
assert.Equal(t, []any{"RS256"}, respMap["id_token_signing_alg_values_supported"])
930+
931+
defer test.MockVariableValue(&setting.OAuth2.Enabled, false)()
932+
MakeRequest(t, NewRequest(t, "GET", urlOpenidConfiguration), http.StatusNotFound)
933+
}

0 commit comments

Comments
 (0)