#!/usr/bin/env python3
"""CE HTTP ingestion/sharing checks; run inside the existing worker container.

Start only the optional fixture service with compose.feeds.yaml first.
docker --context colima-opencti-tutorial compose -f lab/compose.yaml \
  exec -T worker python < lab/feed-check.py

Uses existing lab credentials without printing them. Creates unique fictional
data and private sharing resources. Stops every created ingestion in finally;
does not delete knowledge, change base configuration, or start a synchronizer.
"""

import csv
import io
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from email.utils import parsedate_to_datetime
from datetime import datetime, timedelta, timezone

from pycti import OpenCTIApiClient


TOKEN = os.environ["OPENCTI_TOKEN"]
BASE = os.environ["OPENCTI_URL"].rstrip("/")
FIXTURE = "http://feed-fixture:8090"
RUN = uuid.uuid4().hex[:12]
api = OpenCTIApiClient(BASE, TOKEN, log_level="ERROR")
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
CREATED = []
FAILURES = []
ARTIFACTS = {"run": RUN}


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 returned errors or no data")
    return result["data"]


def http(url, *, method="GET", data=None, authenticated=False, mime=None):
    headers = {"Accept": "application/taxii+json;version=2.1"} if url.startswith(BASE) else {}
    if authenticated:
        headers["Authorization"] = "Bearer " + TOKEN
    if mime:
        headers["Content-Type"] = mime
    request = urllib.request.Request(url, headers=headers, method=method,
                                     data=json.dumps(data).encode() if data is not None else None)
    try:
        with opener.open(request, timeout=30) as response:
            body = response.read().decode()
            return response.status, json.loads(body), dict(response.headers)
    except urllib.error.HTTPError as exc:
        # Do not expose bodies that might contain deployment details or tokens.
        return exc.code, None, {}


def wait_for(label, check, timeout=210):
    deadline = time.monotonic() + timeout
    next_notice = time.monotonic() + 30
    while time.monotonic() < deadline:
        result = check()
        if result:
            return result
        if time.monotonic() >= next_notice:
            log("WAIT " + label)
            next_notice += 30
        time.sleep(3)
    raise RuntimeError("Timed out: " + label)


def case(label, action):
    log("CASE " + label)
    try:
        action()
    except Exception as exc:
        message = str(exc).replace(TOKEN, "[REDACTED]")
        FAILURES.append({"case": label, "error": type(exc).__name__ + ": " + message})
        log("FAIL " + label + ": " + type(exc).__name__ + ": " + message)


def feed_patch(kind, identifier, patches):
    field = "ingestion" + kind + "FieldPatch"
    data = q("mutation($id:ID!,$input:[EditInput!]!){" + field
             + "(id:$id,input:$input){id ingestion_running}}",
             {"id": identifier, "input": [{"key": key, "value": [str(value).lower() if isinstance(value, bool) else str(value)]}
                                          for key, value in patches.items()]})
    return data[field]


def add_feed(kind, input_data):
    field = "ingestion" + kind + "Add"
    result = q("mutation($input:Ingestion" + kind + "AddInput!){" + field
               + "(input:$input){id name ingestion_running}}", {"input": input_data})[field]
    CREATED.append((kind, result["id"]))
    ARTIFACTS[kind] = result
    log("ARTIFACT " + kind + " " + json.dumps(result))
    return result["id"]


def feed_status(kind, identifier):
    field = "ingestion" + kind
    return q("query($id:String!){" + field + "(id:$id){id name ingestion_running "
             "last_execution_date last_execution_status}}", {"id": identifier})[field]


def observables():
    data = q("""query($search:String!){stixCyberObservables(search:$search,first:50){
      edges{node{id standard_id entity_type observable_value x_opencti_description}}
    }}""", {"search": RUN})
    return {edge["node"]["observable_value"]: edge["node"] for edge in data["stixCyberObservables"]["edges"]}


def fixture_events():
    status, body, _ = http(FIXTURE + "/events?run=" + RUN)
    assert status == 200
    return body


def stop(kind, identifier):
    result = feed_patch(kind, identifier, {"ingestion_running": False})
    assert result["ingestion_running"] is False
    log("PASS stopped " + kind + " " + identifier)


def assert_rss_publication(report):
    with opener.open(FIXTURE + "/rss?run=" + RUN, timeout=30) as response:
        assert response.status == 200
        pub_date = ET.fromstring(response.read()).findtext("channel/item/pubDate")
    assert pub_date, "RSS fixture must provide pubDate"
    expected = parsedate_to_datetime(pub_date).astimezone(timezone.utc)
    actual = datetime.fromisoformat(report["published"].replace("Z", "+00:00")).astimezone(timezone.utc)
    assert actual == expected, "Report publication date differs from RSS source"
    log("PASS RSS publication matches source pubDate in UTC: " + actual.isoformat())


def run_http_feeds(user_id, author_id):
    csv_repr = [{"id": str(uuid.uuid4()), "type": "entity", "target": {"entity_type": "Domain-Name"},
                 "attributes": [{"key": "value", "column": {"column_name": "A"}},
                                {"key": "x_opencti_description", "column": {"column_name": "B"}}]}]
    csv_mapper = q("""mutation($input:CsvMapperAddInput!){csvMapperAdd(input:$input){id errors}}
    """, {"input": {"name": "SecTools Lab Feed CSV " + RUN, "has_header": True,
                      "separator": ",", "representations": json.dumps(csv_repr)}})["csvMapperAdd"]
    assert not csv_mapper["errors"]
    csv_input = {"name": "SecTools Lab CSV HTTP " + RUN, "user_id": user_id,
                 "authentication_type": "none", "uri": FIXTURE + "/csv?run=" + RUN,
                 "csv_mapper_type": "id", "csv_mapper_id": csv_mapper["id"],
                 "ingestion_running": False, "scheduling_period": "PT1H", "ssl_verify": True}
    # Reproducible failure with no polling resource created, followed by corrected Verify.
    bad = {**csv_input, "uri": FIXTURE + "/missing?run=" + RUN}
    try:
        q("mutation($input:IngestionCsvAddInput!){ingestionCsvTester(input:$input){nbEntities}}", {"input": bad})
    except ValueError as exc:
        assert "404" in str(exc), "Expected fixture HTTP 404, got a different error"
        log("PASS CSV Verify negative: nonexistent local source produced HTTP 404; correct URI used next")
    else:
        raise AssertionError("Missing source unexpectedly passed Verify")
    tested = q("""mutation($input:IngestionCsvAddInput!){ingestionCsvTester(input:$input){
      objects nbEntities nbRelationships}}
    """, {"input": csv_input})["ingestionCsvTester"]
    assert tested["nbEntities"] == 2 and tested["nbRelationships"] == 0
    csv_id = add_feed("Csv", csv_input)

    json_repr = [{"id": str(uuid.uuid4()), "type": "entity", "identifier": "$.id",
                  "target": {"entity_type": "Domain-Name", "path": "$.items[*]"},
                  "attributes": [{"key": "value", "mode": "simple", "attr_path": {"path": "$.domain"}},
                                 {"key": "x_opencti_description", "mode": "simple", "attr_path": {"path": "$.note"}}]}]
    json_mapper = q("""mutation($input:JsonMapperAddInput!){jsonMapperAdd(input:$input){id errors}}
    """, {"input": {"name": "SecTools Lab Feed JSON " + RUN,
                      "representations": json.dumps(json_repr)}})["jsonMapperAdd"]
    assert not json_mapper["errors"]
    json_input = {"name": "SecTools Lab JSON HTTP " + RUN, "user_id": user_id,
                  "authentication_type": "none", "uri": FIXTURE + "/json?run=" + RUN + "&offset=$offset",
                  "verb": "GET", "json_mapper_id": json_mapper["id"], "ingestion_running": False,
                  "scheduling_period": "auto", "ssl_verify": True, "query_attributes": [{
                      "type": "data", "from": "$.items", "to": "offset", "data_operation": "count",
                      "state_operation": "sum", "default": "0", "exposed": "query_param"}]}
    tested = q("""mutation($input:IngestionJsonAddInput!){ingestionJsonTester(input:$input){
      objects nbEntities state}}
    """, {"input": json_input})["ingestionJsonTester"]
    assert tested["nbEntities"] == 1 and json.loads(tested["state"])["offset"] == 1
    assert json.loads(tested["objects"])[0]["value"] == "json-feed-1-" + RUN + ".example"
    json_id = add_feed("Json", json_input)
    saved = q("query($id:String!){ingestionJson(id:$id){query_attributes{default}}}",
              {"id": json_id})["ingestionJson"]["query_attributes"]
    offset_default_bug = saved[0]["default"] != "0"
    if offset_default_bug:
        ARTIFACTS["json_offset_default"] = {"submitted": "0", "stored": saved[0]["default"]}
        log("OBSERVED JSON default changed after persistence: " + json.dumps(ARTIFACTS["json_offset_default"]))
    rss_id = add_feed("Rss", {"name": "SecTools Lab RSS HTTP " + RUN, "user_id": user_id,
                              "uri": FIXTURE + "/rss?run=" + RUN, "ingestion_running": False,
                              "scheduling_period": "PT1H", "created_by_ref": author_id,
                              "current_state_date": (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
                              "report_types": ["threat-report"], "ssl_verify": True})
    ARTIFACTS["csv_mapper_id"] = csv_mapper["id"]
    ARTIFACTS["json_mapper_id"] = json_mapper["id"]
    for kind, identifier in [("Csv", csv_id), ("Json", json_id), ("Rss", rss_id)]:
        feed_patch(kind, identifier, {"ingestion_running": True})
    log("PASS HTTP Verify: CSV two mapped objects; JSON first object and next offset=1; three feeds started")

    expected = {f"{kind}-feed-{index}-{RUN}.example": f"SecTools Lab {kind.upper()} HTTP row {index} / {RUN}"
                for kind in ("csv", "json") for index in (1, 2)}

    def found_all():
        found = observables()
        return found if all(value in found for value in expected) else None

    if offset_default_bug:
        wait_for("JSON offset default failure evidence", lambda:
                 feed_status("Json", json_id)["last_execution_status"] == "error")
        evidence = q("query($id:String!){ingestionJsonLogs(id:$id){level message meta}}",
                     {"id": json_id})["ingestionJsonLogs"]
        events = fixture_events()
        assert any((item.get("meta") or {}).get("http_status") == 400 for item in evidence)
        assert any(item["path"] == "/json" and item["offset"] == "false" for item in events)
        ARTIFACTS["json_offset_failure"] = {"logs": evidence, "events": events}
        log("KNOWN LIMIT JSON offset: saved default=false sent to integer-only source, HTTP 400; Verify alone did not reveal it")
        stop("Json", json_id)
        # Documented alternative: source-provided next URL, no query-attribute default.
        # Change only this newly created feed; never patch platform implementation.
        json_input.update({"uri": FIXTURE + "/json?run=" + RUN + "&offset=0",
                           "query_attributes": [], "pagination_with_sub_page": True,
                           "pagination_with_sub_page_attribute_path": "$.next",
                           "pagination_with_sub_page_query_verb": "GET", "ingestion_running": False})
        q("mutation($id:ID!,$input:IngestionJsonAddInput!){ingestionJsonEdit(id:$id,input:$input){id}}",
          {"id": json_id, "input": json_input})
        feed_patch("Json", json_id, {"ingestion_running": True})
        log("RECOVERY JSON uses supported next-URL sub-pagination with literal offset=0 initial URL")
    found = wait_for("CSV and paginated JSON HTTP -> queue -> worker -> knowledge", found_all)
    for value, description in expected.items():
        assert found[value]["x_opencti_description"] == description
    ARTIFACTS["feed_observables"] = [found[value] for value in expected]
    log("PASS CSV/JSON ingestion: four unique Domain-Name values and descriptions read back from main")

    def report_ready():
        result = q("""query($search:String!){reports(search:$search,first:10){edges{node{
          id name published description createdBy{id name} report_types
          externalReferences(first:10){edges{node{url}}}
        }}}}""", {"search": RUN})
        return next((edge["node"] for edge in result["reports"]["edges"]
                     if edge["node"]["name"] == "SecTools Lab RSS HTTP " + RUN), None)

    report = wait_for("RSS HTTP -> Report", report_ready)
    assert report["createdBy"]["id"] == author_id
    assert "unknown" in report["description"] and RUN in report["description"]
    assert "threat-report" in report["report_types"]
    assert any(edge["node"]["url"] == FIXTURE + "/article?run=" + RUN
               for edge in report["externalReferences"]["edges"])
    assert_rss_publication(report)
    ARTIFACTS["rss_report"] = report
    log("PASS RSS ingestion: unique report, publication date, author, report type and original URL read back")
    wait_for("JSON empty page after offset progression", lambda: any(
        event["path"] == "/json" and event["offset"] == "2" for event in fixture_events()))
    events = fixture_events()
    offsets = [event["offset"] for event in events if event["path"] == "/json"]
    assert all(str(index) in offsets for index in (0, 1, 2))
    log("PASS JSON HTTP request offsets: " + json.dumps(offsets) + "; offset=2 returned an empty items array")
    connector_id = q("query($id:String!){ingestionJson(id:$id){connector_id}}", {"id": json_id})["ingestionJson"]["connector_id"]
    connector = q("query($id:String!){connector(id:$id){connector_state}}",
                  {"id": connector_id})["connector"]
    state = connector.get("connector_state")
    if isinstance(state, str):
        state = json.loads(state)
    if offset_default_bug:
        assert state == {}, "Next-URL pagination should not claim a persisted offset cursor"
        log("PASS JSON sub-pagination exhausted next links; connector state={} (no offset cursor claimed)")
    else:
        assert state and state.get("offset") == 2, "Persisted JSON offset state must be 2"
        log("PASS JSON persisted connector state: " + json.dumps(state))
    for kind, identifier in [("Csv", csv_id), ("Json", json_id), ("Rss", rss_id)]:
        status = feed_status(kind, identifier)
        assert status["last_execution_status"] == "success", status
        log("PASS execution " + json.dumps(status))
        stop(kind, identifier)
    ARTIFACTS["fixture_events"] = events


def run_taxii_push(user_id):
    identifier = add_feed("TaxiiCollection", {"name": "SecTools Lab TAXII Push " + RUN,
                                               "user_id": user_id, "confidence_to_score": False,
                                               "authorized_members": [{"id": user_id, "access_right": "view"}]})
    endpoint = BASE + "/taxii2/root/collections/" + identifier + "/objects/"
    now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
    sample = {"type": "malware", "spec_version": "2.1", "id": "malware--" + str(uuid.uuid4()),
              "created": now, "modified": now, "name": "SecTools Lab TAXII Push Malware " + RUN,
              "is_family": False, "description": "Fictional API push fixture / " + RUN}
    code, _, _ = http(endpoint, method="POST", data={"objects": [sample]}, authenticated=True,
                       mime="application/taxii+json;version=2.1")
    assert code == 404, "Stopped push ingester must return HTTP 404; received " + str(code)
    log("PASS stopped TAXII Push rejects request: HTTP " + str(code))
    feed_patch("TaxiiCollection", identifier, {"ingestion_running": True})
    code, _, _ = http(endpoint, method="POST", data={"objects": [sample]}, authenticated=False,
                       mime="application/taxii+json;version=2.1")
    assert code in (401, 403, 404)
    log("PASS TAXII Push anonymous request rejected: HTTP " + str(code))
    code, _, _ = http(endpoint, method="POST", data={"objects": [sample]}, authenticated=True,
                       mime="application/json")
    assert code in (400, 406, 415)
    log("PASS TAXII Push incorrect Content-Type rejected: HTTP " + str(code))
    code, body, _ = http(endpoint, method="POST", data={"objects": [sample]}, authenticated=True,
                          mime="application/taxii+json;version=2.1")
    assert code in (200, 202) and body.get("id"), "Push request did not produce a status resource"
    status_id = body["id"]
    log("PASS TAXII Push accepted: HTTP " + str(code) + "; status=" + str(body.get("status")))

    def completed():
        code, body, _ = http(BASE + "/taxii2/root/status/" + status_id + "/", authenticated=True)
        assert code == 200
        return body if body.get("status") == "complete" else None

    status = wait_for("TAXII Push status complete", completed)
    assert status.get("failure_count", 0) == 0 and status.get("success_count", 0) >= 1
    matches = api.malware.list(search=sample["name"], first=10)
    found = next(item for item in matches if item["name"] == sample["name"])
    assert found["description"] == sample["description"]
    ARTIFACTS["push_malware"] = {"id": found["id"], "name": found["name"]}
    ARTIFACTS["push_status"] = status
    log("PASS TAXII Push status and exact malware description read-back: " + json.dumps(status))
    stop("TaxiiCollection", identifier)


def run_sharing(user_id):
    source = observables()
    expected = {f"csv-feed-{index}-{RUN}.example" for index in (1, 2)}
    assert expected <= set(source), "CSV feed prerequisite did not complete"
    selected_ids = [source[value]["id"] for value in sorted(expected)]
    filters = {"mode": "and", "filters": [{"key": ["ids"], "values": selected_ids,
                                              "operator": "eq", "mode": "or"}], "filterGroups": []}
    shared = {"name": "SecTools Lab TAXII Sharing " + RUN, "filters": json.dumps(filters),
              "taxii_public": False, "include_inferences": False, "score_to_confidence": False,
              "authorized_members": [{"id": user_id, "access_right": "view"}]}
    collection = q("""mutation($input:TaxiiCollectionAddInput!){taxiiCollectionAdd(input:$input){id name}}
    """, {"input": shared})["taxiiCollectionAdd"]
    ARTIFACTS["taxii_collection"] = collection
    endpoint = BASE + "/taxii2/root/collections/" + collection["id"] + "/objects/"
    code, _, _ = http(endpoint)
    assert code in (401, 403, 404)
    log("PASS private TAXII collection denies anonymous read: HTTP " + str(code))
    collected = []
    cursor = None
    page_count = 0
    for _ in range(10):
        params = {"limit": 1}
        if cursor:
            params["next"] = cursor
        code, body, _ = http(endpoint + "?" + urllib.parse.urlencode(params), authenticated=True)
        assert code == 200
        collected.extend(body.get("objects", []))
        page_count += 1
        if not body.get("more"):
            break
        assert body.get("next") and body["next"] != cursor
        cursor = body["next"]
    else:
        raise AssertionError("TAXII pagination did not terminate")
    actual = {item["value"] for item in collected if item.get("type") == "domain-name"}
    assert actual == expected and page_count >= 2
    log("PASS private TAXII GET pagination: " + str(page_count) + " pages; exactly the two selected CSV domains")
    ARTIFACTS["taxii_pages"] = page_count

    pull_id = add_feed("Taxii", {"name": "SecTools Lab TAXII Pull " + RUN, "user_id": user_id,
                                 "uri": BASE + "/taxii2/root", "collection": collection["id"],
                                 "version": "v21", "authentication_type": "bearer", "authentication_value": TOKEN,
                                 "ingestion_running": False, "scheduling_period": "PT1H", "ssl_verify": True,
                                 "confidence_to_score": False,
                                 "added_after_start": (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()})
    feed_patch("Taxii", pull_id, {"ingestion_running": True})
    status = wait_for("TAXII pull of local private collection", lambda: (
        (s if s["last_execution_status"] == "success" else None)
        if (s := feed_status("Taxii", pull_id)) else None))
    logs = q("query($id:String!){ingestionTaxiiLogs(id:$id){level message meta}}", {"id": pull_id})["ingestionTaxiiLogs"]
    assert any((entry.get("meta") or {}).get("objects_count", 0) >= 2 for entry in logs), "No fetched object count in TAXII log"
    after = observables()
    assert all(after[value]["id"] == source[value]["id"] for value in expected)
    log("PASS TAXII Pull fetched >=2 objects; same-platform replay kept the same observable IDs (upsert scope)")
    ARTIFACTS["taxii_pull_status"] = status
    ARTIFACTS["taxii_pull_logs"] = logs
    stop("Taxii", pull_id)

    stream = q("""mutation($input:StreamCollectionAddInput!){streamCollectionAdd(input:$input){id name stream_public}}
    """, {"input": {"name": "SecTools Lab Stream Verify " + RUN, "filters": json.dumps(filters),
                      "stream_live": True, "stream_public": False,
                      "authorized_members": [{"id": user_id, "access_right": "view"}]}})["streamCollectionAdd"]
    ARTIFACTS["stream_collection"] = stream
    fetched = q("""query($input:SynchronizerFetchInput){synchronizerFetch(input:$input){id name}}
    """, {"input": {"uri": BASE, "token": TOKEN, "ssl_verify": True}})["synchronizerFetch"]
    assert any(item["id"] == stream["id"] for item in fetched)
    test_input = {"name": "SecTools Lab Verify Only " + RUN, "uri": BASE, "token": TOKEN,
                  "stream_id": stream["id"], "user_id": user_id, "listen_deletion": False,
                  "no_dependencies": True, "synchronized": False, "ssl_verify": True}
    tested = q("mutation($input:SynchronizerAddInput){synchronizerTest(input:$input)}",
               {"input": test_input})["synchronizerTest"]
    assert tested == "Connection success", "Stream connection test did not confirm success: " + str(tested)
    log("PASS Stream remote discovery and connection test: " + str(tested)
        + "; synchronizer NOT created or started, no self-ingestion")


def run_csv_sharing(user_id):
    source = observables()
    expected = {f"csv-feed-{index}-{RUN}.example" for index in (1, 2)}
    assert expected <= set(source), "CSV ingestion prerequisite did not complete"
    filters = {"mode": "and", "filters": [{"key": ["ids"],
               "values": [source[value]["id"] for value in sorted(expected)],
               "operator": "eq", "mode": "or"}], "filterGroups": []}
    payload = {"name": "SecTools Lab CSV Sharing " + RUN, "feed_types": ["Domain-Name"],
               "feed_attributes": [
                   {"attribute": "domain", "mappings": [{"type": "Domain-Name", "attribute": "value"}]},
                   {"attribute": "source_note", "mappings": [{"type": "Domain-Name", "attribute": "x_opencti_description"}]}],
               "feed_date_attribute": "created_at", "feed_public": False,
               "filters": json.dumps(filters), "include_header": True,
               "rolling_time": 1440, "separator": ",",
               "authorized_members": [{"id": user_id, "access_right": "view"}]}
    created = q("mutation($input:FeedAddInput!){feedAdd(input:$input){id name feed_public}}",
                {"input": payload})["feedAdd"]
    ARTIFACTS["csv_sharing"] = created
    url = BASE + "/feeds/" + created["id"]
    code, _, _ = http(url)
    assert code in (401, 403, 404)
    log("PASS private CSV sharing rejects anonymous download: HTTP " + str(code))
    request = urllib.request.Request(url, headers={"Authorization": "Bearer " + TOKEN})
    with opener.open(request, timeout=30) as response:
        assert response.status == 200
        rows = list(csv.DictReader(io.StringIO(response.read().decode())))
    assert len(rows) == 2 and {row["domain"] for row in rows} == expected
    assert all(row["source_note"] == source[row["domain"]]["x_opencti_description"] for row in rows)
    log("PASS private CSV sharing: header + exact 2 selected rows, descriptions preserved; JSON/RSS excluded")
    ARTIFACTS["csv_sharing_rows"] = rows


def main():
    log("RUN " + RUN + " UTC " + datetime.now(timezone.utc).isoformat())
    status, _, _ = http(FIXTURE + "/health")
    assert status == 200, "Start feed-fixture service first"
    result = q("""query{about{version} me{id} __type(name:"IngestionCsvMapperType"){enumValues{name}}}
    """)
    assert "id" in {value["name"] for value in result["__type"]["enumValues"]}
    user_id = result["me"]["id"]
    ARTIFACTS["version"] = result["about"]["version"]
    log("PASS live schema/version " + ARTIFACTS["version"] + "; fixture reachable from Docker worker")
    identities = api.identity.list(search="SecTools Lab", first=50)
    author_id = next(item["id"] for item in identities if item["name"] == "SecTools Lab")
    case("CSV/JSON/RSS HTTP ingestion", lambda: run_http_feeds(user_id, author_id))
    if os.environ.get("FEED_CHECK_HTTP_ONLY") == "1":
        log("SCOPE HTTP-only follow-up; previously passed TAXII/Stream cases are not repeated")
    else:
        case("Native private CSV sharing", lambda: run_csv_sharing(user_id))
        case("TAXII Push start/stop/auth/status", lambda: run_taxii_push(user_id))
        case("TAXII sharing/pull and Stream Verify", lambda: run_sharing(user_id))


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        FAILURES.append({"case": "setup", "error": type(exc).__name__ + ": " + str(exc).replace(TOKEN, "[REDACTED]")})
        log("FAIL setup: " + str(exc))
    finally:
        for kind, identifier in reversed(CREATED):
            try:
                stop(kind, identifier)
            except Exception as exc:
                FAILURES.append({"case": "cleanup", "kind": kind, "id": identifier,
                                 "error": str(exc).replace(TOKEN, "[REDACTED]")})
                log("FAIL stop " + kind + " " + identifier + ": " + str(exc))
        log("RESULT " + json.dumps(ARTIFACTS, ensure_ascii=False))
        log("FAILURES " + json.dumps(FAILURES, ensure_ascii=False))
        log("LIMITS API/HTTP only; existing lab admin identity; no least-privilege role matrix; no cross-platform Stream replication; no EE or production data deletion")
    sys.exit(1 if FAILURES else 0)
