Files
dpl/scripts/project-domains/public_client.py
T

193 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Signed public-domain consumer. Run only on the owning project's server.
Canonical source: ATOM integrations/domainhub/public_client.py; copies are versioned.
"""
import argparse
import fcntl
import hashlib
import hmac
import json
import os
import re
import subprocess
import tempfile
import time
import uuid
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
from urllib.error import HTTPError
MAX_AGE = 86400
TERMINAL = {'sent', 'failed', 'uncertain', 'cancelled', 'rejected'}
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_a, **_k): return None
def read(path, default=None):
try: return json.loads(Path(path).read_text())
except (OSError, ValueError): return default
def atomic(path, data):
path=Path(path); path.parent.mkdir(parents=True, exist_ok=True)
fd,name=tempfile.mkstemp(prefix='.'+path.name, dir=path.parent)
try:
with os.fdopen(fd,'w') as out:
os.fchmod(out.fileno(),0o640)
json.dump(data,out,ensure_ascii=False,separators=(',',':'))
out.flush(); os.fsync(out.fileno())
os.replace(name,path)
directory=os.open(path.parent,os.O_RDONLY)
try: os.fsync(directory)
finally: os.close(directory)
finally:
if os.path.exists(name): os.unlink(name)
def request(url, key, data=None, extra=None):
headers={'Authorization':'Bearer '+key,'Accept':'application/json',**(extra or {})}
if data is not None: headers['Content-Type']='application/json'
req=Request(url,data=json.dumps(data,ensure_ascii=False,separators=(',',':')).encode() if data is not None else None,headers=headers)
with build_opener(NoRedirect()).open(req,timeout=12) as response:
body=response.read(1048577)
if len(body)>1048576: raise ValueError('response_too_large')
return response.headers,body
def signed(config, path, transport=request, now=None):
headers,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/'+path,config['key'])
stamp=headers.get('X-DomainHub-Timestamp',''); signature=headers.get('X-DomainHub-Signature','')
now=time.time() if now is None else now
if not stamp.isdigit() or abs(now-int(stamp))>120: raise ValueError('invalid_timestamp')
expected=hmac.new(config['key'].encode(),stamp.encode()+b'.'+body,hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected,signature): raise ValueError('invalid_signature')
data=json.loads(body)
if any(data.get(k)!=config[k] for k in ['project','environment','instance']): raise ValueError('wrong_scope')
if type(data.get('version')) is not int or data['version']<1: raise ValueError('invalid_version')
return data,body,headers
def validate_manifest(manifest, config):
if manifest.get('schema')!='domainhub.public.v1' or not isinstance(manifest.get('providers'),dict): raise ValueError('invalid_schema')
if set(manifest['providers'])!=set(config['providers']): raise ValueError('wrong_providers')
for provider in manifest['providers'].values():
entries=provider.get('entries')
if not isinstance(entries,list): raise ValueError('invalid_entries')
codes=set()
for entry in entries:
u=urlsplit(entry.get('url',''))
if u.scheme!='https' or not u.hostname or u.username or u.password or u.query or u.fragment or u.port not in (None,443) or any(c.isspace() for c in entry['url']): raise ValueError('invalid_public_url')
if entry.get('role') not in {'primary','navigation','direct_access'} or type(entry.get('eligible')) is not bool or entry.get('code') in codes: raise ValueError('invalid_entry')
codes.add(entry['code'])
if entry['eligible'] and (entry.get('access')!='available' or entry.get('reason') is not None): raise ValueError('invalid_eligibility')
selected=provider.get('selected')
if selected is not None and (selected not in entries or not selected['eligible']): raise ValueError('invalid_selection')
def current(state, now=None):
now=time.time() if now is None else now
return isinstance(state,dict) and 0<=now-state.get('checked_at',0)<=MAX_AGE
def available(state, provider, now=None):
if not current(state,now): return None
selected=state['manifest']['providers'].get(provider,{}).get('selected')
if not selected or not selected.get('eligible') or selected.get('access')!='available': return None
until=selected.get('valid_until')
if until:
from datetime import datetime, timezone
stamp=datetime.fromisoformat(until).replace(tzinfo=timezone.utc).timestamp()
if stamp <= (time.time() if now is None else now): return None
return selected
def runtime_check(config, version):
result=subprocess.run(config['validate_command'],env={**os.environ,'DOMAINHUB_EXPECT_VERSION':str(version)},capture_output=True,timeout=20)
if result.returncode: raise ValueError('runtime_verification_failed')
return json.loads(result.stdout or b'{}')
def sync(config, force=False, transport=request, verify=runtime_check, now=None):
now=int(time.time() if now is None else now)
path=Path(config['state_path']); state=read(path,{})
watermark=read(str(path)+'.watermark',{'version':0,'digest':''})
meta,_,_=signed(config,'version',transport,now)
if meta.get('schema')!='domainhub.public-version.v1' or not re.fullmatch('[a-f0-9]{64}',meta.get('digest','')): raise ValueError('invalid_version_response')
if meta['version']<watermark['version'] or (meta['version']==watermark['version'] and watermark['digest']!=meta['digest']): raise ValueError('rollback_or_conflict')
changed=state.get('digest')!=meta['digest'] or state.get('manifest',{}).get('version')!=meta['version']
if changed or force:
manifest,body,headers=signed(config,'snapshot',transport,now)
digest=hashlib.sha256(body).hexdigest()
if manifest['version']<meta['version'] or manifest['version']<watermark['version']: raise ValueError('stale_snapshot')
if manifest['version']==meta['version'] and digest!=meta['digest']: raise ValueError('snapshot_digest_mismatch')
validate_manifest(manifest,config)
if manifest['version']==watermark['version'] and digest!=watermark['digest']: raise ValueError('same_version_conflict')
state={'manifest':manifest,'digest':digest,'delivery':int(headers['X-DomainHub-Delivery']),'checked_at':now}
else:
validate_manifest(state['manifest'],config)
state={**state,'checked_at':now,'delivery':meta['delivery']}
atomic(str(path)+'.watermark',{'version':state['manifest']['version'],'digest':state['digest']})
atomic(path,state)
# ACK only after the consuming application's resolver reads the active file.
if config.get('catalog_path'):
provider=state['manifest']['providers'][config['catalog_provider']]
records=[]
candidates=sorted([e for e in provider['entries'] if e['eligible'] and e['role']!='navigation'], key=lambda e:(0 if e['role']=='direct_access' else 1,-e['priority'], -__import__('datetime').datetime.fromisoformat(e['activated_at']).timestamp(),e['code']))
preferred=candidates[0]['code'] if candidates else None
for e in provider['entries']:
item={'domain':e['hostname'],'role':'direct' if e['role']=='direct_access' else e['role'],'domainhub':e['code'],'eligible':e['eligible'],'recommended':e['code']==preferred}
if e['access']!='available': item['access']=e['access']
records.append(item)
atomic(config['catalog_path'],{'source':'domainhub.public.v1','version':state['manifest']['version'],'domains':records})
context=verify(config,state['manifest']['version'])
atomic(str(path)+'.runtime',context)
_,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/deliveries/'+str(state['delivery'])+'/ack',config['key'],{'version':state['manifest']['version'],'digest':state['digest'],'status':'applied'})
if json.loads(body).get('status')!='applied': raise ValueError('invalid_ack')
return {'version':state['manifest']['version'],'changed':changed,'status':'applied'}
def incidents(config, state, journal, now):
active=journal.setdefault('active',{}); outbox=journal.setdefault('outbox',[])
context=read(config['state_path']+'.runtime',{})
for code in config['providers']:
selection=available(state,code,now)
if selection is None and code not in active:
incident=str(uuid.uuid4()); active[code]=incident
provider=(state or {}).get('manifest',{}).get('providers',{}).get(code,{})
reasons=';'.join(e['hostname']+': '+str(e.get('reason') or '不可用') for e in provider.get('entries',[]))
if not current(state,now): reasons='快照缺失或超过24小时未成功同步。'+reasons
text=f"【{config['label']} - {code}无可用广告域名】\n该服务商已暂停自动引流。\n原因:{reasons}\n版本:{(state or {}).get('manifest',{}).get('version','无')}\n投放状态:{json.dumps(context,ensure_ascii=False)}\n请补充可用入口或核实后明确恢复域名。"
outbox.append({'key':'domainhub.'+incident+'.critical','bot':'critical','text':text,'status':'pending','receipt':None,'retry_at':0,'attempts':0})
elif selection is not None and code in active:
incident=active.pop(code)
outbox.append({'key':'domainhub.'+incident+'.recovery','bot':'notification','text':f"【{config['label']} - {code}广告域名恢复】\n当前选用:{selection['url']}\n版本:{state['manifest']['version']}\n仍遵守原投放开关和暂避风头模式。",'status':'pending','receipt':None,'retry_at':0,'attempts':0})
def alerts(config, now=None, transport=request):
if not config.get('alerts_enabled'): return
now=int(time.time() if now is None else now); path=config['state_path']+'.alerts'
journal=read(path,{'active':{},'outbox':[]})
incidents(config,read(config['state_path']),journal,now)
atomic(path,journal)
for message in [m for m in journal['outbox'] if m['status'] not in TERMINAL and m['retry_at']<=now][:5]:
message['attempts']+=1; delay=min(21600,900*(2**min(message['attempts']-1,5)))
try:
endpoint=config['telehub_url'].rstrip('/')+'/api/v1/messages'
if message['receipt']: _,body=transport(endpoint+'/'+message['receipt'],config['telehub_key'])
else: _,body=transport(endpoint,config['telehub_key'],{'bot':message['bot'],'target':'base','text':message['text']},{'Idempotency-Key':message['key']})
receipt=json.loads(body)['data']
if (not re.fullmatch('[a-f0-9-]{36}',receipt.get('id','')) or receipt.get('status') not in TERMINAL|{'queued','sending'} or receipt.get('bot_code')!=message['bot'] or receipt.get('target_code')!='base' or (message['receipt'] and message['receipt']!=receipt['id'])): raise ValueError('invalid_receipt')
message.update(receipt=receipt['id'],status=receipt['status'],error=None)
except HTTPError as exc:
message['error']='http_'+str(exc.code)
if exc.code==429: delay=max(delay,int(exc.headers.get('Retry-After','0')) if exc.headers.get('Retry-After','0').isdigit() else 0)
elif 400<=exc.code<500: message['status']='rejected'
except (OSError,ValueError,KeyError,TimeoutError): message['error']='transport_or_receipt'
message['retry_at']=now+delay; atomic(path,journal)
def main():
parser=argparse.ArgumentParser();parser.add_argument('--config',required=True);parser.add_argument('--full',action='store_true');args=parser.parse_args()
config=read(args.config)
if not config or config.get('environment')!='production' or not re.fullmatch('dhc_[a-f0-9]{64}',config.get('key','')): raise SystemExit('invalid_private_configuration')
if urlsplit(config['hub_url']).scheme!='https': raise SystemExit('invalid_hub_url')
path=Path(config['state_path']); path.parent.mkdir(parents=True,exist_ok=True)
with open(str(path)+'.lock','a') as lock:
try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError: return
try: print(json.dumps(sync(config,args.full)))
except Exception as exc: print(json.dumps({'status':'sync_failed','error':type(exc).__name__}))
alerts(config)
if __name__=='__main__': main()