Optimize access_token lookup using PAT prefix detection
What does this MR do and why?
This MR optimizes the /api/v4/personal_access_tokens/self endpoint (and other PAT-authenticated endpoints) by skipping the expensive OAuth token lookup when the token clearly has a Personal Access Token prefix (glpat-).
Problem
When authenticating via Authorization: Bearer <PAT>, the current flow:
- Calls
find_oauth_access_tokenfirst - This triggers
OauthAccessToken.by_token()which runs PBKDF2 hashing with 20,000 iterations (~9ms) - Token is not found in OAuth table (because it's a PAT)
- Falls back to
find_personal_access_token(SHA256 hash, ~4ms)
Total: ~13ms just for token lookup
Solution
Check if the token has a known PAT prefix (glpat-) before attempting OAuth lookup. If it does, skip OAuth entirely and go directly to find_personal_access_token.
This optimization applies to all token delivery methods:
-
PRIVATE-TOKENheader -
private_tokenquery parameter -
Authorization: Bearerheader (the slow path that's now optimized)
Benchmarks
| Header Type | Before | After |
|---|---|---|
Authorization: Bearer (PAT) |
~13.4ms | ~4.4ms |
PRIVATE-TOKEN (PAT) |
~4.4ms | ~4.4ms |
Backward Compatibility
Tokens without a known prefix still go through the OAuth lookup first, then fall back to PAT lookup — maintaining full backward compatibility for:
- Legacy tokens without prefix
- Actual OAuth tokens
- IAM JWT tokens
Related issues
Closes https://gitlab.com/gitlab-org/gitlab/-/issues/569170
MR acceptance checklist
-
Tests added for the new
pat_prefix_token?method -
Tests added for skip-OAuth behavior in
find_user_from_access_token - Existing tests pass
Edited by Smriti Garg