-
Notifications
You must be signed in to change notification settings - Fork 168
feat(proxy): resolve push identity from token via SCM provider API #1604
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
coopernetes
wants to merge
5
commits into
main
Choose a base branch
from
feat/token-id-mapping
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f2bd7e5
feat(proxy): resolve push identity from token via SCM provider API (#…
coopernetes 45efa1f
fix(proxy): remove dead email fallback and add fetch timeout in token…
coopernetes 10ed5bc
fix(proxy): extend token cache TTL to 7 days with sliding expiry
coopernetes c33a413
fix: remove parsePush from core logic chain, it is explicitly called …
coopernetes 33712fa
refactor(api): remove redundant git-account endpoints, evict token ca…
coopernetes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
120 changes: 120 additions & 0 deletions
120
src/proxy/processors/push-action/resolveUserFromToken.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| /** | ||
| * Copyright 2026 GitProxy Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import { Request } from 'express'; | ||
|
|
||
| import { Action, Step } from '../../actions'; | ||
| import { getProviderForHost, scmTokenCache } from './tokenIdentity'; | ||
| import { findUserByGitAccount } from '../../../db'; | ||
| import { getErrorMessage } from '../../../utils/errors'; | ||
|
|
||
| async function exec(req: Request, action: Action): Promise<Action> { | ||
| const step = new Step('resolveUserFromToken'); | ||
|
|
||
| if (req.user) { | ||
| step.log(`User already resolved via session auth: ${action.user}`); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| try { | ||
| const authHeader = req.headers?.authorization; | ||
| if (!authHeader) { | ||
| step.log('No Authorization header — cannot resolve push identity from token'); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const [scheme, encoded] = authHeader.split(' '); | ||
| if (!scheme || !encoded || scheme.toLowerCase() !== 'basic') { | ||
|
coopernetes marked this conversation as resolved.
|
||
| step.log('Authorization header is not Basic — cannot resolve push identity'); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const credentials = Buffer.from(encoded, 'base64').toString(); | ||
| const separatorIndex = credentials.indexOf(':'); | ||
| if (separatorIndex === -1) { | ||
| step.log('Malformed Basic auth credentials'); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const token = credentials.slice(separatorIndex + 1); | ||
|
|
||
| let hostname: string; | ||
| try { | ||
| hostname = new URL(action.url).hostname; | ||
| } catch { | ||
| step.log(`Cannot parse hostname from action URL: ${action.url}`); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const provider = getProviderForHost(hostname); | ||
| if (!provider) { | ||
| step.log(`No token identity provider for host '${hostname}' — identity resolution skipped`); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const cached = scmTokenCache.lookup(provider.name, token); | ||
| if (cached) { | ||
| step.log(`${provider.name}: resolved push identity from cache: ${cached}`); | ||
| action.user = cached; | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| const identity = await provider.fetchScmIdentity(token); | ||
| if (!identity) { | ||
| step.log( | ||
| `${provider.name}: failed to resolve identity from token (invalid token or missing scope?)`, | ||
| ); | ||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| step.log(`${provider.name}: resolved SCM identity from token: ${identity.login}`); | ||
|
|
||
| const user = await findUserByGitAccount(identity.login); | ||
| if (user) { | ||
| step.log( | ||
| `Mapped SCM identity '${identity.login}' to git-proxy user '${user.username}' (${user.email})`, | ||
| ); | ||
| action.user = user.username; | ||
| action.userEmail = user.email; | ||
| scmTokenCache.store(provider.name, token, user.username); | ||
| } else { | ||
| step.log( | ||
| `No git-proxy user has gitAccount '${identity.login}' — ` + | ||
| `falling back to SCM identity. ` + | ||
| `Users can associate their account via PUT /api/v1/user/:username/git-account`, | ||
| ); | ||
| action.user = identity.login; | ||
| } | ||
| } catch (error: unknown) { | ||
| const msg = getErrorMessage(error); | ||
| step.log(`Failed to resolve push identity from token: ${msg}`); | ||
| } | ||
|
|
||
| action.addStep(step); | ||
| return action; | ||
| } | ||
|
|
||
| exec.displayName = 'resolveUserFromToken.exec'; | ||
|
|
||
| export { exec }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| /** | ||
| * Copyright 2026 GitProxy Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import crypto from 'crypto'; | ||
|
|
||
| export type ScmUserInfo = { | ||
| login: string; | ||
| }; | ||
|
|
||
| type CacheEntry = { username: string; provider: string; cachedAt: number }; | ||
| // 7 days — PATs are rarely rotated more frequently than this in practice; the cache is a | ||
| // rate-limit optimization only (keys are one-way SHA-512 hashes, not recoverable tokens). | ||
| const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000; | ||
|
|
||
| export class ScmTokenCache { | ||
| private readonly cache = new Map<string, CacheEntry>(); | ||
| private readonly ttlMs: number; | ||
|
|
||
| constructor(ttlMs = DEFAULT_TTL_MS) { | ||
| this.ttlMs = ttlMs; | ||
| } | ||
|
|
||
| private key(provider: string, token: string): string { | ||
| return crypto.createHash('sha512').update(`${provider}:${token}`).digest('hex'); | ||
| } | ||
|
|
||
| lookup(provider: string, token: string): string | null { | ||
| const k = this.key(provider, token); | ||
| const entry = this.cache.get(k); | ||
| if (!entry) return null; | ||
| if (Date.now() - entry.cachedAt > this.ttlMs) { | ||
| this.cache.delete(k); | ||
| return null; | ||
| } | ||
| entry.cachedAt = Date.now(); | ||
| return entry.username; | ||
| } | ||
|
|
||
| store(provider: string, token: string, username: string): void { | ||
| this.cache.set(this.key(provider, token), { username, provider, cachedAt: Date.now() }); | ||
| } | ||
|
|
||
| evictByUsername(provider: string, username: string): void { | ||
| for (const [k, entry] of this.cache.entries()) { | ||
| if (entry.username === username && entry.provider === provider) this.cache.delete(k); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const scmTokenCache = new ScmTokenCache(); | ||
|
|
||
| export interface TokenIdentityProvider { | ||
| readonly name: string; | ||
| matches(hostname: string): boolean; | ||
| fetchScmIdentity(token: string): Promise<ScmUserInfo | null>; | ||
| } | ||
|
|
||
| type GitHubUserResponse = { | ||
| login: string; | ||
| }; | ||
|
|
||
| export class GitHubTokenIdentityProvider implements TokenIdentityProvider { | ||
| readonly name = 'github'; | ||
|
|
||
| matches(hostname: string): boolean { | ||
| return hostname === 'github.com'; | ||
| } | ||
|
|
||
| async fetchScmIdentity(token: string): Promise<ScmUserInfo | null> { | ||
| try { | ||
| const response = await fetch('https://api.github.com/user', { | ||
|
coopernetes marked this conversation as resolved.
|
||
| headers: { | ||
| Authorization: `token ${token}`, | ||
| Accept: 'application/vnd.github+json', | ||
| }, | ||
| signal: AbortSignal.timeout(5000), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| console.warn( | ||
| `GitHub /user API returned ${response.status} — token may be invalid or lack read:user scope`, | ||
| ); | ||
| return null; | ||
| } | ||
|
|
||
| const user: GitHubUserResponse = await response.json(); | ||
| return { | ||
| login: user.login, | ||
| }; | ||
| } catch (e) { | ||
| console.warn(`Failed to fetch GitHub identity: ${e}`); | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const providers: TokenIdentityProvider[] = [new GitHubTokenIdentityProvider()]; | ||
|
|
||
| export function getProviderForHost(hostname: string): TokenIdentityProvider | null { | ||
| return providers.find((p) => p.matches(hostname)) ?? null; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.