95 lines
5.1 KiB
Python
95 lines
5.1 KiB
Python
"""Dedicated read-inventory process: never starts cron, gateway, rooms, MCP or PTY."""
|
|
from pathlib import Path
|
|
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
|
|
from hermes_cli.dashboard_auth.registry import register_global_provider
|
|
from hermes_cli import web_server
|
|
import uvicorn
|
|
|
|
def secret(name):
|
|
p=Path('/run/secrets')/name
|
|
if not p.is_file() or p.stat().st_size>4096: raise RuntimeError('Runtime credential unavailable')
|
|
value=p.read_text().strip()
|
|
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'
|
|
# Enforce an outer exact route/method allowlist. Installed public health/status stay
|
|
# internal; protected inventory still uses installed provider middleware.
|
|
allowed={'/api/health','/api/profiles','/api/status','/api/analytics/usage','/api/sessions','/api/cron/jobs','/api/model/info'}
|
|
@web_server.app.middleware('http')
|
|
async def readonly_gate(request:Request,call_next):
|
|
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)
|
|
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':
|
|
await send({'type':'websocket.close','code':1008})
|
|
return
|
|
await web_server.app(scope,receive,send)
|
|
return NoSockets()
|
|
|
|
if __name__=='__main__':
|
|
# No upstream lifespan: no eager schema reconciliation or hosted-room recovery.
|
|
# Data is an operator-prepared independent snapshot, NEVER the gateway's volume.
|
|
uvicorn.run(build_app(),host='0.0.0.0',port=9119,lifespan='off',access_log=False,log_level='warning')
|