Repository navigation
fix: cap hostile parsers and bind servers to loopback - #290
Conversation
Record what the save, mod, weave, LLM, asset, net, and supply-chain paths actually do, and add tests that fail until those parsers reject oversized or out-of-root input. No parser behavior changes. Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
Reject oversized save headers, vitals lists, and LZ4 output before allocation. Jail glTF, cell, and script paths with safe_under. Keep LocalHttpClient on loopback unless explicitly opted in. The matchmaking default listens on 127.0.0.1 and release builds refuse the published dev key. The in-engine server ignores client actor ids and requires a real token outside debug and test builds. Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configuration
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| target: fuzz_decode_msg | ||
| steps: | ||
| - name: Checkout | ||
| uses: actions/checkout@v5 |
| uses: actions/checkout@v5 | ||
|
|
||
| - name: Install nightly toolchain | ||
| uses: dtolnay/rust-toolchain@nightly |
| components: llvm-tools-preview | ||
|
|
||
| - name: Cache cargo-fuzz | ||
| uses: actions/cache@v4 |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bf9de2bfce
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let hostport = rest.split('/').next().unwrap_or(""); | ||
| let host = if let Some(bracketed) = hostport.strip_prefix('[') { | ||
| bracketed.split(']').next().unwrap_or("") | ||
| } else { | ||
| hostport.split(':').next().unwrap_or("") | ||
| }; |
There was a problem hiding this comment.
Parse the URL authority before accepting loopback
A URL with userinfo such as http://127.0.0.1:password@evil.example passes this check because splitting on : yields 127.0.0.1, but reqwest interprets evil.example as the actual host. When with_api_key is used, the subsequent request sends both the bearer token and prompt to that remote host, bypassing the intended loopback restriction. Parse the URL with a standards-compliant URL parser and validate its resolved host instead.
Useful? React with 👍 / 👎.
| token, | ||
| policy: pol, | ||
| } => { | ||
| println!("Hello from {name}"); | ||
| if let Some(tok) = token { | ||
| if tok != "dev" { | ||
| println!("unauthenticated or unknown token: {}", tok); | ||
| } | ||
| } | ||
| // Map name to viewer id | ||
| let mapped = match name.as_str() { | ||
| "player" | "player1" => self.player_id, | ||
| "comp" | "companion" => self.companion_id, | ||
| "enemy" => self.enemy_id, | ||
| _ => self.player_id, | ||
| }; | ||
| { | ||
| let mut v = viewer_id.lock().await; | ||
| *v = mapped; | ||
| if !hello_token_accepted(token.as_deref()) { | ||
| eprintln!("rejected hello from {name}: token is not accepted"); | ||
| break; | ||
| } | ||
| authed = true; |
There was a problem hiding this comment.
Gate outbound snapshots on successful authentication
The new authed state only protects inbound plan/input handling; the snapshot-pusher task is spawned before authentication and has no access to this flag. A client that never sends ClientHello can therefore keep receiving periodic snapshots, and breaking on an invalid token does not stop the detached task that owns the WebSocket sink. Delay spawning the pusher or gate its sends until the token has been accepted, and explicitly terminate it when authentication fails.
Useful? React with 👍 / 👎.
| fn decompress_lz4_capped(payload: &[u8]) -> Result<Vec<u8>> { | ||
| if payload.len() >= 4 { | ||
| let declared = | ||
| u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize; | ||
| if declared > MAX_AWSV_UNCOMPRESSED_BYTES { | ||
| bail!( | ||
| "declared uncompressed size exceeds cap ({declared} > {MAX_AWSV_UNCOMPRESSED_BYTES})" |
There was a problem hiding this comment.
Keep save writes within the new read limits
For a legitimate bundle whose serialized payload exceeds 16 MiB, write_awsv still writes the file and SaveManager::save reports success, but this new check makes every subsequent load reject that same file. The same mismatch exists when incompressible data produces more than 4 MiB compressed output, which is plausible because WorldState::ecs_blob is arbitrary and documented as potentially already compressed. Enforce both limits before committing a save, or ensure files produced by the writer remain readable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Copilot review overview
5 open findings
This fuzz target writes to a fixed filename in the system temp dir, which can collide if the fuzzer… · New Jailing glTF file URIs relative tostd::env::current_dir()makes behavior depend on the process… · New The audit/PoC language says constructors 'refuse' non-loopback URLs, but the implementation… · New URL validation via manual string splitting is brittle (userinfo, percent-encoding, unusual but… · New This bullet repeats the/healthz+/regionssentences twice (and repeats the… · New
What changed in this PR
Hardens multiple externally-facing parsers and network defaults based on the security audit: adds size caps (save/net LZ4), path traversal jailing (assets/scripts), safer server defaults (loopback bind + dev-key refusal in release), plus PoC regression tests and nightly fuzzing targets/workflow.
Changes:
- Add explicit size caps for
.awsvcompressed payloads and LZ4 declared output sizes (save + net proto), plus decoding-from-bytes helpers. - Default server bind addresses to loopback and refuse published dev signing keys outside debug/test; tighten in-engine server hello/auth behavior.
- Add PoC security tests, cargo-fuzz targets, and a nightly fuzz workflow; update architecture/audit docs accordingly.
| File | Description |
|---|---|
| persistence/aw-save/src/lib.rs | Adds .awsv caps, in-memory decode API, and capped LZ4 decompression + PoC test. |
| persistence/aw-save/fuzz/fuzz_targets/fuzz_awsv.rs | Adds fuzz target for in-memory .awsv decoding. |
| persistence/aw-save/fuzz/Cargo.toml | Adds cargo-fuzz package config for aw-save. |
| net/aw-net-server/tests/loopback_default.rs | Verifies ServerConfig::default() binds loopback and uses the published dev key. |
| net/aw-net-server/tests/family5_tls_signature_path.rs | Updates comment to reflect loopback default bind. |
| net/aw-net-server/src/main.rs | Enforces --shared-key-hex in release builds; adjusts tracing usage. |
| net/aw-net-server/src/lib.rs | Defaults binds to loopback; refuses published dev key outside debug/test in spawn_server. |
| net/aw-net-proto/tests/security_poc.rs | Adds PoC test for rejecting oversized LZ4 declared output in decode_msg. |
| net/aw-net-proto/src/lib.rs | Adds LZ4 declared output cap + published dev key helpers; uses capped decompress in decode_msg. |
| net/aw-net-proto/fuzz/fuzz_targets/fuzz_decode_msg.rs | Adds fuzz target for decode_msg across codecs. |
| net/aw-net-proto/fuzz/Cargo.toml | Adds cargo-fuzz package config for aw-net-proto. |
| examples/llm_integration/src/main.rs | Adds explicit opt-in env var for allowing remote LLM endpoints. |
| docs/current/SECURITY_AUDIT.md | Adds/updates audit findings, PoCs, and fuzzing plan documentation. |
| docs/architecture/security.md | Updates wired/dormant surfaces and doc version. |
| docs/architecture/persistence_ecs.md | Updates persistence load-path documentation to reflect new caps. |
| docs/architecture/net_ecs.md | Updates net-ecs architecture doc for loopback defaults and LZ4 cap. |
| docs/architecture/net.md | Updates in-engine server auth behavior documentation and doc version. |
| docs/architecture/asset.md | Updates asset doc to reflect safe_under usage. |
| astraweave-scripting/tests/security_poc.rs | Adds PoC test for rejecting .. traversal in ScriptLoader. |
| astraweave-scripting/src/loader.rs | Adds script path jailing via safe_under before reading. |
| astraweave-scripting/src/lib.rs | Applies jailed paths in hot-reload metadata/read path. |
| astraweave-net/src/lib.rs | Tightens hello/token gate + ignores client actor id; uses server player id. |
| astraweave-llm/src/lib.rs | Adds loopback-only URL behavior by default + explicit remote opt-in; adds PoC test. |
| astraweave-combat/tests/security_poc.rs | Adds PoC test asserting vitals record-count cap. |
| astraweave-combat/src/save.rs | Enforces MAX_VITALS_RECORDS cap inside decode_vitals. |
| astraweave-combat/fuzz/fuzz_targets/fuzz_vitals.rs | Adds fuzz target for decode_vitals. |
| astraweave-combat/fuzz/Cargo.toml | Adds cargo-fuzz package config for astraweave-combat. |
| astraweave-asset/tests/security_poc.rs | Adds PoCs for rejecting .. in glTF URIs and cell asset paths. |
| astraweave-asset/src/lib.rs | Jails glTF file URIs via safe_under. |
| astraweave-asset/src/cell_loader.rs | Jails cell asset paths via safe_under. |
| astraweave-asset/fuzz/fuzz_targets/fuzz_gltf_json.rs | Adds fuzz target for glTF JSON parsing path. |
| astraweave-asset/fuzz/fuzz_targets/fuzz_cell_ron.rs | Adds fuzz target for cell RON loading via temp file. |
| astraweave-asset/fuzz/Cargo.toml | Registers new fuzz targets in existing asset fuzz crate. |
| astraweave-asset/Cargo.toml | Adds astraweave-security dependency for path jailing. |
| .github/workflows/fuzz-nightly.yml | Adds nightly scheduled fuzz workflow running key parser targets with time caps. |
🧠 Review effort: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| let path = std::env::temp_dir().join("aw-fuzz-cell.ron"); | ||
| if std::fs::write(&path, data).is_ok() { | ||
| let _ = astraweave_asset::cell_loader::load_cell_from_ron_sync(&path); |
| let base = std::env::current_dir().context("asset jail base")?; | ||
| let path = astraweave_security::path::safe_under(&base, std::path::Path::new(uri)) | ||
| .map_err(|err| anyhow!("path traversal rejected: {err}"))?; | ||
| let bytes = std::fs::read(&path).with_context(|| format!("Read uri {uri}"))?; |
| /// Create a client. Non-loopback URLs are replaced with `http://127.0.0.1:11434`. | ||
| /// Use [`Self::allowing_remote`] to keep a caller-supplied host. |
| let Some(rest) = url | ||
| .strip_prefix("http://") | ||
| .or_else(|| url.strip_prefix("https://")) | ||
| else { | ||
| return false; | ||
| }; | ||
| let hostport = rest.split('/').next().unwrap_or(""); | ||
| let host = if let Some(bracketed) = hostport.strip_prefix('[') { | ||
| bracketed.split(']').next().unwrap_or("") | ||
| } else { | ||
| hostport.split(':').next().unwrap_or("") | ||
| }; | ||
| let host = host.trim().to_ascii_lowercase(); | ||
| host == "localhost" || host == "127.0.0.1" || host == "::1" |
| **Notes:** | ||
| - `--disable-tls` is `cfg(not(debug_assertions))`-rejected (server/main.rs:120-123) — release builds cannot disable TLS. | ||
| - HTTP admin on 0.0.0.0:8789: `/healthz` returns `"ok"`, `/regions` returns hardcoded `["us-east","us-west","eu-central"]` (server/main.rs:160-164). No real region-resolution logic; the string list is decorative. | ||
| - HTTP admin defaults to `127.0.0.1:8789` (was `0.0.0.0`). `/healthz` returns `"ok"`, `/regions` returns hardcoded `["us-east","us-west","eu-central"]`. No real region-resolution logic; the string list is decorative. Release builds refuse `SigningKey::dev_default`. `/healthz` returns `"ok"`, `/regions` returns hardcoded `["us-east","us-west","eu-central"]` (server/main.rs:160-164). No real region-resolution logic; the string list is decorative. |


Description
Lands the main-side caps from
docs/current/SECURITY_AUDIT.md. Hostile input is rejected. Bytes that already decode stay the same, so the required replay hashes do not change..awsvdeclared length is checked before the payload buffer is allocated (4 MiB compressed, 16 MiB LZ4 output).decode_msgrejects an LZ4 declared output above 4 MiB.safe_under. There is no second jail.LocalHttpClient::newandwith_api_keykeep only loopback URLs.allowing_remoteis the explicit opt-in (LOCAL_LLM_ALLOW_REMOTE=1in the integration example).ServerConfig::defaultbinds127.0.0.1. Release builds refuse the published dev signing key.AW_GAME_TOKEN(not the literaldev).All seven proof-of-concept tests pass. Linux replay hashes match the pinned values, including
combat_resolve975aae72e3c83a2335be05142eea2bf2ae4413d621fc5009ed6019f89e2a6e52..github/workflows/fuzz-nightly.ymlruns five targets for 120 seconds each. It is not on pull requests.Secret scanning and push protection are already enabled. The audit doc says so.
PR #214, #252, and #205 are not touched. Do not merge this draft.
Type of change
Release servers that used the published dev key or
0.0.0.0now fail closed. Debug and test builds still boot with the dev key on loopback. Valid saves and replay fixtures are unchanged.Security Considerations
astraweave-assetnow depends on the existingastraweave-securitycrate so it can callsafe_under...paths are rejected. The seven proof tests pass.AW_GAME_TOKENoutside debug/test and ignores client actor ids.Checklist
Local checks: the seven PoCs,
aw-savetests,aw-net-prototests,aw-net-servertests,astraweave-netintegration and coverage tests, glTF loader tests, combat logic tests, and both replay-hash tests.cargo clippy --lib -D warningsis clean foraw-save,aw-net-proto,aw-net-server,astraweave-net,astraweave-asset, andastraweave-scripting.