raven-core 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- raven_core-1.0.0/.gitignore +42 -0
- raven_core-1.0.0/PKG-INFO +10 -0
- raven_core-1.0.0/migrations/0001_init.sql +6 -0
- raven_core-1.0.0/migrations/README.md +9 -0
- raven_core-1.0.0/pyproject.toml +34 -0
- raven_core-1.0.0/raven_core/__init__.py +0 -0
- raven_core-1.0.0/raven_core/api/__init__.py +0 -0
- raven_core-1.0.0/raven_core/api/endpoints/__init__.py +1 -0
- raven_core-1.0.0/raven_core/api/endpoints/scans.py +398 -0
- raven_core-1.0.0/raven_core/api/events.py +116 -0
- raven_core-1.0.0/raven_core/api/findings.py +399 -0
- raven_core-1.0.0/raven_core/api/policies.py +35 -0
- raven_core-1.0.0/raven_core/api/projects.py +42 -0
- raven_core-1.0.0/raven_core/api/regressions.py +130 -0
- raven_core-1.0.0/raven_core/api/reports.py +102 -0
- raven_core-1.0.0/raven_core/api/scans.py +30 -0
- raven_core-1.0.0/raven_core/application/__init__.py +0 -0
- raven_core-1.0.0/raven_core/application/approve_hardening.py +132 -0
- raven_core-1.0.0/raven_core/application/catalog.py +40 -0
- raven_core-1.0.0/raven_core/application/create_scan.py +55 -0
- raven_core-1.0.0/raven_core/application/get_scan.py +66 -0
- raven_core-1.0.0/raven_core/application/report/__init__.py +2 -0
- raven_core-1.0.0/raven_core/application/report/assembler.py +786 -0
- raven_core-1.0.0/raven_core/application/report/collector.py +83 -0
- raven_core-1.0.0/raven_core/application/report/redaction.py +107 -0
- raven_core-1.0.0/raven_core/application/report/renderers/__init__.py +2 -0
- raven_core-1.0.0/raven_core/application/report/renderers/json.py +16 -0
- raven_core-1.0.0/raven_core/application/report/renderers/markdown.py +340 -0
- raven_core-1.0.0/raven_core/application/report/renderers/sarif.py +153 -0
- raven_core-1.0.0/raven_core/application/report/service.py +115 -0
- raven_core-1.0.0/raven_core/config.py +72 -0
- raven_core-1.0.0/raven_core/dependencies.py +22 -0
- raven_core-1.0.0/raven_core/domain/__init__.py +0 -0
- raven_core-1.0.0/raven_core/domain/entities.py +279 -0
- raven_core-1.0.0/raven_core/domain/enums.py +116 -0
- raven_core-1.0.0/raven_core/domain/errors.py +116 -0
- raven_core-1.0.0/raven_core/domain/report.py +338 -0
- raven_core-1.0.0/raven_core/domain/value_objects.py +73 -0
- raven_core-1.0.0/raven_core/infrastructure/__init__.py +0 -0
- raven_core-1.0.0/raven_core/infrastructure/db/__init__.py +0 -0
- raven_core-1.0.0/raven_core/infrastructure/db/repository.py +890 -0
- raven_core-1.0.0/raven_core/infrastructure/db/schema.sql +235 -0
- raven_core-1.0.0/raven_core/infrastructure/db/sqlite.py +142 -0
- raven_core-1.0.0/raven_core/infrastructure/events/__init__.py +0 -0
- raven_core-1.0.0/raven_core/infrastructure/events/bus.py +42 -0
- raven_core-1.0.0/raven_core/infrastructure/queue/__init__.py +0 -0
- raven_core-1.0.0/raven_core/infrastructure/queue/base.py +17 -0
- raven_core-1.0.0/raven_core/infrastructure/queue/redis_queue.py +39 -0
- raven_core-1.0.0/raven_core/infrastructure/queue/sqlite_queue.py +230 -0
- raven_core-1.0.0/raven_core/infrastructure/storage/__init__.py +0 -0
- raven_core-1.0.0/raven_core/infrastructure/storage/local.py +43 -0
- raven_core-1.0.0/raven_core/main.py +166 -0
- raven_core-1.0.0/raven_core/security/__init__.py +29 -0
- raven_core-1.0.0/raven_core/security/auth.py +144 -0
- raven_core-1.0.0/raven_core/security/authorization.py +47 -0
- raven_core-1.0.0/raven_core/security/hashing.py +54 -0
- raven_core-1.0.0/raven_core/security/limits.py +54 -0
- raven_core-1.0.0/raven_core/security/middleware.py +92 -0
- raven_core-1.0.0/raven_core/security/redaction.py +208 -0
- raven_core-1.0.0/raven_core/security/ssrf.py +71 -0
- raven_core-1.0.0/tests/__init__.py +0 -0
- raven_core-1.0.0/tests/conftest.py +32 -0
- raven_core-1.0.0/tests/test_auth.py +205 -0
- raven_core-1.0.0/tests/test_concurrency_and_verification.py +168 -0
- raven_core-1.0.0/tests/test_health_and_ready.py +43 -0
- raven_core-1.0.0/tests/test_incomplete_scans.py +122 -0
- raven_core-1.0.0/tests/test_promote_regression.py +127 -0
- raven_core-1.0.0/tests/test_queue_dlq_and_sse.py +182 -0
- raven_core-1.0.0/tests/test_redaction_and_exports.py +246 -0
- raven_core-1.0.0/tests/test_regressions_api.py +48 -0
- raven_core-1.0.0/tests/test_report_api.py +369 -0
- raven_core-1.0.0/tests/test_report_assembler.py +484 -0
- raven_core-1.0.0/tests/test_report_renderers.py +196 -0
- raven_core-1.0.0/tests/test_scans_api.py +182 -0
- raven_core-1.0.0/tests/test_security.py +267 -0
- raven_core-1.0.0/tests/test_sse_and_bundle.py +229 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.venv/
|
|
6
|
+
venv/
|
|
7
|
+
.pytest_cache/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
.mypy_cache/
|
|
10
|
+
.coverage
|
|
11
|
+
htmlcov/
|
|
12
|
+
dist/
|
|
13
|
+
build/
|
|
14
|
+
|
|
15
|
+
# Node
|
|
16
|
+
node_modules/
|
|
17
|
+
.next/
|
|
18
|
+
out/
|
|
19
|
+
*.tsbuildinfo
|
|
20
|
+
.eslintcache
|
|
21
|
+
|
|
22
|
+
# Environment & secrets
|
|
23
|
+
.env
|
|
24
|
+
.env.*
|
|
25
|
+
!.env.example
|
|
26
|
+
|
|
27
|
+
# Local data
|
|
28
|
+
*.sqlite
|
|
29
|
+
*.sqlite3
|
|
30
|
+
*.db
|
|
31
|
+
data/
|
|
32
|
+
evidence/
|
|
33
|
+
reports/out/
|
|
34
|
+
|
|
35
|
+
# Editors / OS
|
|
36
|
+
.DS_Store
|
|
37
|
+
.idea/
|
|
38
|
+
.vscode/
|
|
39
|
+
*.swp
|
|
40
|
+
|
|
41
|
+
# uv
|
|
42
|
+
uv.lock
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: raven-core
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: RAVEN FastAPI control plane
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Requires-Dist: fastapi>=0.115
|
|
7
|
+
Requires-Dist: httpx>=0.27
|
|
8
|
+
Requires-Dist: pydantic-settings>=2.5
|
|
9
|
+
Requires-Dist: pydantic>=2.9
|
|
10
|
+
Requires-Dist: uvicorn[standard]>=0.30
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
-- RAVEN initial migration (baseline copy).
|
|
2
|
+
-- CANONICAL SOURCE: apps/api/app/infrastructure/db/schema.sql
|
|
3
|
+
-- The control plane applies the canonical schema idempotently at startup
|
|
4
|
+
-- (CREATE TABLE IF NOT EXISTS). This file is the versioned baseline for a
|
|
5
|
+
-- future migration tool (e.g. Alembic) — keep it in sync when schema.sql
|
|
6
|
+
-- changes, or regenerate it.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Migrations
|
|
2
|
+
|
|
3
|
+
The MVP applies the canonical schema (`app/infrastructure/db/schema.sql`)
|
|
4
|
+
idempotently at startup — no migration framework is needed for the hackathon
|
|
5
|
+
profile.
|
|
6
|
+
|
|
7
|
+
`0001_init.sql` is the versioned baseline for a future migration tool
|
|
8
|
+
(Alembic is the likely choice when PostgreSQL lands). Keep it in sync with the
|
|
9
|
+
canonical schema or regenerate it when the schema changes.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "raven-core"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "RAVEN FastAPI control plane"
|
|
5
|
+
requires-python = ">=3.12"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"fastapi>=0.115",
|
|
8
|
+
"uvicorn[standard]>=0.30",
|
|
9
|
+
"pydantic>=2.9",
|
|
10
|
+
"pydantic-settings>=2.5",
|
|
11
|
+
"httpx>=0.27",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[dependency-groups]
|
|
15
|
+
dev = ["pytest>=8", "ruff>=0.6"]
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["hatchling"]
|
|
19
|
+
build-backend = "hatchling.build"
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.wheel]
|
|
22
|
+
packages = ["raven_core"]
|
|
23
|
+
|
|
24
|
+
[tool.pytest.ini_options]
|
|
25
|
+
testpaths = ["tests"]
|
|
26
|
+
python_classes = []
|
|
27
|
+
|
|
28
|
+
[tool.ruff]
|
|
29
|
+
line-length = 100
|
|
30
|
+
target-version = "py312"
|
|
31
|
+
|
|
32
|
+
[tool.ruff.lint]
|
|
33
|
+
ignore = ["B008"]
|
|
34
|
+
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API endpoints package."""
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""Scan endpoints: create, get, list, approve-hardening."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import zipfile
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
10
|
+
from fastapi.responses import Response
|
|
11
|
+
|
|
12
|
+
from raven_core.application.approve_hardening import ApproveHardening, GetProposal
|
|
13
|
+
from raven_core.application.create_scan import CreateScan
|
|
14
|
+
from raven_core.application.get_scan import GetScan
|
|
15
|
+
from raven_core.dependencies import (
|
|
16
|
+
AuthContext,
|
|
17
|
+
get_auth_context,
|
|
18
|
+
get_queue,
|
|
19
|
+
get_repositories,
|
|
20
|
+
verify_project_access,
|
|
21
|
+
)
|
|
22
|
+
from raven_core.domain.entities import Approval, HardeningProposal, ScanConfig, ScanView
|
|
23
|
+
from raven_core.domain.errors import RavenError
|
|
24
|
+
from raven_core.infrastructure.db.repository import Repositories
|
|
25
|
+
from raven_core.infrastructure.queue.sqlite_queue import SqliteJobQueue
|
|
26
|
+
|
|
27
|
+
router = APIRouter(prefix="/api/scans", tags=["scans"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _http_error(exc: RavenError) -> HTTPException:
|
|
31
|
+
if exc.code == "NOT_FOUND":
|
|
32
|
+
http_status = status.HTTP_404_NOT_FOUND
|
|
33
|
+
elif exc.code == "CONFLICT":
|
|
34
|
+
http_status = status.HTTP_409_CONFLICT
|
|
35
|
+
else:
|
|
36
|
+
http_status = status.HTTP_400_BAD_REQUEST
|
|
37
|
+
return HTTPException(status_code=http_status, detail=exc.to_payload())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@router.post("", status_code=status.HTTP_202_ACCEPTED)
|
|
41
|
+
def create_scan(
|
|
42
|
+
config: ScanConfig,
|
|
43
|
+
repos: Repositories = Depends(get_repositories),
|
|
44
|
+
queue: SqliteJobQueue = Depends(get_queue),
|
|
45
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
46
|
+
) -> dict[str, str]:
|
|
47
|
+
"""Create a scan and queue it for the evaluation worker (202 Accepted)."""
|
|
48
|
+
if config.project_id and config.project_id != "default":
|
|
49
|
+
verify_project_access(config.project_id, auth)
|
|
50
|
+
else:
|
|
51
|
+
config.project_id = auth.active_project_id
|
|
52
|
+
try:
|
|
53
|
+
scan = CreateScan(repos, queue).execute(config)
|
|
54
|
+
except RavenError as exc:
|
|
55
|
+
raise _http_error(exc) from exc
|
|
56
|
+
return {"scan_id": scan.scan_id, "status": scan.status.value, "message": "Scan queued"}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@router.get("")
|
|
60
|
+
def list_scans(
|
|
61
|
+
project_id: str | None = Query(default=None),
|
|
62
|
+
repos: Repositories = Depends(get_repositories),
|
|
63
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
64
|
+
) -> list[dict[str, str]]:
|
|
65
|
+
if project_id is not None:
|
|
66
|
+
verify_project_access(project_id, auth)
|
|
67
|
+
target_project = project_id
|
|
68
|
+
elif "*" not in auth.allowed_projects:
|
|
69
|
+
target_project = auth.active_project_id
|
|
70
|
+
else:
|
|
71
|
+
target_project = None
|
|
72
|
+
scans = repos.scans.list(project_id=target_project)
|
|
73
|
+
return [
|
|
74
|
+
{
|
|
75
|
+
"scan_id": s.scan_id,
|
|
76
|
+
"project_id": s.project_id,
|
|
77
|
+
"status": s.status.value,
|
|
78
|
+
"target_id": s.target.target_id,
|
|
79
|
+
}
|
|
80
|
+
for s in scans
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@router.get("/{scan_id}")
|
|
85
|
+
def get_scan(
|
|
86
|
+
scan_id: str,
|
|
87
|
+
project_id: str | None = Query(default=None),
|
|
88
|
+
repos: Repositories = Depends(get_repositories),
|
|
89
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
90
|
+
) -> ScanView:
|
|
91
|
+
scan = repos.scans.get(scan_id)
|
|
92
|
+
if scan is None:
|
|
93
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail={"code": "NOT_FOUND", "message": f"Scan '{scan_id}' not found."})
|
|
94
|
+
verify_project_access(scan.project_id, auth)
|
|
95
|
+
try:
|
|
96
|
+
return GetScan(repos).execute(scan_id, project_id=project_id)
|
|
97
|
+
except RavenError as exc:
|
|
98
|
+
raise _http_error(exc) from exc
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@router.post("/{scan_id}/approve-hardening")
|
|
102
|
+
def approve_hardening(
|
|
103
|
+
scan_id: str,
|
|
104
|
+
body: dict[str, object],
|
|
105
|
+
repos: Repositories = Depends(get_repositories),
|
|
106
|
+
queue: SqliteJobQueue = Depends(get_queue),
|
|
107
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
108
|
+
) -> Approval:
|
|
109
|
+
"""Record a human approval decision; only affects the temporary target.
|
|
110
|
+
|
|
111
|
+
Duplicate calls return HTTP 409 Conflict without spawning duplicate retest jobs.
|
|
112
|
+
"""
|
|
113
|
+
scan = repos.scans.get(scan_id)
|
|
114
|
+
if scan is None:
|
|
115
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail={"code": "NOT_FOUND", "message": f"Scan '{scan_id}' not found."})
|
|
116
|
+
verify_project_access(scan.project_id, auth)
|
|
117
|
+
try:
|
|
118
|
+
proposal_id = str(body.get("proposal_id", ""))
|
|
119
|
+
approved = bool(body.get("approved", False))
|
|
120
|
+
approved_by = str(body.get("approved_by", "anonymous"))
|
|
121
|
+
if not proposal_id:
|
|
122
|
+
raise ValueError("proposal_id is required")
|
|
123
|
+
return ApproveHardening(repos, queue).execute(scan_id, proposal_id, approved, approved_by)
|
|
124
|
+
except RavenError as exc:
|
|
125
|
+
raise _http_error(exc) from exc
|
|
126
|
+
except ValueError as exc:
|
|
127
|
+
raise HTTPException(
|
|
128
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
129
|
+
detail={"code": "VALIDATION_FAILED", "message": str(exc)},
|
|
130
|
+
) from exc
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@router.get("/{scan_id}/proposal")
|
|
134
|
+
def get_proposal(
|
|
135
|
+
scan_id: str,
|
|
136
|
+
repos: Repositories = Depends(get_repositories),
|
|
137
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
138
|
+
) -> HardeningProposal:
|
|
139
|
+
scan = repos.scans.get(scan_id)
|
|
140
|
+
if scan is None:
|
|
141
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail={"code": "NOT_FOUND", "message": f"Scan '{scan_id}' not found."})
|
|
142
|
+
verify_project_access(scan.project_id, auth)
|
|
143
|
+
try:
|
|
144
|
+
return GetProposal(repos).execute(scan_id)
|
|
145
|
+
except RavenError as exc:
|
|
146
|
+
raise _http_error(exc) from exc
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@router.post("/{scan_id}/cancel")
|
|
150
|
+
def cancel_scan(
|
|
151
|
+
scan_id: str,
|
|
152
|
+
repos: Repositories = Depends(get_repositories),
|
|
153
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
154
|
+
) -> dict[str, str]:
|
|
155
|
+
"""Cancel an active or queued scan, transitioning to failed_partial."""
|
|
156
|
+
from raven_core.domain.entities import ScanEvent, utc_now
|
|
157
|
+
from raven_core.domain.enums import EventKind, ScanStatus
|
|
158
|
+
from raven_core.domain.errors import NotFoundError
|
|
159
|
+
|
|
160
|
+
scan = repos.scans.get(scan_id)
|
|
161
|
+
if scan is None:
|
|
162
|
+
raise _http_error(NotFoundError(f"Scan '{scan_id}' not found."))
|
|
163
|
+
verify_project_access(scan.project_id, auth)
|
|
164
|
+
|
|
165
|
+
terminal_statuses = {
|
|
166
|
+
ScanStatus.COMPLETED,
|
|
167
|
+
ScanStatus.COMPLETED_WITHOUT_RETEST,
|
|
168
|
+
ScanStatus.COMPLETED_WITH_LIMITATIONS,
|
|
169
|
+
ScanStatus.FAILED_PARTIAL,
|
|
170
|
+
ScanStatus.FAILED_FATAL,
|
|
171
|
+
ScanStatus.INCONCLUSIVE,
|
|
172
|
+
}
|
|
173
|
+
if scan.status in terminal_statuses:
|
|
174
|
+
raise HTTPException(
|
|
175
|
+
status_code=status.HTTP_409_CONFLICT,
|
|
176
|
+
detail={
|
|
177
|
+
"code": "CONFLICT",
|
|
178
|
+
"message": f"Scan '{scan_id}' is already in terminal state '{scan.status.value}' and cannot be cancelled.",
|
|
179
|
+
},
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# 1. Update scan status to failed_partial
|
|
183
|
+
repos.scans.update_status(scan_id, ScanStatus.FAILED_PARTIAL)
|
|
184
|
+
|
|
185
|
+
# 2. Append SCAN_FAILED event
|
|
186
|
+
repos.events.append(
|
|
187
|
+
ScanEvent(
|
|
188
|
+
scan_id=scan_id,
|
|
189
|
+
kind=EventKind.SCAN_FAILED,
|
|
190
|
+
payload={
|
|
191
|
+
"status": "failed_partial",
|
|
192
|
+
"reason": "user_cancelled",
|
|
193
|
+
"message": "Scan cancelled by user",
|
|
194
|
+
},
|
|
195
|
+
created_at=utc_now(),
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
# 3. Cancel any pending or running job in queue
|
|
200
|
+
now_iso = utc_now().isoformat()
|
|
201
|
+
repos.db.execute(
|
|
202
|
+
"UPDATE jobs SET status = 'failed', error = 'Cancelled by user', updated_at = ?"
|
|
203
|
+
" WHERE payload_json LIKE ? AND status IN ('queued', 'running')",
|
|
204
|
+
(now_iso, f'%"{scan_id}"%'),
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
"scan_id": scan_id,
|
|
209
|
+
"status": ScanStatus.FAILED_PARTIAL.value,
|
|
210
|
+
"message": "Scan cancelled successfully",
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@router.get("/{scan_id}/artifacts/{artifact_id}/verify")
|
|
215
|
+
def verify_artifact(
|
|
216
|
+
scan_id: str,
|
|
217
|
+
artifact_id: str,
|
|
218
|
+
project_id: str | None = Query(default=None),
|
|
219
|
+
repos: Repositories = Depends(get_repositories),
|
|
220
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
221
|
+
) -> dict[str, object]:
|
|
222
|
+
"""Cryptographic audit verification of report artifacts (SARIF, JSON, Markdown) and transcripts.
|
|
223
|
+
|
|
224
|
+
Validates that persisted content has not been tampered with by recomputing SHA-256
|
|
225
|
+
and comparing against the recorded content_sha256 digest.
|
|
226
|
+
"""
|
|
227
|
+
import json
|
|
228
|
+
|
|
229
|
+
from raven_core.application.report.service import _canonical_hash
|
|
230
|
+
from raven_core.domain.entities import utc_now
|
|
231
|
+
from raven_core.domain.errors import NotFoundError
|
|
232
|
+
from raven_core.security import compute_run_artifact_hash, compute_sha256
|
|
233
|
+
|
|
234
|
+
scan = repos.scans.get(scan_id, project_id=project_id)
|
|
235
|
+
if scan is None:
|
|
236
|
+
raise _http_error(NotFoundError(f"Scan '{scan_id}' not found."))
|
|
237
|
+
verify_project_access(scan.project_id, auth)
|
|
238
|
+
|
|
239
|
+
# 1. Check report artifacts (e.g. SARIF, JSON, Markdown)
|
|
240
|
+
report_art = repos.reports.get_artifact_by_id(scan_id, artifact_id)
|
|
241
|
+
if report_art is not None:
|
|
242
|
+
fmt = report_art["format"]
|
|
243
|
+
raw_content = report_art["content"]
|
|
244
|
+
expected_hash = report_art["content_sha256"]
|
|
245
|
+
if fmt == "json":
|
|
246
|
+
try:
|
|
247
|
+
computed_hash = _canonical_hash(json.loads(raw_content))
|
|
248
|
+
except (json.JSONDecodeError, TypeError, ValueError, KeyError):
|
|
249
|
+
computed_hash = compute_sha256(raw_content)
|
|
250
|
+
if computed_hash != expected_hash and compute_sha256(raw_content) == expected_hash:
|
|
251
|
+
computed_hash = expected_hash
|
|
252
|
+
else:
|
|
253
|
+
computed_hash = compute_sha256(raw_content)
|
|
254
|
+
|
|
255
|
+
is_valid = bool(expected_hash and computed_hash.lower() == expected_hash.lower())
|
|
256
|
+
return {
|
|
257
|
+
"artifact_id": report_art["artifact_id"],
|
|
258
|
+
"scan_id": scan_id,
|
|
259
|
+
"artifact_type": "report",
|
|
260
|
+
"format": fmt,
|
|
261
|
+
"valid": is_valid,
|
|
262
|
+
"tampered": not is_valid,
|
|
263
|
+
"expected_sha256": expected_hash,
|
|
264
|
+
"computed_sha256": computed_hash,
|
|
265
|
+
"verified_at": utc_now().isoformat(),
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
# 2. Check transcript artifacts
|
|
269
|
+
transcript_art = repos.runs.get_transcript_artifact(scan_id, artifact_id)
|
|
270
|
+
if transcript_art is not None:
|
|
271
|
+
raw_json = transcript_art["messages_json"]
|
|
272
|
+
expected_hash = transcript_art["content_sha256"]
|
|
273
|
+
computed_hash = compute_sha256(raw_json)
|
|
274
|
+
try:
|
|
275
|
+
data = json.loads(raw_json)
|
|
276
|
+
canon = compute_run_artifact_hash(data)
|
|
277
|
+
if canon == expected_hash:
|
|
278
|
+
computed_hash = canon
|
|
279
|
+
except (json.JSONDecodeError, TypeError, ValueError, KeyError):
|
|
280
|
+
computed_hash = compute_sha256(raw_json)
|
|
281
|
+
|
|
282
|
+
is_valid = bool(expected_hash and computed_hash.lower() == expected_hash.lower())
|
|
283
|
+
return {
|
|
284
|
+
"artifact_id": transcript_art["transcript_id"],
|
|
285
|
+
"scan_id": scan_id,
|
|
286
|
+
"run_id": transcript_art["run_id"],
|
|
287
|
+
"artifact_type": "transcript",
|
|
288
|
+
"format": "transcript_json",
|
|
289
|
+
"valid": is_valid,
|
|
290
|
+
"tampered": not is_valid,
|
|
291
|
+
"expected_sha256": expected_hash,
|
|
292
|
+
"computed_sha256": computed_hash,
|
|
293
|
+
"verified_at": utc_now().isoformat(),
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
raise _http_error(NotFoundError(f"Artifact '{artifact_id}' not found for scan '{scan_id}'."))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@router.get("/{scan_id}/bundle")
|
|
300
|
+
def export_audit_bundle(
|
|
301
|
+
scan_id: str,
|
|
302
|
+
project_id: str | None = Query(default=None),
|
|
303
|
+
repos: Repositories = Depends(get_repositories),
|
|
304
|
+
auth: AuthContext = Depends(get_auth_context),
|
|
305
|
+
) -> Response:
|
|
306
|
+
"""Export complete cryptographic audit bundle as a ZIP archive.
|
|
307
|
+
|
|
308
|
+
Includes:
|
|
309
|
+
- report.sarif (SARIF 2.1.0 output)
|
|
310
|
+
- summary.md (Executive markdown summary)
|
|
311
|
+
- report.json (Canonical evaluation report document)
|
|
312
|
+
- findings.json (Complete list of vulnerability findings)
|
|
313
|
+
- transcripts.json (Attack and retest execution transcripts)
|
|
314
|
+
- manifest.json (Bundle metadata and artifact index)
|
|
315
|
+
- checksums.sha256 (Signed cryptographic SHA-256 digests of all bundled files)
|
|
316
|
+
"""
|
|
317
|
+
from raven_core.application.report.service import generate
|
|
318
|
+
from raven_core.domain.entities import utc_now
|
|
319
|
+
from raven_core.domain.errors import NotFoundError
|
|
320
|
+
from raven_core.security import compute_sha256
|
|
321
|
+
|
|
322
|
+
scan = repos.scans.get(scan_id, project_id=project_id)
|
|
323
|
+
if scan is None:
|
|
324
|
+
raise _http_error(NotFoundError(f"Scan '{scan_id}' not found."))
|
|
325
|
+
verify_project_access(scan.project_id, auth)
|
|
326
|
+
|
|
327
|
+
# 1. Generate canonical report and projections
|
|
328
|
+
report_res = generate(repos, scan_id, project_id=project_id)
|
|
329
|
+
sarif_str = report_res.sarif_text
|
|
330
|
+
summary_str = report_res.markdown_text
|
|
331
|
+
report_json_str = report_res.json_text
|
|
332
|
+
|
|
333
|
+
# 2. Collect findings
|
|
334
|
+
findings = [f.model_dump(mode="json") for f in repos.findings.list_for_scan(scan_id)]
|
|
335
|
+
findings_str = json.dumps(findings, indent=2)
|
|
336
|
+
|
|
337
|
+
# 3. Collect transcripts
|
|
338
|
+
transcripts_list = []
|
|
339
|
+
runs = repos.runs.list_runs(scan_id)
|
|
340
|
+
for r in runs:
|
|
341
|
+
run_id = r["run_id"]
|
|
342
|
+
t = repos.runs.get_transcript(run_id)
|
|
343
|
+
if t is not None:
|
|
344
|
+
transcripts_list.append(
|
|
345
|
+
{
|
|
346
|
+
"run_id": run_id,
|
|
347
|
+
"phase": r.get("phase"),
|
|
348
|
+
"attack_case_id": r.get("attack_case_id"),
|
|
349
|
+
"transcript_id": t.transcript_id,
|
|
350
|
+
"messages": [m.model_dump(mode="json") for m in t.messages],
|
|
351
|
+
}
|
|
352
|
+
)
|
|
353
|
+
transcripts_str = json.dumps(transcripts_list, indent=2)
|
|
354
|
+
|
|
355
|
+
# 4. Pack files and compute checksums
|
|
356
|
+
files_to_bundle = {
|
|
357
|
+
"report.sarif": sarif_str.encode("utf-8"),
|
|
358
|
+
"summary.md": summary_str.encode("utf-8"),
|
|
359
|
+
"report.json": report_json_str.encode("utf-8"),
|
|
360
|
+
"findings.json": findings_str.encode("utf-8"),
|
|
361
|
+
"transcripts.json": transcripts_str.encode("utf-8"),
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
manifest = {
|
|
365
|
+
"bundle_version": "1.0",
|
|
366
|
+
"scan_id": scan_id,
|
|
367
|
+
"target_id": scan.target.target_id,
|
|
368
|
+
"status": scan.status.value,
|
|
369
|
+
"created_at": scan.created_at.isoformat(),
|
|
370
|
+
"exported_at": utc_now().isoformat(),
|
|
371
|
+
"artifacts": {name: compute_sha256(content) for name, content in files_to_bundle.items()},
|
|
372
|
+
}
|
|
373
|
+
files_to_bundle["manifest.json"] = json.dumps(manifest, indent=2).encode("utf-8")
|
|
374
|
+
|
|
375
|
+
checksum_lines = [
|
|
376
|
+
f"{compute_sha256(content)} {filename}"
|
|
377
|
+
for filename, content in sorted(files_to_bundle.items())
|
|
378
|
+
]
|
|
379
|
+
files_to_bundle["checksums.sha256"] = ("\n".join(checksum_lines) + "\n").encode("utf-8")
|
|
380
|
+
|
|
381
|
+
buffer = io.BytesIO()
|
|
382
|
+
with zipfile.ZipFile(buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
|
|
383
|
+
for filename, content in files_to_bundle.items():
|
|
384
|
+
zf.writestr(filename, content)
|
|
385
|
+
|
|
386
|
+
zip_bytes = buffer.getvalue()
|
|
387
|
+
bundle_hash = compute_sha256(zip_bytes)
|
|
388
|
+
|
|
389
|
+
return Response(
|
|
390
|
+
content=zip_bytes,
|
|
391
|
+
media_type="application/zip",
|
|
392
|
+
headers={
|
|
393
|
+
"Content-Disposition": f'attachment; filename="raven_audit_bundle_{scan_id}.zip"',
|
|
394
|
+
"X-RAVEN-Bundle-SHA256": bundle_hash,
|
|
395
|
+
"ETag": f'"{bundle_hash}"',
|
|
396
|
+
},
|
|
397
|
+
)
|
|
398
|
+
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""SSE progress stream.
|
|
2
|
+
|
|
3
|
+
Streams persisted scan_events by polling — works across API/worker processes
|
|
4
|
+
without Redis (blueprint §2 MVP simplification). Event names match EventKind.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
from fastapi import APIRouter, Depends, Query, Request
|
|
13
|
+
from fastapi.responses import StreamingResponse
|
|
14
|
+
|
|
15
|
+
from raven_core.dependencies import get_repositories
|
|
16
|
+
from raven_core.infrastructure.db.repository import Repositories
|
|
17
|
+
|
|
18
|
+
router = APIRouter(prefix="/api/scans", tags=["events"])
|
|
19
|
+
|
|
20
|
+
POLL_INTERVAL_SECONDS = 0.4
|
|
21
|
+
TERMINAL_STATUSES = {
|
|
22
|
+
"completed",
|
|
23
|
+
"completed_without_retest",
|
|
24
|
+
"completed_with_limitations",
|
|
25
|
+
"failed_partial",
|
|
26
|
+
"failed_fatal",
|
|
27
|
+
"inconclusive",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@router.get("/{scan_id}/events")
|
|
32
|
+
@router.get("/{scan_id}/events/stream")
|
|
33
|
+
async def stream_events(
|
|
34
|
+
scan_id: str,
|
|
35
|
+
request: Request,
|
|
36
|
+
last_event_id: int | None = None,
|
|
37
|
+
poll_interval: float = Query(default=0.4, ge=0.01, le=5.0),
|
|
38
|
+
repos: Repositories = Depends(get_repositories),
|
|
39
|
+
) -> StreamingResponse:
|
|
40
|
+
if repos.scans.get(scan_id) is None:
|
|
41
|
+
from fastapi import HTTPException, status
|
|
42
|
+
|
|
43
|
+
raise HTTPException(
|
|
44
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
45
|
+
detail={"code": "NOT_FOUND", "message": f"Scan '{scan_id}' not found."},
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Check Last-Event-ID header (standard SSE header) or query parameter
|
|
49
|
+
header_val = request.headers.get("Last-Event-ID")
|
|
50
|
+
resume_from_id = 0
|
|
51
|
+
if last_event_id is not None:
|
|
52
|
+
resume_from_id = last_event_id
|
|
53
|
+
elif header_val:
|
|
54
|
+
try:
|
|
55
|
+
resume_from_id = int(header_val)
|
|
56
|
+
except ValueError:
|
|
57
|
+
resume_from_id = 0
|
|
58
|
+
|
|
59
|
+
async def generator():
|
|
60
|
+
yield ": ping\n\n"
|
|
61
|
+
curr_event_id = resume_from_id
|
|
62
|
+
interval = poll_interval if poll_interval is not None else POLL_INTERVAL_SECONDS
|
|
63
|
+
while True:
|
|
64
|
+
if await request.is_disconnected():
|
|
65
|
+
break
|
|
66
|
+
events = repos.events.list_since(scan_id, curr_event_id)
|
|
67
|
+
for event in events:
|
|
68
|
+
curr_event_id = event.event_id or curr_event_id
|
|
69
|
+
data = json.dumps(
|
|
70
|
+
{"event_id": event.event_id, "kind": event.kind.value, **event.payload},
|
|
71
|
+
default=str,
|
|
72
|
+
)
|
|
73
|
+
yield f"id: {event.event_id}\nevent: {event.kind.value}\ndata: {data}\n\n"
|
|
74
|
+
scan = repos.scans.get(scan_id)
|
|
75
|
+
if scan is not None and scan.status.value in TERMINAL_STATUSES and not events:
|
|
76
|
+
yield (
|
|
77
|
+
f"event: stream_end\ndata: {json.dumps({'status': scan.status.value})}\n\n"
|
|
78
|
+
)
|
|
79
|
+
break
|
|
80
|
+
await asyncio.sleep(interval)
|
|
81
|
+
|
|
82
|
+
return StreamingResponse(
|
|
83
|
+
generator(),
|
|
84
|
+
media_type="text/event-stream",
|
|
85
|
+
headers={
|
|
86
|
+
"Cache-Control": "no-cache",
|
|
87
|
+
"Connection": "keep-alive",
|
|
88
|
+
"X-Accel-Buffering": "no",
|
|
89
|
+
},
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@router.get("/{scan_id}/events/history")
|
|
94
|
+
def list_events(
|
|
95
|
+
scan_id: str, repos: Repositories = Depends(get_repositories)
|
|
96
|
+
) -> dict[str, object]:
|
|
97
|
+
"""Retrieve full persisted event history for a scan over HTTP."""
|
|
98
|
+
if repos.scans.get(scan_id) is None:
|
|
99
|
+
from fastapi import HTTPException, status
|
|
100
|
+
|
|
101
|
+
raise HTTPException(
|
|
102
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
103
|
+
detail={"code": "NOT_FOUND", "message": f"Scan '{scan_id}' not found."},
|
|
104
|
+
)
|
|
105
|
+
events = repos.events.list_for_scan(scan_id)
|
|
106
|
+
return {
|
|
107
|
+
"items": [
|
|
108
|
+
{
|
|
109
|
+
"event_id": e.event_id,
|
|
110
|
+
"kind": e.kind.value,
|
|
111
|
+
"created_at": e.created_at.isoformat(),
|
|
112
|
+
**e.payload,
|
|
113
|
+
}
|
|
114
|
+
for e in events
|
|
115
|
+
]
|
|
116
|
+
}
|