Skip to content

feat(oauth): Add PKCE support for OAuth2 authorization code flow - #104418

Merged
dcramer merged 18 commits into
masterfrom
oauth21-pkce
Dec 19, 2025
Merged

dcramer merged 18 commits into
masterfrom
oauth21-pkce

Conversation

@dcramer

@dcramer dcramer commented Dec 4, 2025

Copy link
Copy Markdown
Member

Implements RFC 7636 Proof Key for Code Exchange (PKCE) to protect OAuth2 authorization code grants from interception attacks. Adds code_challenge and code_challenge_method support to the authorize endpoint, and validates code_verifier in the token endpoint. Supports both S256 and plain methods.

Refs #99002

Replaces #99452

@dcramer
dcramer requested review from a team as code owners December 4, 2025 21:07
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Dec 4, 2025
@github-actions

github-actions Bot commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

This PR has a migration; here is the generated SQL for src/sentry/migrations/1012_add_pkce_to_apigrant.py

for 1012_add_pkce_to_apigrant in sentry

--
-- Add field code_challenge to apigrant
--
ALTER TABLE "sentry_apigrant" ADD COLUMN "code_challenge" varchar(128) NULL;
--
-- Add field code_challenge_method to apigrant
--
ALTER TABLE "sentry_apigrant" ADD COLUMN "code_challenge_method" varchar(10) NULL;

@codecov

codecov Bot commented Dec 4, 2025 •

Copy link
Copy Markdown

❌ 2 Tests Failed:

Tests completed Failed Passed Skipped
30797 2 30795 246
View the top 2 failed test(s) by shortest run time
tests.sentry.web.frontend.test_oauth_token.OAuthTokenCodeTest::test_inactive_application_rejects_token_creation
Stack Traces | 0.379s run time
#x1B[1m#x1B[.../web/frontend/test_oauth_token.py#x1B[0m:330: in test_inactive_application_rejects_token_creation
    assert resp.status_code == 400
#x1B[1m#x1B[31mE   assert 401 == 400#x1B[0m
#x1B[1m#x1B[31mE    +  where 401 = <HttpResponse status_code=401, "application/json">.status_code#x1B[0m
tests.sentry.web.frontend.test_oauth_token.OAuthTokenRefreshTokenTest::test_inactive_application_rejects_token_refresh
Stack Traces | 0.583s run time
#x1B[1m#x1B[.../web/frontend/test_oauth_token.py#x1B[0m:659: in test_inactive_application_rejects_token_refresh
    assert resp.status_code == 400
#x1B[1m#x1B[31mE   assert 401 == 400#x1B[0m
#x1B[1m#x1B[31mE    +  where 401 = <HttpResponse status_code=401, "application/json">.status_code#x1B[0m

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Moves PKCE validation and OAuth security checks from the endpoint layer to the
model layer. The oauth_token endpoint now calls ApiToken.from_grant() instead
of duplicating token creation logic with .objects.create().

Enhances from_grant() to handle redirect_uri binding and PKCE verification
inside the lock, fixing TOCTOU race conditions where an application could be
deactivated or grant could be reused between validation and token creation.

All validations now properly invalidate grants on failure per RFC 6749 §10.5.
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
@dcramer

dcramer commented Dec 18, 2025

Copy link
Copy Markdown
Member Author

i think we're good to go

@michelletran-sentry michelletran-sentry left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally LGTM. There's just the one question about removing the status filter for getting ApiApplication.

@@ -286,7 +325,18 @@ def _logged_out_post(
response = super().post(request, application=application, **kwargs)
# once they login, bind their user ID
if request.user.is_authenticated:
request.session["oa2"]["uid"] = request.user.id
# Regenerate session to prevent session fixation attacks

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this prevents attackers (who somehow has the user's session id before they're logged in) from reusing that session after the user has logged in (so now, the attacker can call /authorize again and it will see the user as already authenticated). I'm not sure whether it's simple to get/inject a session id onto a Sentry cookie, so this might not be that exploitable. But from what I've read (on ChatGPT and other sources), cycling the session id after authenticating is a best practice on this endpoint.

Comment thread src/sentry/web/frontend/oauth_token.py Resolved
Comment thread src/sentry/models/apitoken.py Resolved
)
logger.warning(
"Token request for inactive application",
extra={"client_id": client_id, "application_id": application.id},

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (secret)](1) as clear text.

Copilot Autofix

AI 11 months ago

In general, to fix clear-text logging of sensitive information, either stop logging the sensitive fields, or replace them with non-sensitive derivatives (e.g., hashes, redacted forms, or booleans like “exists/does_not_exist”) that still allow debugging without exposing secrets. For OAuth flows, you should never log client secrets, access tokens, or refresh tokens; client IDs may be logged only if you are certain they are not considered sensitive in your environment, but when in doubt, redact or transform them.

For this specific issue, we only need to change the log call around lines 170–173. We should avoid logging the raw client_id while still allowing operators to correlate events to an application when needed. A safe approach without changing existing behavior elsewhere is:

  • Replace extra={"client_id": client_id, "application_id": application.id} with:
    • either an indicator like client_id_provided: bool(client_id) and keep application_id, or
    • a hashed version of client_id (e.g., using hashlib.sha256(client_id.encode()).hexdigest()), which avoids logging the clear-text value.

Because we want minimal impact and no new imports if possible, using a boolean flag is simplest and does not require new dependencies. This keeps the log useful (“was there a client id?”) but ensures that no value derived from user-supplied credentials is logged. Concretely:

  • In src/sentry/web/frontend/oauth_token.py, locate the logger.warning("Token request for inactive application", extra={...}) call.
  • Replace the extra dict to remove client_id, and optionally add client_id_provided (derived from bool(client_id)), leaving application_id unchanged.

No new methods or imports are required for this fix.

Suggested changeset 1
src/sentry/web/frontend/oauth_token.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/sentry/web/frontend/oauth_token.py b/src/sentry/web/frontend/oauth_token.py
--- a/src/sentry/web/frontend/oauth_token.py
+++ b/src/sentry/web/frontend/oauth_token.py
@@ -169,7 +169,10 @@
             )
             logger.warning(
                 "Token request for inactive application",
-                extra={"client_id": client_id, "application_id": application.id},
+                extra={
+                    "client_id_provided": bool(client_id),
+                    "application_id": application.id,
+                },
             )
             # For authorization_code, invalidate the grant per RFC 6749 §10.5
             if grant_type == GrantTypes.AUTHORIZATION:
EOF
@@ -169,7 +169,10 @@
)
logger.warning(
"Token request for inactive application",
extra={"client_id": client_id, "application_id": application.id},
extra={
"client_id_provided": bool(client_id),
"application_id": application.id,
},
)
# For authorization_code, invalidate the grant per RFC 6749 §10.5
if grant_type == GrantTypes.AUTHORIZATION:
Copilot is powered by AI and may make mistakes. Always verify output.
Comment thread src/sentry/web/frontend/oauth_token.py Resolved
@dcramer

dcramer commented Dec 19, 2025

Copy link
Copy Markdown
Member Author

YOLO

@dcramer
dcramer merged commit 2a8e629 into master Dec 19, 2025
@dcramer
dcramer deleted the oauth21-pkce branch December 19, 2025 20:27
@github-actions github-actions Bot locked and limited conversation to collaborators Jan 4, 2026

This branch was successfully deployed

1 active deployment
Preview — 163597a6 Deployed Dec 19, 2025 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants