Make snapshot inventory provenance explicit and deny false live readiness
This commit is contained in:
1 parent
01f56c6db7
commit
d6db634a35
16 files changed
+443
-35
No files matched your search
@@ -12,7 +12,7 @@ export class HermesManagementModule {
|
||||
policy: RuntimeAuthorizer = {authorize: async () => false},
|
||||
): DynamicModule {
|
||||
const broker = new HermesSessionBroker(credentials);
|
||||
return this.register({origin:'http://canina-hermes:9119',token:()=>broker.token()},policy);
|
||||
return this.register({origin:'http://canina-hermes-inventory:9119',token:()=>broker.token()},policy);
|
||||
}
|
||||
|
||||
static register(
|
||||
|
||||
@@ -34,7 +34,7 @@ describe('server-only Hermes session broker',()=>{
|
||||
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(url).toBe('http://canina-hermes-inventory:9119/auth/password-login');
|
||||
expect(JSON.parse(options.body)).toEqual({provider:'basic',username:'backend',password:'test-only'});
|
||||
expect(options.redirect).toBe('error');
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ export class HermesSessionBroker {
|
||||
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})});
|
||||
const response=await this.fetcher('http://canina-hermes-inventory: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');
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface Health {
|
||||
version: string;
|
||||
commit: string;
|
||||
auth_required: boolean;
|
||||
provenance?: Row;
|
||||
}
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
@@ -57,7 +58,12 @@ export class HermesAdapter {
|
||||
private readonly config: HermesConfig,
|
||||
private readonly fetcher: typeof fetch = fetch,
|
||||
) {
|
||||
if (config.origin !== 'http://canina-hermes:9119')
|
||||
if (
|
||||
![
|
||||
'http://canina-hermes:9119',
|
||||
'http://canina-hermes-inventory:9119',
|
||||
].includes(config.origin)
|
||||
)
|
||||
throw new HermesError('CONFIGURATION');
|
||||
this.origin = config.origin;
|
||||
}
|
||||
@@ -122,7 +128,12 @@ export class HermesAdapter {
|
||||
} finally {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
}
|
||||
return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
|
||||
const data: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
if (this.origin === 'http://canina-hermes-inventory:9119') {
|
||||
const rows = Array.isArray(data) ? data : [data];
|
||||
for (const row of rows) provenance(row, true);
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (error instanceof HermesError) throw error;
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
@@ -132,12 +143,16 @@ export class HermesAdapter {
|
||||
}
|
||||
}
|
||||
async health(): Promise<Health> {
|
||||
const health = fields(await this.request('/api/health'), {
|
||||
ok: 'boolean',
|
||||
version: 'string',
|
||||
commit: 'string',
|
||||
auth_required: 'boolean',
|
||||
}) as unknown as Health;
|
||||
const raw = await this.request('/api/health');
|
||||
const health = {
|
||||
...fields(raw, {
|
||||
ok: 'boolean',
|
||||
version: 'string',
|
||||
commit: 'string',
|
||||
auth_required: 'boolean',
|
||||
}),
|
||||
...provenance(raw),
|
||||
} as unknown as Health;
|
||||
if (!health.auth_required) throw new HermesError('AUTH_REQUIRED');
|
||||
return health;
|
||||
}
|
||||
@@ -151,23 +166,47 @@ export class HermesAdapter {
|
||||
});
|
||||
if (raw.gateway_state !== null && typeof raw.gateway_state !== 'string')
|
||||
throw new HermesError('CONTRACT');
|
||||
return { ...row, gateway_state: raw.gateway_state as Json };
|
||||
return {
|
||||
...row,
|
||||
gateway_state: raw.gateway_state as Json,
|
||||
...provenance(raw),
|
||||
...(raw.provenance
|
||||
? {
|
||||
gateway_running: false,
|
||||
active_agents: 0,
|
||||
gateway_state: null,
|
||||
overall: 'unknown',
|
||||
liveGatewayState: 'unknown',
|
||||
liveActiveAgents: null,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
async profiles(): Promise<Row[]> {
|
||||
return list(object(await this.request('/api/profiles')).profiles).map((r) =>
|
||||
fields(r, {
|
||||
name: 'string',
|
||||
is_default: 'boolean',
|
||||
gateway_running: 'boolean',
|
||||
return list(object(await this.request('/api/profiles')).profiles).map(
|
||||
(r) => ({
|
||||
...fields(r, {
|
||||
name: 'string',
|
||||
is_default: 'boolean',
|
||||
gateway_running: 'boolean',
|
||||
}),
|
||||
...provenance(r),
|
||||
...(object(r).provenance
|
||||
? { gateway_running: false, liveGatewayState: 'unknown' }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
async modelInfo(profile: string): Promise<Row> {
|
||||
return fields(await this.request('/api/model/info', profile), {
|
||||
model: 'string',
|
||||
provider: 'string',
|
||||
effective_context_length: 'number',
|
||||
});
|
||||
const raw = await this.request('/api/model/info', profile);
|
||||
return {
|
||||
...fields(raw, {
|
||||
model: 'string',
|
||||
provider: 'string',
|
||||
effective_context_length: 'number',
|
||||
}),
|
||||
...provenance(raw),
|
||||
};
|
||||
}
|
||||
async modelOptions(profile: string): Promise<Row[]> {
|
||||
return list(
|
||||
@@ -189,6 +228,7 @@ export class HermesAdapter {
|
||||
);
|
||||
return {
|
||||
...fields(raw, { period_days: 'number' }),
|
||||
...provenance(raw),
|
||||
totals: fields(raw.totals, {
|
||||
total_input: 'number',
|
||||
total_output: 'number',
|
||||
@@ -218,7 +258,11 @@ export class HermesAdapter {
|
||||
is_active: 'boolean',
|
||||
}),
|
||||
);
|
||||
return { ...fields(raw, { total: 'number' }), sessions: rows };
|
||||
return {
|
||||
...fields(raw, { total: 'number' }),
|
||||
sessions: rows,
|
||||
...provenance(raw),
|
||||
};
|
||||
}
|
||||
async crons(profile: string): Promise<Row[]> {
|
||||
return list(await this.request('/api/cron/jobs', profile)).map((r) =>
|
||||
@@ -265,5 +309,34 @@ function scoped(
|
||||
): Row {
|
||||
const row = fields(value, schema);
|
||||
if (row.profile !== profile) throw new HermesError('FORBIDDEN');
|
||||
return row;
|
||||
return { ...row, ...provenance(value) };
|
||||
}
|
||||
|
||||
/** Snapshot provenance is mandatory on inventory origin; never synthesize a capture time. */
|
||||
function provenance(value: unknown, required = false): Row {
|
||||
const raw = object(value);
|
||||
if (!raw.provenance && !required) return {};
|
||||
const p = object(raw.provenance);
|
||||
if (
|
||||
p.source !== 'snapshot' ||
|
||||
p.liveProcess !== 'unknown' ||
|
||||
typeof p.capturedAt !== 'string' ||
|
||||
!p.capturedAt.endsWith('Z') ||
|
||||
!Number.isFinite(Date.parse(p.capturedAt)) ||
|
||||
Date.parse(p.capturedAt) > Date.now() ||
|
||||
typeof p.ageSeconds !== 'number' ||
|
||||
!Number.isInteger(p.ageSeconds) ||
|
||||
p.ageSeconds < 0 ||
|
||||
!['fresh', 'stale'].includes(String(p.freshness))
|
||||
)
|
||||
throw new HermesError('CONTRACT');
|
||||
return {
|
||||
provenance: {
|
||||
source: 'snapshot',
|
||||
capturedAt: p.capturedAt,
|
||||
ageSeconds: p.ageSeconds,
|
||||
freshness: p.freshness as string,
|
||||
liveProcess: 'unknown',
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { loadRuntimeGrants } from './runtime-read.module';
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
describe('reviewed runtime grants file', () => {
|
||||
it('loads an exact reviewed file and fails closed for malformed grants', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'runtime-grants-'));
|
||||
const file = join(dir, 'grants.json');
|
||||
try {
|
||||
await writeFile(file, JSON.stringify({ 'subject-1': ['default'] }));
|
||||
expect(await loadRuntimeGrants(file, dir)).toEqual({
|
||||
'subject-1': ['default'],
|
||||
});
|
||||
for (const invalid of [
|
||||
null,
|
||||
[],
|
||||
{ 'subject-1': [] },
|
||||
{ 'subject-1': ['default', 'default'] },
|
||||
{ 'subject-1': ['../x'] },
|
||||
{ 'subject-1': [3] },
|
||||
{ 'subject-1': ['default'], extra: true },
|
||||
]) {
|
||||
await writeFile(file, JSON.stringify(invalid));
|
||||
await expect(loadRuntimeGrants(file, dir)).rejects.toThrow();
|
||||
}
|
||||
await expect(loadRuntimeGrants('/etc/passwd')).rejects.toThrow();
|
||||
} finally {
|
||||
await rm(dir, { recursive: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -27,13 +27,27 @@ export interface VerifiedRuntimeRequest {
|
||||
export class RuntimeReadAccess {
|
||||
private readonly grants: Readonly<Record<string, readonly string[]>>;
|
||||
constructor(grants: Readonly<Record<string, readonly string[]>>) {
|
||||
if (
|
||||
!grants ||
|
||||
typeof grants !== 'object' ||
|
||||
Array.isArray(grants) ||
|
||||
Object.keys(grants).length > 1000
|
||||
)
|
||||
throw new Error('Invalid runtime access configuration');
|
||||
const copy: Record<string, readonly string[]> = Object.create(null);
|
||||
for (const [subject, profiles] of Object.entries(grants)) {
|
||||
if (
|
||||
!subject ||
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9@._:-]{0,127}$/.test(subject) ||
|
||||
['__proto__', 'constructor', 'prototype'].includes(subject) ||
|
||||
!Array.isArray(profiles) ||
|
||||
profiles.length === 0 ||
|
||||
profiles.some((p) => !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(p))
|
||||
profiles.length > 100 ||
|
||||
new Set(profiles).size !== profiles.length ||
|
||||
profiles.some(
|
||||
(p) =>
|
||||
typeof p !== 'string' ||
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(p),
|
||||
)
|
||||
)
|
||||
throw new Error('Invalid runtime access configuration');
|
||||
copy[subject] = Object.freeze([...profiles]);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { DynamicModule, Module } from '@nestjs/common';
|
||||
import { open } from 'node:fs/promises';
|
||||
import { open, lstat } from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { HermesManagementModule } from './hermes-management.module';
|
||||
import {
|
||||
RuntimeReadAccess,
|
||||
@@ -24,8 +26,46 @@ export async function runtimeSecret(path: string): Promise<string> {
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
/** Exact fixed mount roots only; startup fails closed, never browser/JWT grants. */
|
||||
export async function loadRuntimeGrants(
|
||||
path = '/run/secrets/hermes_runtime_grants',
|
||||
reviewedRoot?: string,
|
||||
): Promise<Readonly<Record<string, readonly string[]>>> {
|
||||
const roots = reviewedRoot
|
||||
? [resolve(reviewedRoot)]
|
||||
: ['/run/secrets', '/etc/canina'];
|
||||
if (!roots.includes(dirname(path)) || resolve(path) !== path)
|
||||
throw new HermesError('CONFIGURATION');
|
||||
try {
|
||||
const stat = await lstat(path);
|
||||
if (
|
||||
!stat.isFile() ||
|
||||
stat.isSymbolicLink() ||
|
||||
stat.size > 65536 ||
|
||||
stat.mode & 0o022
|
||||
)
|
||||
throw new Error();
|
||||
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const data: unknown = JSON.parse(await file.readFile('utf8'));
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data))
|
||||
throw new Error();
|
||||
new RuntimeReadAccess(data as Record<string, readonly string[]>);
|
||||
return data as Record<string, readonly string[]>;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
} catch {
|
||||
throw new HermesError('CONFIGURATION');
|
||||
}
|
||||
}
|
||||
@Module({})
|
||||
export class RuntimeReadModule {
|
||||
static async registerFromFile(
|
||||
path = '/run/secrets/hermes_runtime_grants',
|
||||
): Promise<DynamicModule> {
|
||||
return this.register(await loadRuntimeGrants(path));
|
||||
}
|
||||
static register(
|
||||
grants: Readonly<Record<string, readonly string[]>>,
|
||||
): DynamicModule {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
const provenance = {
|
||||
source: 'snapshot',
|
||||
capturedAt: '2020-01-01T00:00:00Z',
|
||||
ageSeconds: 100,
|
||||
freshness: 'stale',
|
||||
liveProcess: 'unknown',
|
||||
};
|
||||
function adapter(data: unknown) {
|
||||
return new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes-inventory:9119',
|
||||
token: () => Promise.resolve('test'),
|
||||
},
|
||||
jest.fn(() =>
|
||||
Promise.resolve(new Response(JSON.stringify(data), { status: 200 })),
|
||||
) as typeof fetch,
|
||||
);
|
||||
}
|
||||
describe('snapshot provenance boundary', () => {
|
||||
it('rejects missing provenance from dedicated inventory origin', async () => {
|
||||
await expect(
|
||||
adapter({
|
||||
ok: true,
|
||||
version: '1',
|
||||
commit: 'x',
|
||||
auth_required: true,
|
||||
}).health(),
|
||||
).rejects.toMatchObject({ code: 'CONTRACT' });
|
||||
});
|
||||
it('cannot present copied gateway scalars as live telemetry', async () => {
|
||||
const row = await adapter({
|
||||
version: '1',
|
||||
gateway_running: true,
|
||||
active_agents: 12,
|
||||
gateway_state: 'running',
|
||||
overall: 'ok',
|
||||
provenance,
|
||||
}).status('default');
|
||||
expect(row).toMatchObject({
|
||||
gateway_running: false,
|
||||
active_agents: 0,
|
||||
gateway_state: null,
|
||||
overall: 'unknown',
|
||||
liveGatewayState: 'unknown',
|
||||
liveActiveAgents: null,
|
||||
provenance,
|
||||
});
|
||||
});
|
||||
it('profile readiness cannot be inferred from copied PID state', async () => {
|
||||
const rows = await adapter({
|
||||
profiles: [
|
||||
{
|
||||
name: 'default',
|
||||
is_default: true,
|
||||
gateway_running: true,
|
||||
provenance,
|
||||
},
|
||||
],
|
||||
provenance,
|
||||
}).profiles();
|
||||
expect(rows[0]).toMatchObject({
|
||||
gateway_running: false,
|
||||
liveGatewayState: 'unknown',
|
||||
provenance,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
**Superseded wiring/provenance: see [snapshot repair](hermes-snapshot-provenance.md). Do not use literal grants or the old DNS alias below.**
|
||||
|
||||
# Runtime read vertical slice (not deployed)
|
||||
|
||||
Branch feature/v4-runtime-completion, base 5507fbc. No AppModule, live gateway,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Snapshot provenance repair — integration contract
|
||||
|
||||
This is independent snapshot inventory, **not a live Hermes executor**. No Production,
|
||||
deployment, live gateway edits, or RELEASE_AUTHORIZE execution is included.
|
||||
|
||||
## Parent-owned application wiring
|
||||
|
||||
Keep AuthModule/JwtStrategy. Replace literal user grants in parent-owned app.module.ts with:
|
||||
|
||||
```ts
|
||||
RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
```
|
||||
|
||||
Nest supports the resulting Promise<DynamicModule> in imports. Alternatively pass the
|
||||
reviewed nonsecret file `/etc/canina/runtime-grants.json`. No env/JWT/browser grant
|
||||
input is accepted by this registration. File is JSON object mapping exact verified DB
|
||||
user IDs to nonempty unique profile arrays; `{}` explicitly denies everyone. Missing,
|
||||
malformed, symlinked, group/world-writable, oversized files fail startup closed. Mount
|
||||
read-only and provision via reviewed configuration/secrets management; do not commit
|
||||
real user grants. Existing explicit register(grants) remains for tests/legacy consumers.
|
||||
Backend also mounts `/run/secrets/hermes_username` and `hermes_password` read-only.
|
||||
No app.module.ts modification belongs to this commit.
|
||||
|
||||
## Required coordinated origin change
|
||||
|
||||
Authenticated management module and broker now exclusively use
|
||||
`http://canina-hermes-inventory:9119`. compose.readonly.yml uses the distinct alias
|
||||
`canina-hermes-inventory`, NEVER `canina-hermes`. Generic adapter allowlist retains
|
||||
both reviewed exact origins for compatibility with separate existing consumers.
|
||||
No arbitrary origin/env URL accepted. Parent must cherry-pick broker/module/adapter
|
||||
and inventory compose together; do not add an alias to the existing gateway.
|
||||
No deployment performed. External network should still be internal and only contain
|
||||
backend/inventory; the distinct alias cannot shadow the live canina-hermes hostname.
|
||||
|
||||
## Snapshot exporter/operator gate
|
||||
|
||||
Every independent inventory root must include `snapshot-manifest.json`:
|
||||
|
||||
```json
|
||||
{"schemaVersion":1,"source":"snapshot","capturedAt":"2026-10-23T12:00:00Z"}
|
||||
```
|
||||
|
||||
The example is a schema example, NOT an actual capture attestation. Exporter must
|
||||
write the real capture instant from the approved consistent export. Never copy the
|
||||
example, use startup time, filesystem mtime, or claim this change captures/refreshes
|
||||
snapshots. Missing/invalid/future manifest prevents startup. It is revalidated per
|
||||
successful GET; invalid after startup returns503. Manifest is exporter metadata,
|
||||
not a cryptographic proof of consistency. Immutable reviewed export provisioning
|
||||
remains required. Fresh means age <=3600 seconds, otherwise stale; even fresh is
|
||||
NOT live readiness. No snapshot scheduler installed.
|
||||
|
||||
## Additive public response fields / panel handoff
|
||||
|
||||
All object read DTOs (health/status/usage/sessions/model-info) add:
|
||||
`provenance:{source:'snapshot',capturedAt:string,ageSeconds:number,freshness:'fresh'|'stale',liveProcess:'unknown'}`.
|
||||
Profile and schedule array shapes are preserved: provenance is on each row. Empty
|
||||
arrays have no rows to annotate; use the health response to display snapshot metadata.
|
||||
Profile rows add `liveGatewayState:'unknown'`; status adds the same plus
|
||||
`liveActiveAgents:null`. Existing required scalars remain typed but are conservative
|
||||
placeholders: `gateway_running:false`, `active_agents:0`, `gateway_state:null`,
|
||||
`overall:'unknown'`. False/zero MUST NOT render as measured offline/idle: when
|
||||
provenance.source is snapshot use the explicit unknown fields, label snapshot and
|
||||
show capturedAt/freshness. Health.ok only means inventory HTTP app responsiveness,
|
||||
never live gateway readiness. Profile existence is inventory availability, NOT
|
||||
process readiness. Adapter enforces provenance on dedicated snapshot origin and
|
||||
conservatively overwrites copied PID-derived status/profile scalars again.
|
||||
|
||||
Installed status handler was unsafe here: it probes gateway HTTP/PIDs/platforms and
|
||||
can stall despite this being an independent snapshot. Snapshot server replaces that
|
||||
route with measured package version and explicit unknown process fields; no status
|
||||
probe is run. Password auth/mutation denial/WebSocket denial remain intact.
|
||||
|
||||
## Executed acceptance
|
||||
|
||||
Remote disposable network-none exact pinned Hermes image, no original volumes:
|
||||
manifest-missing regression failed first; TCP login/profile/health/status provenance
|
||||
and stale capture assertions now pass; authenticated sockets denied1008. Disposable
|
||||
Node22 copy of source/dependencies: 9 hermes-management suites /34 tests pass and
|
||||
full backend tsc build passes. Adapter copied-live-state regression failed first;
|
||||
grants-loader missing-function regression failed first. Compiled actual Node broker
|
||||
-> TCP pinned server -> adapter -> policy-filtered profiles/status passes, deny reads
|
||||
zero credentials. Test timestamps/credentials are fixtures, not live telemetry.
|
||||
The first HTTP retry raced fixture startup and returned UNAVAILABLE; retry after
|
||||
server startup passed. No claim of full app/user-flow or live runtime integration.
|
||||
|
||||
Full non-DB Jest regression: 108 suites/854 tests passed; 1 suite/18 tests skipped. No RELEASE_AUTHORIZE suite was enabled.
|
||||
@@ -13,7 +13,7 @@ services:
|
||||
secrets: [hermes_username, hermes_password, hermes_signing_key]
|
||||
networks:
|
||||
backend:
|
||||
aliases: [canina-hermes]
|
||||
aliases: [canina-hermes-inventory]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cap_drop: [ALL]
|
||||
pids_limit: 128
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import os,tempfile,importlib.util
|
||||
os.environ['HERMES_HOME']=tempfile.mkdtemp()
|
||||
os.environ['HERMES_SERVE_HEADLESS']='1'
|
||||
from pathlib import Path
|
||||
import json
|
||||
(Path(os.environ["HERMES_HOME"])/"snapshot-manifest.json").write_text(json.dumps({"schemaVersion":1,"source":"snapshot","capturedAt":"2020-01-01T00:00:00Z"}))
|
||||
spec=importlib.util.spec_from_file_location('runtime_serve','/contract/serve.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
m.secret=lambda name:'isolated-test-only-'+name+'x'*32
|
||||
import uvicorn
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Dedicated read-inventory process: never starts cron, gateway, rooms, MCP or PTY."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import os, json
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from plugins.dashboard_auth.basic import BasicAuthProvider, hash_password
|
||||
@@ -15,7 +16,38 @@ def secret(name):
|
||||
if not value or '\n' in value or '\r' in value: raise RuntimeError('Runtime credential unavailable')
|
||||
return value
|
||||
|
||||
def snapshot_provenance():
|
||||
try:
|
||||
path=Path(os.environ['HERMES_HOME'])/'snapshot-manifest.json'
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size>4096:
|
||||
raise ValueError()
|
||||
data=json.loads(path.read_text())
|
||||
if set(data)!={'schemaVersion','source','capturedAt'} or data['schemaVersion']!=1 or data['source']!='snapshot':
|
||||
raise ValueError()
|
||||
captured=data['capturedAt']
|
||||
if not isinstance(captured,str) or not captured.endswith('Z'):
|
||||
raise ValueError()
|
||||
at=datetime.fromisoformat(captured.replace('Z','+00:00'))
|
||||
age=(datetime.now(timezone.utc)-at).total_seconds()
|
||||
if age<0: raise ValueError()
|
||||
return {'source':'snapshot','capturedAt':captured,'ageSeconds':int(age),
|
||||
'freshness':'fresh' if age<=3600 else 'stale','liveProcess':'unknown'}
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
raise RuntimeError('Valid snapshot manifest required') from None
|
||||
|
||||
def build_app():
|
||||
snapshot_provenance()
|
||||
# Never execute installed status: it probes PIDs, gateway HTTP and platform health.
|
||||
web_server.app.router.routes[:] = [route for route in web_server.app.router.routes
|
||||
if getattr(route,'path',None)!='/api/status']
|
||||
@web_server.app.get('/api/status')
|
||||
async def snapshot_status():
|
||||
from hermes_cli.web_server import get_version_info
|
||||
return {'version':get_version_info().base_version,'gateway_running':False,
|
||||
'gateway_state':None,'active_agents':0,'overall':'unknown',
|
||||
'liveGatewayState':'unknown','liveActiveAgents':None}
|
||||
# Place before installed catch-all UI route.
|
||||
web_server.app.router.routes.insert(0, web_server.app.router.routes.pop())
|
||||
register_global_provider(BasicAuthProvider(username=secret('hermes_username'),password_hash=hash_password(secret('hermes_password')),secret=secret('hermes_signing_key').encode(),ttl_seconds=300))
|
||||
web_server.app.state.auth_required=True
|
||||
web_server.app.state.bound_host='0.0.0.0'
|
||||
@@ -27,7 +59,27 @@ def build_app():
|
||||
path=request.url.path
|
||||
if not ((request.method=='GET' and path in allowed) or (request.method=='POST' and path=='/auth/password-login')):
|
||||
return JSONResponse({'detail':'Unavailable'},status_code=404)
|
||||
return await call_next(request)
|
||||
response=await call_next(request)
|
||||
if request.method!='GET' or response.status_code!=200: return response
|
||||
try:
|
||||
provenance=snapshot_provenance()
|
||||
except RuntimeError:
|
||||
return JSONResponse({'detail':'Snapshot unavailable'},status_code=503)
|
||||
body=b''.join([chunk async for chunk in response.body_iterator])
|
||||
data=json.loads(body)
|
||||
def annotate(row):
|
||||
return {**row,'provenance':provenance}
|
||||
if isinstance(data,list):
|
||||
data=[annotate(row) for row in data]
|
||||
else:
|
||||
data=annotate(data)
|
||||
if path=='/api/profiles':
|
||||
data['profiles']=[{**annotate(row),'gateway_running':False,'liveGatewayState':'unknown'} for row in data['profiles']]
|
||||
if path=='/api/status':
|
||||
# Legacy required scalars are conservative placeholders, NOT measurements.
|
||||
data.update(gateway_running=False,active_agents=0,overall='unknown',gateway_state=None,
|
||||
liveGatewayState='unknown',liveActiveAgents=None)
|
||||
return JSONResponse(data,headers={'Cache-Control':'no-store'})
|
||||
class NoSockets:
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope['type']=='websocket':
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
// Execute inside disposable compiled backend runner sharing fixture network namespace.
|
||||
const assert=require('node:assert/strict');
|
||||
const {HermesSessionBroker}=require('/work/dist/hermes-management/hermes-session-broker');
|
||||
const {HermesAdapter}=require('/work/dist/hermes-management/hermes.adapter');
|
||||
const {HermesIntegrationService}=require('/work/dist/hermes-management/hermes-integration.service');
|
||||
const {HermesSessionBroker}=require('/opt/backend/dist/hermes-management/hermes-session-broker');
|
||||
const {HermesAdapter}=require('/opt/backend/dist/hermes-management/hermes.adapter');
|
||||
const {HermesIntegrationService}=require('/opt/backend/dist/hermes-management/hermes-integration.service');
|
||||
const fetcher=(input,options)=>{const url=new URL(String(input));url.hostname='127.0.0.1';return fetch(url,options);};
|
||||
(async()=>{
|
||||
let reads=0;
|
||||
const broker=new HermesSessionBroker(async()=>{reads++;return {username:'isolated-test-only-hermes_username'+'x'.repeat(32),password:'isolated-test-only-hermes_password'+'x'.repeat(32)};},fetcher);
|
||||
const adapter=new HermesAdapter({origin:'http://canina-hermes:9119',token:()=>broker.token()},fetcher);
|
||||
const adapter=new HermesAdapter({origin:'http://canina-hermes-inventory:9119',token:()=>broker.token()},fetcher);
|
||||
const runtime=new HermesIntegrationService(adapter,{authorize:async(p,action,profile)=>p.subject==='test-admin'&&action==='runtime.read'&&(!profile||profile==='default')});
|
||||
await assert.rejects(()=>runtime.health({subject:'denied',profiles:[]}),{code:'FORBIDDEN'});assert.equal(reads,0);
|
||||
const principal={subject:'test-admin',profiles:['default']};
|
||||
assert.equal((await runtime.health(principal)).auth_required,true);
|
||||
const profiles=await runtime.profiles(principal);assert(profiles.some(p=>p.name==='default'));assert(profiles.every(p=>p.name==='default'));
|
||||
await assert.rejects(()=>runtime.status(principal,'outside'),{code:'FORBIDDEN'});
|
||||
const status=await runtime.status(principal,'default');assert.equal(status.overall,'unknown');assert.equal(status.liveActiveAgents,null);assert.equal(status.provenance.source,'snapshot');
|
||||
assert.equal(profiles[0].provenance.source,'snapshot');assert.equal(profiles[0].liveGatewayState,'unknown');
|
||||
assert.equal(reads,1);
|
||||
console.log('PASS real Node broker -> pinned TCP Hermes login -> adapter -> policy-filtered profiles; deny performs zero secret reads; cache coalesced');
|
||||
})().catch(e=>{console.error(e.code||'contract failure');process.exitCode=1;});
|
||||
@@ -7,6 +7,21 @@ spec=importlib.util.spec_from_file_location('runtime_serve','/contract/serve.py'
|
||||
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
values={'hermes_username':'contract','hermes_password':secrets.token_urlsafe(32),'hermes_signing_key':secrets.token_urlsafe(32)}
|
||||
module.secret=lambda name:values[name]
|
||||
# A capture timestamp is supplied by a reviewed exporter, never inferred at boot.
|
||||
import json
|
||||
manifest=Path(os.environ['HERMES_HOME'])/'snapshot-manifest.json'
|
||||
for invalid in [None, {}, {'schemaVersion':1,'source':'snapshot','capturedAt':'not-a-date'}, {'schemaVersion':1,'source':'snapshot','capturedAt':'2999-01-01T00:00:00Z'}]:
|
||||
if invalid is None:
|
||||
manifest.unlink(missing_ok=True)
|
||||
else:
|
||||
manifest.write_text(json.dumps(invalid))
|
||||
try:
|
||||
module.build_app()
|
||||
except (RuntimeError, ValueError):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('invalid or missing manifest accepted')
|
||||
manifest.write_text(json.dumps({'schemaVersion':1,'source':'snapshot','capturedAt':'2020-01-01T00:00:00Z'}))
|
||||
app=module.build_app()
|
||||
import uvicorn
|
||||
server=uvicorn.Server(uvicorn.Config(app,host='0.0.0.0',port=9119,lifespan='off',access_log=False,log_level='warning'))
|
||||
@@ -22,7 +37,26 @@ with httpx.Client(base_url='http://127.0.0.1:9119') as c:
|
||||
r=c.post('/auth/password-login',json={'provider':'basic','username':values['hermes_username'],'password':values['hermes_password']})
|
||||
assert r.status_code==200 and r.json()['ok'] is True
|
||||
assert c.get('/api/profiles').status_code==200
|
||||
assert c.get('/api/health').json()['auth_required'] is True
|
||||
health=c.get('/api/health').json()
|
||||
assert health['auth_required'] is True
|
||||
assert health['provenance']['source']=='snapshot'
|
||||
assert health['provenance']['capturedAt']=='2020-01-01T00:00:00Z'
|
||||
assert health['provenance']['freshness']=='stale'
|
||||
assert health['provenance']['liveProcess']=='unknown'
|
||||
profiles=c.get('/api/profiles').json()['profiles']
|
||||
assert profiles and all(p['liveGatewayState']=='unknown' and p['gateway_running'] is False and p['provenance']['source']=='snapshot' for p in profiles)
|
||||
status=c.get('/api/status',params={'profile':'default'}).json()
|
||||
assert status['overall']=='unknown' and status['gateway_state'] is None
|
||||
assert status['gateway_running'] is False and status['active_agents']==0
|
||||
assert status['liveActiveAgents'] is None and status['liveGatewayState']=='unknown'
|
||||
for path in ['/api/model/info','/api/analytics/usage','/api/sessions','/api/cron/jobs']:
|
||||
response=c.get(path,params={'profile':'default'})
|
||||
if response.status_code==200:
|
||||
data=response.json()
|
||||
if isinstance(data,list):
|
||||
assert all(r['provenance']['source']=='snapshot' for r in data)
|
||||
else:
|
||||
assert data['provenance']['source']=='snapshot'
|
||||
assert c.post('/api/cron/jobs/example/resume').status_code==404
|
||||
assert c.get('/api/config').status_code==404
|
||||
assert c.get('/api/ws').status_code==404
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import os,tempfile,importlib.util
|
||||
os.environ['HERMES_HOME']=tempfile.mkdtemp()
|
||||
from pathlib import Path
|
||||
import json
|
||||
(Path(os.environ['HERMES_HOME'])/'snapshot-manifest.json').write_text(json.dumps({'schemaVersion':1,'source':'snapshot','capturedAt':'2020-01-01T00:00:00Z'}))
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
spec=importlib.util.spec_from_file_location('runtime_serve','/contract/serve.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
|
||||
|
||||
Reference in new issue
Block a user