Fix all five findings from the independent OAuth security audit
An independent model reviewed the MCP and OAuth surfaces. All five findings were verified against the code before changing anything; none were false positives. audit.md is kept as the record of what was reviewed. F1 (High) - refresh reuse detection forgot the token family. Only the current hash and one predecessor lived on the grant, and each rotation overwrote the predecessor. A thief who rotated a stolen token twice made the victim's original unrecognisable: replaying it returned "unknown token" instead of revoking the family, and the thief kept working. Refresh tokens are now rows in OAuthRefreshToken, one per generation, retained for the life of the family and consumed by a guarded update on usedAt - which also means two concurrent uses of the same token can no longer both succeed. This corrects a claim I made when the OAuth server shipped: reuse detection covered one generation, not the family. F2 (Medium) - issueAccessToken wrote scopes back onto the grant, so redeeming a stale authorization code redefined standing consent. Token issuance is not consent; the consent endpoint is now the only writer. Codes are additionally bound to a grant id and epoch, with a coversScopes check behind that. F3 (Medium) - revocation was reversible. Reconnecting a disconnected app cleared revokedAt and left credentials that had raced the revoke usable again. Every approval now starts a clean epoch: the counter advances and prior access tokens, refresh tokens and unconsumed codes are destroyed. Token writes are conditional on the epoch they validated, so a revoke that wins a race aborts them. Refresh also now requires offline_access to still be granted. F4 (Medium) - loopback redirect matching compared only scheme, host and path, silently accepting a differing query, fragment or userinfo. RFC 9700 2.1 wants exact matching apart from the RFC 8252 port exception; that is what it does now. F5 (Low) - get_collection_stats returned bar and recipe counts under drinks:read. Gated on the caller actually holding bar:read. Verified with regression tests for each: the two-rotation attack now revokes the family, concurrent refresh yields exactly one winner, a pre-narrowing code is refused, disconnect-reconnect leaves old credentials dead, and Claude Code's ephemeral-port callback still works while query/userinfo/fragment variants are rejected. Existing protections re-checked - code replay, PKCE mismatch, deny, confidential-client rejection, and the MCP tools themselves. Note for deploy: OAuthAuthCode gains a required grantId, so existing rows must be cleared first. They are 60-second ephemeral codes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
This commit is contained in:
@@ -126,13 +126,18 @@ export function isRegisterableRedirectUri(value: string): boolean {
|
||||
/**
|
||||
* Matching a redirect at authorize time.
|
||||
*
|
||||
* Exact string equality, except for loopback addresses where the port is
|
||||
* ignored. This is the single most common cause of a silently broken native
|
||||
* client: Claude Code registers http://localhost/callback and
|
||||
* http://127.0.0.1/callback, then redirects to an ephemeral port such as
|
||||
* http://localhost:51234/callback. RFC 8252 section 7.3 requires the port to be
|
||||
* Exact string equality, except for loopback addresses where the PORT ALONE is
|
||||
* ignored. Claude Code registers http://localhost/callback and then redirects to
|
||||
* an ephemeral port such as http://localhost:51234/callback, so exact matching
|
||||
* would reject every native client. RFC 8252 section 7.3 requires the port to be
|
||||
* ignored for the IP-literal form; the same is applied to localhost so Claude
|
||||
* Code works at all.
|
||||
*
|
||||
* Everything else must match exactly. An earlier version compared only scheme,
|
||||
* host and path, which silently accepted a request that differed in query,
|
||||
* fragment or userinfo - and a callback that forwards its query is then a route
|
||||
* for delivering the authorization code somewhere the client never registered.
|
||||
* RFC 9700 section 2.1 requires exact matching apart from the loopback port.
|
||||
*/
|
||||
export function redirectUriMatches(registered: string, requested: string): boolean {
|
||||
if (registered === requested) return true
|
||||
@@ -145,11 +150,19 @@ export function redirectUriMatches(registered: string, requested: string): boole
|
||||
return false
|
||||
}
|
||||
if (!isLoopback(a) || !isLoopback(b)) return false
|
||||
return (
|
||||
a.protocol === b.protocol &&
|
||||
a.hostname === b.hostname &&
|
||||
a.pathname === b.pathname
|
||||
)
|
||||
|
||||
// A fragment is never legal on a redirect URI (RFC 6749 3.1.2).
|
||||
if (a.hash || b.hash) return false
|
||||
// Credentials in a redirect target are a spoofing aid and never needed here.
|
||||
if (a.username || a.password || b.username || b.password) return false
|
||||
|
||||
// Normalise away only the port, then require the rest to be identical.
|
||||
const strip = (u: URL) => {
|
||||
const c = new URL(u.toString())
|
||||
c.port = ""
|
||||
return c.toString()
|
||||
}
|
||||
return strip(a) === strip(b)
|
||||
}
|
||||
|
||||
export function findMatchingRedirectUri(
|
||||
@@ -187,22 +200,31 @@ export interface IssuedTokens {
|
||||
refresh_token?: string
|
||||
}
|
||||
|
||||
/** Thrown when a grant was revoked or re-consented while a request was in flight. */
|
||||
export class GrantStateError extends Error {
|
||||
constructor(message = "This authorization is no longer valid.") {
|
||||
super(message)
|
||||
this.name = "GrantStateError"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints an access token against a grant.
|
||||
*
|
||||
* Refresh tokens are deliberately NOT handled here. The two call sites need
|
||||
* different behaviour - the code exchange creates the first one, a refresh
|
||||
* rotates the existing one and has to record the previous hash for replay
|
||||
* detection - and doing it in here once meant the rotation was silently
|
||||
* overwritten and the token handed back matched nothing on file.
|
||||
* Two things this deliberately does NOT do:
|
||||
*
|
||||
* The access token is an ordinary McpAccessToken row with source "oauth", the
|
||||
* same shape a hand-minted one has, so verifyMcpToken needs no OAuth awareness.
|
||||
* Previously outstanding tokens on the grant are revoked, so a refresh replaces
|
||||
* rather than accumulates.
|
||||
* - It does not write scopes back to the grant. Token issuance is not consent,
|
||||
* and treating it as such let a stale authorization code redefine what the
|
||||
* user had most recently agreed to. The consent endpoint is the only writer.
|
||||
* - It does not touch refresh tokens. Those have their own lineage.
|
||||
*
|
||||
* The whole write is conditional on the grant still being active AT THE EPOCH
|
||||
* the caller validated. A revoke racing this call makes the guarded update
|
||||
* affect zero rows and the transaction aborts, rather than leaving a live token
|
||||
* hanging off a revoked grant to be resurrected by a later re-consent.
|
||||
*/
|
||||
export async function issueAccessToken(
|
||||
grantId: string,
|
||||
grant: { id: string; epoch: number },
|
||||
userId: string,
|
||||
scopes: string[],
|
||||
clientName: string
|
||||
@@ -210,8 +232,14 @@ export async function issueAccessToken(
|
||||
const access = generateMcpToken()
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const { count } = await tx.oAuthGrant.updateMany({
|
||||
where: { id: grant.id, epoch: grant.epoch, revokedAt: null },
|
||||
data: { lastUsedAt: new Date() },
|
||||
})
|
||||
if (count !== 1) throw new GrantStateError()
|
||||
|
||||
await tx.mcpAccessToken.updateMany({
|
||||
where: { grantId, revokedAt: null },
|
||||
where: { grantId: grant.id, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
})
|
||||
await tx.mcpAccessToken.create({
|
||||
@@ -222,14 +250,10 @@ export async function issueAccessToken(
|
||||
name: clientName,
|
||||
scopes: accessScopes(scopes),
|
||||
source: "oauth",
|
||||
grantId,
|
||||
grantId: grant.id,
|
||||
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
|
||||
},
|
||||
})
|
||||
await tx.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: { scopes, lastUsedAt: new Date() },
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -240,23 +264,70 @@ export async function issueAccessToken(
|
||||
}
|
||||
}
|
||||
|
||||
/** Stores a freshly minted refresh token on the grant, keeping the old hash for replay detection. */
|
||||
export async function storeRefreshToken(
|
||||
grantId: string,
|
||||
hash: string,
|
||||
previousHash: string | null
|
||||
): Promise<void> {
|
||||
await prisma.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: {
|
||||
refreshHash: hash,
|
||||
refreshPrevHash: previousHash,
|
||||
refreshExpiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
|
||||
},
|
||||
/**
|
||||
* Mints the next refresh token in a family, guarded on the grant's epoch for the
|
||||
* same reason as above.
|
||||
*/
|
||||
export async function issueRefreshToken(
|
||||
grant: { id: string; epoch: number },
|
||||
generation: number
|
||||
): Promise<string> {
|
||||
const { token, hash } = generateRefreshToken()
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const active = await tx.oAuthGrant.count({
|
||||
where: { id: grant.id, epoch: grant.epoch, revokedAt: null },
|
||||
})
|
||||
if (active !== 1) throw new GrantStateError()
|
||||
|
||||
await tx.oAuthRefreshToken.create({
|
||||
data: {
|
||||
grantId: grant.id,
|
||||
tokenHash: hash,
|
||||
generation,
|
||||
expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
/** Kills a grant and every access token it issued. */
|
||||
export type RefreshConsumption =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "expired" }
|
||||
| { kind: "reuse"; grantId: string }
|
||||
| { kind: "ok"; grantId: string; generation: number }
|
||||
|
||||
/**
|
||||
* Redeems a refresh token exactly once.
|
||||
*
|
||||
* Every generation is retained, so a token from any point in the family's life
|
||||
* is still recognisable as reuse - which is the whole point. The guarded update
|
||||
* on `usedAt` means two concurrent presentations of the same token cannot both
|
||||
* win: the loser is reported as reuse, which is indistinguishable from theft and
|
||||
* treated the same way.
|
||||
*/
|
||||
export async function consumeRefreshToken(hash: string): Promise<RefreshConsumption> {
|
||||
const row = await prisma.oAuthRefreshToken.findUnique({
|
||||
where: { tokenHash: hash },
|
||||
select: { id: true, grantId: true, generation: true, usedAt: true, expiresAt: true },
|
||||
})
|
||||
|
||||
if (!row) return { kind: "unknown" }
|
||||
if (row.usedAt) return { kind: "reuse", grantId: row.grantId }
|
||||
if (row.expiresAt <= new Date()) return { kind: "expired" }
|
||||
|
||||
const { count } = await prisma.oAuthRefreshToken.updateMany({
|
||||
where: { id: row.id, usedAt: null },
|
||||
data: { usedAt: new Date() },
|
||||
})
|
||||
if (count !== 1) return { kind: "reuse", grantId: row.grantId }
|
||||
|
||||
return { kind: "ok", grantId: row.grantId, generation: row.generation }
|
||||
}
|
||||
|
||||
/** Kills a grant, every access token it issued, and its whole refresh family. */
|
||||
export async function revokeGrant(grantId: string): Promise<void> {
|
||||
const now = new Date()
|
||||
await prisma.$transaction([
|
||||
@@ -264,13 +335,13 @@ export async function revokeGrant(grantId: string): Promise<void> {
|
||||
where: { grantId, revokedAt: null },
|
||||
data: { revokedAt: now },
|
||||
}),
|
||||
prisma.oAuthRefreshToken.deleteMany({ where: { grantId } }),
|
||||
// Outstanding codes die too, so one minted before the revoke cannot be
|
||||
// redeemed against a later re-consent.
|
||||
prisma.oAuthAuthCode.deleteMany({ where: { grantId, consumedAt: null } }),
|
||||
prisma.oAuthGrant.update({
|
||||
where: { id: grantId },
|
||||
data: {
|
||||
revokedAt: now,
|
||||
refreshHash: null,
|
||||
refreshPrevHash: null,
|
||||
},
|
||||
data: { revokedAt: now },
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user