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

fix(gateway): three bugs that made ChatGPT connector setup fail after sign-in

ruv40c1744ec836
diff --git a/plugins/ruflo-x-gateway/src/oauth.mjs b/plugins/ruflo-x-gateway/src/oauth.mjs
index ad0f835af4..b551a81a3f 100644
--- a/plugins/ruflo-x-gateway/src/oauth.mjs
+++ b/plugins/ruflo-x-gateway/src/oauth.mjs
@@ -71,19 +71,37 @@ export function _resetJwksForTest() { jwks = null; jwksFor = null; }
*
* @returns {Promise<{ ok: true, scopes: string[], subject?: string } | { ok: false, error: string, description: string }>}
*/
-export async function verifyAccessToken(token, { issuer, jwksUri, audience }) {
+export async function verifyAccessToken(token, { issuer, jwksUri, audience, audienceOk }) {
if (!token) return { ok: false, error: 'invalid_request', description: 'no bearer token' };
try {
+ // Audience is checked BELOW rather than by jose, because a single expected
+ // value cannot express "this resource's own client, or any client that
+ // dynamically registered for it". jose would need the full list up front,
+ // and the DCR set changes at runtime.
const { payload } = await jwtVerify(token, keySet(jwksUri), {
issuer,
- ...(audience ? { audience } : {}),
clockTolerance: 30,
});
+ const auds = payload.aud === undefined ? []
+ : (Array.isArray(payload.aud) ? payload.aud.map(String) : [String(payload.aud)]);
+ if (audience || audienceOk) {
+ // An aud-less token is never acceptable: it is bound to no resource, so
+ // any resource accepting it becomes a confused deputy.
+ if (auds.length === 0) {
+ return { ok: false, error: 'invalid_token', observedAudience: '-',
+ description: 'token carries no aud claim, so it is not bound to this resource' };
+ }
+ const accept = audienceOk || ((a) => a === audience);
+ if (!auds.some(accept)) {
+ return { ok: false, error: 'invalid_token', observedAudience: auds.join(','),
+ description: `token audience (${auds.join(',')}) is not this resource` };
+ }
+ }
// `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 };
+ return { ok: true, scopes, subject: payload.sub ? String(payload.sub) : undefined, audience: auds[0] };
} 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
@@ -98,7 +116,7 @@ export async function verifyAccessToken(token, { issuer, jwksUri, audience }) {
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 ((audience || audienceOk) && !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 };
diff --git a/plugins/ruflo-x-gateway/src/server.mjs b/plugins/ruflo-x-gateway/src/server.mjs
index b96dfd0def..ae12d6f086 100644
--- a/plugins/ruflo-x-gateway/src/server.mjs
+++ b/plugins/ruflo-x-gateway/src/server.mjs
@@ -57,10 +57,21 @@ export function createGateway({ relay, keyFile, port } = {}) {
return { mode: 'denied', error: 'invalid_request',
description: 'this deployment has no OAuth audience configured and will not accept bearer tokens' };
}
+ // Accept this resource's own client, AND any client that registered itself
+ // through RFC 7591 dynamic registration. A `dcr-` client is constrained at
+ // registration to swarm:* / openid / email — this resource's own scopes —
+ // so by construction its token was minted FOR this resource. Rejecting it
+ // would make dynamic registration useless: a self-registered client's token
+ // carries aud=<its own client_id>, never `ruflo-x-gateway`.
+ //
+ // This is exactly as strong as the registration gate: if `federation:*` or
+ // any other resource's scopes ever become self-registrable, this stops being
+ // safe. Keep those two facts together.
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 };
+ audienceOk: (aud) => aud === OAUTH_CLIENT_ID || aud.startsWith('dcr-') });
+ return v.ok ? { mode: 'oauth', scopes: v.scopes, subject: v.subject, audience: v.audience }
+ : { mode: 'denied', error: v.error, description: v.description,
+ observedAudience: v.observedAudience };
}
const text = (o) => ({ content: [{ type: 'text', text: JSON.stringify(o) }] });
@@ -201,10 +212,29 @@ export function createGateway({ relay, keyFile, port } = {}) {
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' && req.method === 'GET') {
+ // Streamable HTTP allows a GET to open a server->client SSE stream, but
+ // this transport is STATELESS (sessionIdGenerator: undefined) so there is
+ // no session to attach one to: the SDK holds the socket open and Cloud Run
+ // eventually severs it at 300s with "Truncated response body". A client
+ // probing GET then waits five minutes instead of failing in milliseconds.
+ // 405 is the spec's answer for a server that does not offer the GET stream.
+ res.writeHead(405, { 'content-type': 'application/json', allow: 'POST, OPTIONS' });
+ return res.end(JSON.stringify({ error: 'method_not_allowed',
+ error_description: 'this MCP endpoint is stateless; use POST' }));
+ }
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 auth = await oauthContext(req);
+ // Log BEFORE the refusal, or a denied request leaves no trace and the logs
+ // say "no token arrived" when a token arrived and was rejected. That blind
+ // spot cost a live debugging session.
+ 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}`
+ + (auth.mode === 'denied' ? ` reason=${auth.error} aud=${auth.observedAudience || '-'}` : ''));
+ } catch { /* logging must never break a request */ }
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
@@ -213,10 +243,6 @@ export function createGateway({ relay, keyFile, port } = {}) {
'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);
diff --git a/plugins/ruflo-x-gateway/test/oauth.test.mjs b/plugins/ruflo-x-gateway/test/oauth.test.mjs
index 3ea084c83f..e155c80458 100644
--- a/plugins/ruflo-x-gateway/test/oauth.test.mjs
+++ b/plugins/ruflo-x-gateway/test/oauth.test.mjs
@@ -135,7 +135,11 @@ test('a browser-session token (no iss/aud) cannot act here', async () => {
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/);
+ // Assert the PROPERTY, not the wording: a session token is refused because
+ // it is bound to no resource. Which claim is named first depends on
+ // verification order and is not what matters.
+ assert.match(r.wwwAuth || '', /not bound to this resource/);
+ assert.match(r.wwwAuth || '', /carries no (iss|aud)/);
});
} finally { as.close(); }
});
@@ -220,3 +224,43 @@ test('with no audience configured, a bearer token is refused rather than honoure
}
}
});
+
+test('a dynamically registered client\'s token is accepted; a stranger\'s is not', async () => {
+ // DCR mints clients whose tokens carry aud=<their own client_id>, never
+ // `ruflo-x-gateway` — so pinning a single audience made dynamic registration
+ // useless. This resource accepts `dcr-` audiences BECAUSE registration
+ // constrains those clients to this resource's own scopes. If that constraint
+ // is ever loosened, this acceptance stops being safe.
+ const as = await fakeAuthServer();
+ try {
+ await withGateway(as, async (port) => {
+ const dcr = await as.mint({ scope: SCOPE_PUBLISH, audience: 'dcr-0123456789abcdef' });
+ const ok = await call(port, 'federation_identity', {}, { authorization: `Bearer ${dcr}` });
+ assert.equal(ok.status, 200, 'a dcr- client must be able to use this resource');
+
+ // Still refused: another Cognitum resource's client.
+ const other = await as.mint({ scope: SCOPE_PUBLISH, audience: 'chatgpt-federation' });
+ assert.equal((await call(port, 'federation_identity', {}, { authorization: `Bearer ${other}` })).status, 401);
+
+ // And a name that merely CONTAINS dcr- must not pass — prefix, not substring.
+ const sneaky = await as.mint({ scope: SCOPE_PUBLISH, audience: 'not-a-dcr-client' });
+ assert.equal((await call(port, 'federation_identity', {}, { authorization: `Bearer ${sneaky}` })).status, 401,
+ 'audience matching must be a prefix check, not a substring check');
+ });
+ } finally { as.close(); }
+});
+
+test('GET /mcp is refused immediately instead of hanging a stateless stream', async () => {
+ // It used to hold the socket until Cloud Run severed it at 300s, so a client
+ // probing GET waited five minutes instead of failing in milliseconds.
+ const as = await fakeAuthServer();
+ try {
+ await withGateway(as, async (port) => {
+ const t0 = Date.now();
+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, { headers: { accept: 'text/event-stream' } });
+ assert.equal(r.status, 405);
+ assert.match(r.headers.get('allow') || '', /POST/);
+ assert.ok(Date.now() - t0 < 2000, 'must answer immediately, not hold the stream open');
+ });
+ } finally { as.close(); }
+});