Backport #37704
This PR hardens OAuth token exchange validation by binding exchanged
credentials to the client and redirect URI that originally obtained
them.
What it changes:
- reject refresh token exchanges when the refresh token belongs to a
different OAuth application
- reject authorization code exchanges when the `redirect_uri` in the
token request differs from the `redirect_uri` stored with the
authorization code
- add integration coverage for:
- authorization code exchange with a mismatched redirect URI
- refresh token reuse across two different dynamically created OAuth
applications
Why:
OAuth authorization codes and refresh tokens must remain bound to the
client context that originally received them. Without those checks:
- a valid authorization code can be redeemed against a different
registered redirect URI of the same client
- a refresh token can be replayed by a different OAuth client
---------
Co-authored-by: Nicolas <bircni@icloud.com>
Backport #37588 by @pandareen
## Summary
Fixes
[go-gitea/gitea#37564](https://github.com/go-gitea/gitea/issues/37564):
when an OIDC provider returns a `picture` claim, Gitea is supposed to
download that image as the user's avatar (if `[oauth2_client]
UPDATE_AVATAR = true`). Two latent bugs prevented this from working
consistently:
1. **Default Go User-Agent rejected by some image hosts.**
`oauth2UpdateAvatarIfNeed` used `http.Get`, which sends `User-Agent:
Go-http-client/1.1`. Hosts like `upload.wikimedia.org` reject that UA
with `403`, and every error path silently returned, so the user was left
with an identicon and **no log line** to diagnose the issue.
2. **Link-account *register* path skipped avatar sync.** First-time OIDC
sign-ins where auto-registration is disabled (or required a
username/password retype) go through `LinkAccountPostRegister`, which
created the user but never called `oauth2SignInSync`. So the avatar /
full name / SSH keys from the IdP were dropped on the floor for those
users, even though the existing-account-link path (`oauth2LinkAccount`)
and the auto-register path (`handleOAuth2SignIn`) both already did the
sync.
## Changes
- `routers/web/auth/oauth.go` — `oauth2UpdateAvatarIfNeed` now uses
`http.NewRequest` + `http.DefaultClient.Do`, sets `User-Agent: Gitea
<version>`, and logs every failure path at `Warn` (invalid URL, fetch
error, non-200, body read error, oversize body, upload error). No silent
failures.
- `routers/web/auth/linkaccount.go` — `LinkAccountPostRegister` now
calls `oauth2SignInSync` after a successful user creation, mirroring the
auto-register and link-existing-account flows.
- `tests/integration/oauth_avatar_test.go` — new
`TestOAuth2AvatarFromPicture` integration test with five sub-cases:
- `AutoRegister_FetchesAvatarFromPictureWithGiteaUA` — happy path,
asserts `use_custom_avatar=true`, an avatar hash is set, exactly one
HTTP request was made, and the request carried a `Gitea ` UA. The mock
server enforces the UA prefix to mirror real-world hosts that reject
Go's default UA.
- `AutoRegister_NonOK_DoesNotUpdateAvatar` — server returns 403; user's
avatar must remain unset.
- `AutoRegister_EmptyPicture_NoFetch` — empty `picture` claim must not
trigger any HTTP request.
- `AutoRegister_UpdateAvatarFalse_NoFetch` — `UPDATE_AVATAR=false` must
not trigger any HTTP request.
- `LinkAccountRegister_FetchesAvatarFromPicture` — guards the
`linkaccount.go` fix; without the new `oauth2SignInSync` call this
assertion fails.
## Test plan
- [x] `go test -tags 'sqlite sqlite_unlock_notify' -run
'^TestOAuth2AvatarFromPicture$' ./tests/integration/ -v` — 5/5 sub-tests
pass.
- [x] Manual: log in as a Keycloak user with `picture` claim pointing at
`https://avatars.githubusercontent.com/u/9919?v=4` — Gitea avatar is
replaced with the GitHub picture.
- [x] Manual: same flow with `https://upload.wikimedia.org/...` —
request now succeeds (or returns a clearly logged `Warn` line if
rate-limited with `429`); previously it silently 403'd.
- [x] Manual: `UPDATE_AVATAR=false` — user keeps the identicon, no
outbound request in container logs.
- [ ] Reviewer: please double-check that no other call sites of
`oauth2UpdateAvatarIfNeed` rely on the old `http.Get` behaviour.
## Related
- Upstream issue: go-gitea/gitea#37564
--------------------------------------------
AI Editor was used in this PR
---------
Signed-off-by: silverwind <me@silverwind.io>
Co-authored-by: pandareen <7270563+pandareen@users.noreply.github.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: Claude (Opus 4.7) <noreply@anthropic.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Nicolas <bircni@icloud.com>
Backport #37327 by @prettysunflower
Nyallo~
In pull request #36901, a change is made so that the link to
authentication sources is now escaped with the QueryEscape filter.
https://github.com/go-gitea/gitea/pull/36901/changes#diff-34c39c9736a8b62e293c0c0b24c4b5b8c1c792790018c5809f9ff2cbc12b16b1R4
The problem is that [QueryEscape replace spaces with the `+`
character](https://cs.opensource.google/go/go/+/refs/tags/go1.26.2:src/net/url/url.go;l=234;drc=917949cc1d16c652cb09ba369718f45e5d814d8f),
and this is not unescaped when a user tries to log in with an
authentication source that contains a space, which throws an error.
This commit fixes that by unescaping the provider name in the URL.
---
Example of the error, on my instance, when I try to log in with
`prettysunflower's auth`
```
2026/04/21 00:11:41 routers/web/auth/oauth.go:42:SignInOAuth() [E] SignIn: oauth2 source not found, name: "prettysunflower's+auth"
/go/src/code.gitea.io/gitea/routers/web/auth/oauth.go:42 (0x2cfa5c5)
/usr/local/go/src/reflect/value.go:586 (0x51e245)
/usr/local/go/src/reflect/value.go:369 (0x51d0f8)
/go/src/code.gitea.io/gitea/modules/web/handler.go:181 (0x1a6aaf6)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:188 (0x1a6ab65)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:188 (0x1a6ab65)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:188 (0x1a6ab65)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/services/context/context.go:217 (0x2df1b23)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/gitea.com/go-chi/session@v0.0.0-20251124165456-68e0254e989e/session.go:258 (0x197eb82)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/chain.go:31 (0x1a61d05)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:479 (0x1a64fae)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:73 (0x1a628c2)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:321 (0x1a6421a)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/chain.go:31 (0x1a61d05)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:479 (0x1a64fae)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/middleware/get_head.go:37 (0x2c33a67)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:73 (0x1a628c2)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:321 (0x1a6421a)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/routers/common/maintenancemode.go:50 (0x2b752da)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/chain.go:31 (0x1a61d05)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:479 (0x1a64fae)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/routing/logger_manager.go:124 (0x127d1ec)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/chi-middleware/proxy@v1.1.1/middleware.go:37 (0x2b76acf)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/routers/common/middleware.go:89 (0x2b78cd6)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/routers/common/middleware.go:104 (0x2b7890f)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/src/code.gitea.io/gitea/modules/web/handler.go:145 (0x1a6afb5)
/usr/local/go/src/net/http/server.go:2286 (0x94dc88)
/go/pkg/mod/github.com/go-chi/chi/v5@v5.2.5/mux.go:90 (0x1a62881)
/go/src/code.gitea.io/gitea/modules/web/router.go:286 (0x1a6d2a2)
/go/src/code.gitea.io/gitea/modules/web/router.go:221 (0x1a6cbc6)
/usr/local/go/src/net/http/server.go:3311 (0x96e36d)
/usr/local/go/src/net/http/server.go:2073 (0x94bd6f)
/usr/local/go/src/runtime/asm_amd64.s:1771 (0x49af20)
```
Signed-off-by: prettysunflower <me@prettysunflower.moe>
Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: prettysunflower <me@prettysunflower.moe>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Backport #36085 by @eliroca
When authentication is handled externally by a reverse proxy SSO
provider, users can be redirected to an external logout URL or relative
path defined on the reverse proxy.
Co-authored-by: Elisei Roca <eroca@suse.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Fixes: #36846
1. When there is only on OAuth2 login method, automatically direct to it
2. Fix legacy problems in code, including:
* Rename template filename and fix TODO comments
* Fix legacy variable names
* Add missing SSPI variable for template
* Fix unnecessary layout, remove garbage styles
* Only do AppUrl(ROOT_URL) check when it is needed (avoid unnecessary
warnings to end users)
---------
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
The logic of "URLJoin" is unclear and it is often abused.
Also:
* Correct the `resolveLinkRelative` behavior
* Fix missing "PathEscape" in `ToTag`
* Fix more FIXMEs, and add new FIXMEs for newly found problems
* Refactor "auth page common template data"
- set OAuth2 authorization code `ValidUntil` on creation and add expiry
checks during exchange
- return a specific error when codes are invalidated twice to prevent
concurrent reuse
- add unit tests covering validity timestamps, expiration, and double
invalidation
---
Generate by a coding agent with Codex 5.2
---------
Signed-off-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
At logout time, if the user authenticated via OIDC, we look up the
provider's `end_session_endpoint` (already discovered by Goth from the
OIDC metadata) and redirect there with `client_id` and
`post_logout_redirect_uri`.
Non-OIDC OAuth2 providers (GitHub, GitLab, etc.) are unaffected — they
fall back to local-only logout.
Fix#14270
---------
Signed-off-by: Nikita Vakula <nikita.vakula@alpsalpine.com>
Co-authored-by: Nikita Vakula <nikita.vakula@alpsalpine.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
The banner allows site operators to communicate important announcements
(e.g., maintenance windows, policy updates, service notices) directly
within the UI.
The maintenance mode only allows admin to access the web UI.
* Fix#2345
* Fix#9618
---------
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Fix#35998
1. Fix `<a rel>` :
* "_blank" already means "noopener"
* "noreferrer" is already provided by page's `<meta name="referrer">`
2. Fix "redirect_to" mechisam
* Use "referer" header to determine the redirect link for a successful
login
3. Simplify code and merge duplicate logic
This pull request adds an option to automatically verify SSH keys from
LDAP authentication sources.
This allows a correct authentication and verification workflow for
LDAP-enabled organizations; under normal circumstances SSH keys in LDAP
are not managed by users manually.
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.
This PR adds a feature to direct users to appropriate pages after system
installation:
- If no admin credentials were provided during installation, redirect to
the registration page with a prominent notice about creating the first
administrative account
- If admin credentials were already set, redirect directly to the login
page

---------
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Fix#880
Design:
1. A global setting `security.TWO_FACTOR_AUTH`.
* To support org-level config, we need to introduce a better "owner
setting" system first (in the future)
2. A user without 2FA can login and may explore, but can NOT read or
write to any repositories via API/web.
3. Keep things as simple as possible.
* This option only aggressively suggest users to enable their 2FA at the
moment, it does NOT guarantee that users must have 2FA before all other
operations, it should be good enough for real world use cases.
* Some details and tests could be improved in the future since this
change only adds a check and seems won't affect too much.
---------
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Fix password form missing whilst linking account even with
`ENABLE_PASSWORD_SIGNIN_FORM = true`.
Remove redundant empty box in account linking sign up page when
`LinkAccountMode` is true.
---------
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
In history (from some legacy frameworks), both `:name` and `name` are
supported as path path name, `:name` is an alias to `name`.
To make code consistent, now we should only use `name` but not `:name`.
Also added panic check in related functions to make sure the name won't
be abused in case some downstreams still use them.
Usually enterprise/organization users would like to only allow OAuth2
login.
This PR adds a new config option to disable the password-based login
form. It is a simple and clear approach and won't block the future
login-system refactoring works.
Fix a TODO in #24821
Replace #21851Close#7633 , close#13606
Resolve#31609
This PR was initiated following my personal research to find the
lightest possible Single Sign-On solution for self-hosted setups. The
existing solutions often seemed too enterprise-oriented, involving many
moving parts and services, demanding significant resources while
promising planetary-scale capabilities. Others were adequate in
supporting basic OAuth2 flows but lacked proper user management
features, such as a change password UI.
Gitea hits the sweet spot for me, provided it supports more granular
access permissions for resources under users who accept the OAuth2
application.
This PR aims to introduce granularity in handling user resources as
nonintrusively and simply as possible. It allows third parties to inform
users about their intent to not ask for the full access and instead
request a specific, reduced scope. If the provided scopes are **only**
the typical ones for OIDC/OAuth2—`openid`, `profile`, `email`, and
`groups`—everything remains unchanged (currently full access to user's
resources). Additionally, this PR supports processing scopes already
introduced with [personal
tokens](https://docs.gitea.com/development/oauth2-provider#scopes) (e.g.
`read:user`, `write:issue`, `read:group`, `write:repository`...)
Personal tokens define scopes around specific resources: user info,
repositories, issues, packages, organizations, notifications,
miscellaneous, admin, and activitypub, with access delineated by read
and/or write permissions.
The initial case I wanted to address was to have Gitea act as an OAuth2
Identity Provider. To achieve that, with this PR, I would only add
`openid public-only` to provide access token to the third party to
authenticate the Gitea's user but no further access to the API and users
resources.
Another example: if a third party wanted to interact solely with Issues,
it would need to add `read:user` (for authorization) and
`read:issue`/`write:issue` to manage Issues.
My approach is based on my understanding of how scopes can be utilized,
supported by examples like [Sample Use Cases: Scopes and
Claims](https://auth0.com/docs/get-started/apis/scopes/sample-use-cases-scopes-and-claims)
on auth0.com.
I renamed `CheckOAuthAccessToken` to `GetOAuthAccessTokenScopeAndUserID`
so now it returns AccessTokenScope and user's ID. In the case of
additional scopes in `userIDFromToken` the default `all` would be
reduced to whatever was asked via those scopes. The main difference is
the opportunity to reduce the permissions from `all`, as is currently
the case, to what is provided by the additional scopes described above.
Screenshots:




---------
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
1. move "internal-lfs" route mock to "common-lfs"
2. fine tune tests
3. fix "realm" strings, according to RFC:
https://datatracker.ietf.org/doc/html/rfc2617:
* realm = "realm" "=" realm-value
* realm-value = quoted-string
4. clarify some names of the middlewares, rename `ignXxx` to `optXxx` to
match `reqXxx`, and rename ambiguous `requireSignIn` to `reqGitSignIn`