Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`가
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docs/SECURITY_GUARDRAIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
45 changes: 44 additions & 1 deletion docs/SERVER.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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`.
`XAZZ_STREAMING`.
52 changes: 51 additions & 1 deletion docs/design/security-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,54 @@ README 등 사용자 문서에서 "샌드박스 런타임"이라는 표현은

- 서브프로세스 실행 경계 → **프로세스 격리(process isolation)**
- 사전 실행 검사 → **정적 가드레일(guardrail) 게이트**
- 실행 시간 제한 → **타임아웃 하드닝**
- 실행 시간 제한 → **타임아웃 하드닝**

## 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.
71 changes: 71 additions & 0 deletions docs/evidence/audit-hmac-windows-2026-10-22.md
Original file line number Diff line number Diff line change
@@ -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).
1 change: 1 addition & 0 deletions xazz-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }

Expand Down
Loading
Loading