Claude MCP skill broken authentication via race condition in OAuth2 token exchange and session creation — SA-SKL-AUTH9
OAuth2 authorization flows involve a sequence of operations — code validation, token exchange, session creation — that must be atomic to be secure. When these operations are split across non-atomic reads and writes (a database read to check if a code was used, followed by a separate write to mark it used, with no locking between them), two concurrent requests can each pass the check before either has marked the code as used. SA-SKL-AUTH9 covers four race conditions in MCP skill platform OAuth2 implementations: an authorization code that can be exchanged twice by racing the callback endpoint, a session created before the CSRF state parameter is validated, a JWT refresh token that can be used twice under concurrent requests, and an account linking race that creates duplicate user accounts for the same identity.
/auth/callback with the same code both pass the "is code used?" check before either writes "used"; two separate access tokens issued for one authorization; session hijackingstate parameter CSRF validation completes — attacker replays a valid code from one OAuth flow into another browser's callback URL; session is pre-created and later validated against attacker's state; account takeover via CSRFPOST /auth/refresh reads token validity, issues new access token, then revokes old refresh token; two concurrent requests both pass the validity check before either revokes; two valid access tokens issued from one refresh token; session duplicationAUTH9-001 — Authorization code double-exchange race
An OAuth2 authorization code is a one-time credential: it must be exchanged exactly once for an access token. The check-then-act sequence (read "is used?" → exchange code → write "used") has a race condition if the check and write are not atomic. An attacker who intercepts a redirect with a valid authorization code can replay the callback URL in two concurrent requests within the race window (typically milliseconds). Both requests read "not used", both exchange the code with the OAuth provider, and both succeed. The OAuth provider may reject the second exchange — but only if the provider implements one-time-use code enforcement, which is not universal. Even if the provider rejects the second, the first exchange has already succeeded, and the attacker has obtained a valid access token for the victim's account.
// VULNERABLE — AUTH9-001
// Non-atomic check-then-mark in OAuth callback. Two concurrent requests both pass.
app.get('/auth/callback', async (req, res) => {
const { code, state } = req.query;
// Step 1: check if code was already used
const used = await db.oauthCodes.findOne({ code, used: true });
if (used) return res.status(400).send('Code already used');
// RACE WINDOW: between this check and the update below,
// a second concurrent request also passes the check above
// Step 2: exchange code with OAuth provider
const tokens = await oauth.exchangeCode(code); // may succeed for both if window is wide
// Step 3: mark code as used — but it's already too late; second request also passes step 1
await db.oauthCodes.updateOne({ code }, { $set: { used: true } });
// Both requests reach here — two sessions created for one authorization
const session = await createSession(tokens.access_token);
res.redirect(`/dashboard?session=${session.id}`);
});
// FIXED — AUTH9-001
// Use an atomic findOneAndUpdate with upsert + unique index to enforce one-time use.
// If two concurrent requests race, exactly one succeeds and one gets a write error.
// Database setup: unique index on the code field
// db.oauthCodes.createIndex({ code: 1 }, { unique: true })
app.get('/auth/callback', async (req, res) => {
const { code, state } = req.query;
// FIX: atomic insert of the code — if already inserted, throws duplicate key error
// No separate check: the insert itself is the check-and-mark in one operation
let codeRecord;
try {
codeRecord = await db.oauthCodes.insertOne({
code,
usedAt: new Date(),
state,
});
} catch (err) {
if (err.code === 11000) { // MongoDB duplicate key
return res.status(400).send('Code already used');
}
throw err;
}
// Only one request reaches here — the race loser got the duplicate key error above
const tokens = await oauth.exchangeCode(code);
const session = await createSession(tokens.access_token);
res.redirect(`/dashboard?session=${session.id}`);
});
AUTH9-002 — Session created before state validation
The OAuth2 state parameter is a CSRF protection mechanism: the client generates a random value, includes it in the authorization URL, and verifies that the same value is returned in the callback. Its purpose is defeated if any persistent work (session creation, user lookup) happens before the state is validated. An attacker who can observe a valid authorization code (via a referrer leak, a misconfigured redirect, or a browser history attack) can craft a callback URL with the stolen code. If the callback endpoint creates a session before validating the state, the session creation succeeds and may be associated with the attacker's browser if the state validation step is bypassed or confused.
// VULNERABLE — AUTH9-002
// Session created (or user upserted) before state parameter validation.
// Attacker replays stolen code — session partially created before validation fails.
app.get('/auth/callback', async (req, res) => {
const { code, state } = req.query;
// Step 1: exchange code — creates/updates user in DB
const tokens = await oauth.exchangeCode(code);
const userInfo = await oauth.getUserInfo(tokens.access_token);
// VULNERABLE: user upserted in DB before state is checked
const user = await db.users.findOneAndUpdate(
{ email: userInfo.email },
{ $setOnInsert: { createdAt: new Date(), plan: 'free' } },
{ upsert: true, returnDocument: 'after' }
);
// Step 2: validate state — but user is already created/updated above
const storedState = await redis.get(`oauth:state:${req.sessionID}`);
if (state !== storedState) {
// User was upserted above — partial state corruption; CSRF protection ineffective
return res.status(400).send('Invalid state parameter');
}
await createSession(user);
res.redirect('/dashboard');
});
// FIXED — AUTH9-002
// Always validate state FIRST before any database writes or token exchanges.
// State check is a pure read with no side effects — safe to do first.
app.get('/auth/callback', async (req, res) => {
const { code, state } = req.query;
// FIX: validate state BEFORE any token exchange or DB write
const storedState = await redis.getdel(`oauth:state:${req.sessionID}`);
if (!storedState || state !== storedState) {
return res.status(400).send('Invalid or missing state parameter');
}
// State validated — now safe to exchange the code and write to DB
const tokens = await oauth.exchangeCode(code);
const userInfo = await oauth.getUserInfo(tokens.access_token);
const user = await db.users.findOneAndUpdate(
{ email: userInfo.email },
{ $setOnInsert: { createdAt: new Date(), plan: 'free' } },
{ upsert: true, returnDocument: 'after' }
);
await createSession(user);
res.redirect('/dashboard');
});
AUTH9-003 — JWT refresh token race
Short-lived access tokens require a refresh mechanism. The refresh endpoint reads the stored refresh token, verifies it is valid, issues a new access token (and sometimes a new refresh token), and revokes the old refresh token. The race condition is in the read-issue-revoke sequence: if two concurrent requests arrive at the refresh endpoint with the same refresh token before either has completed the revocation step, both pass the validity check, both issue new access tokens, and the token rotation mechanism fails. The attacker obtains two valid access tokens — one more than authorized — from a single refresh token.
// VULNERABLE — AUTH9-003
// Non-atomic refresh token check-and-revoke. Two concurrent refreshes both succeed.
app.post('/auth/refresh', async (req, res) => {
const { refreshToken } = req.body;
// Step 1: check if refresh token is valid and not revoked
const stored = await db.refreshTokens.findOne({ token: refreshToken, revoked: false });
if (!stored) return res.status(401).json({ error: 'Invalid refresh token' });
// RACE WINDOW: second concurrent request also passes step 1 here
// Step 2: issue new access token
const accessToken = jwt.sign({ sub: stored.userId }, JWT_SECRET, { expiresIn: '15m' });
// Step 3: revoke old refresh token — too late; second request passed step 1
await db.refreshTokens.updateOne({ token: refreshToken }, { $set: { revoked: true } });
res.json({ accessToken });
});
// FIXED — AUTH9-003
// Use findOneAndUpdate with $set: { revoked: true } and filter: { revoked: false }.
// Exactly one concurrent request will find revoked:false and atomically set revoked:true.
// The other request gets null (document not found with revoked:false).
app.post('/auth/refresh', async (req, res) => {
const { refreshToken } = req.body;
// FIX: atomic find-and-revoke — only one concurrent request can win
// Both requests arrive; the first atomically sets revoked:true and gets the document
// The second sees { revoked: true } and gets null — rejected
const stored = await db.refreshTokens.findOneAndUpdate(
{ token: refreshToken, revoked: false }, // filter: unrevoked only
{ $set: { revoked: true, revokedAt: new Date() } }, // mark revoked atomically
{ returnDocument: 'before' } // return pre-update document to get userId
);
if (!stored) {
return res.status(401).json({ error: 'Invalid or already-used refresh token' });
}
// Only one request reaches here — the other got null above
const accessToken = jwt.sign({ sub: stored.userId, plan: stored.plan }, JWT_SECRET, {
algorithm: 'HS256',
expiresIn: '15m',
issuer: 'skillaudit.dev',
});
// Issue new refresh token for token rotation
const newRefreshToken = crypto.randomBytes(32).toString('hex');
await db.refreshTokens.insertOne({
token: newRefreshToken,
userId: stored.userId,
revoked: false,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
});
res.json({ accessToken, refreshToken: newRefreshToken });
});
AUTH9-004 — Account linking race creates duplicate users
MCP skill platforms commonly support multiple OAuth providers (GitHub, Google, GitLab). When a user links a new provider, the backend looks up the existing user by email, then links the new provider to that user. If two providers are linked in concurrent requests (e.g., the user clicks both "Link GitHub" and "Link Google" in quick succession), two separate lookups may each find no existing user and both create new user records for the same email. Subsequent logins via GitHub route to one user record and logins via Google route to the other — the user's audit history, skill submissions, and billing plan are split across two accounts.
// VULNERABLE — AUTH9-004
// Non-atomic user lookup + create during OAuth account linking.
// Two concurrent OAuth callbacks both create new user records for the same email.
async function handleOAuthCallback(oauthProvider, userInfo) {
// Step 1: check if user with this email exists
let user = await db.users.findOne({ email: userInfo.email });
// RACE WINDOW: second concurrent callback for same email also finds null here
if (!user) {
// Step 2: create new user — both concurrent requests reach here
user = await db.users.insertOne({
email: userInfo.email,
createdAt: new Date(),
plan: 'free',
providers: [{ name: oauthProvider, id: userInfo.id }],
});
// Two users created with same email — duplicate accounts
} else {
await db.users.updateOne(
{ email: userInfo.email },
{ $addToSet: { providers: { name: oauthProvider, id: userInfo.id } } }
);
}
return user;
}
// FIXED — AUTH9-004
// Use upsert with unique index on email — database enforces one user per email.
// If concurrent inserts race, exactly one succeeds; other gets duplicate key error.
// Database setup: unique index on email
// db.users.createIndex({ email: 1 }, { unique: true })
async function handleOAuthCallback(oauthProvider, userInfo) {
// FIX: findOneAndUpdate with upsert — atomic; unique index prevents duplicate creation
// If user exists: adds provider to their list; returns existing user
// If user doesn't exist: creates user atomically; second concurrent request gets
// either the same document (upsert already done) or a duplicate key error
const result = await db.users.findOneAndUpdate(
{ email: userInfo.email },
{
$setOnInsert: {
email: userInfo.email,
createdAt: new Date(),
plan: 'free',
},
$addToSet: {
providers: { name: oauthProvider, id: userInfo.id },
},
},
{ upsert: true, returnDocument: 'after' }
);
if (!result) {
// Should not happen with upsert — but handle gracefully
throw new Error('Failed to create or find user');
}
return result;
}
Detection: SkillAudit scans OAuth2 callback handlers for non-atomic read-then-write sequences: a findOne() followed by an insertOne() or updateOne() without an intervening database-level lock or atomic operation. It also flags refresh endpoints where the token validity check and the revocation update are separate database operations.
Related patterns
See also SA-SKL-PRIVESC4 for JWT algorithm confusion that allows token forgery without needing a valid code, and SA-SKL-AUTH7 for broken access control via IDOR on audit endpoints — often the target once initial account access is gained through an OAuth race condition.
Scan your MCP skill platform for SA-SKL-AUTH9. SkillAudit's taint analysis engine detects non-atomic OAuth2 check-then-act sequences across your callback, refresh, and account linking endpoints. Get started free.