"""Verify Autonet diagnostic evidence (Python 3.10+, cryptography). Fetch JWKS only from the fixed trusted URL below, using normal TLS verification. Never fetch a key URL from an untrusted token. The caller supplies its previously chosen inputs and challenge, and must atomically consume the challenge once when accepting a delegation result. Signature validation alone does not accept a task. """ import base64 import hashlib import hmac import json import re import time from urllib.parse import urlsplit, urlunsplit from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey KEYS_URL = 'https://autonet.work/health/v1/evidence/keys' def decode(value): if not isinstance(value,str) or not re.fullmatch(r'[A-Za-z0-9_-]+',value):raise ValueError('Invalid base64url') return base64.urlsafe_b64decode(value+'='*(-len(value)%4)) def strict_json(raw): def pairs(items): result={} for k,v in items: if k in result:raise ValueError('Duplicate JSON member') result[k]=v return result def invalid(value):raise ValueError('Non-finite JSON') return json.loads(raw.decode('utf-8'),object_pairs_hook=pairs,parse_constant=invalid) def expected_digest(kind,url,expect,nonce): p=urlsplit(url) if p.scheme not in ('http','https') or not p.hostname or p.query or p.fragment or p.username is not None or p.password is not None: raise ValueError('Invalid expected URL') normalized=urlunsplit((p.scheme,p.netloc,p.path or '/','','')) # v1 uses Python JSON encoding, NOT RFC 8785. Preserve numeric forms (1 vs 1.0), # list order, explicit ports, hostname spelling and supplied assertion fields. raw=json.dumps({'kind':kind,'url':normalized,'expect':expect,'nonce':nonce},sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii') return 'sha256:'+hashlib.sha256(raw).hexdigest() def verify_diagnostic(token,jwks,*,kind,url,nonce,expect=None,now=None,max_age_sec=300): """Return verified claims, including failures. Raises on invalid/stale evidence. Evaluate evidence.ok / assertion_pass and MCP tool_count_complete yourself. Keep the original URL/assertions privately; do not reconstruct expectations from the token. A successful check is one vantage at one time, not an SLA. """ now=time.time() if now is None else now if type(max_age_sec) is not int or not 016384:raise ValueError('Invalid token size') header_raw,payload_raw,signature=token.split('.') header=strict_json(decode(header_raw)) if not isinstance(header,dict) or set(header)!={'alg','kid','typ'} or header['alg']!='EdDSA' or header['typ']!='autonet-diagnostic+jwt':raise ValueError('Unexpected signature header') keys=[k for k in jwks['keys'] if k.get('kid')==header['kid']] if len(keys)!=1:raise ValueError('Unknown/ambiguous key; refresh trusted JWKS once') key=keys[0] if (key['kty'],key['crv'],key['alg'],key['use'])!=('OKP','Ed25519','EdDSA','sig'):raise ValueError('Unexpected verification key') Ed25519PublicKey.from_public_bytes(decode(key['x'])).verify(decode(signature),(header_raw+'.'+payload_raw).encode('ascii')) c=strict_json(decode(payload_raw)) if c['iss']!='https://autonet.work' or c['aud']!='autonet-diagnostic' or c['schema_version']!='autonet-diagnostic-evidence-v1':raise ValueError('Unexpected issuer, audience or schema') if c['kind']!=kind or c['nonce']!=nonce or c['sub']!=c['jti'] or not re.fullmatch(r'dg_[A-Za-z0-9_-]{16}',c['jti']):raise ValueError('Operation or challenge mismatch') if any(type(c[k]) is not int for k in ('iat','exp','observation_started_at','observation_completed_at')):raise ValueError('Invalid timestamps') if not (0