mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* Reformat the tree under ruff 0.16, excluding the subtree nobody may edit Mechanical. `ruff format` with no other change, so the diff can be read as "the formatter moved" rather than reviewed line by line: 218 files, 862 insertions against 1075 deletions, almost all of it collapsing calls that 0.4.10 wrapped and 0.16 fits inside the 140-column limit. `plans/` is excluded in `ruff.toml` rather than reformatted. It is the archived prototype subtree that `.github/workflows/codeql.yml` already excludes and `scripts/check_mypy_baseline.py` excludes from every coverage direction, and the project rules forbid editing anything under it -- so formatting it would be a diff nobody may take. 844 lint findings and ~280 unformatted files live there. They are excluded because they cannot be fixed, which is a different statement from saying the code is clean. * Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ The bump alone reds every open pull request: `ruff format --check` is a hard gate on the required `Python - Lint & Type-check` job and 0.16 formats differently from 0.4.10. The reformat is the previous commit; this one moves the pin, fixes the findings, and answers the scope question. Fourteen declarations now read `>=0.16.8,<0.17` -- seven manifests, three workflows, `.devcontainer/Dockerfile`, and the three `poetry.lock` files that resolve it (now 0.16.9, which is byte-identical to 0.16.8 on both format and lint across this tree). The three findings 0.16 reports on `services/` are fixed, not suppressed: two `C420` comprehensions become `dict.fromkeys` (both values are string literals, so the shared-value hazard does not apply) and one `UP031` percent-format becomes an f-string in a test that counts characters. All three rewrites were asserted equal to the originals before being kept. Scope. `ruff check services/` left `scripts/` -- every CI gate in this repository, the code the rest of its claims are verified by -- linted by nothing. Lint now covers `services/ scripts/ tests/ tools/`, the trees the root `ruff.toml` governs that nothing else lints, and `ruff format --check .` covers everything, because formatting has no semantic content and `.` needs no edit when a tree is added. That surfaced 17 findings outside `services/`, each fixed at the source: two `B007` loops switched to `.values()`, a `B904` re-raise in `security_audit.py` now chains `from exc`, two `E402` imports that genuinely follow a `sys.path` mutation carry a reason next to the marker, and two over-length lines were wrapped. `E501` is ignored for the two detection-spec data modules. Both open their rule table with `# fmt: off`, so the formatter is already opted out of that layout deliberately, and all 199 long lines are single dict or string literals -- 72 positive fixtures, 66 negative, 50 `match_when` clauses, 11 descriptions. Two named files, not `scripts/`. `packages/` and `plugins/` stay outside the lint gate, and the gap is a number rather than a shrug: 91 findings and 2. Two of the five packages are linted by their own workflows under their own configs, and bringing the three published SDKs under this gate means behaviour-touching fixes that belong in a change reviewed as such. * Make packages/aisoc-detections clean under the ruff its own workflow now installs `python-detections.yml` lints `aisoc_detections detections tests` under the pin this PR moved, so the package has to be clean under 0.16 too. Two findings, both fixed at the source rather than silenced: `Callable` moves to `collections.abc`, and a `# noqa: BLE001` that 0.16 correctly reports as unused becomes the sentence it was standing in for -- a detection module is third-party content, so any exception at import is the author's and becomes a DetectionError naming the file. --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
258 lines
9.1 KiB
Python
Executable File
258 lines
9.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Authenticated encryption for backup artifacts.
|
|
|
|
``scripts/backup.sh`` gzips a dump and uploads it. The architecture doc said
|
|
those artifacts were AES-256-GCM encrypted with a SHA-256 manifest; they were
|
|
not, so a bucket misconfiguration exposed every credential, token and event
|
|
row the platform had ever stored. This module is the missing half.
|
|
|
|
Why not ``openssl enc``: it refuses AEAD ciphers outright ("AEAD ciphers not
|
|
supported by the enc utility"), so the usual shell one-liner cannot produce
|
|
GCM. ``cryptography`` is already a dependency of services/api, so AESGCM is
|
|
available without adding one.
|
|
|
|
Format (little to gain from inventing more than needed):
|
|
|
|
magic 8 bytes b"AISOCBK1"
|
|
version 1 byte 0x01
|
|
prefix 8 bytes random nonce prefix for this file
|
|
chunks repeated 4-byte big-endian plaintext length, then GCM output
|
|
(ciphertext || 16-byte tag)
|
|
final 4 bytes 0x00000000, itself an authenticated empty chunk
|
|
|
|
Each chunk gets nonce ``prefix || counter`` (12 bytes total) and carries the
|
|
counter plus a final-chunk flag in its AAD. That buys three properties a
|
|
naive whole-file encrypt does not: chunks cannot be reordered, chunks cannot
|
|
be swapped between files, and a truncated file fails to decrypt rather than
|
|
silently returning a short but valid-looking dump. Truncation is the failure
|
|
that matters here, because a restore from a truncated backup looks like a
|
|
successful restore of a smaller database.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
import secrets
|
|
import struct
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import BinaryIO
|
|
|
|
try:
|
|
from cryptography.exceptions import InvalidTag
|
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
except ImportError: # pragma: no cover - surfaced as an actionable error below
|
|
print(
|
|
"backup_crypt: the 'cryptography' package is required.\n pip install cryptography",
|
|
file=sys.stderr,
|
|
)
|
|
raise SystemExit(2) from None
|
|
|
|
MAGIC = b"AISOCBK1"
|
|
VERSION = 1
|
|
CHUNK_SIZE = 4 * 1024 * 1024
|
|
KEY_BYTES = 32
|
|
TAG_BYTES = 16
|
|
_ENV_KEY = "BACKUP_ENCRYPTION_KEY"
|
|
_ENV_KEY_FILE = "BACKUP_ENCRYPTION_KEY_FILE"
|
|
|
|
|
|
class BackupCryptError(RuntimeError):
|
|
"""Raised for any key, format or authentication problem."""
|
|
|
|
|
|
def load_key() -> bytes:
|
|
"""Read the 32-byte key from the environment.
|
|
|
|
Accepts 64 hex characters in ``BACKUP_ENCRYPTION_KEY`` or a path in
|
|
``BACKUP_ENCRYPTION_KEY_FILE`` (a file is preferable: an env var is
|
|
visible in ``ps`` output and in most container introspection).
|
|
"""
|
|
raw = os.environ.get(_ENV_KEY, "").strip()
|
|
key_file = os.environ.get(_ENV_KEY_FILE, "").strip()
|
|
|
|
if key_file:
|
|
path = Path(key_file)
|
|
if not path.is_file():
|
|
raise BackupCryptError(f"{_ENV_KEY_FILE} points at a missing file: {key_file}")
|
|
raw = path.read_text(encoding="utf-8").strip()
|
|
|
|
if not raw:
|
|
raise BackupCryptError(
|
|
f"No backup encryption key. Set {_ENV_KEY} to 64 hex characters, or "
|
|
f"{_ENV_KEY_FILE} to a file containing them. Generate one with:\n"
|
|
f" python3 scripts/backup_crypt.py keygen"
|
|
)
|
|
|
|
try:
|
|
key = bytes.fromhex(raw)
|
|
except ValueError as exc:
|
|
raise BackupCryptError(f"Backup encryption key is not hex ({exc}). Expected 64 hex characters.") from exc
|
|
|
|
if len(key) != KEY_BYTES:
|
|
raise BackupCryptError(f"Backup encryption key must be {KEY_BYTES} bytes ({KEY_BYTES * 2} hex characters); got {len(key)}.")
|
|
return key
|
|
|
|
|
|
def _aad(counter: int, *, final: bool) -> bytes:
|
|
return MAGIC + bytes([VERSION]) + struct.pack(">I", counter) + (b"\x01" if final else b"\x00")
|
|
|
|
|
|
def encrypt_stream(src: BinaryIO, dst: BinaryIO, key: bytes) -> tuple[str, str, int]:
|
|
"""Encrypt ``src`` into ``dst``. Returns (plaintext sha256, ciphertext sha256, size)."""
|
|
aead = AESGCM(key)
|
|
prefix = secrets.token_bytes(8)
|
|
|
|
plain_digest = hashlib.sha256()
|
|
cipher_digest = hashlib.sha256()
|
|
|
|
def emit(blob: bytes) -> None:
|
|
dst.write(blob)
|
|
cipher_digest.update(blob)
|
|
|
|
emit(MAGIC + bytes([VERSION]) + prefix)
|
|
|
|
counter = 0
|
|
while True:
|
|
chunk = src.read(CHUNK_SIZE)
|
|
if not chunk:
|
|
break
|
|
plain_digest.update(chunk)
|
|
nonce = prefix + struct.pack(">I", counter)
|
|
sealed = aead.encrypt(nonce, chunk, _aad(counter, final=False))
|
|
emit(struct.pack(">I", len(chunk)) + sealed)
|
|
counter += 1
|
|
|
|
# Authenticated end-of-stream marker, so truncation cannot pass as success.
|
|
nonce = prefix + struct.pack(">I", counter)
|
|
sealed = aead.encrypt(nonce, b"", _aad(counter, final=True))
|
|
emit(struct.pack(">I", 0) + sealed)
|
|
|
|
size = dst.tell() if dst.seekable() else -1
|
|
return plain_digest.hexdigest(), cipher_digest.hexdigest(), size
|
|
|
|
|
|
def decrypt_stream(src: BinaryIO, dst: BinaryIO, key: bytes) -> str:
|
|
"""Decrypt ``src`` into ``dst``. Returns the plaintext sha256."""
|
|
aead = AESGCM(key)
|
|
|
|
header = src.read(len(MAGIC) + 1 + 8)
|
|
if len(header) < len(MAGIC) + 1 + 8:
|
|
raise BackupCryptError("File is too short to be an AiSOC backup artifact.")
|
|
if header[: len(MAGIC)] != MAGIC:
|
|
raise BackupCryptError(
|
|
"Not an AiSOC encrypted backup (bad magic). If this artifact predates "
|
|
"backup encryption, decrypt is not required — restore it directly."
|
|
)
|
|
version = header[len(MAGIC)]
|
|
if version != VERSION:
|
|
raise BackupCryptError(f"Unsupported backup format version {version}.")
|
|
prefix = header[len(MAGIC) + 1 :]
|
|
|
|
plain_digest = hashlib.sha256()
|
|
counter = 0
|
|
saw_final = False
|
|
|
|
while True:
|
|
raw_len = src.read(4)
|
|
if not raw_len:
|
|
break
|
|
if len(raw_len) != 4:
|
|
raise BackupCryptError("Truncated chunk header; the artifact is incomplete.")
|
|
(length,) = struct.unpack(">I", raw_len)
|
|
final = length == 0
|
|
sealed = src.read(length + TAG_BYTES)
|
|
if len(sealed) != length + TAG_BYTES:
|
|
raise BackupCryptError("Truncated chunk body; the artifact is incomplete.")
|
|
|
|
nonce = prefix + struct.pack(">I", counter)
|
|
try:
|
|
plain = aead.decrypt(nonce, sealed, _aad(counter, final=final))
|
|
except InvalidTag as exc:
|
|
raise BackupCryptError(
|
|
f"Authentication failed on chunk {counter}. Either the key is wrong or the artifact was modified in transit or at rest."
|
|
) from exc
|
|
|
|
if final:
|
|
saw_final = True
|
|
break
|
|
plain_digest.update(plain)
|
|
dst.write(plain)
|
|
counter += 1
|
|
|
|
if not saw_final:
|
|
raise BackupCryptError(
|
|
"Backup ended without its end-of-stream marker, so it is truncated. Restoring it would silently produce a partial database."
|
|
)
|
|
return plain_digest.hexdigest()
|
|
|
|
|
|
def sha256_file(path: Path) -> str:
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as handle:
|
|
for block in iter(lambda: handle.read(CHUNK_SIZE), b""):
|
|
digest.update(block)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
|
|
sub.add_parser("keygen", help="Print a fresh 256-bit key as hex.")
|
|
|
|
enc = sub.add_parser("encrypt", help="Encrypt a file in place-adjacent (.enc).")
|
|
enc.add_argument("source")
|
|
enc.add_argument("--output", help="Defaults to <source>.enc")
|
|
|
|
dec = sub.add_parser("decrypt", help="Decrypt a .enc artifact.")
|
|
dec.add_argument("source")
|
|
dec.add_argument("--output", help="Defaults to <source> without .enc")
|
|
|
|
digest = sub.add_parser("sha256", help="Print the SHA-256 of a file.")
|
|
digest.add_argument("source")
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
if args.command == "keygen":
|
|
print(secrets.token_bytes(KEY_BYTES).hex())
|
|
return 0
|
|
|
|
if args.command == "sha256":
|
|
print(sha256_file(Path(args.source)))
|
|
return 0
|
|
|
|
source = Path(args.source)
|
|
if not source.is_file():
|
|
print(f"backup_crypt: no such file: {source}", file=sys.stderr)
|
|
return 2
|
|
|
|
try:
|
|
key = load_key()
|
|
if args.command == "encrypt":
|
|
target = Path(args.output) if args.output else source.with_suffix(source.suffix + ".enc")
|
|
with source.open("rb") as src, target.open("wb") as dst:
|
|
plain_sha, cipher_sha, _ = encrypt_stream(src, dst, key)
|
|
# Emitted for the manifest that backup.sh assembles.
|
|
print(f"{plain_sha}\t{cipher_sha}\t{target}")
|
|
else:
|
|
if args.output:
|
|
target = Path(args.output)
|
|
elif source.suffix == ".enc":
|
|
target = source.with_suffix("")
|
|
else:
|
|
target = source.with_name(source.name + ".plain")
|
|
with source.open("rb") as src, target.open("wb") as dst:
|
|
plain_sha = decrypt_stream(src, dst, key)
|
|
print(f"{plain_sha}\t{target}")
|
|
except BackupCryptError as exc:
|
|
print(f"backup_crypt: {exc}", file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|