137 lines
8.1 KiB
Python
137 lines
8.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())
|
|
projected=Path(os.environ['HERMES_HOME'])/'inventory.json'
|
|
if os.environ.get('HERMES_REQUIRE_PROJECTED_INVENTORY')=='1' and not projected.is_file():
|
|
raise RuntimeError('Projected inventory required')
|
|
if projected.exists():
|
|
# Immutable exporter projection, not installed config/session/cron readers.
|
|
if projected.is_symlink() or projected.stat().st_size>32*1024*1024:
|
|
raise RuntimeError('Invalid projected inventory')
|
|
inventory=json.loads(projected.read_text())
|
|
if set(inventory)!={'schemaVersion','profile','sessions'} or inventory['schemaVersion']!=1 or not isinstance(inventory['sessions'],list):
|
|
raise RuntimeError('Invalid projected inventory')
|
|
profile=inventory['profile']
|
|
import re
|
|
if not isinstance(profile,str) or not re.fullmatch('[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}',profile):
|
|
raise RuntimeError('Invalid projected inventory')
|
|
replaced={'/api/profiles','/api/sessions','/api/analytics/usage','/api/cron/jobs','/api/model/info'}
|
|
web_server.app.router.routes[:]=[r for r in web_server.app.router.routes if getattr(r,'path',None) not in replaced]
|
|
async def projected_read(request:Request):
|
|
from fastapi import HTTPException
|
|
path=request.url.path
|
|
requested=request.query_params.get('profile',profile)
|
|
if requested!=profile: raise HTTPException(status_code=404)
|
|
if path=='/api/profiles':
|
|
return {'profiles':[{'name':profile,'is_default':profile=='default','gateway_running':False}]}
|
|
if path=='/api/model/info':
|
|
return {'model':'unknown','provider':'unknown','effective_context_length':0}
|
|
if path=='/api/cron/jobs': return [] # Cron commands deliberately not captured.
|
|
try:
|
|
limit=int(request.query_params.get('limit','20'));offset=int(request.query_params.get('offset','0'))
|
|
days=int(request.query_params.get('days','30'))
|
|
if not 1<=limit<=100 or not 0<=offset<=10000 or not 1<=days<=365: raise ValueError()
|
|
except ValueError: raise HTTPException(status_code=400)
|
|
rows=inventory['sessions']
|
|
if path=='/api/sessions':
|
|
return {'total':len(rows),'sessions':[{k:r[k] for k in ['id','profile','source','is_active']} for r in list(reversed(rows))[offset:offset+limit]],'storage':{}}
|
|
captured=datetime.fromisoformat(snapshot_provenance()['capturedAt'].replace('Z','+00:00')).timestamp()
|
|
filtered=[r for r in rows if captured-days*86400<=r['startedAt']<=captured]
|
|
return {'period_days':days,'totals':{'total_input':sum(r['inputTokens'] for r in filtered),
|
|
'total_output':sum(r['outputTokens'] for r in filtered),'total_sessions':len(filtered),
|
|
'total_estimated_cost':sum(r['estimatedCost'] for r in filtered)}}
|
|
for path in replaced:
|
|
web_server.app.add_api_route(path,projected_read,methods=['GET'])
|
|
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')
|