🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(gateway): OAuth 2.1 on x.ruv.io/mcp, and no credentials as tool arguments
ruvb329f0937cf9
diff --git a/plugins/ruflo-chatgpt-federation/src/server.mjs b/plugins/ruflo-chatgpt-federation/src/server.mjsindex d3355dc2fe..5ced1b853f 100644--- a/plugins/ruflo-chatgpt-federation/src/server.mjs+++ b/plugins/ruflo-chatgpt-federation/src/server.mjs@@ -107,12 +107,13 @@ export function createPublisherService({ relay, keyPath, port } = {}) {}function buildMcp(req, auth) {- // A dedicated header, not Authorization: Cloud Run consumes `Authorization`- // for its own IAM check and answers 401 before the request reaches this- // container, so a token sent that way never arrives. The header is still the- // preferred channel — it stays out of the model's context and out of- // tool-call transcripts — with the argument as a fallback for clients that- // cannot set headers on an MCP connection.+ // Credentials arrive ONLY through the transport, never as a tool argument.+ // An argument is model-generated: it puts the credential in the model's+ // context and in tool-call transcripts, and makes authority something the+ // model can be talked into supplying. Authentication belongs to middleware;+ // the tool receives an already-authenticated identity.+ // (This header is the retired transitional path, dead while OAuth is+ // enforced, and kept only so a pre-OAuth deployment can still be rolled back.)const header = String(req?.headers?.['x-caller-token'] || '').trim();const mcp = new McpServer({ name: 'ruflo-chatgpt-federation', version: VERSION });@@ -133,13 +134,12 @@ export function createPublisherService({ relay, keyPath, port } = {}) {'Sign a message with this connector\'s own key and publish it to a public swarm channel over its own NIP-42 authenticated relay connection. Use when this connector has something the federation needs — a status, a finding, a result. Requires the caller token; public (pub:) channels only, because publishing to a private channel needs a channel key this connector deliberately does not hold.',{ channel: z.string().describe('Public channel id, e.g. "pub:announce".'),msgType: z.string().describe('Message type, e.g. "Status", "Result", "Question".'),- payload: z.record(z.any()).describe('Message body. Never put secrets or credentials here — channel content is readable by every relay member.'),- callerToken: z.string().optional().describe('Caller token, if not supplied as an x-caller-token header.') },- async ({ channel, msgType, payload, callerToken }) => {+ payload: z.record(z.any()).describe('Message body. Never put secrets or credentials here — channel content is readable by every relay member.') },+ async ({ channel, msgType, payload }) => {// OAuth scope is the real gate. The caller token remains a transitional// fallback and only while OAuth is not yet mandatory.const viaOauth = auth.mode === 'oauth' && hasScope(auth.scopes, SCOPE_PUBLISH);- const viaLegacy = auth.mode === 'legacy' && checkCaller(callerToken ?? header);+ const viaLegacy = auth.mode === 'legacy' && checkCaller(header);if (!viaOauth && !viaLegacy) {const why = auth.mode === 'oauth'? `access token lacks ${SCOPE_PUBLISH}`diff --git a/plugins/ruflo-chatgpt-federation/test/oauth.test.mjs b/plugins/ruflo-chatgpt-federation/test/oauth.test.mjsindex 3b42d55893..162c337ae2 100644--- a/plugins/ruflo-chatgpt-federation/test/oauth.test.mjs+++ b/plugins/ruflo-chatgpt-federation/test/oauth.test.mjs@@ -372,3 +372,25 @@ test('the 401 challenge points at the metadata for the path that was requested',});} finally { as.close(); }});++test('no tool accepts a credential as an argument', async () => {+ // Submission requirement, and the right rule regardless: a credential passed+ // as a tool argument is model-generated — it lands in the model's context and+ // in tool-call transcripts, and makes authority something the model can be+ // persuaded to supply. Authentication is the transport's job.+ const as = await fakeAuthServer();+ try {+ await withService(as, { required: false, publicUrl: 'https://cgf.example' }, async (port) => {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, { method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) });+ const raw = await r.text();+ const line = raw.split('\n').find((l) => l.startsWith('data: '));+ for (const t of JSON.parse(line ? line.slice(6) : raw).result.tools) {+ const props = Object.keys(t.inputSchema?.properties || {});+ const creds = props.filter((k) => /token|secret|password|apikey|api_key|credential/i.test(k));+ assert.deepEqual(creds, [], `${t.name} exposes credential argument(s): ${creds.join(', ')}`);+ }+ });+ } finally { as.close(); }+});diff --git a/plugins/ruflo-x-gateway/package.json b/plugins/ruflo-x-gateway/package.jsonindex 29ab7494b5..03b7442217 100644--- a/plugins/ruflo-x-gateway/package.json+++ b/plugins/ruflo-x-gateway/package.json@@ -11,6 +11,7 @@},"dependencies": {"@modelcontextprotocol/sdk": "^1.0.0",+ "jose": "^6.2.12","nostr-tools": "^2.7.0","ws": "^8.18.0","zod": "^3.23.0"diff --git a/plugins/ruflo-x-gateway/src/oauth.mjs b/plugins/ruflo-x-gateway/src/oauth.mjsnew file mode 100644index 0000000000..ad0f835af4--- /dev/null+++ b/plugins/ruflo-x-gateway/src/oauth.mjs@@ -0,0 +1,115 @@+/**+ * OAuth 2.1 resource-server side of the connector (RFC 9728 + RFC 8707 audience,+ * bearer usage per RFC 6750).+ *+ * This module holds no client secret and issues nothing. It advertises which+ * authorization server protects this resource, validates the access token that+ * server issued, and maps scopes onto the gateway's tools. The authorization server+ * is Cognitum's (`https://auth.cognitum.one`), which is a public-client + PKCE+ * server — so there is no client secret anywhere in this design, by construction.+ *+ * OAuth decides *who may ask*. The gateway's own Nostr identity signs, and is+ * never reachable from here.+ */+import { createRemoteJWKSet, jwtVerify } from 'jose';++// The gateway's OWN scopes, deliberately not `federation:*`. Isolation between+// this resource and the ChatGPT Federation connector comes from audience+// pinning — each accepts only tokens whose `aud` is its own client_id — but+// distinct scopes keep a token's authority legible in a log and stop a consent+// screen claiming more than the resource actually grants.+export const SCOPE_READ = 'swarm:read';+export const SCOPE_PUBLISH = 'swarm:publish';++/**+ * RFC 9728 protected-resource metadata. A client that gets a 401 from /mcp reads+ * this to learn which authorization server to go to.+ */+export function protectedResourceMetadata({ resource, issuer }) {+ return {+ resource,+ authorization_servers: [issuer],+ scopes_supported: [SCOPE_READ, SCOPE_PUBLISH],+ bearer_methods_supported: ['header'],+ resource_documentation: `${resource}/`,+ };+}++/** The WWW-Authenticate value that points an unauthenticated client at discovery. */+export function challengeHeader(resourceMetadataUrl, { error, description } = {}) {+ const parts = [`Bearer resource_metadata="${resourceMetadataUrl}"`];+ if (error) parts.push(`error="${error}"`);+ if (description) parts.push(`error_description="${description}"`);+ return parts.join(', ');+}++let jwks = null, jwksFor = null;+function keySet(jwksUri) {+ // Cached across requests; `jose` handles its own key rotation and refresh.+ if (!jwks || jwksFor !== jwksUri) { jwks = createRemoteJWKSet(new URL(jwksUri)); jwksFor = jwksUri; }+ return jwks;+}++/** Reset the cached key set. Tests only. */+export function _resetJwksForTest() { jwks = null; jwksFor = null; }++/**+ * Verify an access token and return its granted scopes.+ *+ * Audience is checked, not merely parsed: a token minted for another Cognitum+ * app must not act on the federation identity just because the same issuer+ * signed it.+ *+ * The audience to expect is this connector's **client_id**, not its resource+ * URL. `auth.cognitum.one` binds `aud` to the requesting OAuth client+ * (services/identity/src/jwt.rs `issue_oauth_access_token`), which is+ * client-audience binding rather than RFC 8707 resource binding. It closes the+ * same confused-deputy hole here because this connector is the only resource+ * its client_id is registered for — a one-client-one-resource assumption that+ * is load-bearing, and the reason `federation:*` must never be added to another+ * client's allowed_scopes.+ *+ * @returns {Promise<{ ok: true, scopes: string[], subject?: string } | { ok: false, error: string, description: string }>}+ */+export async function verifyAccessToken(token, { issuer, jwksUri, audience }) {+ if (!token) return { ok: false, error: 'invalid_request', description: 'no bearer token' };+ try {+ const { payload } = await jwtVerify(token, keySet(jwksUri), {+ issuer,+ ...(audience ? { audience } : {}),+ clockTolerance: 30,+ });+ // `scope` is the RFC 6749 space-delimited form; `scp` is the array form some+ // servers emit. Accept either rather than silently granting nothing.+ const raw = payload.scope ?? payload.scp ?? '';+ const scopes = Array.isArray(raw) ? raw.map(String) : String(raw).split(/\s+/).filter(Boolean);+ return { ok: true, scopes, subject: payload.sub ? String(payload.sub) : undefined };+ } catch (e) {+ // Say WHY, precisely. A correctly-signed token that fails only on iss/aud is a+ // very different problem from a forged one, and `auth.cognitum.one` is measured+ // to issue tokens carrying neither claim (minimax-music services/gateway/src/+ // jwks.rs, citing freetokens ADR-0017). Without this, that shows up as a bare+ // "invalid_token" and costs someone an afternoon.+ //+ // This re-verifies the SIGNATURE only, for diagnosis. It never grants: every+ // path below still returns ok:false.+ let detail = String(e?.message || 'token verification failed').slice(0, 200);+ try {+ const { payload } = await jwtVerify(token, keySet(jwksUri), { clockTolerance: 30 });+ const missing = [];+ if (issuer && !payload.iss) missing.push('iss');+ if (audience && !payload.aud) missing.push('aud');+ if (missing.length) {+ detail = `token signature is valid but carries no ${missing.join(' or ')} claim, so it is not bound to this resource`;+ return { ok: false, error: 'invalid_token', description: detail, signatureValid: true, unboundClaims: missing };+ }+ detail = `token signature is valid but ${detail}`;+ } catch { /* signature genuinely bad — keep the original message */ }+ return { ok: false, error: 'invalid_token', description: detail };+ }+}++/** True when the granted scopes cover the one required. */+export function hasScope(scopes, required) {+ return Array.isArray(scopes) && scopes.includes(required);+}diff --git a/plugins/ruflo-x-gateway/src/server.mjs b/plugins/ruflo-x-gateway/src/server.mjsindex 6dbbdfee52..b96dfd0def 100644--- a/plugins/ruflo-x-gateway/src/server.mjs+++ b/plugins/ruflo-x-gateway/src/server.mjs@@ -18,6 +18,8 @@ import { mintInvite, admitMember } from './relay-admin.mjs';import { attachWsProxy } from './ws-proxy.mjs';import { onboardingGuide } from './onboarding.mjs';import { askSeraphina } from './seraphina.mjs';+import { protectedResourceMetadata, challengeHeader, verifyAccessToken, hasScope, SCOPE_READ, SCOPE_PUBLISH } from './oauth.mjs';+import { createHash } from 'node:crypto';export function createGateway({ relay, keyFile, port } = {}) {const RELAY = relay || process.env.RUFLO_RELAY_URL || 'wss://relay.ruv.io';@@ -25,12 +27,58 @@ export function createGateway({ relay, keyFile, port } = {}) {// Pre-0.3.2 clients pinned the raw Cloud Run host; it stays routable, but relay.ruv.io is canonical.const LEGACY_RELAY = 'wss://buzz-relay-186366152200.us-central1.run.app';const { sk, pubkey } = loadIdentity(keyFile || process.env.RUFLO_NOSTR_KEY || '/data/nostr-gateway.key');+ // ---- OAuth 2.1 (ADR-388). Additive: the admin token keeps working, and an+ // unauthenticated read keeps working, because this gateway is the federation's+ // open front door and closing it would strand every existing participant.+ // What OAuth adds is a second, per-user way to earn write authority.+ const OAUTH_ISSUER = process.env.RUFLO_OAUTH_ISSUER || 'https://auth.cognitum.one';+ const OAUTH_JWKS = process.env.RUFLO_OAUTH_JWKS_URI || `${OAUTH_ISSUER}/.well-known/jwks.json`;+ // The audience this resource pins. auth.cognitum.one binds `aud` to the+ // requesting client_id, so this is what stops a token minted for another+ // Cognitum resource — the ChatGPT Federation connector included — from being+ // replayed here as its holder.+ const OAUTH_CLIENT_ID = (process.env.RUFLO_OAUTH_CLIENT_ID || '').trim();+ const PUBLIC_URL = (process.env.RUFLO_PUBLIC_URL || 'https://x.ruv.io').replace(/\/$/, '');+ // Accepting bearer tokens with no audience to pin them to would honour ANY+ // token this issuer ever minted, for any Cognitum app — a confused deputy with+ // write access to the federation identity. Refuse to offer OAuth at all rather+ // than offer it unsafely; the admin-token path is unaffected.+ const OAUTH_ENABLED = OAUTH_CLIENT_ID.length > 0;+ if (!OAUTH_ENABLED && String(process.env.RUFLO_OAUTH_REQUIRE || '') === 'true') {+ throw new Error('RUFLO_OAUTH_REQUIRE=true needs RUFLO_OAUTH_CLIENT_ID — refusing to enforce OAuth without an audience to bind to');+ }+ const prmUrl = (pathname) => `${PUBLIC_URL}/.well-known/oauth-protected-resource`+ + (pathname === '/mcp' ? '/mcp' : '');++ async function oauthContext(req) {+ const bearer = String(req?.headers?.authorization || '').match(/^Bearer\s+(.+)$/i)?.[1]?.trim();+ if (!bearer) return { mode: 'anonymous', scopes: [] };+ if (!OAUTH_ENABLED) {+ return { mode: 'denied', error: 'invalid_request',+ description: 'this deployment has no OAuth audience configured and will not accept bearer tokens' };+ }+ const v = await verifyAccessToken(bearer, { issuer: OAUTH_ISSUER, jwksUri: OAUTH_JWKS,+ audience: OAUTH_CLIENT_ID || undefined });+ return v.ok ? { mode: 'oauth', scopes: v.scopes, subject: v.subject }+ : { mode: 'denied', error: v.error, description: v.description };+ }+const text = (o) => ({ content: [{ type: 'text', text: JSON.stringify(o) }] });const denied = () => ({ isError: true, content: [{ type: 'text', text: JSON.stringify({ error: 'admin token required or invalid' }) }] });- const gated = (fn) => async (args) => (checkAdmin(args.adminToken) ? fn(args) : denied());- const adminArg = { adminToken: z.string().describe('Gateway admin token (RUFLO_ADMIN_TOKEN). Required for any write made with the gateway identity.') };+ // Either credential may authorise a write: the long-standing admin token, or+ // an access token carrying swarm:publish. `auth` is per-request, closed over+ // by buildMcp.+ const gated = (auth, fn) => async (args) =>+ (checkAdmin(args.adminToken) || (auth?.mode === 'oauth' && hasScope(auth.scopes, SCOPE_PUBLISH)))+ ? fn(args)+ : denied();+ // OPTIONAL, deliberately: there are now two ways to earn write authority, and a+ // required adminToken would make every OAuth-authorised write fail at schema+ // validation before the handler could consider the token at all. The handler+ // is what enforces — absent BOTH credentials it still refuses.+ const adminArg = { adminToken: z.string().optional().describe('Gateway admin token (RUFLO_ADMIN_TOKEN). One of two accepted write credentials; the other is an access token carrying swarm:publish in the Authorization header.') };- function buildMcp(req) {+ function buildMcp(req, auth = { mode: 'anonymous', scopes: [] }) {const mcp = new McpServer({ name: 'ruflo-x-gateway', version: '0.7.0' });// ---- open reads ----mcp.tool('federation_identity', 'Gateway Nostr pubkey + relay. Open read.', {}, async () => text({ pubkey, relay: RELAY, httpBase: HTTP_BASE }));@@ -42,22 +90,22 @@ export function createGateway({ relay, keyFile, port } = {}) {// ---- admin-gated writes (use the GATEWAY identity) ----mcp.tool('federation_join', 'Publish a signed PeerHello AS THE GATEWAY. Admin-gated. Users should join with their own key via invite→claim instead.',{ name: z.string(), platform: z.string().optional(), note: z.string().optional(), ...adminArg },- gated(async ({ name, platform, note }) => text({ ok: true, eventId: await publish(RELAY, sk, 'PeerHello', { from: name, platform, note }) })));+ gated(auth, async ({ name, platform, note }) => text({ ok: true, eventId: await publish(RELAY, sk, 'PeerHello', { from: name, platform, note }) })));mcp.tool('federation_publish', 'Publish a signed coordination message AS THE GATEWAY (Status/Task/Result…). Admin-gated.',{ msgType: z.string(), payload: z.record(z.any()), ...adminArg },- gated(async ({ msgType, payload }) => text({ ok: true, eventId: await publish(RELAY, sk, msgType, payload) })));+ gated(auth, async ({ msgType, payload }) => text({ ok: true, eventId: await publish(RELAY, sk, msgType, payload) })));mcp.tool('claims_issue', 'Issue a work claim AS THE GATEWAY. Admin-gated. One owner per resourceId.',{ resourceId: z.string(), ttlSeconds: z.number().optional(), ...adminArg },- gated(async ({ resourceId, ttlSeconds }) => text({ ok: true, eventId: await publish(RELAY, sk, 'ClaimIssued', { from: pubkey, resourceId, ttlSeconds }), resourceId })));+ gated(auth, async ({ resourceId, ttlSeconds }) => text({ ok: true, eventId: await publish(RELAY, sk, 'ClaimIssued', { from: pubkey, resourceId, ttlSeconds }), resourceId })));mcp.tool('claims_release', 'Release a gateway-held work claim. Admin-gated.',{ resourceId: z.string(), ...adminArg },- gated(async ({ resourceId }) => text({ ok: true, eventId: await publish(RELAY, sk, 'ClaimReleased', { from: pubkey, resourceId }), resourceId })));+ gated(auth, async ({ resourceId }) => text({ ok: true, eventId: await publish(RELAY, sk, 'ClaimReleased', { from: pubkey, resourceId }), resourceId })));mcp.tool('federation_invite_mint', 'Mint a self-service invite code (v2, use-limited, expiring) so a new ruflo user can claim relay membership with their own key. Admin-gated; the gateway must hold relay admin role.',{ ttlSecs: z.number().optional(), maxUses: z.number().optional(), ...adminArg },- gated(async ({ ttlSecs, maxUses }) => text(await mintInvite(HTTP_BASE, sk, { ttlSecs, maxUses }))));+ gated(auth, async ({ ttlSecs, maxUses }) => text(await mintInvite(HTTP_BASE, sk, { ttlSecs, maxUses }))));mcp.tool('federation_admit', 'Admit a pubkey as a relay member directly (NIP-43 kind 9030). Admin-gated.',{ pubkey: z.string(), role: z.enum(['member', 'admin']).optional(), ...adminArg },- gated(async ({ pubkey: pk, role }) => text(await admitMember(RELAY, sk, pk, role))));+ gated(auth, async ({ pubkey: pk, role }) => text(await admitMember(RELAY, sk, pk, role))));// ---- ADR-386 channels ----mcp.tool('channel_list', 'List swarm channels seen recently, with visibility, message count and publisher count. Open read. Public channel ids carry their name (pub:<name>); private ids are opaque (prv:<hex>) and reveal nothing about the topic. Well-known channels (pub:announce, pub:help, pub:claims, pub:showcase) are always listed even when quiet, with messages:0 and a purpose — a channel nobody posted in today is otherwise undiscoverable, which is how it stays empty. Use when you want to find where coordination is happening before reading a stream. Reading the flat firehose with federation_sync instead is wrong once channels are in use, because it mixes unrelated work and cannot show you private traffic exists at all.',{ sinceSeconds: z.number().optional(), limit: z.number().optional() },@@ -71,7 +119,7 @@ export function createGateway({ relay, keyFile, port } = {}) {});mcp.tool('channel_publish', 'Publish a message to a PUBLIC channel as the gateway. Admin-gated. Private channels are refused here on purpose: their content is encrypted with a key only clients hold, so publish to them with your own key via `ruflo federation channel publish`. Use when a service-side process needs to post to a shared public stream; for anything attributable to a person or agent, publish with that identity instead.',{ channel: z.string(), msgType: z.string(), payload: z.record(z.any()), ...adminArg },- gated(async ({ channel, msgType, payload }) => {+ gated(auth, async ({ channel, msgType, payload }) => {// Refuse private BEFORE normalising, so a prv: id gets the real reason rather// than a name-validation error from the public-id helper.if (isPrivateChannel(channel)) throw new Error('private channels cannot be published by the gateway — it holds no channel key (ADR-386); publish with your own key via `ruflo federation channel publish`');@@ -125,14 +173,51 @@ export function createGateway({ relay, keyFile, port } = {}) {const server = createServer(async (req, res) => {securityHeaders(res);+ // A browser-origin MCP client must preflight before it can POST, and cannot+ // read the challenge unless WWW-Authenticate is exposed — without that it+ // never learns where to authenticate.+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('access-control-expose-headers', 'www-authenticate, mcp-session-id, mcp-protocol-version');const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ if (req.method === 'OPTIONS') {+ res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS');+ res.setHeader('access-control-allow-headers',+ 'content-type, authorization, mcp-session-id, mcp-protocol-version, accept');+ res.setHeader('access-control-max-age', '86400');+ return res.writeHead(204).end();+ }+ // RFC 9728. `resource` echoes the identifier the client asked about: a client+ // using <base>/mcp must get <base>/mcp back, not the bare origin.+ if (url.pathname === '/.well-known/oauth-protected-resource'+ || url.pathname === '/.well-known/oauth-protected-resource/mcp') {+ res.writeHead(200, { 'content-type': 'application/json' });+ return res.end(JSON.stringify(protectedResourceMetadata({+ resource: url.pathname.endsWith('/mcp') ? `${PUBLIC_URL}/mcp` : PUBLIC_URL,+ issuer: OAUTH_ISSUER })));+ }if (url.pathname === '/health') return res.writeHead(200).end('ok');if (url.pathname === '/' && req.method === 'GET') { res.writeHead(200, { 'content-type': 'application/json' });- return res.end(JSON.stringify({ service: 'ruflo-x-gateway', version: '0.7.0', mcp: '/mcp', ws: ['/', '/relay'], relay: RELAY, canonicalRelay: RELAY, legacyRelay: LEGACY_RELAY, authNote: 'When connecting via wss://x.ruv.io, sign the NIP-42 AUTH `relay` tag with canonicalRelay (the relay verifies it strictly).', gatewayPubkey: pubkey, resources: ['ruv://federation/registry', 'ruv://federation/onboarding', 'ruv://swarm/roster', 'ruv://claims/board', 'ruv://swarm/channels'] })); }+ return res.end(JSON.stringify({ service: 'ruflo-x-gateway', version: '0.7.0', mcp: '/mcp', ws: ['/', '/relay'], relay: RELAY, canonicalRelay: RELAY, legacyRelay: LEGACY_RELAY, authNote: 'When connecting via wss://x.ruv.io, sign the NIP-42 AUTH `relay` tag with canonicalRelay (the relay verifies it strictly).', gatewayPubkey: pubkey, resources: ['ruv://federation/registry', 'ruv://federation/onboarding', 'ruv://swarm/roster', 'ruv://claims/board', 'ruv://swarm/channels'],+ authorization: { type: 'oauth2', issuer: OAUTH_ISSUER, clientId: OAUTH_CLIENT_ID || null,+ scopes: [SCOPE_READ, SCOPE_PUBLISH], protectedResourceMetadata: prmUrl('/mcp'),+ note: 'Additive: reads stay open and adminToken still works; an access token with swarm:publish is an alternative write credential.' } })); }if (url.pathname === '/mcp') {if (rateLimited(req)) return res.writeHead(429, { 'content-type': 'application/json' }).end('{"error":"rate limited"}');let body; try { body = await readBody(req); } catch { return res.writeHead(413, { 'content-type': 'application/json' }).end('{"error":"payload too large"}'); }- const mcp = buildMcp(req); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });+ const auth = await oauthContext(req);+ if (auth.mode === 'denied') {+ // A bearer was presented and did not verify. Refuse it — never fall back+ // to anonymous, which would silently downgrade a caller that believes it+ // is authenticated.+ res.writeHead(401, { 'content-type': 'application/json',+ 'www-authenticate': challengeHeader(prmUrl(url.pathname), { error: auth.error, description: auth.description }) });+ return res.end(JSON.stringify({ error: auth.error, error_description: auth.description }));+ }+ try {+ const sub = auth.subject ? createHash('sha256').update(auth.subject).digest('hex').slice(0, 12) : '-';+ console.log(`mcp auth=${auth.mode} scopes=${(auth.scopes || []).join('+') || '-'} sub=${sub}`);+ } catch { /* logging must never break a request */ }+ const mcp = buildMcp(req, auth); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });res.on('close', () => { transport.close(); mcp.close(); });await mcp.connect(transport);let parsed; try { parsed = body ? JSON.parse(body) : undefined; } catch { return res.writeHead(400, { 'content-type': 'application/json' }).end('{"error":"invalid json"}'); }diff --git a/plugins/ruflo-x-gateway/test/gateway.test.mjs b/plugins/ruflo-x-gateway/test/gateway.test.mjsindex ce1b128c68..e7703f2b43 100644--- a/plugins/ruflo-x-gateway/test/gateway.test.mjs+++ b/plugins/ruflo-x-gateway/test/gateway.test.mjs@@ -278,8 +278,18 @@ test('seraphina: the tool answers without adminToken while claims_issue still reconst sera = JSON.parse(list.slice(list.indexOf('{'))).result.tools.find((t) => t.name === 'seraphina_guidance');assert.ok(sera, 'seraphina_guidance must be registered');assert.ok(!(sera.inputSchema.required || []).includes('adminToken'), 'adminToken must not be required');+ // adminToken is no longer REQUIRED in the schema — ADR-388 added a second write+ // credential (an access token carrying swarm:publish), and a required argument+ // would reject every OAuth-authorised write at validation before the handler+ // could consider the token. The protection moved to the handler, so assert it+ // THERE rather than dropping it: with neither credential, the write is refused.const gatedWrite = JSON.parse(list.slice(list.indexOf('{'))).result.tools.find((t) => t.name === 'claims_issue');- assert.ok((gatedWrite.inputSchema.required || []).includes('adminToken'), 'writes must still require it');+ assert.ok(!(gatedWrite.inputSchema.required || []).includes('adminToken'),+ 'adminToken must be optional so an OAuth-authorised write can be attempted');+ const refused = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/call',+ params: { name: 'claims_issue', arguments: { resourceId: 'r1' } } });+ assert.match(refused, /admin token required or invalid/,+ 'a write with neither credential must still be refused, at the handler');// The write path is unchanged: still refused without a token.const write = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'claims_issue', arguments: { resourceId: 'x' } } });diff --git a/plugins/ruflo-x-gateway/test/oauth.test.mjs b/plugins/ruflo-x-gateway/test/oauth.test.mjsnew file mode 100644index 0000000000..3ea084c83f--- /dev/null+++ b/plugins/ruflo-x-gateway/test/oauth.test.mjs@@ -0,0 +1,222 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { generateKeyPair, exportJWK, SignJWT } from 'jose';+import { createGateway } from '../src/server.mjs';+import { protectedResourceMetadata, SCOPE_READ, SCOPE_PUBLISH } from '../src/oauth.mjs';++const CLIENT_ID = 'ruflo-x-gateway';++async function fakeAuthServer() {+ const { publicKey, privateKey } = await generateKeyPair('RS256');+ const jwk = { ...(await exportJWK(publicKey)), kid: 'g1', alg: 'RS256', use: 'sig' };+ const srv = createServer((req, res) => {+ if (req.url === '/.well-known/jwks.json') {+ res.writeHead(200, { 'content-type': 'application/json' });+ return res.end(JSON.stringify({ keys: [jwk] }));+ }+ res.writeHead(404).end();+ });+ await new Promise((r) => srv.listen(0, r));+ const issuer = `http://127.0.0.1:${srv.address().port}`;+ const mint = ({ scope, audience, issuer: iss = issuer }) =>+ new SignJWT({ scope }).setProtectedHeader({ alg: 'RS256', kid: 'g1' })+ .setIssuer(iss).setAudience(audience).setSubject('u1')+ .setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1000) + 300).sign(privateKey);+ // The shape auth_web.rs mints: no iss, no aud.+ const mintSession = ({ scope }) =>+ new SignJWT({ scope }).setProtectedHeader({ alg: 'RS256', kid: 'g1' })+ .setSubject('u1').setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1000) + 300).sign(privateKey);+ return { issuer, jwksUri: `${issuer}/.well-known/jwks.json`, mint, mintSession, close: () => srv.close() };+}++async function withGateway(as, fn) {+ const prev = { ...process.env };+ Object.assign(process.env, {+ RUFLO_OAUTH_ISSUER: as.issuer, RUFLO_OAUTH_JWKS_URI: as.jwksUri,+ RUFLO_OAUTH_CLIENT_ID: CLIENT_ID, RUFLO_PUBLIC_URL: 'https://x.example',+ });+ const gw = createGateway({ relay: 'ws://127.0.0.1:1', keyFile: '/tmp/gw-test.key' });+ const port = await gw.listen(0);+ try { return await fn(port, gw); }+ finally {+ gw.server.close();+ for (const k of ['RUFLO_OAUTH_ISSUER','RUFLO_OAUTH_JWKS_URI','RUFLO_OAUTH_CLIENT_ID','RUFLO_PUBLIC_URL']) {+ if (prev[k] === undefined) delete process.env[k]; else process.env[k] = prev[k];+ }+ }+}++const call = (port, name, args = {}, headers = {}) =>+ fetch(`http://127.0.0.1:${port}/mcp`, { method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...headers },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }) })+ .then(async (r) => {+ const raw = await r.text();+ const line = raw.split('\n').find((l) => l.startsWith('data: '));+ let body = null; try { body = JSON.parse(line ? line.slice(6) : raw); } catch {}+ return { status: r.status, wwwAuth: r.headers.get('www-authenticate'), body };+ });+const toolText = (r) => r.body?.result?.content?.[0]?.text ?? JSON.stringify(r.body);++test('the gateway advertises its own scopes, not the connector\'s', () => {+ const m = protectedResourceMetadata({ resource: 'https://x.example', issuer: 'https://auth.example' });+ assert.deepEqual(m.scopes_supported, ['swarm:read', 'swarm:publish']);+ // Sharing federation:* would be safe (audience pinning is what isolates), but+ // distinct scopes keep a consent screen honest about what this resource grants.+ assert.ok(!m.scopes_supported.some((s) => s.startsWith('federation:')));+});++test('discovery echoes the identifier the client asked about', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const bare = await (await fetch(`http://127.0.0.1:${port}/.well-known/oauth-protected-resource`)).json();+ assert.equal(bare.resource, 'https://x.example');+ assert.deepEqual(bare.authorization_servers, [as.issuer]);+ const sfx = await (await fetch(`http://127.0.0.1:${port}/.well-known/oauth-protected-resource/mcp`)).json();+ assert.equal(sfx.resource, 'https://x.example/mcp');+ });+ } finally { as.close(); }+});++test('a browser-origin client can preflight /mcp and read the challenge', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, { method: 'OPTIONS',+ headers: { origin: 'https://chatgpt.com', 'access-control-request-method': 'POST' } });+ assert.equal(r.status, 204);+ assert.match(r.headers.get('access-control-allow-headers') || '', /authorization/);+ assert.match(r.headers.get('access-control-expose-headers') || '', /www-authenticate/);+ });+ } finally { as.close(); }+});++test('anonymous reads still work — the federation front door stays open', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port, gw) => {+ const r = await call(port, 'federation_identity');+ assert.equal(r.status, 200);+ assert.equal(JSON.parse(toolText(r)).pubkey, gw.pubkey);+ });+ } finally { as.close(); }+});++test('a presented bearer that does not verify is refused, never downgraded to anonymous', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const r = await call(port, 'federation_identity', {}, { authorization: 'Bearer nope' });+ assert.equal(r.status, 401);+ assert.match(r.wwwAuth || '', /resource_metadata=".*\/oauth-protected-resource\/mcp"/);+ });+ } finally { as.close(); }+});++test('a token for ANOTHER Cognitum client cannot act here', async () => {+ // The ChatGPT Federation connector's audience. This is the replay this+ // resource must refuse, and it is what audience pinning buys.+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const tok = await as.mint({ scope: `${SCOPE_READ} ${SCOPE_PUBLISH}`, audience: 'chatgpt-federation' });+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });+ assert.equal(r.status, 401);+ });+ } finally { as.close(); }+});++test('a browser-session token (no iss/aud) cannot act here', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const tok = await as.mintSession({ scope: `${SCOPE_READ} ${SCOPE_PUBLISH}` });+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });+ assert.equal(r.status, 401);+ assert.match(r.wwwAuth || '', /carries no iss or aud claim/);+ });+ } finally { as.close(); }+});++test('swarm:publish authorises a write with NO admin token', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const tok = await as.mint({ scope: `${SCOPE_READ} ${SCOPE_PUBLISH}`, audience: CLIENT_ID });+ const r = await call(port, 'federation_publish',+ { msgType: 'Status', payload: { note: 'x' } }, { authorization: `Bearer ${tok}` });+ // Authorisation passed; the relay is unreachable in this test, which is how+ // we know it got past the gate rather than being refused by it.+ assert.doesNotMatch(toolText(r), /admin token required/);+ });+ } finally { as.close(); }+});++test('a read-only token cannot write', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const tok = await as.mint({ scope: SCOPE_READ, audience: CLIENT_ID });+ const r = await call(port, 'federation_publish',+ { msgType: 'Status', payload: {} }, { authorization: `Bearer ${tok}` });+ assert.match(toolText(r), /admin token required/);+ });+ } finally { as.close(); }+});++test('an anonymous write is still refused', async () => {+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const r = await call(port, 'federation_publish', { msgType: 'Status', payload: {} });+ assert.match(toolText(r), /admin token required/);+ });+ } finally { as.close(); }+});++test('adminToken is optional in the schema, or OAuth writes cannot even be attempted', async () => {+ // Regression guard for a defect that looked like working code: while the+ // schema required adminToken, every OAuth-authorised write was rejected at+ // validation before the handler saw the token.+ const as = await fakeAuthServer();+ try {+ await withGateway(as, async (port) => {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, { method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) });+ const raw = await r.text();+ const line = raw.split('\n').find((l) => l.startsWith('data: '));+ const tools = JSON.parse(line ? line.slice(6) : raw).result.tools;+ const pub = tools.find((t) => t.name === 'federation_publish');+ assert.ok(pub, 'federation_publish is exposed');+ assert.ok(!(pub.inputSchema.required || []).includes('adminToken'),+ 'adminToken must not be a required argument once OAuth can authorise writes');+ });+ } finally { as.close(); }+});++test('with no audience configured, a bearer token is refused rather than honoured', async () => {+ // Unconfigured must mean "no OAuth", never "OAuth without an audience" — the+ // latter would accept any token this issuer ever minted, for any app.+ const as = await fakeAuthServer();+ const prev = { ...process.env };+ try {+ Object.assign(process.env, { RUFLO_OAUTH_ISSUER: as.issuer, RUFLO_OAUTH_JWKS_URI: as.jwksUri,+ RUFLO_PUBLIC_URL: 'https://x.example' });+ delete process.env.RUFLO_OAUTH_CLIENT_ID;+ const gw = createGateway({ relay: 'ws://127.0.0.1:1', keyFile: '/tmp/gw-noaud.key' });+ const port = await gw.listen(0);+ try {+ const tok = await as.mint({ scope: SCOPE_PUBLISH, audience: 'anything-at-all' });+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });+ assert.equal(r.status, 401, 'a token must not be honoured when no audience is pinned');+ } finally { gw.server.close(); }+ } finally {+ as.close();+ for (const k of ['RUFLO_OAUTH_ISSUER','RUFLO_OAUTH_JWKS_URI','RUFLO_PUBLIC_URL','RUFLO_OAUTH_CLIENT_ID']) {+ if (prev[k] === undefined) delete process.env[k]; else process.env[k] = prev[k];+ }+ }+});