diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ca9622..9261197 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ Versioning: [Semantic Versioning](https://semver.org/) ## [Unreleased] +### Added — 감사로그 HMAC 인증과 키 분리 (issue #304) + +- 서버가 별도 환경 설정의 키로 각 감사 기록을 HMAC-SHA256 인증한다. 기존 + SHA-256 체인 형식은 유지하며, 키 ID와 인증값을 추가한다. 키 교체 시 과거 키로 + 기존 기록을 검증하고, 실행 자식 프로세스에는 감사 인증 설정을 전달하지 않는다. +- 기존 로그에서 인증을 필수로 할 시작 번호를 신뢰된 서버 설정으로 고정한다. + 해시를 재계산한 위조, 인증값 제거, 잘못된 키는 검증과 추가 기록에서 거부한다. + 키 미설정·기존 미인증 구간은 경고하며, API의 `authenticated`로 인증 여부를 구분한다. +- 감사 기록 실패 시 `POST /security/audit`가 HTTP 500을 반환한다. 잘못된 키 설정이나 + 기존 체인 검증 실패는 서버 시작 단계에서 거부한다. 운영·이관 절차는 `docs/SERVER.md`에 + 정리했다. 정상 기록의 끝부분 삭제·과거 이력 재생 탐지는 외부 체크포인트 작업 #305에 남긴다. + ### Added — Windows 리소스 텔레메트리: Job Object 회계로 CPU·피크 메모리 기록 (issue #128) - Windows에서 `[xazz:resources]` 마커와 `xazz run --json`의 `resources`가 diff --git a/Cargo.lock b/Cargo.lock index 56603bc..c313a91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8373,6 +8373,7 @@ dependencies = [ "encoding_rs", "fs2", "hex", + "hmac 0.13.0", "http-body-util", "hyper", "hyper-util", diff --git a/docs/SECURITY_GUARDRAIL.md b/docs/SECURITY_GUARDRAIL.md index 57a6305..067887c 100644 --- a/docs/SECURITY_GUARDRAIL.md +++ b/docs/SECURITY_GUARDRAIL.md @@ -417,7 +417,7 @@ request and only ever returns that tenant's data. | `POST` | `/security/verify` | Check `sha256(code) == hash` and whether that hash is in the log (proof of audit, not of execution) | | `GET` | `/security/audit/log` | Entire audit log (`{ count, records }`) | | `GET` | `/security/audit/log/{hash}` | Records matching a code hash (**404** when none) | -| `GET` | `/security/audit/chain` | Verify the hash-chain (`{ intact, records }`) | +| `GET` | `/security/audit/chain` | Verify SHA links and configured HMAC policy (`{ intact, records, authenticated, hmac_configured, legacy_records, warning }`); see [audit configuration](SERVER.md#audit-record-authentication-304) | | `POST` | `/security/inference/check` | Runtime output gate: scan a generated response and record the prompt/response hashes as audit evidence | | `GET` | `/runs` | The tenant's recent runs, newest first (capped at 50) | | `GET` | `/runs/{id}` | One run by id, tenant-scoped (**404** when absent) | diff --git a/docs/SERVER.md b/docs/SERVER.md index 82d8377..aece639 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -25,6 +25,49 @@ is allowed (default local-only behavior). `XAZZ_ADMIN_ACTORS` entries split on the **last** `:` so a credential may itself contain colons; `XAZZ_ADMIN_TOKEN` entries are comma-separated. +## Audit record authentication (#304) + +| Variable | Default | Meaning | +|---|---|---| +| `XAZZ_AUDIT_HMAC_KEYS` | unset | Secret JSON object mapping key IDs to hex-encoded keys of at least 32 random bytes. IDs contain 1–64 ASCII letters, digits, `_` or `-`. Keep outside the log directory and source control. | +| `XAZZ_AUDIT_HMAC_ACTIVE_KEY_ID` | unset | ID used to authenticate new records; must exist in `KEYS`. Other keys verify older records. | +| `XAZZ_AUDIT_HMAC_REQUIRED_FROM` | `0` when configured | First record index requiring HMAC. Set once to the existing record count when migrating a trusted legacy log. Never derive this value from an untrusted log on startup. | + +The server loads keys and policy once at startup. It rejects incomplete/invalid +configuration and an existing chain that fails verification, before listening. +All three variables are removed from execution child environments. The HTTP API +has no key setter and cannot choose the signing key or migration boundary. + +For a new log, provision `KEYS` through the service's secret environment, select +the active ID, and leave `REQUIRED_FROM` at zero. Generate keys using a +cryptographically secure random generator; the 32-byte length check does not +measure entropy. Do not put live keys in command lines, repository files, or logs. + +For migration, stop all writers, verify and back up the old log in a trusted +environment, record its count `N`, and configure `REQUIRED_FROM=N` in protected +service configuration. Restart with keys enabled. Existing bytes are preserved; +new entries are signed. The unsigned prefix remains explicitly reported as +legacy, not retroactively authenticated. A boundary beyond the current count is +rejected. Do not increase the boundary to work around a verification failure. + +For rotation, stop writers, add a fresh key under a new ID, switch the active ID, +and restart all instances with the same key ring and boundary. Retain every old +verification key for as long as its records are retained. Missing/wrong keys, +partial authentication fields, malformed tags, and missing mandatory tags fail +verification. Removing keys does not silently downgrade an existing signed log. + +If all three settings are absent, legacy unsigned operation remains available +with an explicit startup warning. `GET /security/audit/chain` returns one locked +snapshot with `{intact, records, authenticated, hmac_configured, legacy_records, +warning}`. `intact` checks the SHA chain and the configured HMAC policy; +`authenticated` is true only for a nonempty valid chain with every record signed. +No-key or mixed legacy chains never report `authenticated: true`. A failed append +returns HTTP 500 from `POST /security/audit`; no record is added. Log I/O or parse +failures also return 500 from the chain endpoint. + +See [the threat model](design/security-model.md#audit-log-authentication-304) +for the file-writer boundary and the external checkpoint work remaining in #305. + ## Bind, paths, and execution | Variable | Default | Meaning | @@ -70,4 +113,4 @@ variables also apply to server-initiated runs. See [GPU & ONNX backends](GPU_BACKENDS.md) for `XAZZ_BACKEND`, `XAZZ_DEVICE`, and `XAZZ_LOG`, [Security guardrail](SECURITY_GUARDRAIL.md) for `XAZZ_POLICY_PATH` and the `XAZZ_SLM_*` hook, and [Data source connectors](CONNECTORS.md) for -`XAZZ_STREAMING`. \ No newline at end of file +`XAZZ_STREAMING`. diff --git a/docs/design/security-model.md b/docs/design/security-model.md index 0a0baa6..75ce229 100644 --- a/docs/design/security-model.md +++ b/docs/design/security-model.md @@ -49,4 +49,54 @@ README 등 사용자 문서에서 "샌드박스 런타임"이라는 표현은 - 서브프로세스 실행 경계 → **프로세스 격리(process isolation)** - 사전 실행 검사 → **정적 가드레일(guardrail) 게이트** -- 실행 시간 제한 → **타임아웃 하드닝** \ No newline at end of file +- 실행 시간 제한 → **타임아웃 하드닝** + +## Audit log authentication (#304) + +The protected asset is the authenticity of records in `audit_log/audit.jsonl`. +The attacker may edit that file and recompute its SHA-256 chain, but cannot read +the server's HMAC keys, change its key ring/migration policy, or execute code in +the trusted server process. A filesystem writer is different from the trusted +server appender, which necessarily holds the key. HMAC is symmetric: anyone with +a verification key can also forge records; it is not a public-key signature. + +The server appends `hmac_key_id` and `hmac` (hex HMAC-SHA256) to each new record +when configured. The MAC covers UTF-8 compact JSON of this ordered tuple: + +```text +["xazz-audit-hmac-sha256-v1", hmac_key_id, index, timestamp, hash, code_length, + outcome, prompt_hash, response_hash, model_fingerprint, prev_hash, record_hash] +``` + +Absent optional values serialize as `null`. Explicit field positions avoid the +legacy NUL-delimited digest's optional-field ambiguity. The old `record_hash` +encoding stays unchanged, preserving existing logs and browser hash replay. +Browser replay checks only SHA links; the server's authentication verdict is +authoritative. Tags are checked using RustCrypto HMAC's constant-time verifier. +Append validates the entire existing chain and HMAC policy under the same +exclusive file handle before signing; readers use the existing shared lock. +This preserves the Windows lock protocol and prevents signing over a forged +history. Work per append is linear in the existing log length. + +Separate the service account/secret configuration permissions from accounts that +can modify the log. On Windows, configure NTFS ACLs on the service configuration +and log directory separately; on Unix use distinct ownership/permissions. Loading +an environment variable does not itself enforce that OS permission boundary. +Execution children do not inherit the audit variables, but a child running under +the server's OS identity is not isolated from that identity's other capabilities. +Server-process compromise, administrator access, or secret/configuration access +is outside this protection. No HTTP request supplies a trusted verification key. + +The migration boundary is trusted configuration, never a field chosen by the +log writer. It prevents stripping all MACs and presenting a forged signed chain +as legacy. Unsigned legacy prefixes are permitted only by explicit configuration +and remain unauthenticated. With keys absent, the API warns and makes no claim +of authentication. Deployment/rotation steps are in [SERVER.md](../SERVER.md). + +**Remaining limits (#305):** a valid older prefix, truncation of the signed tail, +deletion of an entire fresh log, and replay of a valid history under the same key +are not detectable without an external trusted checkpoint/identity. HMAC does +not prove that an event was logged at all, that an HTTP caller was truthful, or +that execution happened; it proves that the trusted appender authenticated the +record. Separate deployments should use separate keys. This change does not +claim forward security, non-repudiation, or OS sandboxing. diff --git a/docs/evidence/audit-hmac-windows-2026-10-22.md b/docs/evidence/audit-hmac-windows-2026-10-22.md new file mode 100644 index 0000000..babd694 --- /dev/null +++ b/docs/evidence/audit-hmac-windows-2026-10-22.md @@ -0,0 +1,71 @@ +# Audit HMAC (#304): Windows verification + +Date: 2026-10-22 (Asia/Seoul). Base: `b347688` (`origin/main`). +Environment: Windows, `stable-x86_64-pc-windows-gnu`, rustc/cargo 1.98.0; +NVIDIA GeForce RTX 4070 Laptop GPU, driver 591.44 detected. + +## Functional checks + +PowerShell settings used for the workspace gates: + +```powershell +$env:CARGO_PROFILE_DEV_DEBUG = '0' +$env:CARGO_PROFILE_TEST_DEBUG = '0' +$env:CARGO_BUILD_JOBS = '4' +cargo fmt --all -- --check +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo test --workspace --locked +git diff --check +``` + +All four checks passed. Tests: **759 passed, 0 failed, 0 ignored** across +18 test-result summaries (including empty doc-test suites). Server coverage: +**132 unit tests + 3 real-process HTTP tests**. Default Cargo features were used; +CUDA/wgpu/ONNX acceptance tests were not enabled. Audit authentication uses CPU +cryptography and does not change GPU backend code. Debug information was disabled +to avoid the documented Windows GNU executable-size limitation. + +The HMAC tests cover RFC 4231's SHA-256 vector, a record payload golden value +independently calculated with Python's standard `hmac`/`json`, recomputed unkeyed +forgeries, field-boundary ambiguity, MAC stripping, bad/unknown keys and malformed +tags, explicit legacy migration, rotation with retained verification keys, and +refusal to append to forged history. Actual server processes exercise production +environment loading, startup rejection, HTTP 500 on failed audit persistence, +authentication status, and two writers sharing one authenticated log on Windows. +All test logs/databases are temporary; the operator's runtime log is not used. + +An initial HTTP run in the tool's network-isolated environment timed out on +loopback connections. The final complete suite ran on the Windows host and +passed. No test was skipped or weakened to work around that restriction. + +## Dependency policy: existing workspace failures + +Used cargo-deny 0.20.2 installed under the ignored `target/qa-304-tools/` directory. + +| Scope / command | Result | +|---|---| +| `cargo deny --all-features check` | Passed; this non-virtual root manifest selects the CLI dependency graph only | +| `cargo deny --workspace --all-features check` | Failed: advisories and licenses; bans and sources passed | +| Same workspace check against a separate source snapshot of `b347688` | Same 37 error diagnostic counts and same 19 RustSec IDs | + +Workspace errors: 16 license-policy rejections, 14 vulnerability diagnostics, +3 unsoundness diagnostics, 2 unmaintained-package diagnostics and 2 yanked +versions (`chacha20 0.10.0`, `spin 0.9.8`). For example, `spin` is reached through +the existing `multer -> axum -> xazz-server` dependency path. The PR changes no +locked package version; it only adds the server's edge to the already-locked +`hmac 0.13.0`. Dependency upgrades and license-policy decisions are separate work. + +The existing CI license job uses the root manifest without `--workspace`, so its +success must not be presented as coverage of all workspace packages. This PR +does not weaken policy or ignore advisories to obtain a passing result. + +Local raw evidence (ignored build output): `target/qa-304-workspace-tests.log`, +`target/qa-304-clippy-final.log`, `target/qa-304-deny.log`, +`target/qa-304-deny-workspace.log`, and `target/qa-304-deny-baseline.log`. + +## Remaining protection boundary + +HMAC protects against a log-file writer without the server's keys/configuration. +Valid-prefix rollback, tail truncation and external checkpoints remain #305. +See [server configuration](../SERVER.md#audit-record-authentication-304) and +[the threat model](../design/security-model.md#audit-log-authentication-304). diff --git a/xazz-server/Cargo.toml b/xazz-server/Cargo.toml index 74c1674..51ebba3 100644 --- a/xazz-server/Cargo.toml +++ b/xazz-server/Cargo.toml @@ -18,6 +18,7 @@ csv = "1" encoding_rs = "0.8" uuid = { version = "1", features = ["v4"] } sha2 = "0.11" +hmac = "0.13" hex = "0.4" chrono = { version = "0.4", features = ["serde"] } diff --git a/xazz-server/src/audit_auth.rs b/xazz-server/src/audit_auth.rs new file mode 100644 index 0000000..3bb15db --- /dev/null +++ b/xazz-server/src/audit_auth.rs @@ -0,0 +1,233 @@ +//! Server-owned audit authentication. Keys/policy never come from log records or HTTP input. +use hmac::{Hmac, KeyInit, Mac}; +use sha2::Sha256; +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use crate::audit_log::AuditRecord; + +pub const ENV_KEYS: &str = "XAZZ_AUDIT_HMAC_KEYS"; +const ENV_ACTIVE: &str = "XAZZ_AUDIT_HMAC_ACTIVE_KEY_ID"; +const ENV_REQUIRED_FROM: &str = "XAZZ_AUDIT_HMAC_REQUIRED_FROM"; + +// Deliberately not Debug/Serialize: no diagnostic or API may print key material. +#[derive(Default)] +pub(crate) struct AuditAuth { + keys: BTreeMap>, + active: Option, + pub required_from: u64, +} + +impl AuditAuth { + pub fn from_settings( + keys: Option<&str>, + active: Option<&str>, + required_from: Option<&str>, + ) -> Result { + let (keys, active) = match (keys, active, required_from) { + (None, None, None) => return Ok(Self::default()), + (Some(keys), Some(active), _) => (keys, active), + _ => return Err("audit HMAC requires both KEYS and ACTIVE_KEY_ID".into()), + }; + // Do not include serde/hex errors: they can contain submitted secrets. + let encoded: BTreeMap = serde_json::from_str(keys) + .map_err(|_| "audit HMAC KEYS must be a JSON object of key IDs to hex keys")?; + let mut decoded = BTreeMap::new(); + for (id, key) in encoded { + if id.is_empty() + || id.len() > 64 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + { + return Err("audit HMAC key IDs must be 1..64 ASCII letters/digits/-/_".into()); + } + let bytes = hex::decode(key).map_err(|_| "audit HMAC key must be hex encoded")?; + if bytes.len() < 32 { + return Err("audit HMAC keys must contain at least 32 bytes".into()); + } + decoded.insert(id, bytes); + } + if !decoded.contains_key(active) { + return Err("audit HMAC active key ID is absent from KEYS".into()); + } + let required_from = required_from + .unwrap_or("0") + .parse::() + .map_err(|_| "audit HMAC REQUIRED_FROM must be a nonnegative integer")?; + Ok(Self { + keys: decoded, + active: Some(active.into()), + required_from, + }) + } + + pub fn enabled(&self) -> bool { + self.active.is_some() + } + + pub fn sign(&self, record: &mut AuditRecord) { + if let Some(id) = &self.active { + record.hmac_key_id = Some(id.clone()); + record.hmac = Some(hex::encode( + record_mac(record, &self.keys[id]).finalize().into_bytes(), + )); + } + } + + pub fn verify(&self, record: &AuditRecord) -> bool { + match (&record.hmac_key_id, &record.hmac) { + (None, None) => !self.enabled() || record.index < self.required_from, + (Some(id), Some(tag)) => { + let Some(key) = self.keys.get(id) else { + return false; + }; + let Ok(bytes) = hex::decode(tag) else { + return false; + }; + // RustCrypto's constant-time comparison; never compare tag strings. + record_mac(record, key).verify_slice(&bytes).is_ok() + } + _ => false, + } + } +} + +fn record_mac(record: &AuditRecord, key: &[u8]) -> Hmac { + // Versioned, unambiguous JSON tuple: binds field positions, null vs empty, + // key ID and every semantic field (legacy NUL-delimited SHA stays unchanged). + let payload = serde_json::to_vec(&( + "xazz-audit-hmac-sha256-v1", + &record.hmac_key_id, + record.index, + &record.timestamp, + &record.hash, + record.code_length, + &record.outcome, + &record.prompt_hash, + &record.response_hash, + &record.model_fingerprint, + &record.prev_hash, + &record.record_hash, + )) + .expect("audit tuple contains only JSON-serializable scalars"); + let mut mac = Hmac::::new_from_slice(key).expect("HMAC accepts any key length"); + mac.update(&payload); + mac +} + +pub(crate) fn configured() -> Result<&'static AuditAuth, String> { + static AUTH: OnceLock> = OnceLock::new(); + AUTH.get_or_init(|| { + // Unit tests inject settings explicitly; never mutate/read operator secrets. + #[cfg(test)] + { Ok(AuditAuth::default()) } + #[cfg(not(test))] + { + fn setting(name: &str) -> Result, String> { + match std::env::var(name) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(_) => Err(format!("{name} must be valid Unicode")), + } + } + let auth = AuditAuth::from_settings( + setting(ENV_KEYS)?.as_deref(), setting(ENV_ACTIVE)?.as_deref(), + setting(ENV_REQUIRED_FROM)?.as_deref(), + )?; + if !auth.enabled() { + eprintln!("[xazz-server] WARNING: audit HMAC is not configured; logs have hash-chain integrity only, no record authentication"); + } else if auth.required_from > 0 { + eprintln!("[xazz-server] WARNING: audit records before index {} are permitted legacy records without authentication", auth.required_from); + } + Ok(auth) + } + }).as_ref().map_err(Clone::clone) +} + +/// Execution children must not inherit the server's audit signing authority. +pub(crate) fn remove_child_credentials(command: &mut std::process::Command) { + for name in [ENV_KEYS, ENV_ACTIVE, ENV_REQUIRED_FROM] { + command.env_remove(name); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rfc4231_sha256_vector() { + // https://www.rfc-editor.org/rfc/rfc4231.html#section-4.2 + let mut mac = Hmac::::new_from_slice(&[0x0b; 20]).unwrap(); + mac.update(b"Hi There"); + let expected = + hex::decode("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7") + .unwrap(); + mac.verify_slice(&expected).unwrap(); + } + + #[test] + fn versioned_record_payload_matches_python_stdlib_hmac() { + // Independent golden: Python json.dumps(ensure_ascii=False, + // separators=(',', ':')) + hmac.new(bytes.fromhex('ab'*32), ..., sha256). + // Pins UTF-8, tuple ordering, null handling, key ID and domain separation. + let record = AuditRecord { + index: 0, + timestamp: "2026-10-22T00:00:00Z".into(), + hash: "abc".into(), + code_length: 4, + outcome: Some("성공".into()), + prompt_hash: None, + response_hash: Some("r".into()), + model_fingerprint: None, + prev_hash: "GENESIS".into(), + record_hash: "digest".into(), + hmac_key_id: Some("old".into()), + hmac: None, + }; + let expected = + hex::decode("e8fec96ef84c8203953e92a8795813659ee30a201f3784322da5a1153380cd10") + .unwrap(); + record_mac(&record, &[0xab; 32]) + .verify_slice(&expected) + .unwrap(); + } + + #[test] + fn invalid_settings_fail_without_echoing_secrets() { + for (keys, active, boundary) in [ + (Some("secret-input"), Some("k1"), None), + (Some(r#"{"k1":"secret-input"}"#), Some("k1"), None), + (Some(r#"{"k1":"abcd"}"#), Some("k1"), None), + (None, Some("k1"), None), + (None, None, Some("1")), + ] { + let err = AuditAuth::from_settings(keys, active, boundary) + .err() + .unwrap(); + assert!(!err.contains("secret-input")); + } + let keys = format!(r#"{{"k1":"{}"}}"#, "ab".repeat(32)); + assert!(AuditAuth::from_settings(Some(&keys), Some("missing"), None).is_err()); + assert!(AuditAuth::from_settings(Some(&keys), Some("k1"), Some("-1")).is_err()); + assert!(AuditAuth::from_settings(Some(&keys), Some("k1"), Some("2")).is_ok()); + } + + #[test] + fn child_does_not_inherit_signing_configuration() { + let mut command = std::process::Command::new("unused"); + command + .env(ENV_KEYS, "test-secret") + .env(ENV_ACTIVE, "k1") + .env(ENV_REQUIRED_FROM, "0"); + remove_child_credentials(&mut command); + for name in [ENV_KEYS, ENV_ACTIVE, ENV_REQUIRED_FROM] { + assert!( + command + .get_envs() + .any(|(key, value)| key == name && value.is_none()) + ); + } + } +} diff --git a/xazz-server/src/audit_log.rs b/xazz-server/src/audit_log.rs index d839b10..d14b937 100644 --- a/xazz-server/src/audit_log.rs +++ b/xazz-server/src/audit_log.rs @@ -1,4 +1,4 @@ -//! xazz-server audit_log.rs — SHA-256 audit log (append-only JSONL) +//! SHA-256 audit log with optional server-owned HMAC-SHA256 record authentication. //! //! Persists all security audit records in a JSONL file on disk. //! Each record contains the SHA-256 hash of the code, a timestamp, and the hash @@ -10,6 +10,7 @@ //! //! JSONL file location: `audit_log/audit.jsonl` in the server's working directory +use crate::audit_auth::{self, AuditAuth}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::sync::Mutex; @@ -82,12 +83,16 @@ pub struct AuditRecord { pub model_fingerprint: Option, /// SHA-256 hash of the previous record (forms the chain) — the first record is "GENESIS" pub prev_hash: String, - /// SHA-256 hash of this whole record (excluding prev_hash) + /// Legacy SHA-256 digest, including prev_hash; excludes digest/auth fields. pub record_hash: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hmac_key_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hmac: Option, } impl AuditRecord { - /// For hash-chain verification — recomputes record_hash and checks the prev_hash link + /// Checks the legacy digest only. Chain/authentication require verify_chain. pub fn verify(&self) -> bool { let computed = compute_record_hash(self); computed == self.record_hash @@ -205,6 +210,24 @@ fn append_to_path( inference: Option<(String, String)>, model_fingerprint: Option<&str>, file_path: &std::path::Path, +) -> Result { + append_authenticated( + code, + outcome, + inference, + model_fingerprint, + file_path, + audit_auth::configured()?, + ) +} + +fn append_authenticated( + code: &str, + outcome: Option<&str>, + inference: Option<(String, String)>, + model_fingerprint: Option<&str>, + file_path: &std::path::Path, + auth: &AuditAuth, ) -> Result { // 1) Serialize concurrent in-process append read-modify-writes. (TOCTOU prevention) // Recovers from a poisoned lock so a single panic cannot disable auditing. @@ -236,6 +259,11 @@ fn append_to_path( .map_err(|e| format!("failed to read audit log: {e}"))?; let existing = parse_records(&contents).map_err(|e| format!("failed to read audit log: {e}"))?; + // Never turn a forged existing history into an authenticated history by + // signing a new head. Validate the SAME locked snapshot before appending. + if !verify_records(&existing, auth).intact { + return Err("audit chain or HMAC authentication failed; append refused".into()); + } let index = existing.len() as u64; let prev_hash = existing .last() @@ -253,12 +281,15 @@ fn append_to_path( model_fingerprint: model_fingerprint.map(|s| s.to_string()), prev_hash, record_hash: String::new(), + hmac_key_id: None, + hmac: None, }; let record_hash = compute_record_hash(&record); - let record = AuditRecord { + let mut record = AuditRecord { record_hash, ..record }; + auth.sign(&mut record); // append-only: the handle is opened in append mode, so the write lands at the // end even though we previously sought to position 0 for reading. @@ -326,18 +357,62 @@ pub fn lookup_by_hash(hash: &str) -> Result, String> { /// Verifies that the whole log hash chain is valid. pub fn verify_chain() -> Result { - verify_chain_at_path(&default_log_path()) + Ok(verification()?.intact) } +#[cfg(test)] fn verify_chain_at_path(file_path: &std::path::Path) -> Result { let records = read_all(file_path)?; - Ok(records_form_valid_chain(&records)) + Ok(verify_records(&records, audit_auth::configured()?).intact) +} + +/// `intact` includes the configured authentication policy; `authenticated` +/// additionally requires a nonempty chain with no unsigned legacy records. +#[derive(Debug, Serialize)] +pub(crate) struct Verification { + pub intact: bool, + pub records: usize, + pub authenticated: bool, + pub hmac_configured: bool, + pub legacy_records: usize, + pub warning: Option<&'static str>, +} + +pub(crate) fn verification() -> Result { + let auth = audit_auth::configured()?; + Ok(verify_records(&read_all(&default_log_path())?, auth)) +} + +fn verify_records(records: &[AuditRecord], auth: &AuditAuth) -> Verification { + let legacy_records = records + .iter() + .filter(|r| r.hmac.is_none() && r.hmac_key_id.is_none()) + .count(); + let intact = records_form_valid_chain(records) + && (!auth.enabled() || records.len() as u64 >= auth.required_from) + && records.iter().all(|r| auth.verify(r)); + Verification { + intact, + records: records.len(), + authenticated: intact && auth.enabled() && !records.is_empty() && legacy_records == 0, + hmac_configured: auth.enabled(), + legacy_records, + warning: if !intact { + Some("audit chain or HMAC authentication failed") + } else if !auth.enabled() { + Some("HMAC is not configured; hash-chain integrity is not record authentication") + } else if legacy_records > 0 { + Some("legacy prefix is permitted but not authenticated") + } else { + None + }, + } } fn records_form_valid_chain(records: &[AuditRecord]) -> bool { let mut prev = "GENESIS".to_string(); - for r in records { - if r.prev_hash != prev || !r.verify() { + for (index, r) in records.iter().enumerate() { + if r.index != index as u64 || r.prev_hash != prev || !r.verify() { return false; } prev = r.record_hash.clone(); @@ -349,6 +424,206 @@ fn records_form_valid_chain(records: &[AuditRecord]) -> bool { mod tests { use super::*; + fn auth(active: &str, boundary: u64) -> AuditAuth { + let keys = format!( + r#"{{"old":"{}","new":"{}","alias":"{}"}}"#, + "ab".repeat(32), + "cd".repeat(32), + "ab".repeat(32) + ); + AuditAuth::from_settings(Some(&keys), Some(active), Some(&boundary.to_string())).unwrap() + } + + fn rewrite_chain(records: &mut [AuditRecord]) { + let mut prev = "GENESIS".to_string(); + for (index, record) in records.iter_mut().enumerate() { + record.index = index as u64; + record.prev_hash = prev; + record.record_hash = compute_record_hash(record); + prev = record.record_hash.clone(); + } + } + + fn signed_history(path: &std::path::Path) -> Vec { + let settings = auth("old", 0); + for code in ["one", "two", "three"] { + append_authenticated( + code, + Some("success"), + Some((hash_code("p"), hash_code("r"))), + Some("model"), + path, + &settings, + ) + .unwrap(); + } + read_all(path).unwrap() + } + + #[test] + fn hmac_rejects_recomputed_forgery_and_does_not_append_to_it() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut records = signed_history(&path); + let settings = auth("old", 0); + assert!(verify_records(&records, &settings).authenticated); + records[0].outcome = Some("forged".into()); + rewrite_chain(&mut records); + assert!( + records_form_valid_chain(&records), + "attack defeats hash-only verification" + ); + assert!(!verify_records(&records, &settings).intact); + let forged = records + .iter() + .map(|r| serde_json::to_string(r).unwrap() + "\n") + .collect::(); + std::fs::write(&path, &forged).unwrap(); + assert!(append_authenticated("next", None, None, None, &path, &settings).is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), forged); + } + + #[test] + fn hmac_binds_each_field_and_optional_field_positions() { + let dir = tempfile::tempdir().unwrap(); + let records = signed_history(&dir.path().join("audit.jsonl")); + let settings = auth("old", 0); + // Even a file writer who updates *all* unkeyed hashes cannot change fields. + let mutations: &[fn(&mut AuditRecord)] = &[ + |r| r.timestamp.push('x'), + |r| r.hash.push('x'), + |r| r.code_length += 1, + |r| r.outcome = Some("changed".into()), + |r| r.prompt_hash = Some("changed".into()), + |r| r.response_hash = Some("changed".into()), + |r| r.model_fingerprint = None, + |r| r.hmac_key_id = Some("alias".into()), // same key, different ID + ]; + for mutate in mutations { + let mut forged = records.clone(); + mutate(&mut forged[0]); + rewrite_chain(&mut forged); + assert!(!verify_records(&forged, &settings).intact); + } + // The legacy digest conflates some optional fields; HMAC must not. + let mut record = records[0].clone(); + record.outcome = Some("x".into()); + record.prompt_hash = None; + record.record_hash = compute_record_hash(&record); + settings.sign(&mut record); + record.outcome = None; + record.prompt_hash = Some("x".into()); + assert!(record.verify()); + assert!(!settings.verify(&record)); + } + + #[test] + fn hmac_rejects_auth_stripping_unknown_wrong_and_malformed_keys_or_tags() { + let dir = tempfile::tempdir().unwrap(); + let records = signed_history(&dir.path().join("audit.jsonl")); + let settings = auth("old", 0); + for mutate in [ + (|r: &mut AuditRecord| { + r.hmac = None; + r.hmac_key_id = None; + }) as fn(&mut AuditRecord), + |r| r.hmac = None, + |r| r.hmac_key_id = None, + |r| r.hmac_key_id = Some("unknown".into()), + |r| r.hmac = Some("zz".into()), + |r| r.hmac = Some("00".into()), + |r| r.hmac = Some("00".repeat(32)), + ] { + let mut forged = records.clone(); + for r in &mut forged { + mutate(r); + } + assert!(!verify_records(&forged, &settings).intact); + } + assert!(!verify_records(&records, &AuditAuth::default()).intact); + let keys = format!(r#"{{"old":"{}"}}"#, "ef".repeat(32)); + let wrong = AuditAuth::from_settings(Some(&keys), Some("old"), None).unwrap(); + assert!(!verify_records(&records, &wrong).intact); + } + + #[test] + fn hmac_rotation_preserves_old_records_and_requires_old_verification_key() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + signed_history(&path); + let before = std::fs::read(&path).unwrap(); + let rotated = auth("new", 0); + let next = append_authenticated("four", None, None, None, &path, &rotated).unwrap(); + assert_eq!(next.hmac_key_id.as_deref(), Some("new")); + assert!(std::fs::read(&path).unwrap().starts_with(&before)); + let records = read_all(&path).unwrap(); + assert!(verify_records(&records, &rotated).authenticated); + let keys = format!(r#"{{"new":"{}"}}"#, "cd".repeat(32)); + let missing_old = AuditAuth::from_settings(Some(&keys), Some("new"), None).unwrap(); + assert!(!verify_records(&records, &missing_old).intact); + assert!(append_authenticated("five", None, None, None, &path, &missing_old).is_err()); + } + + #[test] + fn legacy_migration_is_explicit_and_cannot_downgrade_signed_records() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + append_authenticated("legacy", None, None, None, &path, &AuditAuth::default()).unwrap(); + let before = std::fs::read(&path).unwrap(); + let legacy = read_all(&path).unwrap(); + let report = verify_records(&legacy, &AuditAuth::default()); + assert!(report.intact && !report.authenticated && report.warning.is_some()); + assert!(!verify_records(&legacy, &auth("old", 0)).intact); + assert!(!verify_records(&legacy, &auth("old", 2)).intact); + let migration = auth("old", 1); + append_authenticated("signed", None, None, None, &path, &migration).unwrap(); + assert!(std::fs::read(&path).unwrap().starts_with(&before)); + let mut records = read_all(&path).unwrap(); + let report = verify_records(&records, &migration); + assert!(report.intact && !report.authenticated); + assert_eq!(report.legacy_records, 1); + records[1].hmac = None; + records[1].hmac_key_id = None; + assert!(!verify_records(&records, &migration).intact); + // Removing configured keys must not silently resume unsigned append. + assert!( + append_authenticated("unsigned", None, None, None, &path, &AuditAuth::default()) + .is_err() + ); + } + + #[test] + fn concurrent_authenticated_writes_are_verifiable_on_windows() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let writers: Vec<_> = (0..4) + .map(|i| { + let path = path.clone(); + std::thread::spawn(move || { + let settings = auth("old", 0); + for j in 0..8 { + append_authenticated( + &format!("{i}:{j}"), + None, + None, + None, + &path, + &settings, + ) + .unwrap(); + assert!(verify_records(&read_all(&path).unwrap(), &settings).intact); + } + }) + }) + .collect(); + for writer in writers { + writer.join().unwrap(); + } + let report = verify_records(&read_all(&path).unwrap(), &auth("old", 0)); + assert_eq!(report.records, 32); + assert!(report.authenticated); + } + #[test] fn read_all_waits_for_exclusive_writer_lock() { use std::sync::mpsc::{self, RecvTimeoutError}; @@ -641,6 +916,8 @@ mod tests { model_fingerprint: None, prev_hash: "GENESIS".to_string(), record_hash: String::new(), + hmac_key_id: None, + hmac: None, }; r.record_hash = compute_record_hash(&r); // Golden value — pins the sha2 0.11 hex output so the chain stays stable. @@ -712,6 +989,8 @@ mod tests { model_fingerprint: None, prev_hash: "GENESIS".into(), record_hash: String::new(), + hmac_key_id: None, + hmac: None, }; r1.record_hash = compute_record_hash(&r1); // a record whose previous hash does not match @@ -726,6 +1005,8 @@ mod tests { model_fingerprint: None, prev_hash: "WRONG".into(), record_hash: String::new(), + hmac_key_id: None, + hmac: None, }; r2.record_hash = compute_record_hash(&r2); let recs = vec![r1, r2]; diff --git a/xazz-server/src/main.rs b/xazz-server/src/main.rs index 118162d..2378330 100644 --- a/xazz-server/src/main.rs +++ b/xazz-server/src/main.rs @@ -48,6 +48,7 @@ use tokio::sync::{OwnedMutexGuard, OwnedSemaphorePermit, Semaphore}; use tower_http::cors::{AllowOrigin, Any, CorsLayer}; use tower_http::services::ServeDir; +mod audit_auth; mod audit_log; mod guardrail; mod slm; @@ -484,6 +485,18 @@ struct SchemaColumn { #[tokio::main] async fn main() { + // Validate trusted audit configuration before accepting any requests. + match audit_log::verification() { + Ok(report) if report.intact => {} + Ok(_) => { + eprintln!("[xazz-server] audit authentication failed at startup"); + std::process::exit(1); + } + Err(error) => { + eprintln!("[xazz-server] {error}"); + std::process::exit(1); + } + } // create the uploads/ directory upfront let _ = std::fs::create_dir_all("uploads"); @@ -1151,6 +1164,7 @@ async fn run_execution_job( // while the (possibly-dropped) handler future is alive. let _slot = slot; let tmp_path = tmp.path().to_path_buf(); + audit_auth::remove_child_credentials(&mut command); let output = command .arg(&tmp_path) // The server interprets this override as the CLI path, while the @@ -1604,30 +1618,22 @@ struct AuditResponse { record_hash: Option, } -async fn handle_security_audit(Json(payload): Json) -> Json { +async fn handle_security_audit( + Json(payload): Json, +) -> Result, (StatusCode, String)> { let hash = audit_log::hash_code(&payload.code); - // Persist to the append-only audit log (the hash is returned even on failure) - let stored = audit_log::append(&payload.code); - - match stored { - Ok(record) => Json(AuditResponse { - hash, - algorithm: "SHA-256".to_string(), - timestamp: record.timestamp.clone(), - code_length: payload.code.len(), - index: Some(record.index), - record_hash: Some(record.record_hash.clone()), - }), - Err(_e) => Json(AuditResponse { - hash, - algorithm: "SHA-256".to_string(), - timestamp: chrono::Utc::now().to_rfc3339(), - code_length: payload.code.len(), - index: None, - record_hash: None, - }), - } + // A failed authenticated append must not look like a successful audit. + let record = + audit_log::append(&payload.code).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?; + Ok(Json(AuditResponse { + hash, + algorithm: "SHA-256".to_string(), + timestamp: record.timestamp.clone(), + code_length: payload.code.len(), + index: Some(record.index), + record_hash: Some(record.record_hash.clone()), + })) } // ── POST /security/verify ──────────────────────────────────────────────────── @@ -1702,11 +1708,8 @@ async fn handle_audit_lookup( // ── GET /security/audit/chain ──────────────────────────────────────────────── async fn handle_audit_chain() -> Result, (StatusCode, String)> { - let valid = audit_log::verify_chain().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?; - let count = audit_log::all() - .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))? - .len(); - Ok(Json(json!({ "intact": valid, "records": count }))) + let report = audit_log::verification().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?; + Ok(Json(json!(report))) } // ── GET /security/policy ───────────────────────────────────────────────────── diff --git a/xazz-server/tests/audit_hmac_http.rs b/xazz-server/tests/audit_hmac_http.rs new file mode 100644 index 0000000..5770ff3 --- /dev/null +++ b/xazz-server/tests/audit_hmac_http.rs @@ -0,0 +1,224 @@ +//! Real server process tests: exercise production env loading and HTTP handlers, +//! using temporary logs/DBs and per-child settings (no global env mutation). +use serde_json::{Value, json}; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +struct Server { + child: Child, + addr: SocketAddr, +} +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} +impl Server { + fn spawn(dir: &Path, settings: &[(&str, String)], starts: bool) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_xazz-server")); + // Don't inherit the operator's auth/DB/path settings or audit keys. + for (key, _) in std::env::vars_os() { + if key + .to_string_lossy() + .to_ascii_uppercase() + .starts_with("XAZZ_") + { + cmd.env_remove(key); + } + } + cmd.current_dir(dir) + .env("XAZZ_BIND", addr.to_string()) + .stdout(Stdio::null()) + .stderr(std::fs::File::create(dir.join("server.stderr")).unwrap()); + for (key, value) in settings { + cmd.env(key, value); + } + drop(listener); + let mut server = Self { + child: cmd.spawn().unwrap(), + addr, + }; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + if let Some(status) = server.child.try_wait().unwrap() { + assert!( + !starts && !status.success(), + "unexpected server exit: {status}: {}", + std::fs::read_to_string(dir.join("server.stderr")).unwrap_or_default() + ); + return server; + } + if TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() { + assert!(starts, "invalid settings/history must prevent startup"); + return server; + } + assert!( + Instant::now() < deadline, + "server startup/exit timed out: {}", + std::fs::read_to_string(dir.join("server.stderr")).unwrap_or_default() + ); + std::thread::sleep(Duration::from_millis(25)); + } + } + + fn request(&self, path: &str, body: Option) -> (u16, String) { + let mut stream = TcpStream::connect(self.addr).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let method = if body.is_some() { "POST" } else { "GET" }; + let body = body.map(|b| b.to_string()).unwrap_or_default(); + write!(stream, "{method} {path} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", self.addr, body.len()).unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + let (headers, body) = response.split_once("\r\n\r\n").unwrap(); + ( + headers.split_whitespace().nth(1).unwrap().parse().unwrap(), + body.into(), + ) + } + + fn json(&self, path: &str, body: Option) -> Value { + let (status, response) = self.request(path, body); + assert_eq!(status, 200, "{response}"); + serde_json::from_str(&response).unwrap() + } +} + +fn settings(active: &str, boundary: u64) -> Vec<(&'static str, String)> { + vec![ + ( + "XAZZ_AUDIT_HMAC_KEYS", + json!({"old": "ab".repeat(32), "new": "cd".repeat(32)}).to_string(), + ), + ("XAZZ_AUDIT_HMAC_ACTIVE_KEY_ID", active.into()), + ("XAZZ_AUDIT_HMAC_REQUIRED_FROM", boundary.to_string()), + ] +} + +#[test] +fn production_hmac_configuration_rotation_and_tamper_rejection() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit_log/audit.jsonl"); + let server = Server::spawn(dir.path(), &settings("old", 0), true); + server.json("/security/audit", Some(json!({"code": "한글\ncode"}))); + let report = server.json("/security/audit/chain", None); + assert_eq!(report["authenticated"], true); + assert_eq!(report["records"], 1); + let records = server.json("/security/audit/log", None); + assert_eq!(records["records"][0]["hmac_key_id"], "old"); + assert!(!records.to_string().contains(&"ab".repeat(32))); + drop(server); + + let server = Server::spawn(dir.path(), &settings("new", 0), true); + server.json("/security/audit", Some(json!({"code": "rotated"}))); + assert_eq!( + server.json("/security/audit/chain", None)["authenticated"], + true + ); + let records = server.json("/security/audit/log", None); + assert_eq!(records["records"][0]["hmac_key_id"], "old"); + assert_eq!(records["records"][1]["hmac_key_id"], "new"); + + // File-only attacker strips every authentication field. SHA hashes remain valid. + let forged = records["records"] + .as_array() + .unwrap() + .iter() + .map(|record| { + let mut record = record.clone(); + record.as_object_mut().unwrap().remove("hmac"); + record.as_object_mut().unwrap().remove("hmac_key_id"); + record.to_string() + "\n" + }) + .collect::(); + std::fs::write(&path, &forged).unwrap(); + let report = server.json("/security/audit/chain", None); + assert_eq!(report["intact"], false); + assert_eq!(report["authenticated"], false); + assert_eq!( + server + .request("/security/audit", Some(json!({"code": "must fail"}))) + .0, + 500 + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), forged); + drop(server); + drop(Server::spawn(dir.path(), &settings("new", 0), false)); + assert!( + std::fs::read_to_string(dir.path().join("server.stderr")) + .unwrap() + .contains("audit authentication failed at startup") + ); +} + +#[test] +fn production_legacy_migration_and_invalid_config() { + let dir = tempfile::tempdir().unwrap(); + let server = Server::spawn(dir.path(), &[], true); + server.json("/security/audit", Some(json!({"code": "legacy"}))); + let report = server.json("/security/audit/chain", None); + assert_eq!(report["intact"], true); + assert_eq!(report["authenticated"], false); + assert!(report["warning"].is_string()); + drop(server); + assert!( + std::fs::read_to_string(dir.path().join("server.stderr")) + .unwrap() + .contains("WARNING") + ); + drop(Server::spawn(dir.path(), &settings("old", 0), false)); + let server = Server::spawn(dir.path(), &settings("old", 1), true); + server.json("/security/audit", Some(json!({"code": "signed"}))); + let report = server.json("/security/audit/chain", None); + assert_eq!(report["intact"], true); + assert_eq!(report["legacy_records"], 1); + assert_eq!(report["authenticated"], false); + drop(server); + // No-key restart cannot silently accept a previously signed chain. + drop(Server::spawn(dir.path(), &[], false)); + assert!( + std::fs::read_to_string(dir.path().join("server.stderr")) + .unwrap() + .contains("audit authentication failed at startup") + ); + let invalid = [("XAZZ_AUDIT_HMAC_KEYS", "never-print-this-secret".into())]; + drop(Server::spawn(dir.path(), &invalid, false)); + assert!( + !std::fs::read_to_string(dir.path().join("server.stderr")) + .unwrap() + .contains("never-print-this-secret") + ); +} + +#[test] +fn two_server_processes_share_an_authenticated_chain() { + let dir = tempfile::tempdir().unwrap(); + let first = Server::spawn(dir.path(), &settings("old", 0), true); + let second = Server::spawn(dir.path(), &settings("old", 0), true); + std::thread::scope(|scope| { + for (writer, server) in [&first, &second].into_iter().enumerate() { + scope.spawn(move || { + for index in 0..8 { + server.json( + "/security/audit", + Some(json!({"code": format!("{writer}:{index}")})), + ); + assert_eq!(server.json("/security/audit/chain", None)["intact"], true); + } + }); + } + }); + let report = first.json("/security/audit/chain", None); + assert_eq!(report["records"], 16); + assert_eq!(report["authenticated"], true); +}