Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

feat(federation): OAuth 2.1 resource server, and retract the Cloud Run header claim

ruv51f3a0a22e96
diff --git a/plugins/ruflo-chatgpt-federation/README.md b/plugins/ruflo-chatgpt-federation/README.md
index 22ba4656c8..84797d43f4 100644
--- a/plugins/ruflo-chatgpt-federation/README.md
+++ b/plugins/ruflo-chatgpt-federation/README.md
@@ -91,9 +91,41 @@ forgets to pin fails loudly instead of rolling the identity over.
connector that cannot mint a Google ID token. Authority to publish comes from the
caller token, not from Cloud Run IAM.
-Send that token as **`x-caller-token`**, not `Authorization`. Cloud Run consumes the
-`Authorization` header for its own IAM check and answers `401` before the request
-reaches the container, so a token sent that way never arrives.
+`Authorization` carries the OAuth access token (see below). The transitional
+`x-caller-token` header is a separate, temporary door that closes when
+`CGF_OAUTH_REQUIRED=true`.
+
+> An earlier version of this file claimed Cloud Run strips or rejects `Authorization`
+> on public services. That was wrong. Retested across every header shape β€” absent,
+> garbage, JWT-shaped, non-Bearer scheme, and the real token β€” on both `GET /` and
+> `POST /mcp`: all 200, header delivered. The single 401 that produced the claim never
+> reproduced.
+
+## Authorization
+
+OAuth 2.1 against Cognitum's authorization server, which is public-client + PKCE β€”
+`token_endpoint_auth_methods_supported: ["none"]`, so **there is no client secret in
+this design**.
+
+| | |
+|---|---|
+| Issuer | `https://auth.cognitum.one` |
+| Authorize | `https://auth.cognitum.one/oauth/authorize` |
+| Token | `https://auth.cognitum.one/oauth/token` |
+| JWKS | `https://auth.cognitum.one/.well-known/jwks.json` |
+| Resource metadata | `<service>/.well-known/oauth-protected-resource` (RFC 9728) |
+| Scopes | `federation:read` for the two reads, `federation:publish` for the write |
+| Audience | the service URL β€” a token minted for another Cognitum resource is refused |
+
+An unauthenticated or unverifiable request to `/mcp` gets `401` with
+`WWW-Authenticate: Bearer resource_metadata="…"`, which is what starts a client's
+discovery.
+
+`CGF_OAUTH_REQUIRED` is the switch. Unset, reads stay open and `x-caller-token` still
+authorises publish, so the connector keeps working while the authorization server side
+is registered. Set to `true`, both transitional doors close and every call needs a
+scoped token. Flip it only once OAuth has passed end to end β€” that is the last step,
+not the first.
## Rotate
diff --git a/plugins/ruflo-chatgpt-federation/package-lock.json b/plugins/ruflo-chatgpt-federation/package-lock.json
index 10fff98300..c879c934c2 100644
--- a/plugins/ruflo-chatgpt-federation/package-lock.json
+++ b/plugins/ruflo-chatgpt-federation/package-lock.json
@@ -10,6 +10,7 @@
"license": "MIT",
"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-chatgpt-federation/package.json b/plugins/ruflo-chatgpt-federation/package.json
index 5222821dc9..9352dd02e4 100644
--- a/plugins/ruflo-chatgpt-federation/package.json
+++ b/plugins/ruflo-chatgpt-federation/package.json
@@ -11,10 +11,13 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0",
+ "jose": "^6.2.12",
"nostr-tools": "^2.7.0",
"ws": "^8.18.0",
"zod": "^3.23.0"
},
- "engines": { "node": ">=20" },
+ "engines": {
+ "node": ">=20"
+ },
"license": "MIT"
}
diff --git a/plugins/ruflo-chatgpt-federation/src/oauth.mjs b/plugins/ruflo-chatgpt-federation/src/oauth.mjs
new file mode 100644
index 0000000000..a353fdbf6b
--- /dev/null
+++ b/plugins/ruflo-chatgpt-federation/src/oauth.mjs
@@ -0,0 +1,82 @@
+/**
+ * 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 three 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.
+ *
+ * The Nostr key is not reachable from here. OAuth decides *who may ask*; the
+ * signing key answers, and never leaves `signing-key.mjs`.
+ */
+import { createRemoteJWKSet, jwtVerify } from 'jose';
+
+export const SCOPE_READ = 'federation:read';
+export const SCOPE_PUBLISH = 'federation: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
+ * resource must not act on the federation identity just because it is signed by
+ * the same issuer. That is the whole point of RFC 8707.
+ *
+ * @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) {
+ const code = e?.code === 'ERR_JWT_EXPIRED' ? 'invalid_token' : 'invalid_token';
+ return { ok: false, error: code, description: String(e?.message || 'token verification failed').slice(0, 200) };
+ }
+}
+
+/** 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-chatgpt-federation/src/server.mjs b/plugins/ruflo-chatgpt-federation/src/server.mjs
index 5a9028d43f..43217cde1b 100644
--- a/plugins/ruflo-chatgpt-federation/src/server.mjs
+++ b/plugins/ruflo-chatgpt-federation/src/server.mjs
@@ -5,12 +5,20 @@
* GET / service info (pubkey is public; nothing else is)
* POST /mcp MCP, stateless
*
- * Surface is deliberately three tools and no resources. `federation_identity` and
- * `channel_sync` are open reads. `channel_publish` is the only write, it publishes
- * only to `pub:` channels, and it requires the caller token β€” because that token,
- * not the model, is what authorises speaking as this federation identity.
+ * Surface is deliberately three tools and no resources.
*
- * The signing key is never an input, an output, a resource, or a log line.
+ * Authorisation is OAuth 2.1 against Cognitum's authorization server: a bearer
+ * token in `Authorization`, validated here against the issuer's JWKS, carrying
+ * `federation:read` for the two reads and `federation:publish` for the write.
+ * There is no client secret in this design β€” that server is public-client + PKCE.
+ *
+ * While OAuth is being wired up (CGF_OAUTH_REQUIRED unset), the service still
+ * accepts the older `x-caller-token` for publish and leaves reads open, so the
+ * connector keeps working through the transition. Setting CGF_OAUTH_REQUIRED
+ * closes both of those and is the end state.
+ *
+ * OAuth decides who may ask. The signing key answers, and is never an input, an
+ * output, a resource, or a log line.
*/
import { createServer } from 'node:http';
import { timingSafeEqual } from 'node:crypto';
@@ -19,6 +27,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
import { z } from 'zod';
import { loadSigner, redact } from './signing-key.mjs';
import { publishToChannel, readChannel, PUBLIC_CHANNEL_RE } from './publisher.mjs';
+import { protectedResourceMetadata, challengeHeader, verifyAccessToken, hasScope, SCOPE_READ, SCOPE_PUBLISH } from './oauth.mjs';
const VERSION = '0.1.0';
const MAX_BODY = 256 * 1024;
@@ -50,9 +59,38 @@ export function createPublisherService({ relay, keyPath, port } = {}) {
const RELAY = relay || process.env.CGF_RELAY_URL || 'wss://relay.ruv.io';
const signer = loadSigner(keyPath); // throws at boot if custody is wrong β€” by design
const text = (o) => ({ content: [{ type: 'text', text: JSON.stringify(o) }] });
+ // An OAuth caller must carry the scope; a legacy caller (no token, OAuth not yet
+ // mandatory) keeps the reads it has always had.
+ const needs = (auth, scope) => (auth.mode !== 'oauth' || hasScope(auth.scopes, scope))
+ ? null
+ : { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: `access token lacks ${scope}` }) }] };
const fail = (e) => ({ isError: true, content: [{ type: 'text', text: JSON.stringify({ error: redact(e?.message || e) }) }] });
- function buildMcp(req) {
+ const OAUTH_ISSUER = process.env.CGF_OAUTH_ISSUER || 'https://auth.cognitum.one';
+ const OAUTH_JWKS = process.env.CGF_OAUTH_JWKS_URI || `${OAUTH_ISSUER}/.well-known/jwks.json`;
+ const OAUTH_REQUIRED = String(process.env.CGF_OAUTH_REQUIRED || '') === 'true';
+ const resourceUrl = () => (process.env.CGF_PUBLIC_URL || '').replace(/\/$/, '');
+ const prmUrl = () => `${resourceUrl()}/.well-known/oauth-protected-resource`;
+
+ /**
+ * Resolve what this request is allowed to do.
+ * oauth β€” a verified token; scopes decide.
+ * legacy β€” no token at all, and OAuth is not yet mandatory.
+ * denied β€” a token that did not verify, or none while OAuth is mandatory.
+ */
+ async function authContext(req) {
+ const bearer = String(req?.headers?.authorization || '').match(/^Bearer\s+(.+)$/i)?.[1]?.trim();
+ if (bearer) {
+ const v = await verifyAccessToken(bearer, { issuer: OAUTH_ISSUER, jwksUri: OAUTH_JWKS,
+ audience: resourceUrl() || undefined });
+ if (!v.ok) return { mode: 'denied', ...v };
+ return { mode: 'oauth', scopes: v.scopes, subject: v.subject };
+ }
+ if (OAUTH_REQUIRED) return { mode: 'denied', error: 'invalid_request', description: 'authorization required' };
+ return { mode: 'legacy', scopes: [] };
+ }
+
+ 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
@@ -65,14 +103,15 @@ export function createPublisherService({ relay, keyPath, port } = {}) {
mcp.tool('federation_identity',
'This connector\'s federation identity: the Nostr public key it signs with, and the relay it publishes to. Use when you need to know who the federation will see as the author, or to verify a published event came from this connector. The secret key is never returned by any tool.',
{},
- async () => text({ pubkey: signer.pubkey, relay: RELAY, service: 'ruflo-chatgpt-federation', version: VERSION }));
+ async () => needs(auth, SCOPE_READ) ?? text({ pubkey: signer.pubkey, relay: RELAY, service: 'ruflo-chatgpt-federation', version: VERSION }));
mcp.tool('channel_sync',
'Read recent messages from a ruflo swarm channel (e.g. pub:announce, pub:help). Use before publishing, to see what has already been said and avoid duplicating it. Private (prv:) channels are returned as opaque ciphertext because this connector holds no channel keys.',
{ channel: z.string().optional().describe('Channel id, e.g. "pub:announce". Omit for the whole swarm stream.'),
sinceSeconds: z.number().optional().describe('Look-back window in seconds (default 3600).'),
limit: z.number().optional().describe('Maximum events to return (default 100).') },
- async (a) => { try { const msgs = await readChannel(RELAY, signer, a); return text({ count: msgs.length, messages: msgs }); } catch (e) { return fail(e); } });
+ async (a) => { const no = needs(auth, SCOPE_READ); if (no) return no;
+ try { const msgs = await readChannel(RELAY, signer, a); return text({ count: msgs.length, messages: msgs }); } catch (e) { return fail(e); } });
mcp.tool('channel_publish',
'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.',
@@ -81,8 +120,15 @@ export function createPublisherService({ relay, keyPath, port } = {}) {
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 }) => {
- if (!checkCaller(callerToken ?? header)) {
- return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: 'caller token required or invalid' }) }] };
+ // 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);
+ if (!viaOauth && !viaLegacy) {
+ const why = auth.mode === 'oauth'
+ ? `access token lacks ${SCOPE_PUBLISH}`
+ : 'caller token required or invalid';
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: why }) }] };
}
if (!PUBLIC_CHANNEL_RE.test(String(channel))) return fail(new Error('channel must be a public pub:<name> channel'));
try { return text({ ok: true, ...(await publishToChannel(RELAY, signer, { channel, msgType, payload })) }); }
@@ -102,12 +148,31 @@ export function createPublisherService({ relay, keyPath, port } = {}) {
return res.end(JSON.stringify({ service: 'ruflo-chatgpt-federation', version: VERSION, mcp: '/mcp',
relay: RELAY, pubkey: signer.pubkey,
tools: ['federation_identity', 'channel_sync', 'channel_publish'],
- publishAuth: 'x-caller-token: <caller token>' }));
+ authorization: { type: 'oauth2', issuer: OAUTH_ISSUER,
+ scopes: [SCOPE_READ, SCOPE_PUBLISH],
+ protectedResourceMetadata: prmUrl(),
+ enforced: OAUTH_REQUIRED,
+ transitionalHeader: OAUTH_REQUIRED ? null : 'x-caller-token' } }));
+ }
+ // RFC 9728 discovery. Served at both the bare path and the /mcp-suffixed one,
+ // because clients differ on which they probe.
+ if (url.pathname === '/.well-known/oauth-protected-resource'
+ || url.pathname === '/.well-known/oauth-protected-resource/mcp') {
+ res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });
+ return res.end(JSON.stringify(protectedResourceMetadata({
+ resource: resourceUrl() || `https://${req.headers.host}`, issuer: OAUTH_ISSUER })));
}
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 authContext(req);
+ if (auth.mode === 'denied') {
+ // 401 + WWW-Authenticate is what starts a client's OAuth discovery.
+ res.writeHead(401, { 'content-type': 'application/json',
+ 'www-authenticate': challengeHeader(prmUrl(), { error: auth.error, description: auth.description }) });
+ return res.end(JSON.stringify({ error: auth.error, error_description: auth.description }));
+ }
+ 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-chatgpt-federation/test/oauth.test.mjs b/plugins/ruflo-chatgpt-federation/test/oauth.test.mjs
new file mode 100644
index 0000000000..b97260c479
--- /dev/null
+++ b/plugins/ruflo-chatgpt-federation/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 { writeFileSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { generateKeyPair, exportJWK, SignJWT } from 'jose';
+import { generateSecretKey } from 'nostr-tools/pure';
+import { createPublisherService } from '../src/server.mjs';
+import { protectedResourceMetadata, challengeHeader, SCOPE_READ, SCOPE_PUBLISH } from '../src/oauth.mjs';
+
+const dir = mkdtempSync(join(tmpdir(), 'cgf-oauth-'));
+const keyPath = join(dir, 'signing-key');
+writeFileSync(keyPath, Buffer.from(generateSecretKey()).toString('hex'), { mode: 0o600 });
+
+// A stand-in authorization server: publishes a JWKS and mints tokens we control.
+async function fakeAuthServer() {
+ const { publicKey, privateKey } = await generateKeyPair('RS256');
+ const jwk = { ...(await exportJWK(publicKey)), kid: 'test-1', 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, expSeconds = 300 }) =>
+ new SignJWT({ scope })
+ .setProtectedHeader({ alg: 'RS256', kid: 'test-1' })
+ .setIssuer(iss).setAudience(audience).setSubject('user-1')
+ .setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1000) + expSeconds)
+ .sign(privateKey);
+ return { issuer, jwksUri: `${issuer}/.well-known/jwks.json`, mint, close: () => srv.close() };
+}
+
+async function withService(as, { required, publicUrl }, fn) {
+ const prev = { ...process.env };
+ Object.assign(process.env, {
+ CGF_OAUTH_ISSUER: as.issuer, CGF_OAUTH_JWKS_URI: as.jwksUri,
+ CGF_PUBLIC_URL: publicUrl, CGF_OAUTH_REQUIRED: required ? 'true' : '',
+ });
+ const svc = createPublisherService({ relay: 'ws://127.0.0.1:1', keyPath });
+ const port = await svc.listen(0);
+ try { return await fn(port, svc); }
+ finally { svc.server.close(); for (const k of ['CGF_OAUTH_ISSUER','CGF_OAUTH_JWKS_URI','CGF_PUBLIC_URL','CGF_OAUTH_REQUIRED']) { 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: '));
+ return { status: r.status, wwwAuth: r.headers.get('www-authenticate'),
+ body: line || raw.startsWith('{') ? JSON.parse(line ? line.slice(6) : raw) : raw };
+ });
+
+const toolText = (b) => b.result?.content?.[0]?.text ?? JSON.stringify(b);
+
+test('protected-resource metadata names the authorization server and both scopes', () => {
+ const m = protectedResourceMetadata({ resource: 'https://x.example', issuer: 'https://auth.example' });
+ assert.equal(m.resource, 'https://x.example');
+ assert.deepEqual(m.authorization_servers, ['https://auth.example']);
+ assert.deepEqual(m.scopes_supported, ['federation:read', 'federation:publish']);
+ assert.deepEqual(m.bearer_methods_supported, ['header']);
+});
+
+test('the challenge header points a client at discovery', () => {
+ const h = challengeHeader('https://x.example/.well-known/oauth-protected-resource', { error: 'invalid_token' });
+ assert.match(h, /^Bearer resource_metadata="https:\/\/x\.example\/\.well-known\/oauth-protected-resource"/);
+ assert.match(h, /error="invalid_token"/);
+});
+
+test('discovery is served at both paths clients probe', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ for (const path of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp']) {
+ const r = await fetch(`http://127.0.0.1:${port}${path}`);
+ assert.equal(r.status, 200, path);
+ const m = await r.json();
+ assert.deepEqual(m.authorization_servers, [as.issuer]);
+ assert.equal(m.resource, 'https://cgf.example');
+ }
+ });
+ } finally { as.close(); }
+});
+
+test('with OAuth required, an unauthenticated call gets 401 and a discovery pointer', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const r = await call(port, 'federation_identity');
+ assert.equal(r.status, 401);
+ assert.match(r.wwwAuth, /resource_metadata="https:\/\/cgf\.example\/\.well-known\/oauth-protected-resource"/);
+ });
+ } finally { as.close(); }
+});
+
+test('a token from another issuer is refused', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const tok = await as.mint({ scope: SCOPE_READ, audience: 'https://cgf.example', issuer: 'https://evil.example' });
+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });
+ assert.equal(r.status, 401);
+ assert.match(r.wwwAuth, /error="invalid_token"/);
+ });
+ } finally { as.close(); }
+});
+
+test('a token minted for a different resource is refused', async () => {
+ // Same issuer, wrong audience. Without this check any Cognitum token would be
+ // able to act on the federation identity β€” which is the point of RFC 8707.
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const tok = await as.mint({ scope: SCOPE_PUBLISH, audience: 'https://some-other.cognitum.one' });
+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });
+ assert.equal(r.status, 401);
+ });
+ } finally { as.close(); }
+});
+
+test('an expired token is refused', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const tok = await as.mint({ scope: SCOPE_READ, audience: 'https://cgf.example', expSeconds: -3600 });
+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });
+ assert.equal(r.status, 401);
+ });
+ } finally { as.close(); }
+});
+
+test('federation:read reads, but does not publish', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port, svc) => {
+ const tok = await as.mint({ scope: SCOPE_READ, audience: 'https://cgf.example' });
+ const auth = { authorization: `Bearer ${tok}` };
+
+ const id = await call(port, 'federation_identity', {}, auth);
+ assert.equal(id.status, 200);
+ assert.equal(JSON.parse(toolText(id.body)).pubkey, svc.pubkey);
+
+ const pub = await call(port, 'channel_publish',
+ { channel: 'pub:announce', msgType: 'Status', payload: {} }, auth);
+ assert.match(toolText(pub.body), /lacks federation:publish/);
+ });
+ } finally { as.close(); }
+});
+
+test('a scopeless token cannot even read', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const tok = await as.mint({ scope: '', audience: 'https://cgf.example' });
+ const r = await call(port, 'federation_identity', {}, { authorization: `Bearer ${tok}` });
+ assert.match(toolText(r.body), /lacks federation:read/);
+ });
+ } finally { as.close(); }
+});
+
+test('federation:publish reaches the publish path (and fails only at the relay)', async () => {
+ const as = await fakeAuthServer();
+ try {
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const tok = await as.mint({ scope: `${SCOPE_READ} ${SCOPE_PUBLISH}`, audience: 'https://cgf.example' });
+ const r = await call(port, 'channel_publish',
+ { channel: 'pub:announce', msgType: 'Status', payload: {} }, { authorization: `Bearer ${tok}` });
+ // Authorisation passed; the relay is unreachable in this test, which is how
+ // we know the request got past the gate rather than being refused by it.
+ assert.equal(r.status, 200);
+ assert.doesNotMatch(toolText(r.body), /lacks federation:publish|caller token/);
+ });
+ } finally { as.close(); }
+});
+
+test('the transitional caller token still works only while OAuth is not enforced', async () => {
+ const as = await fakeAuthServer();
+ const prev = process.env.CGF_CALLER_TOKEN;
+ process.env.CGF_CALLER_TOKEN = 'transitional';
+ try {
+ await withService(as, { required: false, publicUrl: 'https://cgf.example' }, async (port) => {
+ const open = await call(port, 'federation_identity');
+ assert.equal(open.status, 200, 'reads stay open during the transition');
+ const pub = await call(port, 'channel_publish',
+ { channel: 'pub:announce', msgType: 'Status', payload: {} }, { 'x-caller-token': 'transitional' });
+ assert.doesNotMatch(toolText(pub.body), /caller token required/);
+ });
+ await withService(as, { required: true, publicUrl: 'https://cgf.example' }, async (port) => {
+ const pub = await call(port, 'channel_publish',
+ { channel: 'pub:announce', msgType: 'Status', payload: {} }, { 'x-caller-token': 'transitional' });
+ assert.equal(pub.status, 401, 'enforcing OAuth must close the transitional door');
+ });
+ } finally { as.close(); if (prev === undefined) delete process.env.CGF_CALLER_TOKEN; else process.env.CGF_CALLER_TOKEN = prev; }
+});
+
+test('the service info advertises the authorization server and enforcement state', async () => {
+ // This block is how an operator (and a human debugging a connector) learns which
+ // AS to use and whether the transitional door is still open. It silently missed
+ // its patch anchor once; this test is why that cannot recur unnoticed.
+ const as = await fakeAuthServer();
+ try {
+ for (const required of [false, true]) {
+ await withService(as, { required, publicUrl: 'https://cgf.example' }, async (port) => {
+ const info = await (await fetch(`http://127.0.0.1:${port}/`)).json();
+ assert.equal(info.authorization.type, 'oauth2');
+ assert.equal(info.authorization.issuer, as.issuer);
+ assert.deepEqual(info.authorization.scopes, [SCOPE_READ, SCOPE_PUBLISH]);
+ assert.equal(info.authorization.protectedResourceMetadata,
+ 'https://cgf.example/.well-known/oauth-protected-resource');
+ assert.equal(info.authorization.enforced, required);
+ assert.equal(info.authorization.transitionalHeader, required ? null : 'x-caller-token');
+ });
+ }
+ } finally { as.close(); }
+});
diff --git a/plugins/ruflo-chatgpt-federation/test/publisher.test.mjs b/plugins/ruflo-chatgpt-federation/test/publisher.test.mjs
index 8a9a2d3db1..7649829819 100644
--- a/plugins/ruflo-chatgpt-federation/test/publisher.test.mjs
+++ b/plugins/ruflo-chatgpt-federation/test/publisher.test.mjs
@@ -211,7 +211,9 @@ async function rpc(port, body, headers = {}) {
body: JSON.stringify(body) });
const raw = await res.text();
const line = raw.split('\n').find((l) => l.startsWith('data: '));
- return JSON.parse(line ? line.slice(6) : raw);
+ const out = JSON.parse(line ? line.slice(6) : raw);
+ out._status = res.status; out._wwwAuth = res.headers.get('www-authenticate');
+ return out;
}
test('the MCP surface is exactly three tools, and none of them can return the key', async () => {
@@ -243,12 +245,15 @@ test('channel_publish refuses without the caller token and publishes with it', a
params: { name: 'channel_publish', arguments: { channel: 'pub:announce', msgType: 'Status', payload: {} } } });
assert.match(denied.result.content[0].text, /caller token required/);
- // Authorization is NOT the channel: Cloud Run consumes it upstream, so a
- // client that sends the token there must be told no, not silently allowed.
+ // Authorization is the OAuth channel now, so the caller token sent there is
+ // not a caller token at all β€” it is an unverifiable access token, and the
+ // answer is a 401 that starts discovery, not a quiet grant.
const wrongHeader = await rpc(port, { jsonrpc: '2.0', id: 3, method: 'tools/call',
params: { name: 'channel_publish', arguments: { channel: 'pub:announce', msgType: 'Status', payload: {} } } },
{ authorization: 'Bearer test-caller-token' });
- assert.match(wrongHeader.result.content[0].text, /caller token required/);
+ assert.equal(wrongHeader._status, 401);
+ assert.match(wrongHeader._wwwAuth || '', /^Bearer resource_metadata=/);
+ assert.match(wrongHeader._wwwAuth || '', /error="invalid_token"/);
const ok = await rpc(port, { jsonrpc: '2.0', id: 2, method: 'tools/call',
params: { name: 'channel_publish', arguments: { channel: 'pub:announce', msgType: 'Status', payload: { note: 'hi' } } } },