From 5507fbcb29018019eca724dae83976430ed19567 Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 23 Oct 2026 11:05:27 +0000 Subject: [PATCH] Add server-only Hermes login broker with deny-first module registration --- .../hermes-management.module.spec.ts | 8 +++ .../hermes-management.module.ts | 9 ++++ .../hermes-session-broker.spec.ts | 53 +++++++++++++++++++ .../hermes-session-broker.ts | 35 ++++++++++++ 4 files changed, 105 insertions(+) create mode 100644 backend/src/hermes-management/hermes-session-broker.spec.ts create mode 100644 backend/src/hermes-management/hermes-session-broker.ts diff --git a/backend/src/hermes-management/hermes-management.module.spec.ts b/backend/src/hermes-management/hermes-management.module.spec.ts index afac4940..47002d59 100644 --- a/backend/src/hermes-management/hermes-management.module.spec.ts +++ b/backend/src/hermes-management/hermes-management.module.spec.ts @@ -16,3 +16,11 @@ it('requires explicit registration and denies by default without publishing cont ).rejects.toMatchObject({ code: 'FORBIDDEN' }); await module.close(); }); + +it('registers backend credential broker without acquiring credentials before policy authorization', async () => { + const credentials=jest.fn().mockResolvedValue({username:'backend',password:'test-only'}); + const module=await Test.createTestingModule({imports:[HermesManagementModule.registerAuthenticated(credentials)]}).compile(); + await expect(module.get(HermesIntegrationService).health({subject:'admin',profiles:[]})).rejects.toMatchObject({code:'FORBIDDEN'}); + expect(credentials).not.toHaveBeenCalled(); + await module.close(); +}); diff --git a/backend/src/hermes-management/hermes-management.module.ts b/backend/src/hermes-management/hermes-management.module.ts index 7c6c10f1..3798e6ce 100644 --- a/backend/src/hermes-management/hermes-management.module.ts +++ b/backend/src/hermes-management/hermes-management.module.ts @@ -1,4 +1,5 @@ import { DynamicModule, Module } from '@nestjs/common'; +import { HermesSessionBroker } from './hermes-session-broker'; import { HermesAdapter, HermesConfig } from './hermes.adapter'; import { HermesIntegrationService, @@ -6,6 +7,14 @@ import { } from './hermes-integration.service'; @Module({}) export class HermesManagementModule { + static registerAuthenticated( + credentials: () => Promise<{username:string;password:string}>, + policy: RuntimeAuthorizer = {authorize: async () => false}, + ): DynamicModule { + const broker = new HermesSessionBroker(credentials); + return this.register({origin:'http://canina-hermes:9119',token:()=>broker.token()},policy); + } + static register( config: HermesConfig, policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) }, diff --git a/backend/src/hermes-management/hermes-session-broker.spec.ts b/backend/src/hermes-management/hermes-session-broker.spec.ts new file mode 100644 index 00000000..0e058e18 --- /dev/null +++ b/backend/src/hermes-management/hermes-session-broker.spec.ts @@ -0,0 +1,53 @@ +import { afterEach } from '@jest/globals'; +import { HermesSessionBroker } from './hermes-session-broker'; +const credentials = async () => ({username:'backend',password:'test-only'}); +const response = () => new Response('{"ok":true}', {headers:{'set-cookie':'hermes_session_at=verified-test-token; Max-Age=60; Path=/; HttpOnly'}}); +describe('server-only Hermes session broker',()=>{ + afterEach(()=>{jest.useRealTimers();}); + it('renews expired cached access without retaining the refresh cookie',async()=>{ + jest.useFakeTimers(); + const fetcher=jest.fn().mockImplementation(async()=>response()); + const broker=new HermesSessionBroker(credentials,fetcher); + await broker.token(); + await jest.advanceTimersByTimeAsync(51000); + await broker.token(); + expect(fetcher).toHaveBeenCalledTimes(2); + }); + it('bounds credential waits and releases the pending login after timeout',async()=>{ + jest.useFakeTimers(); + const load=jest.fn().mockImplementationOnce(()=>new Promise(()=>{})).mockImplementation(credentials); + const broker=new HermesSessionBroker(load,jest.fn().mockImplementation(async()=>response())); + const result=expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'}); + await jest.advanceTimersByTimeAsync(5001);await result; + expect(await broker.token()).toBe('verified-test-token'); + }); + it('rejects oversized response bodies and short cookie lifetimes',async()=>{ + for(const res of [new Response('x'.repeat(4097)),new Response('{"ok":true}',{headers:{'set-cookie':'hermes_session_at=token; Max-Age=1; Path=/'}})]){ + await expect(new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(res)).token()).rejects.toMatchObject({message:'Hermes auth_required'}); + } + }); + + it('coalesces login, caches only access token and uses installed password-login contract',async()=>{ + const fetcher=jest.fn().mockImplementation(async()=>response()); + const broker=new HermesSessionBroker(credentials,fetcher); + expect(await Promise.all([broker.token(),broker.token()])).toEqual(['verified-test-token','verified-test-token']); + expect(await broker.token()).toBe('verified-test-token'); + expect(fetcher).toHaveBeenCalledTimes(1); + const [url,options]=fetcher.mock.calls[0]; + expect(url).toBe('http://canina-hermes:9119/auth/password-login'); + expect(JSON.parse(options.body)).toEqual({provider:'basic',username:'backend',password:'test-only'}); + expect(options.redirect).toBe('error'); + }); + it('fails closed without echoing credentials, response bodies or provider errors',async()=>{ + for(const result of [new Response('private secret',{status:401}),new Response('{"ok":true}'),new Response('{"ok":false}',{headers:{'set-cookie':'hermes_session_at=bad; Max-Age=60'}})]){ + const broker=new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(result)); + await expect(broker.token()).rejects.toMatchObject({message:'Hermes auth_required'}); + } + }); + it('does not cache failures and permits a later successful login',async()=>{ + const fetcher=jest.fn().mockRejectedValueOnce(new Error('sensitive upstream')).mockImplementationOnce(async()=>response()); + const broker=new HermesSessionBroker(credentials,fetcher); + await expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'}); + expect(await broker.token()).toBe('verified-test-token'); + }); +}); diff --git a/backend/src/hermes-management/hermes-session-broker.ts b/backend/src/hermes-management/hermes-session-broker.ts new file mode 100644 index 00000000..c0f3b500 --- /dev/null +++ b/backend/src/hermes-management/hermes-session-broker.ts @@ -0,0 +1,35 @@ +import { HermesError } from './hermes.adapter'; +export class HermesSessionBroker { + private cached: {token:string;until:number}|undefined; + private pending: Promise|undefined; + constructor(private readonly credentials:()=>Promise<{username:string;password:string}>,private readonly fetcher:typeof fetch=fetch) {} + token():Promise{ + if(this.cached && this.cached.until>Date.now()) return Promise.resolve(this.cached.token); + if(this.pending) return this.pending; + this.pending=this.login().finally(()=>{this.pending=undefined;}); + return this.pending; + } + private async login():Promise{ + const controller=new AbortController(); + const timer=setTimeout(()=>controller.abort(),5000); + try{ + const creds=await Promise.race([this.credentials(),new Promise((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new HermesError('UNAVAILABLE')),{once:true}))]); + if(!creds.username || !creds.password) throw new HermesError('AUTH_REQUIRED'); + const response=await this.fetcher('http://canina-hermes:9119/auth/password-login',{method:'POST',redirect:'error',signal:controller.signal,headers:{'Content-Type':'application/json'},body:JSON.stringify({provider:'basic',...creds})}); + if(!response.ok) throw new HermesError('AUTH_REQUIRED'); + const reader=response.body?.getReader(); + if(!reader) throw new HermesError('AUTH_REQUIRED'); + const chunks:Uint8Array[]=[];let size=0; + try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096)throw new HermesError('AUTH_REQUIRED');chunks.push(value);}}finally{await reader.cancel().catch(()=>undefined);} + const body=JSON.parse(Buffer.concat(chunks).toString('utf8')) as {ok?:unknown}; + const cookies=response.headers.getSetCookie(); + const cookie=cookies.find(c=>c.startsWith('hermes_session_at=')); + const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1]; + const age=Number(cookie?.match(/(?:^|;)\s*Max-Age=(\d+)/i)?.[1]); + if(body.ok!==true || !token || !Number.isSafeInteger(age) || age<30)throw new HermesError('AUTH_REQUIRED'); + this.cached={token,until:Date.now()+Math.min(age-10,300)*1000}; + return token; + }catch(error){if(error instanceof HermesError)throw error;throw new HermesError('UNAVAILABLE');} + finally{clearTimeout(timer);} + } +}