#!/usr/bin/env python3
"""Read-only verification of the OFFICIAL MITRE Connector's real import.

First start lab/compose.mitre.yaml. Then run in the existing worker:
 docker --context colima-opencti-tutorial compose -f lab/compose.yaml \
   exec -T worker python < lab/mitre-check.py
This checker downloads the pinned public source for comparison but NEVER imports
or creates objects. The official connector, queue and worker perform ingestion.
"""
import collections
import hashlib
import json
import os
import sys
import time
import urllib.request
from datetime import datetime, timezone
from pycti import OpenCTIApiClient

TOKEN = os.environ['OPENCTI_TOKEN']
api = OpenCTIApiClient(os.environ['OPENCTI_URL'], TOKEN, log_level='ERROR')
CONNECTOR_ID = os.environ.get('MITRE_CONNECTOR_ID', '374e67f5-3274-48a3-a176-d711a3743403')
SOURCE = 'https://raw.githubusercontent.com/mitre-attack/attack-stix-data/6c3719993d0401de199203ecc3f369544d9e091c/enterprise-attack/enterprise-attack-19.1.json'
SHA256 = 'bdf1ce86a4e604214c5076d37ae4dcb322678afc528df8492e6fdc1b554f5da3'
RESULT = {}


def log(message):
    print(str(message).replace(TOKEN, '[REDACTED]'), flush=True)


def q(document, variables=None):
    result = api.query(document, variables)
    if result.get('errors') or not result.get('data'):
        raise RuntimeError('GraphQL errors or no data')
    return result['data']


def verify_fin10(source_relation):
    result = q('query($id:String!){stixCoreRelationship(id:$id){id relationship_type is_inferred description createdBy{id name} from{... on IntrusionSet{id name}} to{... on AttackPattern{id name x_mitre_id}} externalReferences(first:20){edges{node{source_name url}}}}}', {'id': source_relation['id']})['stixCoreRelationship']
    assert result and result['relationship_type'] == 'uses' and result['is_inferred'] is False
    assert result['from']['name'] == 'FIN10' and result['to']['x_mitre_id'] == 'T1059.001'
    assert result['createdBy']['name'] == 'The MITRE Corporation'
    assert result['description'] == source_relation['description']
    expected_refs = {(ref['source_name'], ref['url']) for ref in source_relation['external_references']}
    actual_refs = {(edge['node']['source_name'], edge['node']['url']) for edge in result['externalReferences']['edges']}
    assert expected_refs == actual_refs, 'FIN10 relationship references differ from pinned source'
    RESULT['fin10_uses_powershell'] = {'source_relationship_stix_id': source_relation['id'], 'read_back': result}
    log('PASS FIN10 -> PowerShell direct uses relation: exact pinned-source description and both reference name/URL pairs verified')
    log('FIN10_SAMPLE ' + json.dumps(RESULT['fin10_uses_powershell'], ensure_ascii=False))


def main():
    log('VERIFY UTC ' + datetime.now(timezone.utc).isoformat())
    log('SCOPE official MITRE Enterprise ATT&CK 19.1; read-only checker; existing lab account; no synthetic data imported')
    raw = urllib.request.urlopen(SOURCE, timeout=120).read()
    assert hashlib.sha256(raw).hexdigest() == SHA256, 'Pinned source hash mismatch'
    bundle = json.loads(raw)
    del raw
    objects = bundle['objects']
    revoked = {o['id'] for o in objects if o.get('revoked', False) or o.get('x_capec_status') == 'Deprecated'}
    kept = [o for o in objects if o['id'] not in revoked and not (o['type'] == 'relationship' and (o['source_ref'] in revoked or o['target_ref'] in revoked))]
    by_id = {o['id']: o for o in kept}
    patterns = [o for o in kept if o['type'] == 'attack-pattern']
    expected = {next(r['external_id'] for r in o['external_references'] if r['source_name'] == 'mitre-attack' and r.get('external_id')): o for o in patterns}
    metadata = {'url': SOURCE, 'sha256': SHA256, 'raw_objects': len(objects), 'after_revoked_filter': len(kept),
                'types_after_revoked_filter': dict(collections.Counter(o['type'] for o in kept)),
                'expected_attack_patterns': len(expected), 'deprecated_in_expected': sum(bool(o.get('x_mitre_deprecated')) for o in patterns),
                'collection': [{'id': o['id'], 'name': o.get('name'), 'version': o.get('x_mitre_version'), 'modified': o.get('modified')} for o in objects if o['type'] == 'x-mitre-collection']}
    RESULT['source'] = metadata
    log('SOURCE ' + json.dumps(metadata))
    deadline = time.monotonic() + int(os.environ.get('MITRE_VERIFY_TIMEOUT', '1800'))
    last_notice = 0
    work = None
    while time.monotonic() < deadline:
        connector = q('query($id:String!){connector(id:$id){id name connector_state works{id name timestamp status completed_time completed_number tracking{import_expected_number import_processed_number} errors{message}}}}', {'id': CONNECTOR_ID})['connector']
        assert connector, 'Official connector has not registered; inspect startup logs'
        works = connector['works'] or []
        if works:
            work = max(works, key=lambda x: x['timestamp'])
            RESULT['work'] = work
            if time.monotonic() - last_notice >= 30 or work['status'] == 'complete':
                log('WORK ' + json.dumps(work))
                last_notice = time.monotonic()
            if work['status'] == 'complete':
                assert not work['errors'], 'Official connector work completed with errors'
                assert work['tracking']['import_expected_number'] > 0
                assert work['tracking']['import_processed_number'] == work['tracking']['import_expected_number']
                RESULT['connector'] = {k: connector[k] for k in ['id', 'name', 'connector_state']}
                break
        time.sleep(5)
    else:
        raise RuntimeError('Official import not complete within timeout; inspect work/worker before retrying; checker writes nothing')
    log('PASS official connector work complete; expected=processed; errors empty')
    author_source = next(o for o in objects if o['type'] == 'identity' and o['name'] == 'The MITRE Corporation')
    author = q('query($id:String!){identity(id:$id){id name}}', {'id': author_source['id']})['identity']
    assert author and author['name'] == author_source['name']
    RESULT['author'] = author
    filters = {'mode': 'and', 'filters': [{'key': ['createdBy'], 'values': [author['id']], 'operator': 'eq', 'mode': 'or'}], 'filterGroups': []}
    cursor = None
    imported = []
    for _ in range(100):
        page = q('query($filters:FilterGroup,$after:ID){attackPatterns(first:100,after:$after,filters:$filters){edges{node{id standard_id name x_mitre_id revoked}} pageInfo{hasNextPage endCursor}}}', {'filters': filters, 'after': cursor})['attackPatterns']
        imported.extend(e['node'] for e in page['edges'])
        if not page['pageInfo']['hasNextPage']:
            break
        assert page['pageInfo']['endCursor'] != cursor
        cursor = page['pageInfo']['endCursor']
    else:
        raise AssertionError('Attack-pattern pagination did not terminate')
    keyed = {p['x_mitre_id']: p for p in imported}
    missing = sorted(set(expected) - set(keyed))
    assert not missing, 'Missing source technique IDs: ' + ','.join(missing[:20])
    assert all(keyed[k]['name'] == source['name'] and keyed[k]['revoked'] is False for k, source in expected.items())
    RESULT['pattern_count'] = {'source_expected': len(expected), 'all_by_author': len(imported), 'matched_expected': len(expected), 'extra_author_ids': sorted(set(keyed) - set(expected))}
    RESULT['imported_attack_pattern_ids'] = [keyed[k]['id'] for k in sorted(expected)]
    log('PASS all ' + str(len(expected)) + ' non-revoked source technique IDs and names read back with MITRE author; pagination complete')
    sample_source = expected['T1059.001']
    sample = q('query($id:String!){attackPattern(id:$id){id standard_id name x_mitre_id revoked createdBy{id name} killChainPhases{kill_chain_name phase_name x_opencti_order} externalReferences(first:100){edges{node{source_name external_id url}}}}}', {'id': sample_source['id']})['attackPattern']
    assert sample and sample['name'] == 'PowerShell' and sample['x_mitre_id'] == 'T1059.001'
    official_ref = next(r for r in sample_source['external_references'] if r.get('external_id') == 'T1059.001')
    assert any(e['node']['external_id'] == 'T1059.001' and e['node']['url'] == official_ref['url'] for e in sample['externalReferences']['edges'])
    assert any(p['kill_chain_name'] == 'mitre-attack-v19' and p['phase_name'] == 'execution' for p in sample['killChainPhases'])
    RESULT['sample_technique'] = sample
    relations = [o for o in kept if o['type'] == 'relationship' and o['source_ref'] == sample_source['id'] and o['relationship_type'] == 'subtechnique-of']
    assert len(relations) == 1
    relationship_source = relations[0]
    parent = q('query($id:String!){attackPattern(id:$id){id name x_mitre_id}}', {'id': relationship_source['target_ref']})['attackPattern']
    result = q('query($from:[String],$to:[String]){stixCoreRelationships(fromId:$from,toId:$to,relationship_type:["subtechnique-of"],first:20){edges{node{id standard_id relationship_type is_inferred}}}}', {'from': [sample['id']], 'to': [parent['id']]})['stixCoreRelationships']['edges']
    assert len(result) == 1 and result[0]['node']['is_inferred'] is False
    RESULT['sample_relationship'] = {'source_relationship_stix_id': relationship_source['id'], 'from': {'id': sample['id'], 'mitre_id': sample['x_mitre_id']}, 'to': parent, 'relation': result[0]['node']}
    log('PASS PowerShell T1059.001: official MITRE URL, versioned execution tactic, and direct subtechnique-of T1059 relation verified')
    log('SAMPLE ' + json.dumps({'author': author, 'pattern_count': RESULT['pattern_count'], 'technique': sample, 'relationship': RESULT['sample_relationship']}, ensure_ascii=False))
    fin10_source = next(o for o in kept if o['type'] == 'relationship' and o['source_ref'] == 'intrusion-set--fbe9387f-34e6-4828-ac28-3080020c597b' and o['target_ref'] == sample_source['id'] and o['relationship_type'] == 'uses')
    verify_fin10(fin10_source)


if __name__ == '__main__':
    try:
        main()
        log('FAILURES []')
    except Exception as error:
        log('FAIL ' + type(error).__name__ + ': ' + str(error))
        log('RESULT ' + json.dumps(RESULT, ensure_ascii=False))
        sys.exit(1)
    log('RESULT ' + json.dumps(RESULT, ensure_ascii=False))
    log('LIMIT official Enterprise 19.1 only; not Mobile/ICS/CAPEC, no external maliciousness verdict, no claim that all source object types are supported')
