mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
fix(oauth): accept private-use redirect schemes and loopback ports
POST /oauth/register refused every single-label private-use scheme, so an
MCP client registering workbuddy:// could not connect at all, while the
error it got back advertised "a private custom scheme" as supported.
The cause was two validators that had drifted apart, both of which run on
registration. The provider required a dot in the scheme name, which RFC
8252 section 7.1 only recommends and which protected nothing
(javascript.evil:// passed it). The service behind it had no
custom-scheme branch whatsoever and no [::1], which is what actually
answered the reporter's second symptom, and its localhost exemption was
not gated on http:. So javascript://localhost/%0aalert(1), blob:, about:,
ftp: and wss: were all accepted through the settings UI, and the consent
flow assigns the stored URI to window.location.href. Only the CSP stood
between that and a navigation. Both now decide through one policy in
oauth.helpers.ts.
Widening the scheme set means the deny-list has to carry its own weight:
it grows by the browser, extension and OS-handler schemes that were
previously blocked only as a side effect of the dot rule, including
ms-msdt (Follina) and the ms- namespace by prefix. intent: is denied,
because Chrome follows its embedded fallback URL, which turns it into an
open redirect the authorization server cannot inspect.
Fixing registration alone would have moved the reporter's [::1]:{port}
failure one step later: TREK matched redirect URIs byte for byte while
RFC 8252 section 7.3 frees the port for loopback, so a native client on
an OS-assigned port got a 302 to consent and then invalid_redirect_uri.
The matcher now relaxes the port, and only the port, for http loopback.
Stored URIs are never canonicalised, so the %3A round-trips untouched.
Note this tightens POST /api/oauth/clients for inputs it accepts today.
That is the security half of the change and applies at create time only,
so no already-registered client changes behaviour.
Closes #2227
This commit is contained in:
@@ -6,6 +6,7 @@ import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types';
|
||||
import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients';
|
||||
import { InvalidClientMetadataError, ServerError } from '@modelcontextprotocol/sdk/server/auth/errors';
|
||||
import { OauthService } from './oauth.service';
|
||||
import { classifyRedirectUri } from './oauth.helpers';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { ALL_SCOPES, DEFAULT_CLIENT_SCOPES } from '../../mcp/scopes';
|
||||
import { getMcpSafeUrl } from '../../app-config';
|
||||
@@ -21,26 +22,21 @@ import { getMcpSafeUrl } from '../../app-config';
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Redirect URI validation (mirrors oauth.ts DCR checks)
|
||||
// Redirect URI validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const DANGEROUS_SCHEMES = new Set([
|
||||
'javascript:', 'data:', 'vbscript:', 'file:', 'blob:', 'about:', 'chrome:', 'chrome-extension:',
|
||||
]);
|
||||
|
||||
// DCR runs this and then createOAuthClient's own check; both now decide through
|
||||
// the one policy in oauth.helpers, which is what closes #2227. The three error
|
||||
// strings stay byte-identical: DCR clients surface error_description verbatim.
|
||||
function assertValidRedirectUris(uris: string[]): void {
|
||||
for (const u of uris) {
|
||||
let url: URL;
|
||||
try { url = new URL(u); } catch {
|
||||
const verdict = classifyRedirectUri(u);
|
||||
if (verdict === 'malformed')
|
||||
throw new InvalidClientMetadataError(`Invalid redirect URI: ${u}`);
|
||||
}
|
||||
if (DANGEROUS_SCHEMES.has(url.protocol))
|
||||
if (verdict === 'dangerous')
|
||||
throw new InvalidClientMetadataError(`Dangerous redirect URI scheme: ${u}`);
|
||||
if (url.protocol === 'https:') continue;
|
||||
if (url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]')) continue;
|
||||
const scheme = url.protocol.slice(0, -1);
|
||||
if (/^[a-z][a-z0-9+.-]*$/i.test(scheme) && scheme.includes('.')) continue;
|
||||
throw new InvalidClientMetadataError('redirect_uris must be HTTPS, loopback HTTP, or a private custom scheme');
|
||||
if (verdict === 'not_allowed')
|
||||
throw new InvalidClientMetadataError('redirect_uris must be HTTPS, loopback HTTP, or a private custom scheme');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,116 @@ export function parseSqliteUtc(ts: string | null | undefined): Date | null {
|
||||
export const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
|
||||
export const CODE_VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Redirect URI validation (RFC 8252)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The three loopback hosts of RFC 8252 §7.3, and exactly the set the MCP SDK's
|
||||
* authorize handler matches on. Registration and authorization have to agree on
|
||||
* this list or a client registers a URI it can never authorize with (#2227).
|
||||
*/
|
||||
export const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
||||
|
||||
/**
|
||||
* Schemes a browser must never be redirected to: script-executing
|
||||
* (javascript:, vbscript:, data:), local-resource (file:, filesystem:,
|
||||
* resource:, jar:, view-source:, blob:, about:), and extension or OS handlers
|
||||
* that reach code outside the page (chrome-extension:, moz-extension:,
|
||||
* safari-extension:, ms-msdt:, which is the Follina handler).
|
||||
*
|
||||
* Most of these were only ever blocked as a side effect of the old "a custom
|
||||
* scheme must contain a dot" rule; dropping that rule to admit workbuddy://
|
||||
* (#2227) would otherwise have admitted them too. `intent:` is denied with
|
||||
* them: Chrome follows its S.browser_fallback_url parameter, which turns any
|
||||
* accepted intent:// redirect into an open redirect. Android apps that need a
|
||||
* redirect register a private-use scheme or an https App Link instead.
|
||||
*/
|
||||
const DANGEROUS_REDIRECT_SCHEMES = new Set([
|
||||
'javascript:', 'data:', 'vbscript:', 'file:', 'blob:', 'about:', 'chrome:', 'chrome-extension:',
|
||||
'view-source:', 'filesystem:', 'resource:', 'jar:', 'moz-extension:', 'safari-extension:',
|
||||
'chrome-search:', 'chrome-untrusted:', 'ms-browser-extension:', 'ms-msdt:', 'android-app:',
|
||||
'intent:', 'search-ms:', 'shell:', 'microsoft-edge:', 'itms-services:',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Everything under `ms-` is a Windows protocol handler (ms-settings:,
|
||||
* ms-search:, ms-officecmd:, …), never a redirect target, and the namespace
|
||||
* grows with every Windows release, so deny the prefix rather than chase it.
|
||||
* Microsoft's own identity redirects use msauth:/msal…: and stay allowed.
|
||||
*/
|
||||
const DANGEROUS_SCHEME_PREFIX = 'ms-';
|
||||
|
||||
/** Transports that are not browser navigations, so never a redirect target. */
|
||||
const NON_REDIRECT_SCHEMES = new Set([
|
||||
'ws:', 'wss:', 'ftp:', 'ftps:', 'mailto:', 'tel:', 'sms:', 'urn:',
|
||||
]);
|
||||
|
||||
export type RedirectUriVerdict = 'ok' | 'malformed' | 'dangerous' | 'not_allowed';
|
||||
|
||||
/**
|
||||
* The single redirect_uri policy for both registration paths, DCR
|
||||
* (POST /oauth/register) and the settings UI (POST /api/oauth/clients), which
|
||||
* used to disagree: DCR refused every single-label private-use scheme while the
|
||||
* settings route accepted javascript://localhost/… (#2227).
|
||||
*
|
||||
* Decisions are made on `url.protocol`, never on the raw string: the WHATWG
|
||||
* parser lowercases the scheme and strips tabs, newlines and leading spaces, so
|
||||
* 'JavaScript:', 'java\tscript:' and ' javascript:' all normalise into the
|
||||
* deny-list instead of sliding past it.
|
||||
*/
|
||||
export function classifyRedirectUri(uri: string): RedirectUriVerdict {
|
||||
let url: URL;
|
||||
try { url = new URL(uri); } catch { return 'malformed'; }
|
||||
|
||||
const protocol = url.protocol;
|
||||
if (DANGEROUS_REDIRECT_SCHEMES.has(protocol) || protocol.startsWith(DANGEROUS_SCHEME_PREFIX)) return 'dangerous';
|
||||
if (NON_REDIRECT_SCHEMES.has(protocol)) return 'not_allowed';
|
||||
if (protocol === 'https:') return 'ok';
|
||||
if (protocol === 'http:') return LOOPBACK_HOSTS.has(url.hostname) ? 'ok' : 'not_allowed';
|
||||
|
||||
// Private-use schemes (RFC 8252 §7.1). The reverse-domain form is a SHOULD,
|
||||
// not a MUST, and requiring a dot bought nothing: 'javascript.evil://x'
|
||||
// passed it while 'workbuddy://…' did not. Two characters minimum so a
|
||||
// Windows path (c:\tmp\cb) is not read as a scheme.
|
||||
const scheme = protocol.slice(0, -1);
|
||||
return /^[a-z][a-z0-9+.-]+$/i.test(scheme) ? 'ok' : 'not_allowed';
|
||||
}
|
||||
|
||||
/**
|
||||
* Byte-exact, with the one relaxation RFC 8252 §7.3 requires: a native client
|
||||
* registers a loopback URI with a placeholder port and then authorizes on the
|
||||
* port the OS handed it, so the port (and only the port) is ignored when both
|
||||
* sides are loopback HTTP. The MCP SDK's authorize handler already relaxes it;
|
||||
* TREK's matcher did not, so the SDK redirected to consent and the validate
|
||||
* route then answered invalid_redirect_uri for the same request (#2227).
|
||||
*
|
||||
* Nothing else is normalised anywhere in the chain: the stored URI is compared
|
||||
* as it was registered, percent-encoding included.
|
||||
*/
|
||||
export function redirectUriMatches(allowed: string, requested: string): boolean {
|
||||
if (allowed === requested) return true;
|
||||
|
||||
let a: URL, r: URL;
|
||||
try {
|
||||
a = new URL(allowed);
|
||||
r = new URL(requested);
|
||||
} catch { return false; }
|
||||
|
||||
if (a.protocol !== 'http:' || r.protocol !== 'http:') return false;
|
||||
if (!LOOPBACK_HOSTS.has(a.hostname) || !LOOPBACK_HOSTS.has(r.hostname)) return false;
|
||||
// Only the port is free. The RFC does not allow localhost↔127.0.0.1 either, and
|
||||
// userinfo and fragment are compared too: the URL parser would otherwise drop
|
||||
// them silently and let 'http://attacker@127.0.0.1:1/cb#x' match a bare
|
||||
// 'http://127.0.0.1:8080/cb'.
|
||||
return a.hostname === r.hostname
|
||||
&& a.pathname === r.pathname
|
||||
&& a.search === r.search
|
||||
&& a.hash === r.hash
|
||||
&& a.username === r.username
|
||||
&& a.password === r.password;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DB row types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -20,10 +20,12 @@ import {
|
||||
CODE_VERIFIER_RE,
|
||||
REFRESH_ROTATION_GRACE_MS,
|
||||
REFRESH_TOKEN_TTL_MS,
|
||||
classifyRedirectUri,
|
||||
generateAccessToken,
|
||||
generateRefreshToken,
|
||||
hashToken,
|
||||
parseSqliteUtc,
|
||||
redirectUriMatches,
|
||||
timingSafeEqualHex,
|
||||
type OAuthClientRow,
|
||||
type OAuthTokenRow,
|
||||
@@ -118,16 +120,15 @@ export class OauthService {
|
||||
if (!isMachineClient && (!redirectUris || redirectUris.length === 0)) return { error: 'At least one redirect URI is required', status: 400 };
|
||||
if (redirectUris.length > 10) return { error: 'Maximum 10 redirect URIs per client', status: 400 };
|
||||
|
||||
// Same policy as the DCR path (#2227). This used to exempt any host named
|
||||
// localhost or 127.0.0.1 regardless of scheme, which let the settings UI
|
||||
// register javascript://localhost/…, and the consent flow then assigns that
|
||||
// stored URI to window.location.href.
|
||||
for (const uri of redirectUris) {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(uri);
|
||||
} catch {
|
||||
return { error: `Invalid redirect URI: ${uri}`, status: 400 };
|
||||
}
|
||||
if (parsed.protocol !== 'https:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') {
|
||||
return { error: `Redirect URI must use HTTPS (localhost exempt): ${uri}`, status: 400 };
|
||||
}
|
||||
const verdict = classifyRedirectUri(uri);
|
||||
if (verdict === 'malformed') return { error: `Invalid redirect URI: ${uri}`, status: 400 };
|
||||
if (verdict === 'dangerous') return { error: `Dangerous redirect URI scheme: ${uri}`, status: 400 };
|
||||
if (verdict === 'not_allowed') return { error: `Redirect URI must use HTTPS, loopback HTTP, or a private custom scheme: ${uri}`, status: 400 };
|
||||
}
|
||||
|
||||
if (!allowedScopes || allowedScopes.length === 0) return { error: 'At least one scope is required', status: 400 };
|
||||
@@ -615,7 +616,12 @@ export class OauthService {
|
||||
}
|
||||
|
||||
const allowedUris: string[] = JSON.parse(client.redirect_uris);
|
||||
if (!params.redirect_uri || !allowedUris.includes(params.redirect_uri)) {
|
||||
// Exact match except for the loopback port, which RFC 8252 §7.3 leaves to
|
||||
// the OS, and which the SDK's authorize handler already relaxes, so a
|
||||
// native client got a 302 to consent and an invalid_redirect_uri from this
|
||||
// route for one and the same request (#2227).
|
||||
const requestedUri = params.redirect_uri;
|
||||
if (!requestedUri || !allowedUris.some(allowed => redirectUriMatches(allowed, requestedUri))) {
|
||||
return { valid: false, error: 'invalid_redirect_uri', error_description: 'redirect_uri does not match any registered URI' };
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user