saikou 1.2.0__py3-none-any.whl
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.
- saikou/__init__.py +44 -0
- saikou/__main__.py +5 -0
- saikou/api.py +329 -0
- saikou/catalog.py +415 -0
- saikou/cli.py +400 -0
- saikou/engine.py +2999 -0
- saikou/llm.py +486 -0
- saikou/sarif.py +73 -0
- saikou/server.py +243 -0
- saikou/service.py +468 -0
- saikou/verify.py +457 -0
- saikou/web/app.css +336 -0
- saikou/web/app.js +1368 -0
- saikou/web/index.html +303 -0
- saikou/web/logo.svg +10 -0
- saikou/web/sample.json +7 -0
- saikou/webassets.py +43 -0
- saikou-1.2.0.dist-info/METADATA +360 -0
- saikou-1.2.0.dist-info/RECORD +23 -0
- saikou-1.2.0.dist-info/WHEEL +4 -0
- saikou-1.2.0.dist-info/entry_points.txt +2 -0
- saikou-1.2.0.dist-info/licenses/LICENSE +177 -0
- saikou-1.2.0.dist-info/licenses/NOTICE +4 -0
saikou/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Saikou - prove that a security fix is real, not just claimed.
|
|
2
|
+
|
|
3
|
+
The engine is standard-library only:
|
|
4
|
+
|
|
5
|
+
from saikou import scan_transformation
|
|
6
|
+
findings = scan_transformation(before, after, language="python")
|
|
7
|
+
blocked = any(f.severity.value == "hard_fail" for f in findings)
|
|
8
|
+
|
|
9
|
+
Command line: `saikou verify BEFORE AFTER`, `saikou diff --base REF`,
|
|
10
|
+
`saikou harden FILE`, `saikou selftest`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .engine import (
|
|
14
|
+
Claim,
|
|
15
|
+
Contract,
|
|
16
|
+
Detection,
|
|
17
|
+
EvidenceLedger,
|
|
18
|
+
Finding,
|
|
19
|
+
LANGUAGES,
|
|
20
|
+
Provenance,
|
|
21
|
+
Severity,
|
|
22
|
+
SurfaceDiff,
|
|
23
|
+
THREAT_CHOICES,
|
|
24
|
+
TIER_MEANING,
|
|
25
|
+
Tier,
|
|
26
|
+
__version__,
|
|
27
|
+
assemble_ledger,
|
|
28
|
+
checks_run,
|
|
29
|
+
detect_language,
|
|
30
|
+
diff_python_surface,
|
|
31
|
+
language_for_path,
|
|
32
|
+
normalise_language,
|
|
33
|
+
normalise_threats,
|
|
34
|
+
run_analyser,
|
|
35
|
+
scan_transformation,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"Claim", "Contract", "Detection", "EvidenceLedger", "Finding", "LANGUAGES", "Provenance",
|
|
40
|
+
"Severity", "SurfaceDiff", "THREAT_CHOICES", "TIER_MEANING", "Tier", "__version__",
|
|
41
|
+
"assemble_ledger", "checks_run", "detect_language", "diff_python_surface",
|
|
42
|
+
"language_for_path", "normalise_language", "normalise_threats", "run_analyser",
|
|
43
|
+
"scan_transformation",
|
|
44
|
+
]
|
saikou/__main__.py
ADDED
saikou/api.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Optional hosted HTTP service (`pip install saikou[api]`).
|
|
2
|
+
|
|
3
|
+
uvicorn saikou.api:app --port 8080
|
|
4
|
+
|
|
5
|
+
GET /healthz liveness (no auth)
|
|
6
|
+
GET /v1/checks the check catalogue, English and Dutch (no auth)
|
|
7
|
+
POST /v1/verify one before/after pair
|
|
8
|
+
POST /v1/verify/batch many file pairs in one request (CI without installing anything)
|
|
9
|
+
POST /harden/intake contract + the questions worth asking
|
|
10
|
+
POST /harden/apply verified hardening + an evidence ledger (one model call)
|
|
11
|
+
GET / playground: the Saikou web app in hosted mode (Verify, Checks)
|
|
12
|
+
|
|
13
|
+
Every error is {"error": {"code": ..., "message": ...}} with a matching HTTP status.
|
|
14
|
+
|
|
15
|
+
Fails closed: without API_TOKENS it refuses to serve unless ENVIRONMENT=dev is set
|
|
16
|
+
explicitly. Requests are rate limited per token and bodies are capped (MAX_BODY_BYTES).
|
|
17
|
+
Hosted means hosted: this module never reads or writes the file system, never runs git
|
|
18
|
+
and never writes a hardened result anywhere. Those operations exist only in the local
|
|
19
|
+
app (saikou.server), which listens on 127.0.0.1.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import secrets
|
|
28
|
+
import time
|
|
29
|
+
from collections import defaultdict, deque
|
|
30
|
+
from typing import Any, Deque, Dict, List, Optional
|
|
31
|
+
|
|
32
|
+
from fastapi import Depends, FastAPI, Header, Request
|
|
33
|
+
from fastapi.exceptions import RequestValidationError
|
|
34
|
+
from fastapi.responses import JSONResponse, Response
|
|
35
|
+
from pydantic import BaseModel, Field
|
|
36
|
+
from starlette.exceptions import HTTPException
|
|
37
|
+
|
|
38
|
+
from . import service, webassets
|
|
39
|
+
from .engine import (
|
|
40
|
+
THREAT_CHOICES,
|
|
41
|
+
TIER_MEANING,
|
|
42
|
+
Contract,
|
|
43
|
+
Session,
|
|
44
|
+
SessionStore,
|
|
45
|
+
__version__,
|
|
46
|
+
build_questions,
|
|
47
|
+
detect_language,
|
|
48
|
+
normalise_language,
|
|
49
|
+
normalise_threats,
|
|
50
|
+
python_surface,
|
|
51
|
+
sha256,
|
|
52
|
+
utc_now,
|
|
53
|
+
)
|
|
54
|
+
from .llm import LLMConfig, LLMError, run_hardening
|
|
55
|
+
from .service import ServiceError
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _int_env(name: str, default: int, minimum: int = 1) -> int:
|
|
59
|
+
try:
|
|
60
|
+
return max(minimum, int(os.getenv(name, str(default))))
|
|
61
|
+
except ValueError:
|
|
62
|
+
return default
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
ENVIRONMENT = os.getenv("ENVIRONMENT", "production")
|
|
66
|
+
MAX_INPUT_CHARS = _int_env("MAX_INPUT_CHARS", 60000, 1000)
|
|
67
|
+
# The batch limit is 400k characters; JSON escaping and UTF-8 can double that.
|
|
68
|
+
MAX_BODY_BYTES = _int_env("MAX_BODY_BYTES", 2_000_000, 10_000)
|
|
69
|
+
API_TOKENS = frozenset(t.strip() for t in os.getenv("API_TOKENS", "").split(",") if t.strip())
|
|
70
|
+
RATE_LIMIT_PER_MINUTE = _int_env("RATE_LIMIT_PER_MINUTE", 20)
|
|
71
|
+
PLAYGROUND = os.getenv("PLAYGROUND", "1") != "0"
|
|
72
|
+
|
|
73
|
+
_sessions = SessionStore(_int_env("SESSION_TTL_S", 1800), _int_env("MAX_SESSIONS", 500))
|
|
74
|
+
_hits: Dict[str, Deque[float]] = defaultdict(deque)
|
|
75
|
+
|
|
76
|
+
_CODES = {400: "bad_request", 401: "unauthorized", 403: "forbidden", 404: "not_found",
|
|
77
|
+
405: "method_not_allowed", 413: "body_too_large", 415: "unsupported_media_type",
|
|
78
|
+
422: "bad_request", 429: "rate_limited", 500: "internal_error",
|
|
79
|
+
502: "model_error", 503: "unavailable"}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class IntakeBody(BaseModel):
|
|
83
|
+
code: str = Field(..., min_length=1, max_length=MAX_INPUT_CHARS)
|
|
84
|
+
language: Optional[str] = Field(None, max_length=40)
|
|
85
|
+
notes: Optional[str] = Field(None, max_length=4000)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ContractBody(BaseModel):
|
|
89
|
+
language: Optional[str] = Field(None, max_length=40)
|
|
90
|
+
target_runtime: str = Field("", max_length=80)
|
|
91
|
+
threat_model: List[str] = Field(default_factory=list, max_length=len(THREAT_CHOICES))
|
|
92
|
+
compat: str = Field("strict_api", pattern="^(strict_api|allow_signature_changes|rewrite_freely)$")
|
|
93
|
+
dependencies: str = Field("stdlib_only", pattern="^(stdlib_only|existing_only|may_add)$")
|
|
94
|
+
error_policy: str = Field("fail_closed", pattern="^(fail_closed|preserve_current)$")
|
|
95
|
+
output_style: str = Field("full_module", pattern="^(full_module|changed_parts)$")
|
|
96
|
+
must_preserve: List[str] = Field(default_factory=list, max_length=200)
|
|
97
|
+
notes: str = Field("", max_length=4000)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ApplyBody(BaseModel):
|
|
101
|
+
session_id: str = Field(..., min_length=8, max_length=200)
|
|
102
|
+
contract: ContractBody = Field(default_factory=ContractBody)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ---------------------------------------------------------------------------------------
|
|
106
|
+
# auth, rate limit, body cap
|
|
107
|
+
# ---------------------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
def require_auth(authorization: str = Header(default="")) -> str:
|
|
110
|
+
if not API_TOKENS:
|
|
111
|
+
if ENVIRONMENT != "dev":
|
|
112
|
+
raise ServiceError(503, "not_configured", "API_TOKENS is unset, so this instance "
|
|
113
|
+
"refuses to serve (set ENVIRONMENT=dev to run an open local "
|
|
114
|
+
"instance).")
|
|
115
|
+
return "dev"
|
|
116
|
+
token = authorization[7:] if authorization.startswith("Bearer ") else ""
|
|
117
|
+
for t in API_TOKENS:
|
|
118
|
+
if secrets.compare_digest(token, t):
|
|
119
|
+
return sha256(t)[:16]
|
|
120
|
+
raise ServiceError(401, "unauthorized", "Invalid or missing bearer token.",
|
|
121
|
+
headers={"WWW-Authenticate": "Bearer"})
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def rate_limit(caller: str = Depends(require_auth)) -> str:
|
|
125
|
+
now = time.monotonic()
|
|
126
|
+
window = _hits[caller]
|
|
127
|
+
while window and now - window[0] > 60:
|
|
128
|
+
window.popleft()
|
|
129
|
+
if len(window) >= RATE_LIMIT_PER_MINUTE:
|
|
130
|
+
wait = max(1, int(60 - (now - window[0])) + 1)
|
|
131
|
+
raise ServiceError(429, "rate_limited", f"Rate limit of {RATE_LIMIT_PER_MINUTE} requests "
|
|
132
|
+
f"per minute exceeded; retry in {wait} s.",
|
|
133
|
+
headers={"Retry-After": str(wait)})
|
|
134
|
+
window.append(now)
|
|
135
|
+
return caller
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _too_large() -> HTTPException:
|
|
139
|
+
return HTTPException(413, f"Request body exceeds {MAX_BODY_BYTES} bytes.")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class BodyLimit:
|
|
143
|
+
"""Reject bodies over MAX_BODY_BYTES: by Content-Length up front, and by counting the
|
|
144
|
+
stream for chunked uploads that declare no length."""
|
|
145
|
+
|
|
146
|
+
def __init__(self, app: Any) -> None:
|
|
147
|
+
self.app = app
|
|
148
|
+
|
|
149
|
+
async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
|
|
150
|
+
if scope["type"] != "http":
|
|
151
|
+
await self.app(scope, receive, send)
|
|
152
|
+
return
|
|
153
|
+
declared = dict(scope.get("headers") or []).get(b"content-length")
|
|
154
|
+
if declared is not None:
|
|
155
|
+
try:
|
|
156
|
+
over = int(declared) > MAX_BODY_BYTES
|
|
157
|
+
except ValueError:
|
|
158
|
+
over = True
|
|
159
|
+
if over:
|
|
160
|
+
await _error(413, "body_too_large", _too_large().detail)(scope, receive, send)
|
|
161
|
+
return
|
|
162
|
+
seen = 0
|
|
163
|
+
|
|
164
|
+
async def capped() -> dict:
|
|
165
|
+
nonlocal seen
|
|
166
|
+
message = await receive()
|
|
167
|
+
if message.get("type") == "http.request":
|
|
168
|
+
seen += len(message.get("body", b""))
|
|
169
|
+
if seen > MAX_BODY_BYTES:
|
|
170
|
+
# An HTTPException survives FastAPI's body parsing unchanged.
|
|
171
|
+
raise _too_large()
|
|
172
|
+
return message
|
|
173
|
+
|
|
174
|
+
await self.app(scope, capped, send)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def _json(request: Request) -> Any:
|
|
178
|
+
raw = await request.body()
|
|
179
|
+
try:
|
|
180
|
+
return json.loads(raw.decode("utf-8"))
|
|
181
|
+
except (UnicodeDecodeError, ValueError):
|
|
182
|
+
raise ServiceError(400, "bad_json", "Request body is not valid UTF-8 JSON.") from None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ---------------------------------------------------------------------------------------
|
|
186
|
+
# app
|
|
187
|
+
# ---------------------------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
_production = ENVIRONMENT == "production"
|
|
190
|
+
app = FastAPI(title="Saikou", version=__version__,
|
|
191
|
+
docs_url=None if _production else "/docs",
|
|
192
|
+
redoc_url=None if _production else "/redoc",
|
|
193
|
+
openapi_url=None if _production else "/openapi.json")
|
|
194
|
+
app.add_middleware(BodyLimit)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _error(status: int, code: str, message: str,
|
|
198
|
+
headers: Optional[Dict[str, str]] = None) -> JSONResponse:
|
|
199
|
+
return JSONResponse({"error": {"code": code, "message": message}}, status_code=status,
|
|
200
|
+
headers=headers)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@app.exception_handler(ServiceError)
|
|
204
|
+
async def _service_error(_request: Request, exc: ServiceError) -> JSONResponse:
|
|
205
|
+
return _error(exc.status, exc.code, exc.message, exc.headers)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@app.exception_handler(HTTPException)
|
|
209
|
+
async def _http_error(_request: Request, exc: HTTPException) -> JSONResponse:
|
|
210
|
+
return _error(exc.status_code, _CODES.get(exc.status_code, "error"), str(exc.detail),
|
|
211
|
+
getattr(exc, "headers", None))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@app.exception_handler(RequestValidationError)
|
|
215
|
+
async def _validation_error(_request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
216
|
+
first = (exc.errors() or [{}])[0]
|
|
217
|
+
where = ".".join(str(p) for p in first.get("loc", ()) if p != "body")
|
|
218
|
+
message = first.get("msg", "Invalid request.")
|
|
219
|
+
return _error(422, "bad_request", f"{where}: {message}" if where else message)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@app.middleware("http")
|
|
223
|
+
async def _headers(request: Request, call_next: Any) -> Response:
|
|
224
|
+
request_id = secrets.token_hex(12)
|
|
225
|
+
response = await call_next(request)
|
|
226
|
+
response.headers.update({"X-Request-ID": request_id,
|
|
227
|
+
"X-Content-Type-Options": "nosniff",
|
|
228
|
+
"X-Frame-Options": "DENY",
|
|
229
|
+
"Referrer-Policy": "no-referrer"})
|
|
230
|
+
response.headers.setdefault("Cache-Control", "no-store")
|
|
231
|
+
return response
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def _run(fn: Any, *args: Any) -> Any:
|
|
235
|
+
# The engine is synchronous and CPU-bound; keep it off the event loop.
|
|
236
|
+
return await asyncio.to_thread(fn, *args)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@app.get("/healthz")
|
|
240
|
+
async def healthz() -> dict:
|
|
241
|
+
return service.health()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@app.get("/v1/checks")
|
|
245
|
+
async def checks() -> dict:
|
|
246
|
+
return service.checks()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@app.post("/v1/verify")
|
|
250
|
+
async def verify(request: Request, caller: str = Depends(rate_limit)) -> dict:
|
|
251
|
+
return await _run(service.verify, await _json(request))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@app.post("/v1/verify/batch")
|
|
255
|
+
async def verify_batch(request: Request, caller: str = Depends(rate_limit)) -> dict:
|
|
256
|
+
return await _run(service.verify_batch, await _json(request))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@app.post("/harden/intake")
|
|
260
|
+
async def intake(body: IntakeBody, caller: str = Depends(rate_limit)) -> dict:
|
|
261
|
+
detection = detect_language(body.code, body.language)
|
|
262
|
+
surface = python_surface(body.code) if detection.language == "python" else None
|
|
263
|
+
session_id = await _sessions.put(Session(body.code, detection, time.time()))
|
|
264
|
+
return {
|
|
265
|
+
"session_id": session_id, "issued_at": utc_now(),
|
|
266
|
+
"detected": {"language": detection.language, "display": detection.display,
|
|
267
|
+
"source": detection.source, "confident": detection.confident,
|
|
268
|
+
"verification_tier": detection.tier.value,
|
|
269
|
+
"tier_means": TIER_MEANING[detection.tier]},
|
|
270
|
+
"input_sha256": sha256(body.code),
|
|
271
|
+
"public_symbols": sorted(surface) if surface else [],
|
|
272
|
+
"proposed_contract": Contract(notes=body.notes or "").as_dict(),
|
|
273
|
+
"questions": build_questions(detection, surface),
|
|
274
|
+
"next": "Answer the questions, then POST the contract to /harden/apply (single use).",
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@app.post("/harden/apply")
|
|
279
|
+
async def apply(body: ApplyBody, caller: str = Depends(rate_limit)) -> dict:
|
|
280
|
+
try:
|
|
281
|
+
config = LLMConfig.from_env()
|
|
282
|
+
except LLMError:
|
|
283
|
+
# The message can quote this server's settings; the caller gets none of them.
|
|
284
|
+
raise ServiceError(503, "model_not_configured", "The model is not configured correctly "
|
|
285
|
+
"on this server, so hardening is unavailable here.") from None
|
|
286
|
+
if not config.api_key:
|
|
287
|
+
# Checked before the session is consumed, so the caller can retry later.
|
|
288
|
+
raise ServiceError(503, "model_not_configured", f"{config.key_hint} is not set on this "
|
|
289
|
+
"server, so hardening is unavailable here.")
|
|
290
|
+
session = await _sessions.take(body.session_id)
|
|
291
|
+
if session is None:
|
|
292
|
+
raise ServiceError(404, "session_not_found", "Unknown, expired or already-used "
|
|
293
|
+
"session. Start at /harden/intake.")
|
|
294
|
+
c = body.contract
|
|
295
|
+
language = normalise_language(c.language or session.detection.language)
|
|
296
|
+
contract = Contract(target_runtime=c.target_runtime,
|
|
297
|
+
threat_model=normalise_threats(c.threat_model),
|
|
298
|
+
compat=c.compat, dependencies=c.dependencies,
|
|
299
|
+
error_policy=c.error_policy, output_style=c.output_style,
|
|
300
|
+
must_preserve=c.must_preserve, notes=c.notes)
|
|
301
|
+
started = time.time()
|
|
302
|
+
try:
|
|
303
|
+
# The model call and bandit are blocking; keep them off the event loop.
|
|
304
|
+
result = await asyncio.to_thread(run_hardening, session.code, language, contract, config)
|
|
305
|
+
except LLMError as exc:
|
|
306
|
+
# The caller does not own this server's key: never pass on the provider's own words.
|
|
307
|
+
raise ServiceError(502, "model_error", exc.public) from None
|
|
308
|
+
out = result.as_dict()
|
|
309
|
+
out.update({"issued_at": utc_now(), "tier_means": TIER_MEANING[result.tier],
|
|
310
|
+
"contract": contract.as_dict(),
|
|
311
|
+
"processing_ms": int((time.time() - started) * 1000)})
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# ---- playground ----------------------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
if PLAYGROUND:
|
|
318
|
+
@app.get("/", include_in_schema=False)
|
|
319
|
+
async def playground() -> Response:
|
|
320
|
+
return Response(webassets.page("hosted"), media_type="text/html; charset=utf-8",
|
|
321
|
+
headers={"Content-Security-Policy": webassets.CSP})
|
|
322
|
+
|
|
323
|
+
@app.get("/assets/{name}", include_in_schema=False)
|
|
324
|
+
async def playground_asset(name: str) -> Response:
|
|
325
|
+
found = webassets.asset(name)
|
|
326
|
+
if found is None:
|
|
327
|
+
raise HTTPException(404, "Not found.")
|
|
328
|
+
content, ctype = found
|
|
329
|
+
return Response(content, media_type=ctype, headers={"Cache-Control": "max-age=300"})
|