"""Actionable assessment report, with full inventory preserved as a separate JSON artifact.""" import hashlib import html import json from pathlib import Path from urllib.parse import quote from samsara.analyzers.summary import summarize MANUAL_STEPS = ['Confirm application and business owners and obtain administrator retirement approval.', 'Validate historical usage across a representative business cycle, including infrequent and offline jobs.', 'Review DNS, load balancers, monitoring, backups, firewall logs and service-account consumers.', 'Verify custom tasks and share consumers; resolve incomplete checks and confirm rollback/retention requirements.'] def export_json(path, data, assessment): Path(path).write_text(json.dumps({'inventory_result':data,'assessment':assessment},indent=2),encoding='utf-8') def inventory_artifact(path, data): payload = (json.dumps(data,indent=2,ensure_ascii=True)+'\n').encode('utf-8') digest = hashlib.sha256(payload).hexdigest() destination = Path(path).with_name(Path(path).stem + '.inventory-' + digest[:12] + '.json') try: with destination.open('xb') as output: output.write(payload) except FileExistsError: if destination.read_bytes() != payload: raise FileExistsError('Existing inventory artifact differs; choose a new report filename.') from None return destination, digest def table(headers, rows): escape = lambda value: html.escape(str(value)) if not rows: return '
None identified in collected evidence. Review missing evidence before drawing conclusions.
' return '| '+escape(h)+' | ' for h in headers) + '
|---|
| '+escape(v)+' | ' for v in row)+'
'+escape(source)+'
' content += ''+escape(data['server']['hostname'])+' · '+escape(data['collected_at'])+'
' content += f"{escape(scoring['explanation'])}
Evidence coverage: {summary['coverage_percent']}% · Evidence confidence: {escape(summary['confidence'])} · {summary['incomplete']} checks need review.
" content += 'Coverage and uncertainty are separate from risk. A zero or low score is not retirement clearance. Historical usage validation and administrator approval are always required.
' content += f"OS type: {escape(summary['os_type'])}
Version: {escape(summary['version'])}
'+escape(scoring['formula'])+'
' content += table(['Workload','Selected rule','Score','Determines final score','Evidence observations'],[(row['title'],row['selected_rule'],row['score'],'Yes (co-leading)' if row['determines_final_score'] else 'No; below the maximum',row['evidence_count']) for row in scoring['breakdown']]) content += 'Policy SHA-256: '+escape(scoring['policy_id'])+'
'+escape(json.dumps(scoring['policy'],indent=2))+'
Inventory name hints only; installed software does not establish active use.
' content += table(['Software','Version','Evidence'],[(r['name'],r['version'],r['evidence']) for r in summary['software'][:12]]) content += 'Nonroutine enabled schedules; configuration does not confirm execution. All tasks remain in the inventory.
' content += table(['Job','Schedule','State'],[(r['name'],r['schedule'],r['status']) for r in summary['jobs'][:12]]) context = [r for r in assessment['findings'] if r['points']==0 and r['id'] not in ('coverage','observation-limits')] content += 'Routine services, administrative shares, client traffic and unknown observations do not receive workload points.
' content += table(['Category','Classification','Context'],[(r['category'],r['classification'],r['evidence']) for r in context]) directions = {} for row in assessment['network_observations']: directions[row['direction']] = directions.get(row['direction'],0)+1 content += 'Direction inferred from listener/PID or ephemeral-port patterns is a heuristic, not a captured initiating handshake. Confirmed workload findings describe attributed observed transport activity, not verified business ownership.
' content += table(['Direction / activity','Observations'],list(sorted(directions.items()))) content += 'Failed and partial checks reduce confidence; they never add workload risk points.
' checks = [] for name in sorted(set(data['checks']) | set(assessment['scoring']['policy']['coverage_weights'])): row = data['checks'].get(name,{'status':'not_collected','message':'No status supplied.'}) errors = '; '.join(f"{e['code']}: {e['message']}" for e in row.get('errors',[])) checks.append((name,row['status'],row.get('started_at','Not supplied'),row.get('completed_at','Not supplied'),row['message'],errors,'; '.join(row.get('permission_limitations',[])),'; '.join(row.get('limitations',[])))) content += table(['Check','Status','started_at (UTC)','completed_at (UTC)','Result','Errors','permission_limitations','Scope limitations'],checks) content += 'Every collected inventory row is preserved separately, including routine services and administrative shares. The analyzer has not changed the collected evidence.
' content += 'Download / open complete inventory JSON
Inventory SHA-256: '+digest+'
' content += table(['Inventory section','Rows'],[(name,len(rows)) for name,rows in data['inventory'].items()]) content += 'JSON assessment export also preserves all raw inventory, classifications, evidence references and policy. Keep the inventory file alongside this HTML when sharing or archiving.
' css = 'body{font:15px system-ui;max-width:1180px;margin:32px auto;padding:20px;color:#233044;line-height:1.55}h1,h2{color:#173c60}.muted{color:#667}.source,.card,details{background:#eef3f8;padding:16px;border-radius:7px}.table{overflow-x:auto}table{border-collapse:collapse;width:100%;margin:12px 0}th,td{border:1px solid #d9e0e8;text-align:left;vertical-align:top;padding:9px;white-space:pre-wrap;overflow-wrap:anywhere}th{background:#eef3f8}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#1263a3}' Path(path).write_text('