fix(security): server-authoritative approval gate + auth/session/file hardening

Remediate the HIGH and security-relevant findings from the 2026-07-11 audit.

H1 — the per-env approval gate is now server-authoritative. The governing
project is resolved from the target node's nearest-claimed ancestor
(`governing_env_policy`/`_tree` + `governing_project_id` +
`ProjectRepository::get_environments_by_id`), independent of the client-supplied
`[project]`. Omitting or spoofing the project block can no longer skip a gate the
owning project established; a to-create group resolves its declared parent's
chain so a fresh subtree node inherits the gate. Fails closed on any read error.

H2 — the API-key prefix slice (`&rest[..8]`) is now the boundary-safe
`rest.get(..8)`, so an attacker-supplied multibyte bearer can't panic the request
task (unauthenticated per-request DoS). Regression test added.

C1 — admin sessions gain an absolute lifetime cap (migration 0070,
`PICLOUD_SESSION_ABSOLUTE_TTL_HOURS`, default 30d): `lookup` filters it, `touch`
clamps the sliding bump to it, so a continuously-used or stolen-but-warm token
self-expires. Mirrors the data-plane app-user cap.

C2 — `Cache-Control: no-store` on the login and API-key-mint responses (the two
that return a raw credential), so a proxy/CDN/browser cache can't retain it.

B8 — file downloads are header-safe: `sanitize_stored_filename` guarantees a
valid `HeaderValue` (no panic on a control-char name) and BOTH the per-app and
group download paths now set attachment + `X-Content-Type-Options: nosniff` +
a restrictive CSP, closing a group-path stored-XSS gap.

Also folds in the server-side plan-warning plumbing (`plan_warnings`,
`PlanResult::warnings`) and the `app_only_reject` message helper that the CLI
plan-preview change builds on, plus operator security notes (reads-open shared-
topic SSE; the `--env` label is advisory, not a boundary).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-11 23:47:35 +02:00
parent b8b047368e
commit 86448beb06
18 changed files with 593 additions and 125 deletions

View File

@@ -303,6 +303,40 @@ pub fn sanitize_stored_content_type(ct: &str) -> String {
}
}
/// Fallback filename when a stored name sanitizes to nothing.
pub const SAFE_FILENAME_FALLBACK: &str = "download";
/// Coerce a stored filename into a value safe to embed in a
/// `Content-Disposition: attachment; filename="…"` header.
///
/// The stored `name` is script/upload-supplied and flows straight into a
/// response header. `HeaderValue` rejects control bytes (`< 0x20`, `0x7f`), so
/// a name containing e.g. a NUL or a raw byte would make the response builder
/// error — and the download handler `.expect()`s that build, turning an
/// attacker-influenced stored name into a per-request panic. We keep only
/// printable ASCII (`0x20..=0x7e`) minus the quoting metacharacters `"` and
/// `\`, replacing anything else with `_`. The result is always a valid
/// `HeaderValue`, so the handler can never panic on it. (Non-ASCII names lose
/// fidelity in this legacy `filename=` param; a future `filename*` UTF-8
/// parameter can restore it — this fix is about never panicking.)
#[must_use]
pub fn sanitize_stored_filename(name: &str) -> String {
// Keep printable ASCII (space included) minus the quoting metacharacters;
// DROP everything else (control bytes, non-ASCII) so the result is always a
// valid HeaderValue. A name that sanitizes to nothing falls back to a
// non-empty default.
let cleaned: String = name
.chars()
.filter(|&c| (c == ' ' || c.is_ascii_graphic()) && c != '"' && c != '\\')
.collect();
let trimmed = cleaned.trim();
if trimmed.is_empty() {
SAFE_FILENAME_FALLBACK.to_string()
} else {
trimmed.to_string()
}
}
/// Reject a collection name that is empty or could escape the per-app
/// files tree. UUID-shaped ids never produce traversal paths, but
/// collection names come from scripts so they're validated defensively
@@ -476,4 +510,38 @@ mod content_type_sanitizer_tests {
);
}
}
#[test]
fn stored_filename_is_header_safe() {
// Audit 2026-07-11 — a stored name with a control byte (NUL, 0x7f,
// CR/LF) or quote/backslash must sanitize to a value safe to embed in a
// `Content-Disposition` header, so the download handler can never panic
// building the response. The invariant HeaderValue requires: every byte
// is visible ASCII (0x20..=0x7e) and never `"` or `\` (quoting metachars).
for name in [
"ok.pdf",
"with space.txt",
"quote\".txt",
"back\\slash.txt",
"nul\u{0}byte.bin",
"del\u{7f}.bin",
"crlf\r\n.txt",
"café.pdf",
"\u{0}\u{7f}",
] {
let clean = sanitize_stored_filename(name);
assert!(!clean.is_empty(), "{name:?} produced an empty filename");
assert!(
clean
.bytes()
.all(|b| (0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\'),
"{name:?} -> {clean:?} has a header-unsafe byte"
);
}
// An all-unsafe name falls back to a non-empty default.
assert_eq!(
sanitize_stored_filename("\u{0}\u{7f}\r\n"),
SAFE_FILENAME_FALLBACK
);
}
}

View File

@@ -66,8 +66,9 @@ pub use events::{EmitError, NoopEventEmitter, ServiceEvent, ServiceEventEmitter}
pub use exec_summary::ExecResponseSummary;
pub use execution_log::{ExecutionLog, ExecutionSource, ExecutionStatus};
pub use files::{
sanitize_stored_content_type, validate_collection as validate_files_collection, FileMeta,
FileUpdate, FilesError, FilesListPage, FilesService, NewFile, NoopFilesService,
sanitize_stored_content_type, sanitize_stored_filename,
validate_collection as validate_files_collection, FileMeta, FileUpdate, FilesError,
FilesListPage, FilesService, NewFile, NoopFilesService, SAFE_FILENAME_FALLBACK,
SAFE_RENDER_FALLBACK,
};
pub use group::Group;