#!/usr/bin/env python3
"""Read-only verification of the official CISA KEV connector's real public data.

Start compose.cisa.yaml first. Run inside worker; no credentials are printed.
The source is fetched once and hashed. No fixture replaces the official feed.
"""
import hashlib
import json
import os
import time
import urllib.request
from datetime import datetime, timezone
from pycti import OpenCTIApiClient

URL = 'https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json'
CONNECTOR = '8c9c7f11-9100-46aa-8d3d-06fd9289e7f1'
api = OpenCTIApiClient(os.environ['OPENCTI_URL'], os.environ['OPENCTI_TOKEN'], log_level='ERROR')

def out(label, value):
    print(label + ' ' + json.dumps(value, ensure_ascii=False), flush=True)

def q(document, variables=None):
    result = api.query(document, variables)
    assert result.get('data') and not result.get('errors'), 'GraphQL error'
    return result['data']

def connector():
    return q('''query($id:String!){connector(id:$id){id name connector_state works{
      id status completed_number errors{message} tracking{import_expected_number import_processed_number}
    }}}''', {'id': CONNECTOR})['connector']

def all_kev():
    cursor = None
    found = {}
    while True:
        data = q('''query($after:ID,$filters:FilterGroup){vulnerabilities(first:500,after:$after,filters:$filters){
          edges{node{id name x_opencti_cisa_kev}} pageInfo{endCursor hasNextPage globalCount}}}''', {
            'after': cursor,
            'filters': {'mode': 'and', 'filters': [{'key': 'x_opencti_cisa_kev', 'values': ['true'], 'operator': 'eq'}], 'filterGroups': []}
        })['vulnerabilities']
        for edge in data['edges']:
            node = edge['node']
            assert node['name'] not in found, 'Duplicate CVE name in KEV result'
            found[node['name']] = node
        if not data['pageInfo']['hasNextPage']:
            return found
        cursor = data['pageInfo']['endCursor']

print('CISA KEV real-source verification ' + datetime.now(timezone.utc).isoformat(), flush=True)
with urllib.request.urlopen(URL, timeout=60) as response:
    raw = response.read()
source = json.loads(raw)
expected = {row['cveID']: row for row in source['vulnerabilities']}
assert len(expected) == source['count']
out('SOURCE', {'url': URL, 'catalogVersion': source['catalogVersion'], 'dateReleased': source['dateReleased'],
               'count': source['count'], 'sha256': hashlib.sha256(raw).hexdigest()})
deadline = time.monotonic() + 1200
while True:
    current = connector()
    assert current is not None, 'Start the official CISA connector first'
    works = current['works'] or []
    errors = [w for w in works if w.get('errors')]
    assert not errors, 'Connector work contains errors; inspect the work before retrying'
    done = [w for w in works if w['status'] == 'complete' and
            (w.get('tracking') or {}).get('import_expected_number', 0) > 0]
    if done and all(w['status'] == 'complete' for w in works):
        break
    assert time.monotonic() < deadline, 'Timed out waiting for worker completion'
    out('WAIT work', works)
    time.sleep(20)
out('CONNECTOR', current)
state = json.loads(current['connector_state'])
assert state['last_update'] == source['dateReleased'], 'Catalog changed or connector state is not current'
rows = all_kev()
assert set(expected).issubset(rows), 'Source CVEs missing from main knowledge'
assert all(rows[name]['x_opencti_cisa_kev'] is True for name in expected)
out('PASS all catalog CVEs stored with KEV flag', {'source': len(expected), 'matched': len(set(expected) & set(rows)), 'total_kev_in_platform': len(rows)})
sample_names = [source['vulnerabilities'][0]['cveID'], source['vulnerabilities'][len(expected)//2]['cveID'], source['vulnerabilities'][-1]['cveID']]
for name in sample_names:
    node = q('''query($id:String!){vulnerability(id:$id){id standard_id name description x_opencti_cisa_kev
      createdBy{... on Identity{name}} objectMarking{definition}
      externalReferences(first:100){edges{node{source_name url external_id}}}
      softwares(first:100,relationshipType:"has"){edges{node{id observable_value}}}
    }}''', {'id': rows[name]['id']})['vulnerability']
    original = expected[name]
    assert original['shortDescription'] in node['description'], 'Source description not retained'
    assert node['createdBy'] and node['createdBy']['name'] == 'Cybersecurity and Infrastructure Security Agency', 'Missing CISA attribution'
    assert any(x['definition'] == 'TLP:CLEAR' for x in node['objectMarking'])
    # This connector version does not populate External References on these samples.
    # Keep the observation visible; attribution and the catalog URL are separate checks.
    assert any(x['node']['observable_value'] == original['product'] for x in node['softwares']['edges']), 'Source product not linked by has relationship'
    out('PASS sample fields and software relationship', node)
out('SAMPLE_IDS', {name: rows[name]['id'] for name in sample_names})
print('LIMIT: validates this downloaded catalog and sample relationships; no claim of future updates, all product versions, or automatic remediation priority.', flush=True)
print('RESULT PASS real CISA catalog -> official Connector -> queue -> Worker -> main knowledge', flush=True)
