Files
canina/infra/hermes-editorial/client.py
2026-10-24 03:45:51 +00:00

113 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Bounded PMO proposal only. No approval, execution, cron or publication API."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import re
import stat
import tempfile
import uuid
import urllib.error
import urllib.request
ENDPOINT = 'https://stageapi.canina.ir/api/internal/prepare-worker/editorial-proposals'
class ClientError(Exception):
pass
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def safe(path):
if not path.is_absolute() or '..' in path.parts:
raise ValueError('Absolute home required')
for p in (path, *path.parents):
if p.is_symlink(): raise ValueError('Symlink refused')
return path
def private_read(path):
safe(path)
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, 'rb') as stream:
s = os.fstat(stream.fileno())
if not stat.S_ISREG(s.st_mode) or s.st_uid != os.getuid() or s.st_nlink != 1 or stat.S_IMODE(s.st_mode) not in (0o400, 0o600) or not 0 < s.st_size <= 16384:
raise ValueError('Private runtime-owned regular file required')
return stream.read(16385)
def atomic(path, data):
fd, name = tempfile.mkstemp(prefix='.pmo-', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as stream:
stream.write(data); stream.flush(); os.fsync(stream.fileno())
os.chmod(name, 0o400); os.replace(name, path)
finally:
if os.path.exists(name): os.unlink(name)
def submit(home, commit, proposal, *, endpoint=ENDPOINT, timeout=15):
# endpoint override is an in-process disposable-test seam, never CLI/config input.
safe(home)
if not re.fullmatch('[0-9a-f]{40}', commit): raise ValueError('Full deployment SHA required')
if not isinstance(proposal, dict) or set(proposal) != {'researchTopic', 'acceptanceCriteria'}:
raise ValueError('Only owner topic and acceptanceCriteria accepted')
topic, criteria = proposal['researchTopic'], proposal['acceptanceCriteria']
if not isinstance(topic, str) or not topic.strip() or len(topic) > 180 or not isinstance(criteria, list) or not 1 <= len(criteria) <= 10 or any(not isinstance(v, str) or not v.strip() or len(v) > 500 for v in criteria):
raise ValueError('Invalid proposal')
token = private_read(home/'editorial-v4/credentials/editorial-pmo-token').decode('ascii')
if not re.fullmatch('[A-Za-z0-9_-]{64}', token): raise ValueError('Invalid credential')
directory = safe(home/'editorial-v4/client-state')
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if directory.stat().st_uid != os.getuid() or stat.S_IMODE(directory.stat().st_mode) != 0o700:
raise ValueError('Private state directory required')
lock = safe(directory/'lock')
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'a') as stream:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
body = {**proposal, 'pilotKind':'editorial-research-to-brief-v1', 'operationMode':'PREPARE', 'environment':'staging', 'scope':'EDITORIAL_RESEARCH_TO_BRIEF', 'commitSha':commit, 'budgetLimitCents':20}
state = safe(directory/'proposal.json')
if state.exists():
stored = json.loads(private_read(state))
request_id = stored.get('requestId')
if str(uuid.UUID(request_id)) != request_id or {k:v for k,v in stored.items() if k != 'requestId'} != body:
raise ValueError('Existing request differs; explicit owner review required')
body = stored
else:
body['requestId'] = str(uuid.uuid4())
atomic(state, json.dumps(body, sort_keys=True).encode())
req = urllib.request.Request(endpoint, data=json.dumps(body).encode(), headers={'Authorization':'Bearer '+token, 'Content-Type':'application/json'}, method='POST')
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
try:
with opener.open(req, timeout=timeout) as response:
if response.status != 201: raise ClientError('Unexpected proposal status')
raw = response.read(16385)
if len(raw)>16384: raise ClientError('Response exceeds bound')
result = json.loads(raw)
if not isinstance(result, dict) or not isinstance(result.get('taskId'), str): raise ClientError('Invalid proposal response')
# Do not reflect arbitrary backend response bodies or credential material.
return {'requestId':body['requestId'], 'taskId':result['taskId']}
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
code = getattr(error, 'code', None)
if isinstance(error, urllib.error.HTTPError): error.close()
raise ClientError('Proposal rejected HTTP '+str(code) if isinstance(code,int) else 'Proposal unavailable; retry same saved request') from None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--proposal-file', type=Path, required=True)
args = parser.parse_args()
try:
home = Path(os.environ['HERMES_HOME'])
deployment = json.loads(private_read(home/'editorial-v4/deployment.json'))
proposal = json.loads(private_read(args.proposal_file))
print(json.dumps(submit(home, deployment['commitSha'], proposal), sort_keys=True))
except (OSError, ValueError, KeyError, ClientError):
parser.exit(1, 'PMO proposal failed (private details suppressed); saved request retained\n')
if __name__ == '__main__': main()