OAuth 2.0 Security Mistakes in MCP Skill Registry GitHub and GitLab Integration
OAuth 2.0 is the backbone of GitHub and GitLab integration in MCP skill registries, but its flexibility makes it easy to implement incorrectly. This post documents four concrete vulnerabilities — two critical, two high — that SkillAudit regularly finds in skill registry codebases, along with working exploit paths and exact fixes for each.
Table of contents
- Findings at a glance
- AUTH15-001 — OAuth state parameter not validated (CSRF account linking)
- AUTH15-002 — redirect_uri omitted on code exchange (open redirect interception)
- AUTH15-003 — GitHub access token stored in localStorage (XSS exposure)
- AUTH15-004 — Webhook HMAC X-Hub-Signature-256 not verified (forged events)
- Compound chain: AUTH15-001 → AUTH15-004
- Detection signatures
- Summary checklist
OAuth state parameter not validated on callback — CSRF account linking
The OAuth 2.0 authorization code flow defines a state parameter specifically to prevent cross-site request forgery. Before redirecting the user to GitHub's authorization endpoint, the server must generate a cryptographically random value, store it somewhere bound to the user's session (a server-side session key or a signed, HttpOnly cookie), and include it in the authorization URL. When GitHub redirects back to the callback URL, the server must verify that the returned state exactly matches what was stored — using a timing-safe comparison — and then delete the stored value so it cannot be replayed. Skipping any part of this sequence breaks the binding between the authorization response and the user who initiated it.
When the state check is absent, an attacker can initiate a GitHub OAuth flow with their own account, capture the resulting callback URL (which contains a one-time authorization code valid for the attacker's GitHub identity), and then trick a logged-in victim into visiting that callback URL — for example via a phishing link, an img tag, or any other CSRF vector. The registry server processes the callback in the context of the victim's authenticated session, completing the account-linking step. The victim's registry account is now associated with the attacker's GitHub identity. The attacker can subsequently authenticate as the victim using GitHub login.
Attack impact: The attacker gains full access to the victim's registry account — their published skills, organization memberships, billing credentials, and any secrets stored against the account. Because the link is at the identity level (not a session hijack), the compromise persists even after the victim changes their password.
// VULNERABLE — /api/auth/github/callback
// No state parameter is generated, stored, or verified.
app.get('/api/auth/github/callback', async (req, res) => {
const { code } = req.query;
// Exchange code for access token immediately — no state check
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
}),
});
const { access_token } = await tokenRes.json();
const ghUser = await fetchGitHubUser(access_token);
// Link GitHub identity to current session's user — no CSRF protection
await db.users.update(
{ id: req.session.userId },
{ githubId: ghUser.id, githubLogin: ghUser.login }
);
res.redirect('/dashboard');
});
// FIXED — generate, store, and verify state using crypto.randomBytes
import crypto from 'crypto';
// Step 1: When initiating OAuth, generate and store state
app.get('/api/auth/github', (req, res) => {
const state = crypto.randomBytes(32).toString('hex');
// Store in server-side session — NOT in a client-readable cookie
req.session.oauthState = state;
req.session.oauthInitiatedAt = Date.now();
const params = new URLSearchParams({
client_id: process.env.GITHUB_CLIENT_ID,
redirect_uri: process.env.GITHUB_REDIRECT_URI,
scope: 'read:user user:email',
state,
});
res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});
// Step 2: On callback, verify state before doing anything else
app.get('/api/auth/github/callback', async (req, res) => {
const { code, state } = req.query;
// Reject if state is missing or session has no stored state
if (!state || !req.session.oauthState) {
return res.status(403).send('OAuth state missing');
}
// Timing-safe comparison prevents timing oracle attacks
const expected = Buffer.from(req.session.oauthState, 'utf8');
const received = Buffer.from(state, 'utf8');
const stateValid =
expected.length === received.length &&
crypto.timingSafeEqual(expected, received);
// Delete stored state immediately — single use only
delete req.session.oauthState;
delete req.session.oauthInitiatedAt;
if (!stateValid) {
return res.status(403).send('OAuth state mismatch — possible CSRF');
}
// Safe to exchange code now
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
redirect_uri: process.env.GITHUB_REDIRECT_URI, // always include
}),
});
const { access_token } = await tokenRes.json();
const ghUser = await fetchGitHubUser(access_token);
await db.users.update(
{ id: req.session.userId },
{ githubId: ghUser.id, githubLogin: ghUser.login }
);
res.redirect('/dashboard');
});
redirect_uri omitted on code exchange — open redirect code interception
RFC 6749 section 10.6 explains the redirect_uri binding requirement clearly: when a client includes a redirect_uri in the authorization request, that exact URI must be supplied again during the token exchange. If the exchange omits the redirect_uri, the authorization server cannot enforce that the code is being redeemed at the same endpoint that received it. Some providers (including older GitHub OAuth App configurations and certain GitLab setups) treat an omitted redirect_uri on exchange as "accept any registered redirect." This creates an interception window.
The concrete attack path works as follows. An attacker first scans the target skill registry for open redirects — pages that accept a to, next, url, or similar query parameter and redirect without validation, such as https://registry.example.com/redirect?to=https://evil.com. If this URL has been registered (even accidentally, perhaps as a catch-all wildcard) in the GitHub OAuth App's allowed redirect URIs, the attacker can craft an authorization URL that lists the open redirect as the redirect_uri. When a victim clicks this link, GitHub redirects to /redirect?to=https://evil.com&code=AUTHORIZATION_CODE. The open redirect forwards the victim's browser — and the authorization code in the URL — to the attacker's server. The attacker then exchanges the code for a token without supplying a redirect_uri, satisfying the provider's loose validation. Result: the attacker holds a valid GitHub access token minted for the victim's authorization.
Attack impact: The attacker obtains a GitHub access token with whatever scopes the victim authorized. For a skill registry that requests repo scope, this means read and write access to all of the victim's GitHub repositories. Even with read:user scope only, the attacker can authenticate as the victim and take over their registry account.
// VULNERABLE — redirect_uri is omitted from the code exchange body
app.get('/api/auth/github/callback', async (req, res) => {
const { code } = req.query;
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
// redirect_uri intentionally omitted — provider may accept any registered URI
}),
});
const { access_token } = await tokenRes.json();
// ...
});
// FIXED — always include the exact registered redirect_uri in the exchange
// The redirect_uri here must match what was sent in the authorization request.
// Store the canonical redirect_uri in an environment variable — never construct
// it dynamically from request headers (Host spoofing).
const GITHUB_REDIRECT_URI = process.env.GITHUB_REDIRECT_URI;
// e.g. "https://registry.example.com/api/auth/github/callback"
app.get('/api/auth/github/callback', async (req, res) => {
const { code, state } = req.query;
// ... state validation first (see AUTH15-001) ...
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
redirect_uri: GITHUB_REDIRECT_URI, // exact match required by RFC 6749 §10.6
}),
});
const data = await tokenRes.json();
if (data.error) {
// Log but do not expose error_description to client
console.error('OAuth exchange error:', data.error);
return res.status(400).send('OAuth exchange failed');
}
const { access_token } = data;
// ... proceed to fetch user and link account ...
});
Additional hardening: Audit your GitHub OAuth App's registered redirect URIs regularly. Never register wildcard domains (https://example.com/*) or non-canonical paths. If the registry has any /redirect, /go, or similar convenience redirect endpoints, ensure they validate the destination against an allowlist before redirecting — open redirects anywhere in the app expand the attack surface for code interception.
GitHub access token stored in localStorage — XSS reads it
Storing a GitHub access token in localStorage is a persistent anti-pattern that continues to appear in MCP skill registry front-end code, usually as an artifact of a quick "make OAuth work" implementation that was never revisited. The core problem is that localStorage is fully accessible to any JavaScript executing in the same origin. This means that any XSS vulnerability — reflected, stored, or DOM-based — can retrieve the token with a single localStorage.getItem('github_token') call and exfiltrate it to an attacker-controlled server. Because GitHub tokens do not expire by default (personal access tokens and OAuth tokens are long-lived), the attacker retains access until the victim explicitly revokes the token in GitHub settings.
The correct architecture keeps the GitHub token entirely on the server. When the OAuth flow completes, the server stores the access token in its database, encrypted at rest, keyed to the user's server-side account. The browser receives only an opaque, HttpOnly session cookie that identifies the session. Any API call that requires GitHub operations is proxied through the registry's own backend — the front end never touches the raw token. This architecture means that XSS vulnerabilities, while still serious, cannot directly exfiltrate the GitHub credential: the attacker would need to also exploit a server-side vulnerability to retrieve the encrypted token from the database.
Attack impact: An attacker who finds a reflected XSS in a search result page, an error message, or a skill description field can harvest GitHub tokens from every user who visits the affected page. GitHub tokens with repo scope provide full read/write access to all repositories. Even read:user tokens enable account takeover via the OAuth login flow.
// VULNERABLE — front-end stores token in localStorage after OAuth callback
// In the browser's callback handler (e.g. a React/SPA route):
async function handleOAuthCallback(code) {
const res = await fetch(`/api/auth/github/exchange?code=${code}`);
const { access_token } = await res.json(); // server returns raw token to browser
// Any XSS on this origin can now do: localStorage.getItem('github_token')
localStorage.setItem('github_token', access_token);
// Later, the token is used directly from the browser:
const repos = await fetch('https://api.github.com/user/repos', {
headers: { Authorization: `Bearer ${localStorage.getItem('github_token')}` },
});
}
// FIXED — token never leaves the server; browser holds only an HttpOnly session cookie
// Server-side callback handler:
app.get('/api/auth/github/callback', async (req, res) => {
const { code, state } = req.query;
// ... state validation (AUTH15-001) ...
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code,
redirect_uri: process.env.GITHUB_REDIRECT_URI,
}),
});
const { access_token } = await tokenRes.json();
// Encrypt before storing — never store raw token
const encrypted = encryptTokenForStorage(access_token); // AES-256-GCM, key from KMS
await db.users.update(
{ id: req.session.userId },
{ githubTokenEnc: encrypted }
);
// Do NOT return access_token to the browser.
// The existing session cookie is the only client-facing credential.
res.redirect('/dashboard');
});
// Server-side proxy for GitHub API calls — browser never touches raw token
app.get('/api/github/repos', requireAuth, async (req, res) => {
const { githubTokenEnc } = await db.users.findById(req.session.userId);
const access_token = decryptToken(githubTokenEnc);
const ghRes = await fetch('https://api.github.com/user/repos', {
headers: { Authorization: `Bearer ${access_token}` },
});
const repos = await ghRes.json();
res.json(repos);
});
Session cookie hardening: Set httpOnly: true, secure: true, sameSite: 'strict' on the session cookie. The httpOnly flag prevents JavaScript from reading it even during XSS — meaning an attacker cannot steal the session token the same way they would have stolen the GitHub token from localStorage.
GitHub webhook HMAC X-Hub-Signature-256 not verified — forged events
When a repository event occurs (a push, a release, a pull request merge), GitHub delivers a POST request to the registry's webhook endpoint and signs the raw body with HMAC-SHA256 using a per-repository secret configured at webhook registration time. The resulting signature is delivered in the X-Hub-Signature-256 header as sha256=<hex-digest>. If the registry handler does not verify this signature before processing the event payload, any HTTP client on the internet can send a POST to the endpoint with a fabricated payload. The fabricated event is indistinguishable from a legitimate one at the application layer.
The consequences are registry-specific but consistently serious. A common pattern is that a push event to main triggers an audit job that re-scans the repository and updates the skill's security grade in the registry. An attacker can forge a push event claiming a push to main for any repository in the registry. This can flood the audit queue with spurious jobs, force arbitrary repositories to re-audit at attacker-chosen timestamps (e.g., just after a temporary grade manipulation), or — in registries that use webhook events to invalidate caches or update metadata — corrupt the displayed security information for any skill. A subtler variant is forging a release event to trigger an automated deployment pipeline.
Attack impact: Queue flooding, CI/CD pipeline triggering, metadata corruption, and cache poisoning without any authentication. The attacker does not need to know the webhook secret — they're exploiting the fact that it is never checked.
// VULNERABLE — webhook body parsed with no HMAC verification
// Middleware ordering makes this especially dangerous: express.json() runs first,
// consuming the raw body, so even if someone later tries to add verification,
// req.rawBody will be unavailable.
app.use(express.json()); // parses body — raw bytes are discarded
app.post('/api/webhooks/github', async (req, res) => {
const event = req.headers['x-github-event'];
const payload = req.body; // attacker-controlled, completely trusted
if (event === 'push' && payload.ref === 'refs/heads/main') {
await auditQueue.enqueue({ repoId: payload.repository.id });
}
res.status(200).send('ok');
});
// FIXED — verify X-Hub-Signature-256 before processing any payload
import crypto from 'crypto';
// Step 1: Capture raw body BEFORE JSON parsing.
// Use express.raw() on the webhook route — do NOT use express.json() globally
// if you need rawBody access.
app.post(
'/api/webhooks/github',
express.raw({ type: 'application/json' }), // raw Buffer, not parsed object
async (req, res) => {
const sigHeader = req.headers['x-hub-signature-256'];
if (!sigHeader) {
return res.status(401).send('Missing X-Hub-Signature-256');
}
// Look up the per-repository secret (or use a single webhook secret)
const rawBody = req.body; // Buffer from express.raw()
// If you have per-repo secrets, extract repoId from URL param or parse
// body tentatively (but do not act on it until signature verified).
const webhookSecret = process.env.GITHUB_WEBHOOK_SECRET;
// Compute expected signature
const expected = 'sha256=' +
crypto.createHmac('sha256', webhookSecret)
.update(rawBody)
.digest('hex');
// Timing-safe comparison to prevent timing oracle
const sigBuffer = Buffer.from(sigHeader, 'utf8');
const expBuffer = Buffer.from(expected, 'utf8');
const signatureValid =
sigBuffer.length === expBuffer.length &&
crypto.timingSafeEqual(sigBuffer, expBuffer);
if (!signatureValid) {
console.warn('Webhook HMAC mismatch — possible forgery attempt');
return res.status(401).send('Invalid signature');
}
// Safe to parse now that signature is verified
const payload = JSON.parse(rawBody.toString('utf8'));
const event = req.headers['x-github-event'];
if (event === 'push' && payload.ref === 'refs/heads/main') {
await auditQueue.enqueue({
repoId: payload.repository.id,
deliveryId: req.headers['x-github-delivery'], // idempotency key
});
}
res.status(200).send('ok');
}
);
Middleware ordering matters: If express.json() or body-parser is registered as a global middleware before the webhook route, the raw body Buffer will have already been consumed and replaced with a parsed object. You cannot reconstruct the original bytes from a parsed object. Always mount express.raw() as a route-scoped middleware on webhook handlers, before any global JSON parsers, or use the verify callback option in express.json() to capture a copy of the raw body into req.rawBody.
Compound chain: AUTH15-001 → AUTH15-004
These four vulnerabilities do not exist in isolation. AUTH15-001 and AUTH15-004 form a particularly dangerous compound chain: the CSRF account-linking flaw is the entry point, and the unverified webhook handler is the payload delivery mechanism. Together they allow an attacker with no prior account access to trigger arbitrary audit jobs on behalf of a victim, manipulating the victim's skill grades and flooding the registry's CI queue — all without ever knowing the victim's password or webhook secret.
Attacker initiates GitHub OAuth with their own account
The attacker visits /api/auth/github, which redirects them to GitHub. They log in with their own GitHub credentials, and GitHub redirects back to /api/auth/github/callback?code=ATTACKER_CODE&state=.... The attacker captures this callback URL — specifically the code value — before their browser follows the redirect.
Attacker tricks victim into visiting the callback URL (AUTH15-001 exploited)
Because the registry does not validate the state parameter, the attacker crafts a link to /api/auth/github/callback?code=ATTACKER_CODE and delivers it to the victim via email, a skill description field, a comment, or any other CSRF vector. The victim, already logged into the registry, follows the link. The registry processes the callback in the context of the victim's session, exchanges the code for the attacker's GitHub token, and writes githubId = attacker_github_id to the victim's account.
Attacker now controls the victim's GitHub identity in the registry
The victim's account is now linked to the attacker's GitHub profile. If the registry uses GitHub identity for repository access decisions, the attacker can query which repositories are associated with the victim's registry skills — the registry will return repositories belonging to the attacker's GitHub account, but it has also inherited visibility into the victim's skill metadata.
Attacker forges webhook events for the victim's repositories (AUTH15-004 exploited)
Because the webhook endpoint does not verify HMAC signatures, the attacker posts a fabricated push event claiming a push to main for any repository ID associated with the victim's skills. The repository.id field is public information available via the GitHub API. The forged event is accepted and an audit job is enqueued. The attacker can repeat this at will — flooding the queue, triggering rescans at adversarial timing, or injecting crafted metadata into the payload (e.g., fake commit SHAs, manipulated branch names) that the registry trusts because the payload was never authenticated.
Downstream impact: audit queue corruption and grade manipulation
The registry processes forged push events and re-audits the targeted repositories on the attacker's schedule. If the attacker can also manipulate the repository contents during the audit window (by using the GitHub identity linked in step 2 to push to the attacker's own repos, which are now associated with the victim's account), they can influence the audit result. The victim's published skills receive a manipulated security grade. At scale, this attack can be used to systematically degrade competitor skills or artificially elevate malicious ones.
Fixing AUTH15-001 (state validation) breaks the chain at step 2 — the CSRF delivery of the attacker's callback URL fails because the state stored in the victim's session does not match. Fixing AUTH15-004 (HMAC verification) independently breaks the chain at step 4 — forged webhook events are rejected regardless of how the GitHub identity linking occurred. Both fixes are required; defense in depth demands that neither vulnerability be treated as tolerable on its own.
Detection signatures used by SkillAudit
SkillAudit uses a combination of AST-based queries (via Babel parser) and grep-level signature matching to surface these patterns during static analysis. The following describes how each finding is detected.
| Finding | Detection method | Signature / query |
|---|---|---|
| AUTH15-001 | AST + control flow | Find route handlers for paths matching /callback|oauth|authorize/i. Check whether req.query.state is read and compared before any fetch() or axios.post() call that sends client_secret. If no timingSafeEqual or strict equality on state is found in the same function scope, flag CRITICAL. |
| AUTH15-002 | AST literal scan | In any object literal passed as the body of a POST to login/oauth/access_token, check for the presence of a redirect_uri key. Absence of the key in the exchange body is flagged CRITICAL. Also flags when redirect_uri is constructed from req.headers.host or req.hostname (host header injection risk). |
| AUTH15-003 | Grep + data-flow | Search for localStorage.setItem calls where the key contains token|access_token|github/i, or where the value derives from an OAuth exchange response. Also detects patterns where an endpoint returns { access_token } in a JSON response body to a browser route (not a machine-to-machine endpoint). |
| AUTH15-004 | AST + middleware order | Find route handlers for paths matching /webhook/i. Check whether x-hub-signature-256 (case-insensitive header read) is compared before any database write, queue enqueue, or shell exec call. Flag HIGH if the header is never read. Additionally checks whether express.json() or bodyParser.json() is registered globally before the webhook route — if so, flag a separate middleware ordering warning because rawBody will be unavailable. |
Complementary dynamic checks: SkillAudit's dynamic probes supplement static analysis. For AUTH15-001, the probe initiates an OAuth flow, captures the state token, then attempts to replay the callback URL in a separate session without that state value. For AUTH15-004, the probe sends a POST to the webhook endpoint with a syntactically valid but HMAC-invalid signature and checks whether the response is 200 (vulnerable) or 401/403 (protected).
Summary checklist
| ID | Severity | Root cause | Fix |
|---|---|---|---|
| AUTH15-001 | Critical | OAuth callback handler does not read, compare, or delete the state parameter — CSRF account linking is trivially possible |
Generate crypto.randomBytes(32) state, store in server-side session, verify with timingSafeEqual on callback, delete after first use; include redirect_uri in authorization URL |
| AUTH15-002 | Critical | Token exchange POST body omits redirect_uri — provider accepts any registered URI, enabling open-redirect-based code interception per RFC 6749 §10.6 |
Always supply the exact canonical redirect_uri (from env var, never from request headers) in the exchange body; audit and tighten all registered redirect URIs in the OAuth App settings |
| AUTH15-003 | High | GitHub access token written to localStorage and exposed to browser JavaScript — readable by any XSS on the same origin |
Store AES-256-GCM encrypted token in database server-side; proxy all GitHub API calls through backend; expose only an HttpOnly, Secure, SameSite=Strict session cookie to the browser |
| AUTH15-004 | High | Webhook handler processes payload without reading or verifying X-Hub-Signature-256 HMAC — unauthenticated event forgery from the open internet |
Capture raw body with express.raw() before JSON parsing; compute HMAC-SHA256 and compare with timingSafeEqual; mount route-scoped raw parser before global JSON middleware; rotate per-repository secrets periodically |
SkillAudit scans MCP skill registry codebases for OAuth misconfiguration patterns including missing state validation, redirect_uri omission, insecure token storage, and missing webhook HMAC verification. Join the waitlist to audit your registry.
Related findings: SA-SKL-AUTH13 (JWT algorithm confusion) — SA-SKL-AUTH14 (brute force) — SA-SKL-PRIVESC6 (org switching) — SA-SKL-AUTH15 (OAuth 2.0 misconfiguration SEO)