"""Typed observation interfaces, separate from production response schemas.""" from build_validate import need, checked_validator from jsonschema import FormatChecker def leaf(schema, pointer): for token in pointer.split('/')[1:]: token=token.replace('~1','/').replace('~0','~') if schema.get('type')=='array' and token.isdigit(): schema=schema.get('items',{}) else: schema=schema.get('properties',{}).get(token,{}) return schema def check(contract): from build_validate import response_branches, response_oracle_body, pointer_value schemas=contract.get('capture_schemas',{}) operations={o['id']:o for o in contract['operations']} need(bool(schemas),'CAPTURE_SCHEMAS_MISSING') for schema in schemas.values():checked_validator(schema) checked=0 for uc in contract['use_cases']: for scenario in uc['scenarios']: for step in scenario.get('execution_steps',[]): need(step['operation_id'] in operations,'EXECUTION_STEP_OPERATION_UNBOUND '+scenario['id']) op=operations[step['operation_id']] # The scenario's own malformed primary request is intentional only when explicitly bound. rejection=(scenario.get('request_expectation')=='schema_rejection' and step['operation_id']==scenario.get('operation_id') and step['request']==scenario['request']) admitted=checked_validator(op['request_schema'],format_checker=FormatChecker()).is_valid(step['request']) need(admitted or rejection,'EXECUTION_STEP_REQUEST_INVALID '+scenario['id']) for binding in scenario.get('replay_bindings',[]): need(binding['operation_id'] in operations,'REPLAY_OPERATION_UNBOUND '+scenario['id']) op=operations[binding['operation_id']] branches=dict(response_branches(op['response_schema'])) need(binding['response_schema_pointer'] in branches,'REPLAY_RESPONSE_UNBOUND '+scenario['id']) body=binding['response_example'] need(checked_validator(op['response_schema'],format_checker=FormatChecker()).is_valid(body) and checked_validator(branches[binding['response_schema_pointer']],format_checker=FormatChecker()).is_valid(body),'REPLAY_WITNESS_INVALID '+scenario['id']) observations=[dict(o,pointer=o['pointer'][len(binding['pointer']):],source='artifact') for o in scenario['expected'] if o['source']==binding['source'] and o['pointer'].startswith(binding['pointer']+'/')] response_oracle_body({'kind':'worker'},dict(scenario,expected=observations,response_example=body)) for observation in scenario['expected']: source=observation['source'];context=scenario['id']+' '+source+' '+observation['pointer'] need(source in schemas,'CAPTURE_SOURCE_UNBOUND '+context) if observation['operator']=='absent': continue schema=leaf(schemas[source],observation['pointer']) need('type' in schema or 'const' in schema or bool(schema.get('enum')),'CAPTURE_POINTER_UNTYPED '+context) value=observation['expected'] operator=observation['operator'] if operator=='eq': need(checked_validator(schema,format_checker=FormatChecker()).is_valid(value),'CAPTURE_VALUE_TYPE '+context) elif operator in ['gte','lte']: need(schema.get('type') in ['integer','number'] and type(value) in [int,float],'CAPTURE_NUMERIC_TYPE '+context) elif operator=='contains': need(schema.get('type') in ['string','array','object'],'CAPTURE_CONTAINS_TYPE '+context) if schema.get('type')=='array':need(checked_validator(schema.get('items',{})).is_valid(value),'CAPTURE_ITEM_TYPE '+context) else:need(isinstance(value,str),'CAPTURE_CONTAINS_VALUE '+context) checked+=1 evidence=scenario.get('schema_rejection_evidence') if evidence: need(scenario.get('request_expectation')=='schema_rejection','CAPTURE_EVIDENCE_NOT_A_REJECTION '+scenario['id']) for ref in [evidence['code'],*evidence['zero_effects']]: need(any(o['source']==ref['source'] and o['pointer']==ref['pointer'] and o['operator']=='eq' for o in scenario['expected']),'CAPTURE_EVIDENCE_UNBOUND '+scenario['id']) return {'typed_capture_predicates_checked':checked,'capture_scope':'Authored capture interfaces; actual runtime captures and business correctness are not certified.'} def validate_capture(contract,scenario_id,capture): """Check supplied runtime observations; never manufacture evidence or run the app.""" from build_validate import response_oracle_body, response_branches, pointer_value scenario=next(s for u in contract['use_cases'] for s in u['scenarios'] if s['id']==scenario_id) op=next(o for o in contract['operations'] if o['id']==scenario['operation_id']) sources={o['source'] for o in scenario['expected']} for source in sources: need(source in capture,'RUNTIME_CAPTURE_SOURCE_MISSING '+source) need(checked_validator(contract['capture_schemas'][source],format_checker=FormatChecker()).is_valid(capture[source]),'RUNTIME_CAPTURE_SCHEMA_INVALID '+source) response_oracle_body({'kind':'verification','response_source':source},dict(scenario,response_example=capture[source])) source=op.get('response_source','http' if op['kind']=='http' else 'artifact') if 'response_schema_pointer' in scenario: need(source in capture,'RUNTIME_RESPONSE_MISSING') need(checked_validator(op['response_schema']).is_valid(capture[source]) and checked_validator(dict(response_branches(op['response_schema']))[scenario['response_schema_pointer']]).is_valid(capture[source]),'RUNTIME_RESPONSE_INVALID') for binding in scenario.get('replay_bindings',[]): body=pointer_value(capture[binding['source']],binding['pointer']) replay_op=next(o for o in contract['operations'] if o['id']==binding['operation_id']) need(checked_validator(replay_op['response_schema'],format_checker=FormatChecker()).is_valid(body) and checked_validator(dict(response_branches(replay_op['response_schema']))[binding['response_schema_pointer']],format_checker=FormatChecker()).is_valid(body),'RUNTIME_REPLAY_RESPONSE_INVALID') return {'valid':True,'scenario_id':scenario_id,'scope':'Supplied capture validation; authenticity and independent application execution require separate provenance.'} if __name__=='__main__': import sys,json from build_validate import load try: result=validate_capture(load(sys.argv[1]),sys.argv[2],load(sys.argv[3])) print(json.dumps(result)) except Exception as error: print(json.dumps({'valid':False,'error':str(error),'scope':'Supplied capture validation only.'}));sys.exit(2)