|
| 1 | +// Copyright 2026 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package integration |
| 5 | + |
| 6 | +import ( |
| 7 | + "encoding/base64" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "net/http/httptest" |
| 11 | + "net/url" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + auth_model "code.gitea.io/gitea/models/auth" |
| 16 | + "code.gitea.io/gitea/models/unittest" |
| 17 | + user_model "code.gitea.io/gitea/models/user" |
| 18 | + "code.gitea.io/gitea/modules/json" |
| 19 | + "code.gitea.io/gitea/modules/setting" |
| 20 | + "code.gitea.io/gitea/modules/test" |
| 21 | + "code.gitea.io/gitea/services/auth/source/oauth2" |
| 22 | + "code.gitea.io/gitea/tests" |
| 23 | + |
| 24 | + "github.com/stretchr/testify/assert" |
| 25 | + "github.com/stretchr/testify/require" |
| 26 | +) |
| 27 | + |
| 28 | +// TestMigrateAzureADV2ToOIDC simulates a login source migration from the Azure AD V2 OAuth2 provider to the OpenID Connect provider, |
| 29 | +// and verifies that setting ExternalIDClaim = "oid" restores account continuity. |
| 30 | +// |
| 31 | +// Background: Azure AD V2 (goth's azureadv2 provider) fetches the user profile from Microsoft Graph API (/v1.0/me) |
| 32 | +// and uses the "id" field - the stable Object ID (OID) - as gothUser.UserID. That OID is stored as ExternalID in external_login_user. |
| 33 | +// |
| 34 | +// When the admin migrates the same source to OpenID Connect, the goth openidConnect provider defaults to ["sub"] for UserIdClaims. |
| 35 | +// Azure AD's "sub" is pairwise (unique per application), so it differs from the OID that was previously stored, |
| 36 | +// causing every existing user to appear as a new account. |
| 37 | +// |
| 38 | +// Setting ExternalIDClaim = "oid" on the OIDC source overrides UserIdClaims to ["oid"], |
| 39 | +// so the same OID is extracted and matched against the existing rows, restoring continuity. |
| 40 | +func TestMigrateAzureADV2ToOIDC(t *testing.T) { |
| 41 | + defer tests.PrepareTestEnv(t)() |
| 42 | + defer test.MockVariableValue(&setting.OAuth2Client.EnableAutoRegistration, true)() |
| 43 | + // Use UserID (gothUser.UserID) as the Gitea username so that different ExternalID values produce different, non-conflicting usernames. |
| 44 | + defer test.MockVariableValue(&setting.OAuth2Client.Username, setting.OAuth2UsernameUserid)() |
| 45 | + |
| 46 | + const ( |
| 47 | + sourceName = "test-migrate-azure" |
| 48 | + |
| 49 | + // oidValue is the stable Azure AD Object ID, used as ExternalID by the Azure AD V2 provider. |
| 50 | + oidValue = "oid-object-id-stable" |
| 51 | + |
| 52 | + // subValue is the pairwise sub issued by Azure AD for OpenID Connect; it differs from oidValue and would produce a separate account if used. |
| 53 | + subValue = "sub-pairwise-value" |
| 54 | + ) |
| 55 | + |
| 56 | + // The fake OIDC server issues tokens containing both sub and oid claims, mirroring what Azure AD v2.0 returns. |
| 57 | + srv := newFakeOIDCServer(t, subValue, oidValue) |
| 58 | + |
| 59 | + // --- Step 1: Establish the legacy Azure AD V2 state --- |
| 60 | + // Create an azureadv2 auth source. In production this would have been the source used before the migration. |
| 61 | + addOAuth2Source(t, sourceName, oauth2.Source{ |
| 62 | + Provider: "azureadv2", |
| 63 | + ClientID: "test-client-id", |
| 64 | + ClientSecret: "test-client-secret", |
| 65 | + CustomURLMapping: &oauth2.CustomURLMapping{ |
| 66 | + Tenant: "test-tenant-id", |
| 67 | + }, |
| 68 | + }) |
| 69 | + authSource, err := auth_model.GetActiveOAuth2SourceByAuthName(t.Context(), sourceName) |
| 70 | + require.NoError(t, err) |
| 71 | + |
| 72 | + // Create a user to represent the "legacy" account that was originally registered through the Azure AD V2 provider. |
| 73 | + legacyUser := &user_model.User{ |
| 74 | + Name: "legacy-azure-user", |
| 75 | + Email: "legacy-azure-user@example.com", |
| 76 | + } |
| 77 | + require.NoError(t, user_model.CreateUser(t.Context(), legacyUser, &user_model.Meta{})) |
| 78 | + require.NoError(t, user_model.LinkExternalToUser(t.Context(), legacyUser, &user_model.ExternalLoginUser{ |
| 79 | + ExternalID: oidValue, |
| 80 | + UserID: legacyUser.ID, |
| 81 | + LoginSourceID: authSource.ID, |
| 82 | + Provider: authSource.Name, |
| 83 | + })) |
| 84 | + |
| 85 | + // --- Step 2: Migrate the source to OIDC without ExternalIDClaim --- |
| 86 | + // The provider type of the OAuth2 source is changed from azureadv2 to openidConnect. |
| 87 | + // Without ExternalIDClaim the goth provider defaults to "sub", which does not match the stored OID, so every sign-in creates a fresh account. |
| 88 | + authSource.Cfg = &oauth2.Source{ |
| 89 | + Provider: "openidConnect", |
| 90 | + ClientID: "test-client-id", |
| 91 | + ClientSecret: "test-client-secret", |
| 92 | + OpenIDConnectAutoDiscoveryURL: srv.URL + "/.well-known/openid-configuration", |
| 93 | + // ExternalIDClaim intentionally not set; goth defaults to "sub". |
| 94 | + } |
| 95 | + err = auth_model.UpdateSource(t.Context(), authSource) |
| 96 | + require.NoError(t, err) |
| 97 | + |
| 98 | + t.Run("without ExternalIDClaim: legacy user is NOT matched", func(t *testing.T) { |
| 99 | + // Confirm the external user with ExternalID=subValue doesn't exist. |
| 100 | + unittest.AssertNotExistsBean(t, &user_model.ExternalLoginUser{ExternalID: subValue, LoginSourceID: authSource.ID}, unittest.OrderBy("external_id ASC")) |
| 101 | + |
| 102 | + doOIDCSignIn(t, sourceName) |
| 103 | + |
| 104 | + // "sub" is now the ExternalID - a new user was auto-registered. |
| 105 | + subEntry := unittest.AssertExistsAndLoadBean(t, &user_model.ExternalLoginUser{ExternalID: subValue, LoginSourceID: authSource.ID}, unittest.OrderBy("external_id ASC")) |
| 106 | + // The auto-registered user is NOT the legacy user. |
| 107 | + assert.NotEqual(t, legacyUser.ID, subEntry.UserID) |
| 108 | + }) |
| 109 | + |
| 110 | + // --- Step 3: Set ExternalIDClaim = "oid" to restore account continuity --- |
| 111 | + // Set ExternalIDClaim = "oid" so that the OIDC source extracts the same Object ID that the Azure AD V2 provider previously stored. |
| 112 | + authSource.Cfg.(*oauth2.Source).ExternalIDClaim = "oid" |
| 113 | + err = auth_model.UpdateSource(t.Context(), authSource) |
| 114 | + require.NoError(t, err) |
| 115 | + |
| 116 | + t.Run("with ExternalIDClaim=oid: legacy user IS matched", func(t *testing.T) { |
| 117 | + // Confirm the legacy oid row has no RawData yet - it was created directly via LinkExternalToUser in setup, without going through an OAuth flow. |
| 118 | + oidEntry := unittest.AssertExistsAndLoadBean(t, &user_model.ExternalLoginUser{ExternalID: oidValue, LoginSourceID: authSource.ID}, unittest.OrderBy("external_id ASC")) |
| 119 | + require.Nil(t, oidEntry.RawData) |
| 120 | + |
| 121 | + doOIDCSignIn(t, sourceName) |
| 122 | + |
| 123 | + // After sign-in, RawData should contain both "oid" and "name". |
| 124 | + oidEntry = unittest.AssertExistsAndLoadBean(t, &user_model.ExternalLoginUser{ExternalID: oidValue, LoginSourceID: authSource.ID}, unittest.OrderBy("external_id ASC")) |
| 125 | + assert.Equal(t, oidValue, oidEntry.RawData["oid"]) |
| 126 | + assert.Equal(t, "OIDC Test User", oidEntry.RawData["name"]) |
| 127 | + |
| 128 | + // The matched user must still be the original legacy user. |
| 129 | + assert.Equal(t, legacyUser.ID, oidEntry.UserID) |
| 130 | + }) |
| 131 | +} |
| 132 | + |
| 133 | +// newFakeOIDCServer starts an httptest.Server that implements the minimum OIDC endpoints needed to complete a sign-in flow: |
| 134 | +func newFakeOIDCServer(t *testing.T, sub, oid string) *httptest.Server { |
| 135 | + t.Helper() |
| 136 | + |
| 137 | + var srv *httptest.Server |
| 138 | + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 139 | + w.Header().Set("Content-Type", "application/json") |
| 140 | + switch r.URL.Path { |
| 141 | + case "/.well-known/openid-configuration": // discovery document |
| 142 | + _ = json.NewEncoder(w).Encode(map[string]string{ |
| 143 | + "issuer": srv.URL, |
| 144 | + "authorization_endpoint": srv.URL + "/authorize", |
| 145 | + "token_endpoint": srv.URL + "/token", |
| 146 | + "userinfo_endpoint": srv.URL + "/userinfo", |
| 147 | + }) |
| 148 | + case "/token": // returns an ID token with both "sub" and "oid" claims so tests can verify which one ends up as ExternalID |
| 149 | + claims := map[string]any{ |
| 150 | + "iss": srv.URL, |
| 151 | + "aud": "test-client-id", |
| 152 | + "exp": time.Now().Add(time.Hour).Unix(), |
| 153 | + "sub": sub, |
| 154 | + "oid": oid, |
| 155 | + } |
| 156 | + payload, _ := json.Marshal(claims) |
| 157 | + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) |
| 158 | + |
| 159 | + // build a JWT-shaped string whose payload encodes claims. |
| 160 | + // goth's decodeJWT only base64-decodes the payload without verifying the signature, so no real signing infrastructure is needed. |
| 161 | + idToken := header + "." + base64.RawURLEncoding.EncodeToString(payload) + ".fakesig" |
| 162 | + |
| 163 | + _ = json.NewEncoder(w).Encode(map[string]any{ |
| 164 | + "access_token": "fake-access-token", |
| 165 | + "token_type": "Bearer", |
| 166 | + "id_token": idToken, |
| 167 | + }) |
| 168 | + case "/userinfo": |
| 169 | + // sub MUST match the id_token sub; goth rejects mismatches. |
| 170 | + _ = json.NewEncoder(w).Encode(map[string]any{ |
| 171 | + "sub": sub, |
| 172 | + "email": sub + "@example.com", |
| 173 | + "name": "OIDC Test User", |
| 174 | + }) |
| 175 | + default: |
| 176 | + http.NotFound(w, r) |
| 177 | + } |
| 178 | + })) |
| 179 | + t.Cleanup(srv.Close) |
| 180 | + return srv |
| 181 | +} |
| 182 | + |
| 183 | +// doOIDCSignIn runs a mock OIDC sign-in flow for the given auth source. |
| 184 | +func doOIDCSignIn(t *testing.T, sourceName string) { |
| 185 | + t.Helper() |
| 186 | + session := emptyTestSession(t) |
| 187 | + |
| 188 | + // Step 1: initiate login |
| 189 | + resp := session.MakeRequest(t, NewRequest(t, "GET", "/user/oauth2/"+sourceName), http.StatusTemporaryRedirect) |
| 190 | + |
| 191 | + // Step 2: extract the UUID state that Gitea embedded in the redirect URL. |
| 192 | + location := resp.Header().Get("Location") |
| 193 | + u, err := url.Parse(location) |
| 194 | + require.NoError(t, err) |
| 195 | + state := u.Query().Get("state") |
| 196 | + require.NotEmpty(t, state, "redirect to OIDC provider must include state") |
| 197 | + |
| 198 | + // Step 3: simulate the provider redirecting back. |
| 199 | + callbackURL := fmt.Sprintf("/user/oauth2/%s/callback?code=test-code&state=%s", sourceName, url.QueryEscape(state)) |
| 200 | + session.MakeRequest(t, NewRequest(t, "GET", callbackURL), http.StatusSeeOther) |
| 201 | +} |
0 commit comments