Add server-only Hermes login broker with deny-first module registration
This commit is contained in:
1 parent
176cc08a6b
commit
5507fbcb29
4 files changed
+105
No files matched your search
@@ -16,3 +16,11 @@ it('requires explicit registration and denies by default without publishing cont
|
|||||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||||
await module.close();
|
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();
|
||||||
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { DynamicModule, Module } from '@nestjs/common';
|
import { DynamicModule, Module } from '@nestjs/common';
|
||||||
|
import { HermesSessionBroker } from './hermes-session-broker';
|
||||||
import { HermesAdapter, HermesConfig } from './hermes.adapter';
|
import { HermesAdapter, HermesConfig } from './hermes.adapter';
|
||||||
import {
|
import {
|
||||||
HermesIntegrationService,
|
HermesIntegrationService,
|
||||||
@@ -6,6 +7,14 @@ import {
|
|||||||
} from './hermes-integration.service';
|
} from './hermes-integration.service';
|
||||||
@Module({})
|
@Module({})
|
||||||
export class HermesManagementModule {
|
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(
|
static register(
|
||||||
config: HermesConfig,
|
config: HermesConfig,
|
||||||
policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) },
|
policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) },
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { HermesError } from './hermes.adapter';
|
||||||
|
export class HermesSessionBroker {
|
||||||
|
private cached: {token:string;until:number}|undefined;
|
||||||
|
private pending: Promise<string>|undefined;
|
||||||
|
constructor(private readonly credentials:()=>Promise<{username:string;password:string}>,private readonly fetcher:typeof fetch=fetch) {}
|
||||||
|
token():Promise<string>{
|
||||||
|
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<string>{
|
||||||
|
const controller=new AbortController();
|
||||||
|
const timer=setTimeout(()=>controller.abort(),5000);
|
||||||
|
try{
|
||||||
|
const creds=await Promise.race([this.credentials(),new Promise<never>((_,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);}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user