diff --git a/.gitea/workflows/hermes-runtime-contract.yml b/.gitea/workflows/hermes-runtime-contract.yml new file mode 100644 index 00000000..29b6bb61 --- /dev/null +++ b/.gitea/workflows/hermes-runtime-contract.yml @@ -0,0 +1,24 @@ +name: Hermes runtime contract review (NO DEPLOY) +on: + workflow_dispatch: +permissions: + contents: read +jobs: + contract-review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + cache-dependency-path: backend/package-lock.json + - run: npm ci --ignore-scripts --no-audit + working-directory: backend + - run: npm test -- --runInBand hermes-management + working-directory: backend + - run: npx tsc -p src/hermes-management/tsconfig.contract.json --noEmit + working-directory: backend + - run: npx tsc -p src/hermes-management/tsconfig.contract.json + working-directory: backend + # No SSH, Docker socket, secrets, deployments, dispatch or runtime mutation. diff --git a/backend/src/hermes-management/hermes-integration.service.spec.ts b/backend/src/hermes-management/hermes-integration.service.spec.ts new file mode 100644 index 00000000..f183ca4c --- /dev/null +++ b/backend/src/hermes-management/hermes-integration.service.spec.ts @@ -0,0 +1,149 @@ +import { HermesIntegrationService } from './hermes-integration.service'; +import { HermesAdapter } from './hermes.adapter'; +describe('backend-owned runtime authorization', () => { + const ctx = { subject: 'admin', profiles: ['seo'] }; + const make = (allow = true, enabled = false) => { + const fetcher = jest + .fn() + .mockResolvedValue( + new Response( + JSON.stringify({ id: 'j', profile: 'seo', enabled: false }), + ), + ); + const authorize = jest.fn().mockResolvedValue(allow); + return { + fetcher, + authorize, + s: new HermesIntegrationService( + new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }, + fetcher, + ), + { authorize }, + enabled, + ), + }; + }; + it('denies missing principal, missing profile, denied policy before upstream IO', async () => { + const { s, fetcher } = make(false); + await expect(s.pauseCron(ctx, 'seo', 'j')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + await expect( + s.pauseCron({ ...ctx, subject: '' }, 'seo', 'j'), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect(s.pauseCron(ctx, 'dev', 'j')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(fetcher).not.toHaveBeenCalled(); + }); + it('allows authorized pause but leaves resume disabled by default', async () => { + const { s, fetcher, authorize } = make(); + await s.pauseCron(ctx, 'seo', 'j'); + expect(authorize).toHaveBeenCalledWith(ctx, 'cron.pause', 'seo'); + await expect(s.resumeCron(ctx, 'seo', 'j')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(fetcher).toHaveBeenCalledTimes(1); + }); + it('fails closed on all execution and never forwards arbitrary events or RPC', async () => { + const { s, fetcher } = make(); + expect(s.capabilities()).toMatchObject({ + chat: false, + control: false, + eventDispatch: false, + cronResume: false, + }); + await expect(s.chat(ctx, 'seo', 'hello')).rejects.toMatchObject({ + code: 'UNSUPPORTED', + }); + await expect(s.control(ctx, 'seo', 'interrupt')).rejects.toMatchObject({ + code: 'UNSUPPORTED', + }); + await expect( + s.dispatchEvent(ctx, 'seo', { type: 'order.created' }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(fetcher).not.toHaveBeenCalled(); + }); + it('fails closed when authorization provider throws', async () => { + const a = new HermesAdapter({ + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }); + const s = new HermesIntegrationService(a, { + authorize: () => Promise.reject(new Error('private')), + }); + await expect(s.health(ctx)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); +}); + +it('checks every read capability and filters the global profile roster', async () => { + const fetcher = jest.fn().mockImplementation((input: URL) => { + const payloads: Record = { + '/api/health': { + ok: true, + version: 'x', + commit: 'x', + auth_required: true, + }, + '/api/status': { + version: 'x', + gateway_running: false, + gateway_state: null, + overall: 'degraded', + active_agents: 0, + }, + '/api/profiles': { + profiles: [ + { name: 'seo', is_default: false, gateway_running: false }, + { name: 'dev', is_default: false, gateway_running: false }, + ], + }, + '/api/model/info': { + model: 'm', + provider: 'p', + effective_context_length: 1, + }, + '/api/model/options': { providers: [] }, + '/api/analytics/usage': { + period_days: 30, + totals: { + total_input: 0, + total_output: 0, + total_sessions: 0, + total_estimated_cost: 0, + }, + }, + '/api/sessions': { sessions: [], total: 0 }, + '/api/cron/jobs': [], + }; + return Promise.resolve( + new Response(JSON.stringify(payloads[input.pathname])), + ); + }); + const authorize = jest.fn().mockResolvedValue(true); + const s = new HermesIntegrationService( + new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }, + fetcher, + ), + { authorize }, + ); + const p = { subject: 'verified', profiles: ['seo'] }; + await s.health(p); + await s.status(p, 'seo'); + expect(await s.profiles(p)).toHaveLength(1); + await s.modelInfo(p, 'seo'); + await s.modelOptions(p, 'seo'); + await s.usage(p, 'seo'); + await s.sessions(p, 'seo'); + await s.crons(p, 'seo'); + expect(authorize).toHaveBeenCalledTimes(8); + expect(authorize.mock.calls.every((c) => c[1] === 'runtime.read')).toBe(true); +}); diff --git a/backend/src/hermes-management/hermes-integration.service.ts b/backend/src/hermes-management/hermes-integration.service.ts new file mode 100644 index 00000000..dc1aa882 --- /dev/null +++ b/backend/src/hermes-management/hermes-integration.service.ts @@ -0,0 +1,126 @@ +import { HermesAdapter, HermesError, Json } from './hermes.adapter'; +/** Context MUST be constructed from verified backend identity, never request bodies. */ +export interface RuntimePrincipal { + subject: string; + profiles: readonly string[]; +} +export type RuntimePermission = + | 'runtime.read' + | 'cron.pause' + | 'cron.resume' + | 'chat' + | 'control' + | 'event.dispatch'; +export interface RuntimeAuthorizer { + authorize( + principal: RuntimePrincipal, + permission: RuntimePermission, + profile?: string, + ): Promise; +} +/** No controller or socket is registered: only the backend gatekeeper can call this seam. */ +export class HermesIntegrationService { + constructor( + private readonly adapter: HermesAdapter, + private readonly policy: RuntimeAuthorizer, + private readonly resumeEnabled = false, + ) {} + capabilities() { + return { + inventory: true, + cronPause: true, + cronResume: this.resumeEnabled, + chat: false, + control: false, + eventDispatch: false, + } as const; + } + private async check( + principal: RuntimePrincipal, + permission: RuntimePermission, + profile?: string, + ): Promise { + if ( + !principal?.subject || + !Array.isArray(principal.profiles) || + (profile && !principal.profiles.includes(profile)) + ) + throw new HermesError('FORBIDDEN'); + try { + if ( + (await this.policy.authorize(principal, permission, profile)) !== true + ) + throw new HermesError('FORBIDDEN'); + } catch { + throw new HermesError('FORBIDDEN'); + } + } + async health(p: RuntimePrincipal) { + await this.check(p, 'runtime.read'); + return this.adapter.health(); + } + async status(p: RuntimePrincipal, profile: string) { + await this.check(p, 'runtime.read', profile); + return this.adapter.status(profile); + } + async profiles(p: RuntimePrincipal) { + await this.check(p, 'runtime.read'); + return (await this.adapter.profiles()).filter( + (r) => typeof r.name === 'string' && p.profiles.includes(r.name), + ); + } + async modelInfo(p: RuntimePrincipal, profile: string) { + await this.check(p, 'runtime.read', profile); + return this.adapter.modelInfo(profile); + } + async modelOptions(p: RuntimePrincipal, profile: string) { + await this.check(p, 'runtime.read', profile); + return this.adapter.modelOptions(profile); + } + async usage(p: RuntimePrincipal, profile: string, days = 30) { + await this.check(p, 'runtime.read', profile); + return this.adapter.usage(profile, days); + } + async sessions(p: RuntimePrincipal, profile: string, limit = 20, offset = 0) { + await this.check(p, 'runtime.read', profile); + return this.adapter.sessions(profile, limit, offset); + } + async crons(p: RuntimePrincipal, profile: string) { + await this.check(p, 'runtime.read', profile); + return this.adapter.crons(profile); + } + async pauseCron(p: RuntimePrincipal, profile: string, id: string) { + await this.check(p, 'cron.pause', profile); + return this.adapter.pauseCron(profile, id); + } + async resumeCron(p: RuntimePrincipal, profile: string, id: string) { + await this.check(p, 'cron.resume', profile); + if (!this.resumeEnabled) throw new HermesError('FORBIDDEN'); + return this.adapter.resumeCron(profile, id); + } + async chat( + p: RuntimePrincipal, + profile: string, + _text: string, + ): Promise { + await this.check(p, 'chat', profile); + throw new HermesError('UNSUPPORTED'); + } + async control( + p: RuntimePrincipal, + profile: string, + _command: 'interrupt', + ): Promise { + await this.check(p, 'control', profile); + throw new HermesError('UNSUPPORTED'); + } + /** Disabled independently of policy: no unreviewed event may become an agent prompt. */ + async dispatchEvent( + p: RuntimePrincipal, + profile: string, + _event: Json, + ): Promise { + await this.check(p, 'event.dispatch', profile); + throw new HermesError('FORBIDDEN'); + } +} diff --git a/backend/src/hermes-management/hermes-management.module.spec.ts b/backend/src/hermes-management/hermes-management.module.spec.ts new file mode 100644 index 00000000..afac4940 --- /dev/null +++ b/backend/src/hermes-management/hermes-management.module.spec.ts @@ -0,0 +1,18 @@ +import { Test } from '@nestjs/testing'; +import { HermesManagementModule } from './hermes-management.module'; +import { HermesIntegrationService } from './hermes-integration.service'; +it('requires explicit registration and denies by default without publishing controllers', async () => { + const module = await Test.createTestingModule({ + imports: [ + HermesManagementModule.register({ + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }), + ], + }).compile(); + const service = module.get(HermesIntegrationService); + await expect( + service.health({ subject: 'admin', profiles: [] }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await module.close(); +}); diff --git a/backend/src/hermes-management/hermes-management.module.ts b/backend/src/hermes-management/hermes-management.module.ts new file mode 100644 index 00000000..7c6c10f1 --- /dev/null +++ b/backend/src/hermes-management/hermes-management.module.ts @@ -0,0 +1,27 @@ +import { DynamicModule, Module } from '@nestjs/common'; +import { HermesAdapter, HermesConfig } from './hermes.adapter'; +import { + HermesIntegrationService, + RuntimeAuthorizer, +} from './hermes-integration.service'; +@Module({}) +export class HermesManagementModule { + static register( + config: HermesConfig, + policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) }, + ): DynamicModule { + return { + module: HermesManagementModule, + providers: [ + { provide: HermesAdapter, useFactory: () => new HermesAdapter(config) }, + { + provide: HermesIntegrationService, + useFactory: (adapter: HermesAdapter) => + new HermesIntegrationService(adapter, policy, false), + inject: [HermesAdapter], + }, + ], + exports: [HermesIntegrationService], + }; + } +} diff --git a/backend/src/hermes-management/hermes.adapter.spec.ts b/backend/src/hermes-management/hermes.adapter.spec.ts new file mode 100644 index 00000000..cffce5af --- /dev/null +++ b/backend/src/hermes-management/hermes.adapter.spec.ts @@ -0,0 +1,240 @@ +import { HermesAdapter, HermesError } from './hermes.adapter'; +const health = { + ok: true, + version: '0.13', + commit: 'abc', + auth_required: true, +}; +describe('installed Hermes health contract', () => { + it('uses pinned internal origin, bearer only server side and strips extra fields', async () => { + const fetcher = jest + .fn() + .mockResolvedValue( + new Response( + JSON.stringify({ ...health, token: 'never', home: '/secret' }), + ), + ); + const adapter = new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('private'), + }, + fetcher, + ); + expect(await adapter.health()).toEqual(health); + expect(fetcher.mock.calls[0][0].toString()).toBe( + 'http://canina-hermes:9119/api/health', + ); + expect(fetcher.mock.calls[0][1].headers.Authorization).toBe( + 'Bearer private', + ); + expect(fetcher.mock.calls[0][1].redirect).toBe('error'); + }); + it('fails closed for bad origin, auth errors, malformed contract and oversized bodies', async () => { + expect( + () => + new HermesAdapter({ + origin: 'https://evil.test', + token: () => Promise.resolve(''), + }), + ).toThrow(HermesError); + for (const response of [ + new Response('private', { status: 401 }), + new Response('{}'), + new Response('x'.repeat(262145)), + ]) { + const a = new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }, + jest.fn().mockResolvedValue(response), + ); + await expect(a.health()).rejects.toBeInstanceOf(HermesError); + } + }); +}); + +describe('bounded profile-scoped REST inventory', () => { + const create = (payload: unknown) => { + const fetcher = jest + .fn() + .mockResolvedValue(new Response(JSON.stringify(payload))); + return { + a: new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }, + fetcher, + ), + fetcher, + }; + }; + it('projects status, profiles, models and usage without raw paths, prompts or credentials', async () => { + expect( + await create({ + version: 'x', + gateway_running: false, + gateway_state: null, + overall: 'degraded', + active_agents: 0, + }).a.status('seo'), + ).toEqual({ + version: 'x', + gateway_running: false, + gateway_state: null, + overall: 'degraded', + active_agents: 0, + }); + expect( + await create({ + profiles: [ + { + name: 'seo', + is_default: false, + gateway_running: false, + path: '/private', + description: 'token=secret', + }, + ], + }).a.profiles(), + ).toEqual([{ name: 'seo', is_default: false, gateway_running: false }]); + expect( + await create({ + model: 'm', + provider: 'p', + effective_context_length: 0, + api_key: 'secret', + }).a.modelInfo('seo'), + ).toEqual({ model: 'm', provider: 'p', effective_context_length: 0 }); + expect( + await create({ + providers: [ + { slug: 'p', name: 'Provider', models: ['m'], api_key: 'secret' }, + ], + current: { api_key: 'secret' }, + }).a.modelOptions('seo'), + ).toEqual([{ slug: 'p', name: 'Provider', models: ['m'] }]); + expect( + await create({ + period_days: 7, + totals: { + total_input: 0, + total_output: 2, + total_sessions: 1, + total_estimated_cost: 0, + }, + tools: { secret: 1 }, + }).a.usage('seo', 7), + ).toEqual({ + period_days: 7, + totals: { + total_input: 0, + total_output: 2, + total_sessions: 1, + total_estimated_cost: 0, + }, + }); + }); + it('uses scoped list contract and rejects unbounded queries or profile escape', async () => { + const { a, fetcher } = create({ + sessions: [ + { + id: 's', + profile: 'seo', + is_active: false, + source: 'cron', + title: 'secret', + }, + ], + total: 1, + storage: {}, + }); + expect(await a.sessions('seo', 20, 0)).toEqual({ + sessions: [{ id: 's', profile: 'seo', is_active: false, source: 'cron' }], + total: 1, + }); + expect(fetcher.mock.calls[0][0].pathname).toBe('/api/sessions'); + expect(fetcher.mock.calls[0][0].searchParams.get('full')).toBe('false'); + await expect(a.sessions('../escape', 20, 0)).rejects.toThrow(); + await expect(a.sessions('seo', 101, 0)).rejects.toThrow(); + await expect(a.usage('seo', 366)).rejects.toThrow(); + await expect( + create({ + sessions: [], + total: 0, + storage: { seo: 'corrupt' }, + }).a.sessions('seo'), + ).rejects.toThrow(); + await expect( + create({ + sessions: [ + { id: 's', profile: 'dev', source: 'cli', is_active: false }, + ], + total: 1, + }).a.sessions('seo'), + ).rejects.toThrow(); + }); + it('lists scoped cron array; pause/resume use exact POST routes without triggers', async () => { + expect( + await create([ + { id: 'j', profile: 'seo', enabled: false, prompt: 'secret' }, + ]).a.crons('seo'), + ).toEqual([{ id: 'j', profile: 'seo', enabled: false }]); + const { a, fetcher } = create({ id: 'j', profile: 'seo', enabled: false }); + expect(await a.pauseCron('seo', 'j')).toEqual({ + id: 'j', + profile: 'seo', + enabled: false, + }); + expect(fetcher.mock.calls[0][0].pathname).toBe('/api/cron/jobs/j/pause'); + expect(fetcher.mock.calls[0][1].method).toBe('POST'); + const resume = create({ id: 'j', profile: 'seo', enabled: true }); + await resume.a.resumeCron('seo', 'j'); + expect(resume.fetcher.mock.calls[0][0].pathname).toBe( + '/api/cron/jobs/j/resume', + ); + await expect(a.pauseCron('seo', '../trigger')).rejects.toThrow(); + }); +}); + +describe('resource budgets and safe errors', () => { + it('does not leak upstream errors or tokens and limits credential waits', async () => { + jest.useFakeTimers(); + const a = new HermesAdapter({ + origin: 'http://canina-hermes:9119', + token: () => new Promise(() => {}), + }); + const result = expect(a.health()).rejects.toMatchObject({ + code: 'UNAVAILABLE', + message: 'Hermes unavailable', + }); + await jest.advanceTimersByTimeAsync(5001); + await result; + jest.useRealTimers(); + }); + it('caps concurrency before upstream IO', async () => { + const resolvers: ((r: Response) => void)[] = []; + const fetcher = jest.fn( + () => + new Promise((r) => { + resolvers.push(r); + }), + ); + const a = new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('secret'), + }, + fetcher, + ); + const calls = Array.from({ length: 4 }, () => a.health()); + const denied = expect(a.health()).rejects.toMatchObject({ code: 'LIMIT' }); + await Promise.resolve(); + await Promise.resolve(); + resolvers.forEach((r) => r(new Response(JSON.stringify(health)))); + await denied; + await Promise.all(calls); + }); +}); diff --git a/backend/src/hermes-management/hermes.adapter.ts b/backend/src/hermes-management/hermes.adapter.ts new file mode 100644 index 00000000..df19b69e --- /dev/null +++ b/backend/src/hermes-management/hermes.adapter.ts @@ -0,0 +1,267 @@ +export type Json = + | null + | boolean + | number + | string + | Json[] + | { [key: string]: Json }; +export type Row = Record; +export type HermesErrorCode = + | 'CONFIGURATION' + | 'AUTH_REQUIRED' + | 'UNAVAILABLE' + | 'CONTRACT' + | 'LIMIT' + | 'FORBIDDEN' + | 'UNSUPPORTED'; +export class HermesError extends Error { + constructor(readonly code: HermesErrorCode) { + super(`Hermes ${code.toLowerCase()}`); + } +} +export interface HermesConfig { + origin: string; + token: () => Promise; +} +export interface Health { + ok: boolean; + version: string; + commit: string; + auth_required: boolean; +} +function object(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new HermesError('CONTRACT'); + return value as Record; +} +function fields( + value: unknown, + schema: Record, +): Row { + const source = object(value); + const result: Row = {}; + for (const [key, type] of Object.entries(schema)) { + if ( + typeof source[key] !== type || + (type === 'number' && !Number.isFinite(source[key])) + ) + throw new HermesError('CONTRACT'); + result[key] = source[key] as Json; + } + return result; +} +export class HermesAdapter { + private readonly origin: string; + private inflight = 0; + constructor( + private readonly config: HermesConfig, + private readonly fetcher: typeof fetch = fetch, + ) { + if (config.origin !== 'http://canina-hermes:9119') + throw new HermesError('CONFIGURATION'); + this.origin = config.origin; + } + private async request( + path: string, + profile?: string, + method = 'GET', + params: Record = {}, + ): Promise { + if ( + profile !== undefined && + !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(profile) + ) + throw new HermesError('FORBIDDEN'); + const url = new URL(path, this.origin); + if (profile) url.searchParams.set('profile', profile); + for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); + if (this.inflight >= 4) throw new HermesError('LIMIT'); + this.inflight++; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 5000); + try { + const token = await Promise.race([ + this.config.token(), + new Promise((_, reject) => + controller.signal.addEventListener( + 'abort', + () => reject(new HermesError('UNAVAILABLE')), + { once: true }, + ), + ), + ]); + if (!token || /[\r\n]/.test(token)) + throw new HermesError('AUTH_REQUIRED'); + const response = await this.fetcher(url, { + method, + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json', + }, + signal: controller.signal, + redirect: 'error', + }); + if ([401, 403].includes(response.status)) + throw new HermesError('AUTH_REQUIRED'); + if (response.status === 404) throw new HermesError('UNSUPPORTED'); + if (!response.ok) throw new HermesError('UNAVAILABLE'); + if (Number(response.headers.get('content-length')) > 262144) + throw new HermesError('LIMIT'); + const reader = response.body?.getReader(); + if (!reader) throw new HermesError('CONTRACT'); + let bytes = 0; + const chunks: Uint8Array[] = []; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > 262144) throw new HermesError('LIMIT'); + chunks.push(value); + } + } finally { + await reader.cancel().catch(() => undefined); + } + return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown; + } catch (error) { + if (error instanceof HermesError) throw error; + throw new HermesError('UNAVAILABLE'); + } finally { + clearTimeout(timer); + this.inflight--; + } + } + async health(): Promise { + return fields(await this.request('/api/health'), { + ok: 'boolean', + version: 'string', + commit: 'string', + auth_required: 'boolean', + }) as unknown as Health; + } + async status(profile: string): Promise { + const raw = object(await this.request('/api/status', profile)); + const row = fields(raw, { + version: 'string', + gateway_running: 'boolean', + overall: 'string', + active_agents: 'number', + }); + if (raw.gateway_state !== null && typeof raw.gateway_state !== 'string') + throw new HermesError('CONTRACT'); + return { ...row, gateway_state: raw.gateway_state as Json }; + } + async profiles(): Promise { + return list(object(await this.request('/api/profiles')).profiles).map((r) => + fields(r, { + name: 'string', + is_default: 'boolean', + gateway_running: 'boolean', + }), + ); + } + async modelInfo(profile: string): Promise { + return fields(await this.request('/api/model/info', profile), { + model: 'string', + provider: 'string', + effective_context_length: 'number', + }); + } + async modelOptions(profile: string): Promise { + return list( + object(await this.request('/api/model/options', profile)).providers, + ).map((r) => { + const row = fields(r, { slug: 'string', name: 'string' }); + const models = list(object(r).models); + if (models.some((m) => typeof m !== 'string')) + throw new HermesError('CONTRACT'); + return { ...row, models: models as string[] }; + }); + } + async usage(profile: string, days = 30): Promise { + bound(days, 1, 365); + const raw = object( + await this.request('/api/analytics/usage', profile, 'GET', { + days: String(days), + }), + ); + return { + ...fields(raw, { period_days: 'number' }), + totals: fields(raw.totals, { + total_input: 'number', + total_output: 'number', + total_sessions: 'number', + total_estimated_cost: 'number', + }), + }; + } + async sessions(profile: string, limit = 20, offset = 0): Promise { + bound(limit, 1, 100); + bound(offset, 0, 10000); + const raw = object( + await this.request('/api/sessions', profile, 'GET', { + limit: String(limit), + offset: String(offset), + full: 'false', + order: 'recent', + }), + ); + if (raw.storage && Object.keys(object(raw.storage)).length) + throw new HermesError('UNAVAILABLE'); + const rows = list(raw.sessions).map((r) => + scoped(r, profile, { + id: 'string', + profile: 'string', + source: 'string', + is_active: 'boolean', + }), + ); + return { ...fields(raw, { total: 'number' }), sessions: rows }; + } + async crons(profile: string): Promise { + return list(await this.request('/api/cron/jobs', profile)).map((r) => + scoped(r, profile, { + id: 'string', + profile: 'string', + enabled: 'boolean', + }), + ); + } + private async cron( + profile: string, + id: string, + action: 'pause' | 'resume', + ): Promise { + if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new HermesError('FORBIDDEN'); + return scoped( + await this.request(`/api/cron/jobs/${id}/${action}`, profile, 'POST'), + profile, + { id: 'string', profile: 'string', enabled: 'boolean' }, + ); + } + pauseCron(profile: string, id: string): Promise { + return this.cron(profile, id, 'pause'); + } + resumeCron(profile: string, id: string): Promise { + return this.cron(profile, id, 'resume'); + } +} + +function list(value: unknown): unknown[] { + if (!Array.isArray(value) || value.length > 1000) + throw new HermesError('CONTRACT'); + return value; +} +function bound(value: number, min: number, max: number): void { + if (!Number.isInteger(value) || value < min || value > max) + throw new HermesError('LIMIT'); +} +function scoped( + value: unknown, + profile: string, + schema: Record, +): Row { + const row = fields(value, schema); + if (row.profile !== profile) throw new HermesError('FORBIDDEN'); + return row; +} diff --git a/backend/src/hermes-management/hermes.transport.spec.ts b/backend/src/hermes-management/hermes.transport.spec.ts new file mode 100644 index 00000000..d78811bd --- /dev/null +++ b/backend/src/hermes-management/hermes.transport.spec.ts @@ -0,0 +1,50 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { HermesAdapter } from './hermes.adapter'; +it('exercises bounded HTTP transport against an isolated server', async () => { + const seen: string[] = []; + const server = createServer((req, res) => { + seen.push(`${req.method} ${req.url}`); + if (req.headers.authorization !== 'Bearer local-test') { + res.writeHead(401).end(); + return; + } + res.setHeader('Content-Type', 'application/json'); + res.end( + JSON.stringify({ + ok: true, + version: 'test', + commit: 'test', + auth_required: true, + api_key: 'redacted', + }), + ); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const port = (server.address() as AddressInfo).port; + const transport: typeof fetch = (input, init) => + fetch( + `http://127.0.0.1:${port}${new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url).pathname}`, + init, + ); + const adapter = new HermesAdapter( + { + origin: 'http://canina-hermes:9119', + token: () => Promise.resolve('local-test'), + }, + transport, + ); + expect(await adapter.health()).toEqual({ + ok: true, + version: 'test', + commit: 'test', + auth_required: true, + }); + expect(seen).toEqual(['GET /api/health']); + } finally { + await new Promise((resolve, reject) => + server.close((e) => (e ? reject(e) : resolve())), + ); + } +}); diff --git a/backend/src/hermes-management/tsconfig.contract.json b/backend/src/hermes-management/tsconfig.contract.json new file mode 100644 index 00000000..b99807ed --- /dev/null +++ b/backend/src/hermes-management/tsconfig.contract.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "../../../.hermes-contract-build", + "incremental": false, + "strict": true + }, + "include": ["./*.ts"], + "exclude": [] +} diff --git a/docs/hermes-runtime-integration.md b/docs/hermes-runtime-integration.md new file mode 100644 index 00000000..e507c5ea --- /dev/null +++ b/docs/hermes-runtime-integration.md @@ -0,0 +1,69 @@ +# Orchestration v4: Hermes runtime seam (review-only) + +## Installed evidence / compatibility + +Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata: + +- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`. +- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`. +- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one. +- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made. +- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched. + +Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`. + +## Supported allowlist + +| Service method | Installed upstream contract | Public projection | +|---|---|---| +| health | GET /api/health | ok/version/commit/auth_required | +| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents | +| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope | +| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length | +| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings | +| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals | +| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total | +| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled | +| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled | +| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** | + +No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects. + +Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations. + +## Authentication and WS discovery + +- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**. +- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs. +- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**. +- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted. +- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed. + +## Wiring (owner integration step, no app.module.ts changes here) + +Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration: + +```ts +HermesManagementModule.register({ + origin: 'http://canina-hermes:9119', + token: () => secretStore.read('hermes_dashboard_access_token'), +}, backendRuntimeAuthorizer) +``` + +Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates. + +Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production. + +## Disabled event dispatch design + +No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection. + +## Manifests and verification + +`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`. + +`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed. + +Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration. + +Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed. diff --git a/infra/hermes-runtime/backend.env.example b/infra/hermes-runtime/backend.env.example new file mode 100644 index 00000000..e9840f06 --- /dev/null +++ b/infra/hermes-runtime/backend.env.example @@ -0,0 +1,5 @@ +# Mount a secret containing a provider-verified Hermes dashboard access token. +# A Canina admin JWT is NOT a Hermes session token. Never expose it in VITE_*. +HERMES_MANAGEMENT_ORIGIN=http://canina-hermes:9119 +HERMES_MANAGEMENT_TOKEN_FILE=/run/secrets/hermes_dashboard_access_token +# Dispatcher/chat/control/resume are disabled in code; no environment flag enables them. diff --git a/infra/hermes-runtime/compose.template.yml b/infra/hermes-runtime/compose.template.yml new file mode 100644 index 00000000..7f76a919 --- /dev/null +++ b/infra/hermes-runtime/compose.template.yml @@ -0,0 +1,27 @@ +# Review-only migration template. Never run automatically; keep gateway/crons unchanged. +name: canina-hermes +services: + canina-hermes: + profiles: [operator-approved-runtime] + image: nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784 + command: [gateway, run] + restart: "no" + environment: + HERMES_HOME: /opt/data + # Existing credentials/config stay in the preserved volume; no replacement config. + volumes: + - canina_hermes_data:/opt/data + networks: [hermes_backend] + # Deliberately no published ports, Docker socket, host filesystem or public labels. + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + pids_limit: 256 + mem_limit: 2g +volumes: + canina_hermes_data: + external: true + name: canina-hermes_canina_hermes_data +networks: + hermes_backend: + external: true + name: canina_hermes_backend