import pathlib,json,sys,copy
LAB=pathlib.Path(__file__).resolve().parents[1]; sys.path.insert(0,str(LAB/'src'))
from identity_boundary import *
policy=json.loads((LAB/'fixture/golden-policy.json').read_text()); base=json.loads((LAB/'fixture/baseline-data.json').read_text())['connections']; checks=[]
def c(n,x): checks.append((n,bool(x)))
internal=base[0]; admin=base[1]
c('server_internal',evaluate_server_identity('internal_api',policy)['decision']=='SERVER_IDENTITY_VERIFIED')
c('client_internal',evaluate_client_identity('internal_api',internal['client_identity'],internal['client_trust_domain'],policy)['decision']=='CLIENT_AUTHENTICATED')
c('action_internal',evaluate_request(internal,policy)['decision']=='ALLOW_ACTION')
c('action_admin',evaluate_request(admin,policy)['decision']=='ALLOW_ACTION')
m=copy.deepcopy(policy); m['contexts']['internal_api']['presented_server_identity']='admin.internal.example'; c('wrong_name',evaluate_server_identity('internal_api',m)['decision']=='DENY_SERVER_IDENTITY_MISMATCH')
m=copy.deepcopy(policy); m['contexts']['internal_api']['server_identity_status']='expired'; c('expired_server',evaluate_server_identity('internal_api',m)['decision']=='DENY_SERVER_IDENTITY_EXPIRED')
bad=dict(internal); bad['client_trust_domain']='dev.example'; bad['client_identity']='spiffe://dev.example/workload/orders-api'; c('wrong_td',evaluate_request(bad,policy)['decision']=='DENY_CLIENT_TRUST_DOMAIN')
bad=dict(internal); bad['client_identity_status']='expired'; c('expired_client',evaluate_request(bad,policy)['decision']=='DENY_CLIENT_IDENTITY_EXPIRED')
bad=dict(internal); bad['action']='admin.read'; r=evaluate_request(bad,policy); c('unauth_action',r['decision']=='DENY_ACTION_UNAUTHORIZED'); c('authn_preserved',r['authenticated'] is True)
bad=dict(internal); bad['tls_version_source']='RFC8446'; c('stale_spec',evaluate_request(bad,policy)['decision']=='DENY_STALE_TLS_SPEC')
row=build_evidence_row(internal,policy); c('row_complete',evidence_row_complete(row)); badrow=dict(row); badrow['residual_risk']=''; c('row_missing',not evidence_row_complete(badrow)); extra=dict(row); extra['extra']='x'; c('row_extra',not evidence_row_complete(extra))
c('transfer_admin',classify_transfer('admin_endpoint')['status']=='REBUILD_IDENTITY_AND_AUTHORIZATION'); c('transfer_no_copy',classify_transfer('admin_endpoint')['copy_primary_identity_policy'] is False); c('prod_false',policy['production_proof'] is False); c('realcert_false',policy['real_certificates'] is False); c('realkey_false',policy['real_private_keys'] is False); c('network_false',policy['network'] is False); c('authn_not_authz',policy['authorization']['authentication_is_not_authorization'] is True)
for n,ok in checks: print(('PASS' if ok else 'FAIL'),n)
print(f'SUMMARY {sum(ok for _,ok in checks)}/{len(checks)} PASS'); raise SystemExit(0 if all(ok for _,ok in checks) else 1)
