mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* fix(wave6): retract what is not built, and remove routes that cannot run
Item 6.1 — detection lifecycle. `detection_rule_versions`,
`detection_shadow_matches` and `shadow_until` have zero readers in
`services/`, and the only `rollback` in the detection endpoints is a
database transaction rollback. So a rule set to `dev` still raises alerts and
a future `shadow_until` still pages. The docs page marks four sections schema
only; README and CHANGELOG say which half works. Separation of duties on
`/detection-proposals/{id}/decide` is real and its claim stands.
Item 6.2 — enterprise IAM. `workload_identities`, `privilege_grants` and
`permission_conditions` have zero readers; `narrow_by_conditions` has zero
callers. Narrowed, keeping API-key rotation, which does work.
Item 6.3 — three intro.md overclaims. Qdrant holds the MITRE technique corpus
for lookup, which is a reference index and not agent memory; no route
recommends rules for uncovered techniques; `GET /taxii/collections` calls
`_demo_only()`.
Item 6.4 — the phishing playbook's "Retract phishing email fleet-wide" step
posts to `${EMAIL_GATEWAY_URL}`, set by nothing, under
`on_failure: continue`.
Item 6.5 — removed `detection_loop.py`. It named `aisoc_alerts`,
`aisoc_detection_rules` and `alerts.evidence`, none of which exist, so a
rename could not fix it; its own test built a fake row for the missing table.
Emptying `KNOWN_MISSING_TABLES` then surfaced three more callers: the
business-context preview (which swallowed the error and silently showed
built-in samples), the case timeline, and the identity timeline — whose
`evidence` and `mitre_technique` are really `raw_event` and
`mitre_techniques`, so it had reported no alerts for every identity on every
deployment. All three repointed. Added a guard refusing promotion of a
comment-only rule body and defaulted the auto-tuner off.
* fix(wave6): CI follow-ups, and make the openapi drift message diagnostic
The playbook step schema allows no `description`, so the retraction
explanation moved into the step name and the playbook description. The
marketplace index is regenerated for the edited pack.
`check_python_route_state` is a shrink-only ratchet and removing
`detection_loop.py` discharged its `_SUGGESTIONS` entry, which the gate
correctly reported as a stale exemption.
The openapi drift was environmental, not a missed regeneration: this venv had
pydantic 2.8.2 against the lockfile's 2.13.5, and 2.13 emits
`additionalProperties: true` on bare `dict` responses where 2.8 did not --
252 lines of diff across the spec, nothing to do with the change. The gate's
advice was to run the command that produced the rejected file, which is the
least useful place it could leave somebody, so it now names a generator
version that disagrees with the lockfile, prints the `pip install` that fixes
it, and shows the first few differing paths. Proven by downgrading pydantic and
reading the message.
* docs(wave6): record the detection-loop route removal as BREAKING
Three paths and three schemas leave the published spec, so every generated SDK
client loses those operations and the policy requires it stated under its own
heading. The migration note is that there is none: the routes queried two
tables and a column that no migration creates, so any caller was already
receiving an error.
186 lines
6.6 KiB
Python
Executable File
186 lines
6.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Export the AiSOC FastAPI OpenAPI schema to docs/openapi.yaml.
|
|
|
|
Usage
|
|
-----
|
|
python scripts/export_openapi.py [--check]
|
|
|
|
--check Diff mode: exit 1 if docs/openapi.yaml differs from what the app
|
|
currently generates. Used by CI to keep the committed schema in sync.
|
|
|
|
The script imports the FastAPI application directly (no running server needed)
|
|
and calls ``app.openapi()`` to get the schema, then serialises it to YAML.
|
|
|
|
MIT License — AiSOC (open-source AI Security Operations Center)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# `scripts/` is on sys.path when this file is run as a program, but not when a
|
|
# test loads it by path with importlib. gate_toolkit sits beside it either way.
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from gate_toolkit import repo_root, self_test_if_requested
|
|
|
|
self_test_if_requested(__file__)
|
|
|
|
# ── Ensure the api service is importable ─────────────────────────────────────
|
|
REPO_ROOT = repo_root()
|
|
API_SRC = REPO_ROOT / "services" / "api"
|
|
if str(API_SRC) not in sys.path:
|
|
sys.path.insert(0, str(API_SRC))
|
|
|
|
# Set minimal env vars so settings validation doesn't fail
|
|
os.environ.setdefault("ENVIRONMENT", "development")
|
|
os.environ.setdefault("SECRET_KEY", "export-openapi-dummy-secret-key-32bytes!")
|
|
os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://x:x@localhost/x")
|
|
|
|
try:
|
|
import yaml # PyYAML
|
|
except ImportError:
|
|
print("ERROR: PyYAML is required. Install with: pip install pyyaml", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
from app.main import app # noqa: E402 (after sys.path manipulation)
|
|
|
|
|
|
def get_schema() -> dict:
|
|
return app.openapi()
|
|
|
|
|
|
def write_yaml(schema: dict, dest: Path) -> None:
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
with dest.open("w", encoding="utf-8") as fh:
|
|
yaml.dump(schema, fh, allow_unicode=True, sort_keys=False, default_flow_style=False)
|
|
print(f"OpenAPI schema written to {dest.relative_to(REPO_ROOT)}")
|
|
|
|
|
|
def _locked_version(package: str) -> str | None:
|
|
"""What `services/api/poetry.lock` pins `package` to, if it can be read."""
|
|
lock = REPO_ROOT / "services" / "api" / "poetry.lock"
|
|
if not lock.exists():
|
|
return None
|
|
wanted = f'name = "{package}"'
|
|
lines = lock.read_text(encoding="utf-8").splitlines()
|
|
for i, line in enumerate(lines):
|
|
if line.strip() == wanted:
|
|
for follow in lines[i + 1 : i + 4]:
|
|
stripped = follow.strip()
|
|
if stripped.startswith("version = "):
|
|
return stripped.split('"')[1]
|
|
return None
|
|
|
|
|
|
def _report_generator_versions() -> None:
|
|
"""Name a toolchain mismatch, because it is the usual cause and the
|
|
message above cannot fix it.
|
|
|
|
The schema is generated by pydantic and FastAPI, and both change their
|
|
output between minors -- pydantic 2.13 emits `additionalProperties: true`
|
|
on bare `dict` responses where 2.8 did not, which is 252 lines of diff
|
|
across this file and nothing to do with anyone's change. Told only to
|
|
"run export_openapi.py", a contributor runs the command that produced the
|
|
rejected file and gets the same result, which is the least useful place a
|
|
gate can leave somebody.
|
|
"""
|
|
for package, module in (("pydantic", "pydantic"), ("fastapi", "fastapi")):
|
|
locked = _locked_version(package)
|
|
try:
|
|
installed = __import__(module).VERSION if package == "pydantic" else __import__(module).__version__
|
|
except Exception: # pragma: no cover - a missing generator fails earlier
|
|
continue
|
|
if locked and installed != locked:
|
|
print(
|
|
f" {package} {installed} is installed and services/api/poetry.lock pins {locked}.\n"
|
|
f" That alone changes the generated schema. Install the locked version first:\n"
|
|
f" pip install '{package}=={locked}'",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
|
|
def _report_first_differences(existing: dict, schema: dict, limit: int = 8) -> None:
|
|
"""Print the first few paths that differ, so the cause is visible here.
|
|
|
|
A gate that says only "these two documents differ" over a 30,000-line file
|
|
leaves the reader to reconstruct the diff by hand.
|
|
"""
|
|
|
|
def walk(a: object, b: object, trail: str) -> list[str]:
|
|
if isinstance(a, dict) and isinstance(b, dict):
|
|
out: list[str] = []
|
|
for key in sorted(set(a) | set(b)):
|
|
if key not in a:
|
|
out.append(f"{trail}.{key}: only in the generated schema")
|
|
elif key not in b:
|
|
out.append(f"{trail}.{key}: only in the committed file")
|
|
else:
|
|
out.extend(walk(a[key], b[key], f"{trail}.{key}"))
|
|
if len(out) >= limit:
|
|
break
|
|
return out
|
|
if a != b:
|
|
return [f"{trail}: committed {a!r} vs generated {b!r}"]
|
|
return []
|
|
|
|
differences = walk(existing, schema, "")[:limit]
|
|
if differences:
|
|
print(" First differences:", file=sys.stderr)
|
|
for line in differences:
|
|
print(f" {line}"[:200], file=sys.stderr)
|
|
|
|
|
|
def check_yaml(schema: dict, dest: Path) -> bool:
|
|
"""Return True if file matches generated schema."""
|
|
if not dest.exists():
|
|
print(f"{dest.relative_to(REPO_ROOT)} does not exist. Run: python scripts/export_openapi.py", file=sys.stderr)
|
|
return False
|
|
|
|
with dest.open("r", encoding="utf-8") as fh:
|
|
existing = yaml.safe_load(fh)
|
|
|
|
if existing != schema:
|
|
print(
|
|
f"{dest.relative_to(REPO_ROOT)} is out of date.\n Run: python scripts/export_openapi.py then commit the result.",
|
|
file=sys.stderr,
|
|
)
|
|
_report_generator_versions()
|
|
_report_first_differences(existing, schema)
|
|
return False
|
|
|
|
print(f"{dest.relative_to(REPO_ROOT)} is up to date.")
|
|
return True
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Export or verify AiSOC OpenAPI schema.")
|
|
parser.add_argument(
|
|
"--check",
|
|
action="store_true",
|
|
help="Exit with code 1 if docs/openapi.yaml differs from the current schema.",
|
|
)
|
|
parser.add_argument(
|
|
"--output",
|
|
default=str(REPO_ROOT / "docs" / "openapi.yaml"),
|
|
help="Destination path (default: docs/openapi.yaml)",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
dest = Path(args.output)
|
|
schema = get_schema()
|
|
|
|
if args.check:
|
|
ok = check_yaml(schema, dest)
|
|
sys.exit(0 if ok else 1)
|
|
else:
|
|
write_yaml(schema, dest)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|