Skip to main content
Menu
Advisories

Apify MCP Server HTTP authentication bypass via prototype-chain lookup in resolvePaymentProvider (\?payment=constructor)

GHSA-FFRR-CJ64-HRF5Published Updated GitHub

Description

@apify/actors-mcp-server resolves the client-controlled ?payment= query parameter by indexing a plain object literal with the raw string, without any own-property/whitelist validation (src/payments/resolve.ts:23). Because JavaScript member access walks the prototype chain, values that name inherited Object.prototype members are found: ?payment=constructor makes providers['constructor'] resolve to the built-in Object constructor, and factory?.() invokes it, returning a truthy empty object {}; ?payment=toString returns the truthy string "[object Object]". This non-provider value is then treated as a legitimate third-party payment provider by the HTTP auth gate, which only tests truthiness (src/dev_server.ts:114, src/dev_server.ts:168 and src/dev_server.ts:182). The Apify API token requirement is therefore skipped entirely: an unauthenticated request that should receive 401 / -32001 is instead admitted into the session-establishment flow and is issued a valid mcp-session-id.

The bypass was reproduced dynamically against the shipped code (npm @apify/actors-mcp-server@0.15.6-beta.1, byte-identical to the audited repository master ee87bb7): without ?payment= the same request returns HTTP 401; with ?payment=constructor it returns HTTP 200 plus a session id; with ?payment=constructor&tools=preview the full MCP initialize handshake completes for an unauthenticated caller. Secondary effects are disclosure of internal implementation details (an uncaught TypeError message is returned to the client) and unbounded allocation of sessions/transports, which are never expired (measured VmRSS growth of ~38 MB over 300 unauthenticated requests). Tool execution remains blocked by a second, independent check in the tool-call engine, so this issue does not directly read user data or run Actors; it is an authentication-control bypass with information disclosure and resource-exhaustion impact.

Details

Root cause. resolvePaymentProvider() maps the ?payment= string to a provider factory through an unvalidated dynamic property lookup:

  • src/payments/resolve.ts:13-25 - resolvePaymentProvider(paymentParam) returns undefined only for empty input, then builds a plain object literal providers with the two own keys skyfire and x402, and performs const factory = providers[paymentParam as PaymentProviderId]; return factory?.(); (lines 23-24). The TypeScript cast as PaymentProviderId erases the 'skyfire' | 'x402' union at runtime, so any client-supplied string is accepted as a property name. There is no Object.prototype.hasOwnProperty.call(providers, paymentParam) guard and no array/Map/switch allow-list.
  • Prototype-chain lookup: for paymentParam = 'constructor', the lookup inherits Object.prototype.constructor, i.e. the built-in Object constructor. factory?.() is therefore Object() (called with this bound to providers), which returns a new empty object {} - truthy. For paymentParam = 'toString' (or 'toLocaleString'), the call returns the truthy string "[object Object]". For paymentParam = 'valueOf' the call returns the providers object itself. For paymentParam = 'hasOwnProperty' / 'isPrototypeOf' / 'propertyIsEnumerable' the call returns false (falsy), and for paymentParam = '__proto__' the lookup yields a non-callable object, so factory?.() throws - those variants produce a normal 401 or a 500, which is why only the function-returning inherited members are the exploit primitive.

Trust-boundary failure. The HTTP entry point uses the truthiness of that value as the only evidence that a legitimate payment provider is in play:

  • src/dev_server.ts:109-122 - resolveRequestAuth(req, res, paymentProvider): the first statement is if (paymentProvider) return { apifyToken: undefined };. Any truthy value - including a bare {} or a string - short-circuits the function, so the extractApiTokenFromRequest() check, the 401 response, and the WWW-Authenticate challenge are never reached.
  • src/dev_server.ts:165-168 (2026-07-28 stateless path, serveStatelessRequest) and src/dev_server.ts:304-309 (2025-11-25 stateful path, POST / handler) obtain the value with new URL(req.url, ...).searchParams.get('payment') - fully client controlled - and derive apifyToken as paymentProvider ? undefined : extractApiTokenFromRequest(req).
  • src/dev_server.ts:182-185 (stateless factory) mirrors the same truthiness test: if (!isDiscoverProbe && !paymentProvider && !apifyToken) { unauthorized = true; throw ... }. A truthy pseudo-provider makes this branch unreachable, so the factory proceeds to new ActorsMcpServer({ ..., paymentProvider, token: apifyToken }) and loadToolsFromUrl().
  • src/dev_server.ts:336-347 - the request then reaches new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), ... }), mcpServer.connect(transport) and transport.handleRequest(...); onsessioninitialized stores the server/transport pair in the module-level maps mcpServers / transports (src/dev_server.ts:234-235) with no TTL, no size cap and no idle reaper (only a client DELETE removes an entry), so each unauthenticated request permanently adds one session object.

Downstream error path (why the client sees internal details). src/mcp/server.ts:499-501 (ActorsMcpServer.toStoredTool) unconditionally calls this.options.paymentProvider.decorateToolSchema(tool) whenever a payment provider is configured. The pseudo-provider has no such method, so an uncaught TypeError is raised while tools are composed; both protocol adapters convert it into a JSON-RPC error and the dev server answers 200 with {"error":{"code":-32603,"message":"this.options.paymentProvider.decorateToolSchema is not a function"}}, leaking an internal implementation detail (class option name and method name) to an unauthenticated caller. With an empty composed tool set (e.g. ?payment=constructor&tools=preview) no decoration happens, and the unauthenticated initialize handshake completes successfully with a server-issued session id.

Impact ceiling (stated explicitly to avoid over-claiming). The tool-call path holds a second, independent gate: src/mcp/tool_call_engine.ts:135 rejects calls when !apifyToken && !paymentProvider?.allowsUnauthenticated && !allowUnauthMode; the pseudo-provider has no allowsUnauthenticated property, so tool calls are refused with an AUTH diagnostic. In addition src/payments/helpers.ts:61-66 calls provider.validatePayment()/removePaymentFields()/getPaymentHeaders()/redactForLogging() on the pseudo-provider and throws. The verified impact is therefore: (1) the token authentication gate is bypassed at the HTTP entry point and unauthenticated sessions are established and usable; (2) internal error/implementation details are disclosed to unauthenticated clients, with log.exception stack traces logged for unauthenticated traffic; (3) unauthenticated, unbounded session/transport allocation (memory exhaustion vector, measured ~38 MB / 300 requests).

Core vulnerable code path:

// src/dev_server.ts:165-169
const paymentProvider = await resolvePaymentProvider(urlParams.get('payment'));

    // No token required in payment mode, mirroring `resolveRequestAuth`.
    const apifyToken = paymentProvider ? undefined : extractApiTokenFromRequest(req);
    let unauthorized = false;

The stateless (2026-07-28) entry point reads the fully client-controlled ?payment= value from the request URL and turns its result into an authentication decision: a truthy return value disables API-token extraction entirely. The same pattern appears in the stateful path at src/dev_server.ts:304-309. This is the source of the tainted value.

// src/dev_server.ts:109-122
function resolveRequestAuth(
    req: Request,
    res: Response,
    paymentProvider: Awaited<ReturnType<typeof resolvePaymentProvider>>,
): { apifyToken: string | undefined } | null {
    if (paymentProvider) return { apifyToken: undefined };

    const apifyToken = extractApiTokenFromRequest(req);
    if (apifyToken) return { apifyToken };

    log.softFail('Apify API token missing on unauthenticated request', { statusCode: 401 });
    res.status(401).set('WWW-Authenticate', UNAUTHORIZED_CHALLENGE).json(UNAUTHORIZED_RESPONSE_BODY);
    return null;
}

The trust-boundary check treats any truthy paymentProvider as a legitimate payment mode and returns { apifyToken: undefined } without sending the 401. Because the value produced from ?payment=constructor is a plain truthy object (not a PaymentProvider), the token requirement is skipped. The stateless analogue is if (!isDiscoverProbe && !paymentProvider && !apifyToken) at src/dev_server.ts:182.

// src/payments/resolve.ts:13-25
export async function resolvePaymentProvider(
    paymentParam: string | null | undefined,
): Promise<PaymentProvider | undefined> {
    if (!paymentParam) return undefined;

    const providers: Record<PaymentProviderId, () => Promise<PaymentProvider>> = {
        skyfire: async () => SkyfirePaymentProvider.create(),
        x402: async () => X402PaymentProvider.create(),
    };

    const factory = providers[paymentParam as PaymentProviderId];
    return factory?.();
}

Root cause: an unvalidated external string is used as an object property name on a plain object literal. The prototype chain makes inherited members resolvable, so constructor yields the Object constructor and toString yields a function that returns a truthy string; factory?.() executes that inherited function. Adding Object.prototype.hasOwnProperty.call(providers, paymentParam) or using a Map/switch allow-list removes the primitive.

// src/mcp/server.ts:499-501
private toStoredTool(tool: ToolEntry): ToolEntry {
        return this.options.paymentProvider ? this.options.paymentProvider.decorateToolSchema(tool) : tool;
    }

The configured (pseudo-)payment provider is dereferenced without an interface guard while tools are composed. For the prototype-chain value this throws TypeError: this.options.paymentProvider.decorateToolSchema is not a function, which is surfaced to the unauthenticated client as -32603 (internal implementation disclosure); when the composed tool set is empty the unauthenticated handshake completes instead.

POC

Preconditions: the MCP HTTP entry point is reachable (in this repository the dev/standby server started with node dist/dev_server.js or pnpm start, listening on 127.0.0.1:3001 by default; the helper is part of the published package's auth/payment routing layer and the file documents that it mirrors apify-mcp-server-internal auth routing, so any deployment that resolves ?payment= with the same function is affected). The attacker needs no Apify API token, no account and no user interaction.

Step 1 - baseline (control). Method POST, endpoint /, headers Content-Type: application/json and Accept: application/json, text/event-stream, body {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}} with no Authorization header. Expected and observed result: HTTP 401, header WWW-Authenticate: Bearer ..., body {"jsonrpc":"2.0","error":{"code":-32001,"message":"Unauthorized: Apify API token is missing. Pass it as Authorization: Bearer <token>, or set ?payment=<provider> ..."},"id":null}.

Step 2 - bypass the gate. Same method, headers and body, but endpoint /?payment=constructor. Expected and observed result: HTTP 200 instead of 401, response header mcp-session-id: <server-generated uuid> is issued, and the response body carries {"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"this.options.paymentProvider.decorateToolSchema is not a function"}} - i.e. the authentication gate was skipped and an internal implementation detail was disclosed. The equivalents ?payment=toString and ?payment=valueOf produce the same truthy pseudo-provider; ?payment=valueOf / ?payment=hasOwnProperty additionally yield HTTP 500 with the server-side log line Cannot convert undefined or null to object ... at resolvePaymentProvider.

Step 3 - complete an unauthenticated session. Method POST, endpoint /?payment=constructor&tools=preview (the empty composed tool set avoids the downstream decoration error), same headers/body. Expected and observed result: HTTP 200 with a full InitializeResult (capabilities for tools, tasks, resources, prompts, logging) and a fresh mcp-session-id - an unauthenticated session is fully established.

Step 4 - use the session. Method POST, endpoint /, header mcp-session-id: <uuid from step 3>, body {"jsonrpc":"2.0","id":5,"method":"tools/list","params":{}}. Expected and observed result: HTTP 200, SSE payload {"result":{"tools":[]},"jsonrpc":"2.0","id":5} - the server accepts and serves further requests on the unauthenticated session.

Step 5 - resource exhaustion. Repeat the step-3 request in a loop (e.g. 300 iterations). Expected and observed result: the server process RSS grows monotonically (VmRSS 110,208 kB -> 131,200 kB -> 147,912 kB), because every unauthenticated initialize registers an ActorsMcpServer + StreamableHTTPServerTransport pair in transports/mcpServers that is never expired or capped.

Impact ceiling for reproduction honesty: calling a tool on such a session does not execute it. The engine gate at src/mcp/tool_call_engine.ts:135 (and the provider method calls in src/payments/helpers.ts:61-66) rejects the call because the pseudo-provider lacks allowsUnauthenticated and the provider methods - the response is an AUTH diagnostic / internal error, not a successful tool result. The demonstrable security effect is the authentication bypass itself plus information disclosure and unauthenticated resource consumption.

Impact

Confidentiality: an unauthenticated caller receives internal implementation details (option and method names from an uncaught TypeError) and unauthenticated traffic triggers log.exception stack traces, which is useful reconnaissance for follow-on attacks and pollutes error monitoring. Integrity/authorization: the API-token authentication gate on the HTTP entry point can be bypassed, and requests that should have been rejected with 401 are admitted into the session-establishment and session-reuse code paths reserved for authenticated clients; the server issues a session identifier to an anonymous caller, i.e. an unauthorized principal obtains authenticated-session capability. Availability: session/transport state is allocated per unauthenticated request with no TTL, no cap and no idle cleanup, so a single anonymous client can grow process memory without bound (measured ~38 MB per 300 requests), and malformed variants produce uncaught exceptions (HTTP 500) on an unauthenticated path. Scope: the code is part of the published package @apify/actors-mcp-server (0.15.6-beta.1, repository master ee87bb7) and the source comments state the same normalization mirrors the production/internal transport for auth and payment routing, so the weakness is in the shared routing logic rather than in a purely local test harness. Not impacted: no direct read of another user's data and no Actor execution, because the tool-call path enforces a second token check and the pseudo-provider cannot decorate or validate tools.

Remediation

  1. Remove the dynamic property lookup in resolvePaymentProvider (src/payments/resolve.ts:23): use an explicit allow-list/Map, e.g. const factories = new Map<PaymentProviderId, () => Promise<PaymentProvider>>([['skyfire', ...], ['x402', ...]]); const factory = factories.get(paymentParam as PaymentProviderId); return factory ? factory() : undefined;, or validate with Object.prototype.hasOwnProperty.call(providers, paymentParam) (never paymentParam in providers). A switch on the literal union is equally safe and keeps the type guarantee. 2) Make the auth decision independent of truthiness: in resolveRequestAuth (src/dev_server.ts:114) and in serveStatelessRequest (src/dev_server.ts:182, :168) require paymentProvider !== undefined and an interface assertion such as typeof paymentProvider?.decorateToolSchema === 'function' && typeof paymentProvider?.removePaymentFields === 'function'; reject otherwise with the normal 401 and log a validation failure. 3) Guard the decoration call in ActorsMcpServer.toStoredTool (src/mcp/server.ts:500) with an optional call/interface check so a malformed provider degrades to a generic error without leaking internal names. 4) Treat an unknown ?payment= value as "no payment mode" (fall back to token authentication) and never as "unauthenticated access". 5) Bound the session store: enforce a maximum number of concurrent sessions and an idle TTL for transports/mcpServers, and re-use the same validation (UUID shape) before any lookup. 6) Regression tests: unit-test resolvePaymentProvider with 'constructor', 'toString', 'valueOf', '__proto__', 'hasOwnProperty' and assert undefined; integration-test that an unauthenticated POST /?payment=<any> still yields 401 unless a real provider is selected, and that no unauthenticated request can allocate a session.

Disclosure Notes

Verification status: dynamically confirmed on the shipped implementation (npm @apify/actors-mcp-server@0.15.6-beta.1, whose dist is byte-identical to this repository's src at master commit ee87bb7), using a local Node.js v22.14.0 process. Observed results: 401 without ?payment=; HTTP 200 + mcp-session-id with ?payment=constructor; complete InitializeResult for ?payment=constructor&tools=preview; HTTP 500 for ?payment=valueOf/hasOwnProperty with an uncaught TypeError in the log; monotonic RSS growth over repeated unauthenticated requests. Patched version: none confirmed (no fix identified at the audited commit; patched_versions is reported as "to be confirmed"). Exposure note: the in-repository dev/standby server binds 127.0.0.1 by default, which limits remote reachability for that specific process, but the vulnerable helper is part of the published package and is documented as mirroring production auth/payment routing, so the fix should be applied in the shared routing code rather than only in the dev harness. No public advisory or CVE identifier is known for this defect at the time of writing; no reference links were verified for it. Recommend coordinated private disclosure per the project's SECURITY.md (security@apify.com or GitHub private vulnerability reporting), then publishing a patched release and a GHSA once a fix ships. Anyone re-testing should use a local instance and their own token-free requests, and must not target third-party deployments without written authorization.

Supplemental Information

Affected products

  • Ecosystem: npm
  • Package name: @apify/actors-mcp-server (apify/apify-mcp-server)
  • Affected versions: 0.15.6-beta.1 and earlier releases that ship the same resolvePaymentProvider implementation (verified against npm 0.15.6-beta.1 and repository master commit ee87bb7); exact lower bound to be confirmed
  • Patched versions: to be confirmed

Severity

  • Scoring method: CVSS v3.1
  • Score: 7.3
  • Vector string: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L

Weaknesses

  • CWE: CWE-287 Improper Authentication (root cause: unvalidated external string used as object property key / prototype-chain lookup, CWE-1321; consequence: unauthenticated resource allocation, CWE-770)

Affected versions

References

GitHub · apify/apify-mcp-server