#!/usr/bin/env python3
"""Check background workers and the misp-modules service, then run an offline enrichment
module (YARA syntax validator) through MISP. No external lookups are made.
Run in lab/: python3 modules-check.py. Enables two lab settings; prints no secrets."""
from misplab import api

workers = api('GET', '/servers/getWorkers')
alive = {}
for queue, info in workers.items():
    if isinstance(info, dict) and 'workers' in info:
        alive[queue] = sum(1 for w in info['workers'] if w.get('alive'))
for queue in ('default', 'prio', 'email', 'update', 'cache'):
    assert alive.get(queue, 0) >= 1, (queue, alive)
print('PASS background workers alive: ' + ', '.join(f'{q}={n}' for q, n in sorted(alive.items())))

for setting, value in (('Plugin.Enrichment_services_enable', True),
                       ('Plugin.Enrichment_yara_syntax_validator_enabled', True)):
    api('POST', f'/servers/serverSettingsEdit/{setting}', {'value': value})
modules = api('GET', '/modules/index')
names = {m['name'] for m in modules}
assert 'yara_syntax_validator' in names, sorted(names)[:10]
print(f'PASS misp-modules reachable from misp-core: {len(modules)} enabled module(s) listed')

good = api('POST', '/modules/queryEnrichment', {'module': 'yara_syntax_validator',
            'yara': 'rule SecToolsLab { strings: $a = "sectools-lab" condition: $a }'})
bad = api('POST', '/modules/queryEnrichment', {'module': 'yara_syntax_validator',
           'yara': 'rule Broken { condition: }'})
assert 'Syntax valid' in str(good) and 'Syntax error' in str(bad), (good, bad)
print('PASS enrichment module round trip: valid rule accepted, broken rule rejected')

# Warninglist：已知不該拿來偵測的值（保留網段、測試網域、熱門服務）。MISP 預設全部停用。
lists = api('GET', '/warninglists/index')
lists = lists['Warninglists'] if isinstance(lists, dict) else lists
wanted = {'List of RFC 5735 CIDR blocks', 'List of RFC 6761 Special-Use Domain Names'}
enabled_before = sum(1 for x in lists if x['Warninglist']['enabled'] in (True, 1, '1'))
for x in lists:
    if x['Warninglist']['name'] in wanted:
        api('POST', f"/warninglists/enableWarninglist/{x['Warninglist']['id']}/1", {})
hits = api('POST', '/warninglists/checkValue', ['192.0.2.10', 'login.example', 'sectools.tw'])
flagged = {value for value, matches in hits.items() if matches} if isinstance(hits, dict) else set()
assert flagged == {'192.0.2.10', 'login.example'}, hits
print(f'PASS warninglists: {len(lists)} shipped, {enabled_before} enabled before this run; after enabling RFC 5735 + RFC 6761, '
      'both training values are flagged as reserved')
