115 lines
6.1 KiB
Python
115 lines
6.1 KiB
Python
"""Bounded, secret-free deployment receipts and monotonic phase accounting."""
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import os
|
|
import tempfile
|
|
import re
|
|
from pathlib import Path
|
|
import time
|
|
|
|
FORMAT = 1
|
|
PHASES = ('release_preparation','production_validation','remote_activation','receipt_retrieval','scope_verification','build','packaging_signing','compression','transfer','decompression',
|
|
'package_validation','database_state_verification','migration_history_verification',
|
|
'database_backup','migration_execution','service_stop','release_installation','release_activation',
|
|
'service_start','application_health_readiness','postactivation_verification','public_acceptance','receipt_generation')
|
|
|
|
|
|
def utc():
|
|
return datetime.now(timezone.utc).isoformat(timespec='milliseconds')
|
|
|
|
|
|
class Receipt:
|
|
def __init__(self, origin='web1'):
|
|
self.started = time.monotonic()
|
|
self.stack = []
|
|
self.data = {'format':FORMAT,'origin':origin,'started_utc':utc(),'completed_utc':None,
|
|
'status':'in-progress','phases':[],'warnings':[],'failures':[],
|
|
'checks':{},'migrations':{'executed':None,'baselined':None},
|
|
'recovery':'No automatic database restore or application rollback. Review protected attempt evidence on failure.'}
|
|
|
|
@contextmanager
|
|
def phase(self, name):
|
|
if name not in PHASES:
|
|
raise ValueError('Unknown measured phase')
|
|
row={'name':name,'started_utc':utc(),'parent':self.stack[-1]['name'] if self.stack else None}
|
|
start=time.monotonic(); state={'name':name,'children':0.0}
|
|
self.stack.append(state)
|
|
try:
|
|
yield
|
|
row['outcome']='passed'
|
|
except BaseException:
|
|
row['outcome']='failed'
|
|
raise
|
|
finally:
|
|
self.stack.pop(); elapsed=time.monotonic()-start
|
|
row.update(completed_utc=utc(),seconds=round(elapsed,6),exclusive_seconds=round(max(0,elapsed-state['children']),6))
|
|
self.data['phases'].append(row)
|
|
if self.stack:self.stack[-1]['children']+=elapsed
|
|
|
|
def component(self, name, seconds, parent):
|
|
"""Import a measured child duration; do not invent cross-process timestamps."""
|
|
import math
|
|
if name not in PHASES or type(seconds) not in (float,int) or not math.isfinite(seconds):
|
|
raise ValueError('Invalid measured component')
|
|
row=next((x for x in reversed(self.data['phases']) if x['name']==parent),None)
|
|
if row is None or not 0<=seconds<=row['seconds']+.001:
|
|
raise ValueError('Component lies outside its measured parent')
|
|
self.data['phases'].append({'name':name,'parent':parent,'seconds':round(seconds,6),
|
|
'exclusive_seconds':round(seconds,6),'started_utc':None,'completed_utc':None,
|
|
'clock':'SQL worker Stopwatch; measured duration, UTC endpoints unavailable','outcome':'passed'})
|
|
row['exclusive_seconds']=round(max(0,row['exclusive_seconds']-seconds),6)
|
|
|
|
def finish(self, status):
|
|
self.data['status']=status
|
|
self.data['completed_utc']=utc()
|
|
total=time.monotonic()-self.started
|
|
accounted=sum(x['seconds'] for x in self.data['phases'] if x['parent'] is None)
|
|
self.data['timing']={'total_seconds':round(total,6),'measured_top_level_seconds':round(accounted,6),
|
|
'unattributed_seconds':round(max(0,total-accounted),6),
|
|
'clock':'monotonic; UTC timestamps for correlation only'}
|
|
performed={x['name'] for x in self.data['phases']}
|
|
for key in ('preparation','server_validation','server_activation','failed_server_operation'):
|
|
nested=self.data.get(key,{})
|
|
performed.update(x['name'] for x in nested.get('phases',[]))
|
|
self.data['unperformed_phases']=[n for n in PHASES if n not in performed]
|
|
return self.data
|
|
|
|
|
|
def sanitized(value):
|
|
"""Defence in depth; callers still collect only explicitly selected facts."""
|
|
if isinstance(value,dict):
|
|
return {k:sanitized(v) for k,v in value.items() if not re.search(
|
|
r'password|connection.?string|private.?key|api.?key|access.?token|refresh.?token|credential',k,re.I)}
|
|
if isinstance(value,list):return [sanitized(x) for x in value]
|
|
if isinstance(value,str) and re.search(r'(?:Password|Pwd|Server|Data Source|User ID|Initial Catalog)\s*=|Bearer\s+|-----BEGIN.*PRIVATE KEY|sk_(?:live|test)_|sk-proj-|whsec_',value,re.I):
|
|
return '[redacted]'
|
|
return value
|
|
|
|
|
|
def summary(data):
|
|
"""Render only known safe fields; never include diagnostics/configuration blobs."""
|
|
data=sanitized(data)
|
|
seconds=data.get('timing',{}).get('total_seconds',0)
|
|
release=data.get('release',{})
|
|
public=data.get('public_https')
|
|
public_result='passed' if public and all(x.get('status')==200 and x.get('tls_verified') for x in public.values()) else 'not-performed'
|
|
if any(x['name']=='public_acceptance' and x.get('outcome')=='failed' for x in data.get('phases',[])):public_result='failed'
|
|
return ('{status}: {release} v{version} source={source} total={seconds:.2f}s; '
|
|
'backup={backup}; migrations-executed={migrations}; public-https={public}; receipt={receipt}').format(
|
|
status=data.get('status','unknown'),release=release.get('id','unavailable'),version=release.get('version','unknown'),
|
|
source=release.get('source_commit','unavailable')[:12],seconds=seconds,
|
|
backup=data.get('database_backup',{}).get('verified','not-performed'),
|
|
migrations=data.get('migrations',{}).get('executed','not-performed'),public=public_result,
|
|
receipt=data.get('deployment_id','local'))
|
|
|
|
|
|
|
|
def write_local(path, data):
|
|
path=Path(path)
|
|
data=sanitized(data)
|
|
for target,body in [(path,json.dumps(data,indent=2)+'\n'),(path.with_suffix('.txt'),summary(data)+'\n')]:
|
|
with tempfile.NamedTemporaryFile(mode='w',dir=target.parent,prefix='.receipt-',delete=False) as stream:
|
|
temporary=Path(stream.name);stream.write(body);stream.flush();os.fsync(stream.fileno())
|
|
temporary.chmod(0o600);os.replace(temporary,target)
|