Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(rpc-proxy): add PATCH session rename passthrough (spec 15 Phase B)
Diego Zacarias208ff57987de
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 4ca7b2106..e05f725d5 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -9,7 +9,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.7.0',externalRestApiVersion: '0.1.81',- rpcProxyVersion: '0.1.72',+ rpcProxyVersion: '0.1.73',desktopVersion: '0.7.0',minimumDesktopVersion: '0.1.252',}diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex bfac45897..aeb8c39d7 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.72",+ "version": "0.1.73","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.72",+ "version": "0.1.73","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex 8d4faf29f..7a8ab6132 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.72",+ "version": "0.1.73","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts b/rpc-proxy/src/__tests__/session-rename-passthrough.test.tsnew file mode 100644index 000000000..a0d3a15ac--- /dev/null+++ b/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts@@ -0,0 +1,220 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { createApp } from '../app.js'+import { createRpcRouter } from '../routes/rpc.js'++const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))+const serviceMock = vi.hoisted(() => ({+ resolveHostConnectionForUser: vi.fn(),+}))++vi.mock('../authToken.js', () => authTokenMock)+vi.mock('../services/mcpProxyService.js', () => serviceMock)++// Spec 15 Fase B / BP1 — PATCH rename passthrough. The rename write path is a+// distinct scope (host:session:write) from the session reads and is NOT+// wake-eligible, so the token carries only host:session:write.+const VALID_CLAIMS = {+ sub: 'user-uuid-123',+ typ: 'user' as const,+ accessScope: 'team' as const,+ teamId: 'team-1',+ scopes: ['host:session:write'],+ hostRefs: ['chatllm'],+ jti: 'j1',+ iat: 1,+ exp: 9999999999,+}++// Edge identity headers are the trust boundary: mcp-host's runtimeEdgeGuard+// trusts x-clerum-edge-user-id (set by the proxy) and rejects any client+// Authorization. resolveHostConnectionForUser is what injects these; the route+// forwards ONLY host.headers, never the inbound Authorization.+const HOST_CONNECTION = {+ name: 'chatllm',+ url: 'http://chatllm:8080',+ headers: {+ 'x-clerum-edge-caller': 'rpc-proxy',+ 'x-clerum-edge-host-ref': 'chatllm',+ 'x-clerum-edge-user-id': 'user-uuid-123',+ },+}++function makeApp() {+ const app = express()+ app.use(express.json())+ app.use(createRpcRouter())+ return app+}++describe('PATCH /rpc/hosts/:hostRef/sessions/:agent/:chatId/name — rename passthrough', () => {+ beforeEach(() => {+ authTokenMock.verifyRpcToken.mockReturnValue(VALID_CLAIMS)+ serviceMock.resolveHostConnectionForUser.mockResolvedValue(HOST_CONNECTION)+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('forwards PATCH to mcp-host with :agent and :chatId in the path and body verbatim', async () => {+ const upstream = { ok: true }+ const fetchMock = vi.fn().mockResolvedValue({+ status: 200,+ headers: new Headers({ 'content-type': 'application/json' }),+ text: async () => JSON.stringify(upstream),+ } as unknown as Response)+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'Quarterly planning' })+ .expect(200)++ expect(res.body).toEqual(upstream)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ const [url, init] = fetchMock.mock.calls[0]+ expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions/chatllm/c1/name')+ expect((init as RequestInit).method).toBe('PATCH')+ // Only the edge headers are forwarded; the client Authorization is not.+ expect((init as RequestInit).headers).toMatchObject(HOST_CONNECTION.headers)+ expect((init as RequestInit).headers).not.toHaveProperty('authorization')+ expect((init as RequestInit).headers).not.toHaveProperty('Authorization')+ // Body reaches the upstream verbatim (re-serialized from the parsed JSON).+ expect((init as RequestInit).body).toBe(JSON.stringify({ title: 'Quarterly planning' }))+ // Bounded upstream timeout (copied from the session reads, unlike /model).+ expect((init as RequestInit).signal).toBeInstanceOf(AbortSignal)+ })++ it('returns 401 when no auth token is presented', async () => {+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .send({ title: 'x' })+ .expect(401)++ expect(fetchMock).not.toHaveBeenCalled()+ expect(serviceMock.resolveHostConnectionForUser).not.toHaveBeenCalled()+ })++ it('returns 403 when the token lacks host:session:write (read scope is not enough)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue({ ...VALID_CLAIMS, scopes: ['host:session:read'] })+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(403)++ expect(fetchMock).not.toHaveBeenCalled()+ expect(serviceMock.resolveHostConnectionForUser).not.toHaveBeenCalled()+ })++ it('returns 403 when the user cannot access the host', async () => {+ serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .patch('/rpc/hosts/other-host/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(403)++ expect(fetchMock).not.toHaveBeenCalled()+ })++ it.each([+ '/rpc/hosts/chatllm/sessions/agent%3Aother/c1/name',+ '/rpc/hosts/chatllm/sessions/agent%0Aother/c1/name',+ '/rpc/hosts/chatllm/sessions/agent/chat%0Aother/name',+ '/rpc/hosts/chat%2Fllm/sessions/chatllm/c1/name',+ ])('rejects unsafe route segments before forwarding upstream: %s', async path => {+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .patch(path)+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(400)++ expect(fetchMock).not.toHaveBeenCalled()+ expect(serviceMock.resolveHostConnectionForUser).not.toHaveBeenCalled()+ })++ it.each([+ { status: 400, body: { error: 'invalid title' } },+ { status: 403, body: { error: 'forbidden' } },+ { status: 404, body: { error: 'session not found' } },+ ])('propagates the upstream $status verbatim', async ({ status, body }) => {+ const fetchMock = vi.fn().mockResolvedValue({+ status,+ headers: new Headers({ 'content-type': 'application/json' }),+ text: async () => JSON.stringify(body),+ } as unknown as Response)+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(status)++ expect(res.body).toEqual(body)+ })++ it('maps a host-down fetch failure to a sanitized 502', async () => {+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed'))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ })++ it('maps an upstream timeout to a sanitized 504', async () => {+ const timeout = new DOMException('The operation was aborted due to timeout', 'TimeoutError')+ const fetchMock = vi.fn().mockRejectedValue(timeout)+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(createApp())+ .patch('/api/v1/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: 'x' })+ .expect(504)++ expect(res.body).toEqual({ error: 'Gateway Timeout' })+ })++ it('does not log the raw title value', async () => {+ const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})+ const fetchMock = vi.fn().mockResolvedValue({+ status: 200,+ headers: new Headers({ 'content-type': 'application/json' }),+ text: async () => JSON.stringify({ ok: true }),+ } as unknown as Response)+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const secret = 'super-secret-title-value'+ await request(makeApp())+ .patch('/rpc/hosts/chatllm/sessions/chatllm/c1/name')+ .set('authorization', 'Bearer user-token')+ .send({ title: secret })+ .expect(200)++ for (const call of infoSpy.mock.calls) {+ expect(JSON.stringify(call)).not.toContain(secret)+ }+ })+})diff --git a/rpc-proxy/src/authToken.ts b/rpc-proxy/src/authToken.tsindex 6e54ce19f..d23e2d848 100644--- a/rpc-proxy/src/authToken.ts+++ b/rpc-proxy/src/authToken.ts@@ -13,6 +13,7 @@ const ALLOWED_SCOPES = new Set<RpcScope>(['host:task:read','host:approval:write','host:session:read',+ 'host:session:write','host:model:write','desktop:view','sandbox:ui:view',diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex 3ca854768..48ade1fc8 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -958,6 +958,79 @@ export function createRpcRouter(): Router {})+ // Rename a session — write path, scoped to host:session:write (a distinct+ // scope from host:session:read, so a read/navigation token can never rename).+ // Passthrough to mcp-host PATCH /v1/runtime/sessions/:agent/:chatId/name: the+ // request body (the new title) is forwarded verbatim, and mcp-host owns title+ // validation, ownership, and the anti-enumeration 404, so its 400/403/404/200+ // pass through unchanged. Title content is NOT validated here (only the path+ // segments); the raw title value is never logged.+ //+ // Deliberately NOT wake-eligible: the Desktop App renames optimistically+ // (local-first) and reconciles on the next listSessions poll, so a suspended+ // host needs no wake-and-hold here — a network/timeout failure surfaces as the+ // ordinary 502/504 and the client keeps the pending rename to retry.+ router.patch(+ '/rpc/hosts/:hostRef/sessions/:agent/:chatId/name',+ requireRpcAuth,+ requireScope('host:session:write'),+ async (req: AuthedRequest, res, next) => {+ try {+ const auth = req.auth!+ const rpcAccessToken = extractAuthToken(req)+ const hostRef = String(req.params.hostRef || '').trim()+ const agent = String(req.params.agent || '').trim()+ const chatId = String(req.params.chatId || '').trim()+ if (+ !isSafeUpstreamPathSegment(hostRef) ||+ !isSafeUpstreamAgentSegment(agent) ||+ !isSafeUpstreamPathSegment(chatId)+ ) {+ res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })+ return+ }+ const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {+ teamId: auth.teamId,+ })+ if (!host) {+ res.status(403).json({ error: 'Forbidden: user cannot access this host' })+ return+ }+ const baseUrl = host.url.replace(/\/+$/, '')+ // Never log the raw title (spec 15 §5): titles are user content.+ console.info(+ `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=rename-session agent=${agent} chatId=${chatId}`+ )+ try {+ // Only host.headers carry the edge identity (x-clerum-edge-user-id and+ // the caller marker); the client Authorization is never forwarded, so+ // mcp-host's runtimeEdgeGuard stays satisfied. Body is re-serialized+ // from the parsed JSON and forwarded verbatim: unlike the /model write+ // path this route does no body-shape guard, since mcp-host owns title+ // validation and returns its own 400 for a malformed body.+ const response = await fetch(+ `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/name`,+ {+ method: 'PATCH',+ headers: { 'content-type': 'application/json', ...host.headers },+ body: JSON.stringify(req.body),+ signal: AbortSignal.timeout(config.upstreamTimeoutMs),+ }+ )+ const body = await response.text()+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ } catch (error) {+ respondUpstreamUnavailable(res, error)+ }+ } catch (error) {+ guardedNext(res, next, error)+ }+ }+ )+// List selectable models for the session — passthrough to mcp-host.// Read-only projection of the in-memory allowlist; scoped to host:session:read// (same as the other session reads). Passes the optional chatId query throughdiff --git a/rpc-proxy/src/types.ts b/rpc-proxy/src/types.tsindex 97fcf4896..aaeccd7a6 100644--- a/rpc-proxy/src/types.ts+++ b/rpc-proxy/src/types.ts@@ -9,6 +9,7 @@ export type RpcScope =| 'host:task:read'| 'host:approval:write'| 'host:session:read'+ | 'host:session:write'| 'host:model:write'| 'desktop:view'| 'sandbox:ui:view'