diff --git a/.codex-review-p1.md b/.codex-review-p1.md deleted file mode 100644 index cb97272fc..000000000 --- a/.codex-review-p1.md +++ /dev/null @@ -1,17 +0,0 @@ -Review scope: `main` (`23c28c55f`)..`HEAD` (`126db872d`), one commit. Read the full diff, AGENTS.md, and the surrounding restore, capture, image cleanup, coordinator teleport, and CI code. Findings are from static review; no Rust or Linux/KVM tests ran. - -1. **MEDIUM — File-backed guests without an NBD disk now enter a live move that cannot advance.** `crates/engram-sandbox-firecracker/src/lib.rs:5375` and `crates/engram-host-agent/src/pooled_backend.rs:8264`. A File-mode guest on a host without the substrate, with a checkpoint chain and page server but a file-backed rootfs, previously returned no source view and selected snapshot rehome. It now passes presetup. The disk lookup still returns `None` (`pooled_backend.rs:8310`), but the coordinator requires a disk manifest and returns `ApiError::Internal("live export has no disk manifest")` (`crates/engram-coordinator/src/teleport.rs:436`). It never persists the export or selects snapshot mode; retry repeats the same failure. This is a supported configuration: NBD setup is optional (`crates/engram-host-agent/src/main.rs:678`), and the new test itself uses no NBD pool. **Smallest fix:** reject a missing live NBD disk with `InvalidSpec` during presetup, before publishing pending state, so the existing coordinator fallback selects snapshot rehome. Add a regression for that fallback; use an NBD-backed guest for successful live-move coverage. - -2. **MEDIUM — Disabling an image makes its running File-mode guests fail capture after the pause.** `crates/engram-host-agent/src/pooled_backend.rs:8481`. Image reconciliation deliberately unlinks the per-image memfile while existing guests still map it (`crates/engram-host-agent/src/image_prefetch.rs:482-505`). Their new `memory_backing` field remains set, so presetup admits them. Linux reports the mapped pathname with ` (deleted)`, which `dirty_map::parse_maps_line` explicitly rejects (`crates/engram-host-agent/src/dirty_map.rs:82-86`). Capture therefore finds no VMAs and returns `Snapshot` after pausing. The coordinator rolls back instead of selecting snapshot rehome (`crates/engram-coordinator/src/teleport.rs:483-493`); each subsequent live attempt fails again. Re-enabling the image creates a new inode and does not repair the old mapping. **Smallest fix:** allow selection of the retained, deleted memfile mapping, with unambiguous mapping identity, or retain memfiles until their last live mapping is gone. Add an image-disable-then-capture regression. A presetup-only file-existence check is insufficient because disable can race capture. - -3. **MEDIUM — The new CI test uses stock Firecracker for a fork-only capture API.** `crates/engram-host-agent/tests/postcopy_source_fresh_create.rs:184-191`. The fixture leaves `cfg.firecracker_bin` at `"firecracker"`. CI installs stock v1.16.0 at that name and stages the fork separately in `ENGRAM_FC_FORK_BIN` (`.github/actions/fc-setup/action.yml:100-139`). The test calls `migration_capture_postcopy`, which calls `snapshot_vmstate_only_package`; this sends `vmstate_only: true`, explicitly documented as rejected by stock Firecracker (`crates/engram-sandbox-firecracker/src/lib.rs:7100-7103`, `src/client.rs:308-323`). Thus the newly added CI target fails at capture before testing the VMA scan. **Smallest fix:** select the staged fork in the fixture and make the CI lane require that artifact. Keep any local missing-fork skip explicit. - -Checked and found sound within this change: - -- The recorded UFFD backing uses the same canonical manifest selection as the actual snapshot load. File restores record the memfile passed to the load API. -- The backing field is persisted and restored on reattach. Old manifests deserialize with `None`, which causes a conservative presetup refusal and snapshot fallback. -- The authoritative guest-swap check still rejects post-copy before pause. This change does not bypass ADR 0112's snapshot disarm path. -- The changed VMA lookup remains inside the existing capture unwind guard; lookup failure does not itself remove the resume, disk-fence cleanup, or presetup-restoration path. Export registration remains after fallible capture work. -- Fresh-mode configuration removal is consistent across the binary, Tilt, and Helm. Resumes still follow `restore_mode`. No coordinator time/randomness calls, teleport writes, wire fields, or Postgres semantics changed, so this diff adds no fencing or conformance obligation there. -- The new integration target is included in the KVM CI lane, and that lane provisions its kernel and agent binary. Its Firecracker selection is the defect listed above. -- `git diff main..HEAD --check` passed. Source files were not modified; only this requested report was added. diff --git a/.codex-review-p5.md b/.codex-review-p5.md deleted file mode 100644 index 0e1ae9733..000000000 --- a/.codex-review-p5.md +++ /dev/null @@ -1,14 +0,0 @@ -Review scope: `23c28c55f..88b4b23e4` (`main..HEAD`), one commit: `88b4b23e4 fix(teleport): live is the admitted kind; the attach step wakes on the harness event`. - -1. **HIGH — Removing the destination live-capability check can turn a supported snapshot move into loss of the running session.** `crates/engram-coordinator/src/teleport.rs:709`; `crates/engram-postgres/src/lib.rs:1188`. Consider a swap-free substrate source and a Firecracker destination configured for File-mode restore, with no usable UFFD handler. The destination can serve ordinary snapshot restores. Its substrate probes report `NotApplicable`, which `host_meets_capabilities` explicitly accepts even with `needs_uffd_substrate: true` (`placement.rs:149-162`). Before this commit, the additional destination check selected `Snapshot`. Now admission always records `Live`, and only the source receives the capability RPC. The source accepts presetup and is frozen while destination restore starts (`teleport.rs:471-482`). Migration restore forces UFFD regardless of the destination's configured mode (`engram-sandbox-firecracker/src/lib.rs:1343`); a handler spawn failure returns a generic VM error (`lib.rs:2203`). It does not carry the `postcopy-never-loaded` marker. After the retry budget, `finish_live_restore` calls `fail_move(..., false)` (`teleport.rs:546-547`), which detaches the session and tombstones the healthy frozen source instead of using the previously supported snapshot path. The session loses its running memory state and falls back to disk recovery or Dead. **Smallest fix:** retain a destination-specific live-capability gate before source capture. The row can still be admitted as Live, then make a fenced transition to Snapshot when the selected destination cannot support live restore. Do not tighten the shared placement predicate, since File-mode snapshot restores must remain supported. Add a regression with a capable source and a File-mode destination; assert snapshot fallback occurs before live capture. - -Checked and found sound within this change: - -- Source presetup still refuses swap-backed guests before freeze or presetup consumption; the refusal takes the existing snapshot capture path. This preserves the ADR 0112 capture boundary. -- Admission still reserves destination capacity in the metadata transaction. The removed request field is an internal Rust field, not a wire or sandbox-manifest field; this change adds no serialization-version requirement. -- Attach uses the injected clock. Its new wait retains the executor heartbeat, and completion still uses the session fence and teleport phase CAS. -- The event wake targets queued teleport operations. The post-requeue generation read covers an event that arrived while the operation was still running and returned RetryAfter. -- PostgreSQL and simulator settlement both distinguish a generation advance with no closed runs from no advance. The shared conformance scenario checks both results. Existing snapshot-refusal and live scenarios remain present. -- Source release still waits for destination drain completion on live moves. The branch does not change capture guards, manifest recovery, or drain-role ordering. - -Validation: static review of the complete branch diff and surrounding production paths. `git diff --check main..HEAD` passed. No compilation, runtime tests, PostgreSQL tests, or KVM tests ran. Only this report was added; source files were not changed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e1ba4ff..e38103701 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,15 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu (RFC 1918, CGNAT), link-local, metadata or other reserved address. A Git server, package registry or other service that resolves only to such an address in your network is no longer reachable from sessions, and no setting turns this off. ([#1849]) +- **The host-fleet operator's DaemonSet and pod access is namespaced.** The chart moves + these rules from the operator's ClusterRole to a new Role and RoleBinding in the release + namespace. A deployer with cluster-admin rights needs no change. If you install the chart + with an identity that has limited RBAC rights, that identity must hold the new Role's + rules before you upgrade, because Kubernetes refuses to create a Role with rules its + creator does not hold: `get`, `list`, `watch` and `patch` on `daemonsets`, and `get`, + `list`, `watch` and `delete` on `pods`, in the release namespace. It also needs `create` + on `roles` and `rolebindings` there, and `bind` on the Role. A HostFleet whose + `daemonSet.namespace` is a different namespace now gets Forbidden. ([#1853]) - **The GitHub `metadata:read` power covers less.** It gave every `GET` under `/repos///`. It now gives the repository itself and the metadata endpoints (events, forks, license, stargazers, subscribers, stats, rules, rulesets, topics, @@ -450,3 +459,4 @@ The first tagged release. See the [#1825]: https://github.com/cortexapps/engrams/pull/1825 [#1826]: https://github.com/cortexapps/engrams/pull/1826 [#1849]: https://github.com/cortexapps/engrams/pull/1849 +[#1853]: https://github.com/cortexapps/engrams/pull/1853 diff --git a/Tiltfile b/Tiltfile index 6c5b2485d..da8417ca7 100644 --- a/Tiltfile +++ b/Tiltfile @@ -1142,14 +1142,13 @@ local_resource('orchestrator', # key whose plaintext lands in var/dev-api-key (gitignored, 0600). # Idempotent — re-mints only when the file is missing or the key row is gone. local_resource('dev-api-key', - cmd=( - 'cd orchestrator && ' + - 'ORCHESTRATOR_DATABASE_URL=' + orchestrator_db_url + ' ' + - 'BETTER_AUTH_SECRET="' + orchestrator_env['BETTER_AUTH_SECRET'] + '" ' + - 'CONTROL_PLANE_BEARER="' + orchestrator_env['CONTROL_PLANE_BEARER'] + '" ' + - 'ENGRAM_KEK_MASTER_KEY="' + orchestrator_env['ENGRAM_KEK_MASTER_KEY'] + '" ' + - 'bun scripts/seed-dev-key.ts ../var/dev-api-key' - ), + cmd='cd orchestrator && bun scripts/seed-dev-key.ts ../var/dev-api-key', + env={ + 'ORCHESTRATOR_DATABASE_URL': orchestrator_db_url, + 'BETTER_AUTH_SECRET': orchestrator_env['BETTER_AUTH_SECRET'], + 'CONTROL_PLANE_BEARER': orchestrator_env['CONTROL_PLANE_BEARER'], + 'ENGRAM_KEK_MASTER_KEY': orchestrator_env['ENGRAM_KEK_MASTER_KEY'], + }, resource_deps=['orchestrator-migrate'], labels=['setup']) diff --git a/crates/engram-app-client/src/config.rs b/crates/engram-app-client/src/config.rs index 587e9d465..1e2b6e055 100644 --- a/crates/engram-app-client/src/config.rs +++ b/crates/engram-app-client/src/config.rs @@ -12,8 +12,9 @@ //! credentials for prod and a local dev stack side by side. use std::collections::BTreeMap; -use std::io; -use std::path::PathBuf; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use serde::{Deserialize, Serialize}; @@ -71,87 +72,285 @@ pub fn resolve_host(flag_url: Option<&str>) -> String { ) } -/// Unreadable or malformed files read as empty, as in the Bun CLI. -fn read_hosts() -> HostsFile { - std::fs::read(hosts_path()) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) - .unwrap_or_default() +fn read_hosts(path: &Path) -> io::Result { + let body = match std::fs::read(path) { + Ok(body) => body, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(HostsFile::default()), + Err(e) => { + return Err(io::Error::new( + e.kind(), + format!("cannot read credentials from {}: {e}", path.display()), + )); + } + }; + serde_json::from_slice(&body).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid credentials JSON in {}: {e}", path.display()), + ) + }) } -fn write_hosts(hosts: &HostsFile) -> io::Result<()> { - let path = hosts_path(); +fn write_hosts(path: &Path, hosts: &HostsFile) -> io::Result<()> { + let dir = path.parent().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "credentials path has no parent", + ) + })?; + create_private_dir(dir)?; let mut body = serde_json::to_vec_pretty(hosts)?; body.push(b'\n'); - std::fs::write(&path, body)?; - restrict(&path) + static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + let (temp_path, file) = loop { + let id = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let temp_path = dir.join(format!(".hosts.{}.{id}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + match options.open(&temp_path) { + Ok(file) => break (temp_path, file), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + }; + // The file closes before the rename: Windows cannot rename an open file. + if let Err(e) = write_synced(file, &body).and_then(|()| std::fs::rename(&temp_path, path)) { + // The write or rename error is the one to report. + let _ = std::fs::remove_file(&temp_path); + return Err(e); + } + sync_dir(dir) } +fn write_synced(mut file: std::fs::File, body: &[u8]) -> io::Result<()> { + file.write_all(body)?; + file.sync_all() +} + +/// Makes a rename in `dir` durable. #[cfg(unix)] -fn restrict(path: &std::path::Path) -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) +fn sync_dir(dir: &Path) -> io::Result<()> { + std::fs::File::open(dir)?.sync_all() } #[cfg(not(unix))] -fn restrict(_path: &std::path::Path) -> io::Result<()> { +fn sync_dir(_dir: &Path) -> io::Result<()> { Ok(()) } -pub fn stored_credential(host: &str) -> Option { - read_hosts().remove(&normalize_host(host)) +pub fn stored_credential(host: &str) -> io::Result> { + Ok(read_hosts(&hosts_path())?.remove(&normalize_host(host))) } pub fn store_credential(host: &str, cred: HostCredential) -> io::Result<()> { let path = hosts_path(); - if let Some(dir) = path.parent() { - create_private_dir(dir)?; - } - let mut hosts = read_hosts(); + let mut hosts = read_hosts(&path)?; hosts.insert(normalize_host(host), cred); - write_hosts(&hosts) + write_hosts(&path, &hosts) } -#[cfg(unix)] -fn create_private_dir(dir: &std::path::Path) -> io::Result<()> { - use std::os::unix::fs::DirBuilderExt; - match std::fs::DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(dir) +fn create_private_dir(dir: &Path) -> io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] { - Ok(()) => Ok(()), - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()), - Err(e) => Err(e), + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); } -} - -#[cfg(not(unix))] -fn create_private_dir(dir: &std::path::Path) -> io::Result<()> { - std::fs::create_dir_all(dir) + builder.create(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) } /// Forget the stored login for `host`. A missing entry is not an error. pub fn delete_credential(host: &str) -> io::Result<()> { - let mut hosts = read_hosts(); + let path = hosts_path(); + let mut hosts = read_hosts(&path)?; if hosts.remove(&normalize_host(host)).is_none() { return Ok(()); } - write_hosts(&hosts) + write_hosts(&path, &hosts) } /// The key for a request against `host`, or `None` when logged out. -pub fn resolve_api_key(host: &str) -> Option { - std::env::var("ENGRAMS_API_KEY") +pub fn resolve_api_key(host: &str) -> io::Result> { + if let Some(key) = std::env::var("ENGRAMS_API_KEY") .ok() .filter(|s| !s.is_empty()) - .or_else(|| stored_credential(host).map(|c| c.api_key)) + { + return Ok(Some(key)); + } + Ok(stored_credential(host)?.map(|c| c.api_key)) } #[cfg(test)] mod tests { use super::*; + struct TestDir(PathBuf); + + impl TestDir { + fn new() -> Self { + static NEXT_DIR: AtomicU64 = AtomicU64::new(0); + loop { + let id = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir() + .join(format!("engram-config-test-{}-{id}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("cannot create test directory: {e}"), + } + } + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn credential() -> HostCredential { + HostCredential { + api_key: "engk_test".into(), + key_id: "key-1".into(), + user: None, + } + } + + #[test] + fn missing_hosts_is_empty_but_read_errors_are_reported() { + let dir = TestDir::new(); + let path = dir.0.join("hosts.json"); + assert!(read_hosts(&path).unwrap().is_empty()); + std::fs::create_dir(&path).unwrap(); + let error = read_hosts(&path).unwrap_err(); + assert!(error.to_string().contains("cannot read credentials")); + assert!(error.to_string().contains(&path.display().to_string())); + } + + #[test] + fn corrupt_hosts_are_not_overwritten() { + // The child has its own environment, so parallel tests cannot change its path. + const CHILD: &str = "ENGRAM_CONFIG_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = TestDir::new(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "config::tests::corrupt_hosts_are_not_overwritten", + ]) + .env(CHILD, "1") + .env("XDG_CONFIG_HOME", &dir.0) + .env_remove("ENGRAMS_API_KEY") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + return; + } + let host = "https://test.example"; + store_credential(host, credential()).unwrap(); + assert_eq!(stored_credential(host).unwrap(), Some(credential())); + let path = hosts_path(); + for body in [ + "", + "{broken", + r#"{"https://test.example":{"apiKey":"engk_test"}}"#, + ] { + std::fs::write(&path, body).unwrap(); + let error = read_hosts(&path).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(error.to_string().contains("invalid credentials JSON")); + assert!(error.to_string().contains(&path.display().to_string())); + assert!(stored_credential(host).is_err()); + assert!(resolve_api_key(host).is_err()); + assert!(store_credential(host, credential()).is_err()); + assert!(delete_credential(host).is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), body); + } + } + + #[test] + fn failed_rename_removes_temporary_file() { + let dir = TestDir::new(); + let path = dir.0.join("hosts.json"); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("keep"), b"unchanged").unwrap(); + assert!(write_hosts(&path, &HostsFile::new()).is_err()); + assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"unchanged"); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1); + } + + #[test] + fn private_dir_rejects_existing_file() { + let dir = TestDir::new(); + let path = dir.0.join("engrams"); + std::fs::write(&path, b"unchanged").unwrap(); + assert!(create_private_dir(&path).is_err()); + assert_eq!(std::fs::read(path).unwrap(), b"unchanged"); + } + + #[cfg(unix)] + #[test] + fn writes_replace_the_file_with_private_permissions() { + use std::io::Read; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let dir = TestDir::new(); + let path = dir.0.join("engrams/hosts.json"); + let hosts = HostsFile::from([("https://test.example".into(), credential())]); + write_hosts(&path, &hosts).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + assert_eq!(read_hosts(&path).unwrap(), hosts); + let mut old_file = std::fs::File::open(&path).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + write_hosts(&path, &HostsFile::new()).unwrap(); + assert!(read_hosts(&path).unwrap().is_empty()); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + assert_ne!( + old_file.metadata().unwrap().ino(), + std::fs::metadata(&path).unwrap().ino() + ); + let mut old_body = Vec::new(); + old_file.read_to_end(&mut old_body).unwrap(); + assert_eq!( + serde_json::from_slice::(&old_body).unwrap(), + hosts + ); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + + #[cfg(unix)] + #[test] + fn private_dir_tightens_existing_permissions() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let dir = TestDir::new(); + let path = dir.0.join("engrams"); + create_private_dir(&path).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o700); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + write_hosts(&path.join("hosts.json"), &HostsFile::new()).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o700); + } + #[test] fn normalize_strips_trailing_slashes() { assert_eq!(normalize_host("https://x.example/"), "https://x.example"); diff --git a/crates/engram-cli/src/commands/auth.rs b/crates/engram-cli/src/commands/auth.rs index 68a2a36ca..bf36057a3 100644 --- a/crates/engram-cli/src/commands/auth.rs +++ b/crates/engram-cli/src/commands/auth.rs @@ -74,6 +74,8 @@ pub async fn login(host: &str, status: &crate::status::Status) -> CliResult { "ENGRAMS_API_KEY is set — it would shadow any stored login. Unset it to use `auth login`.", ); } + // Check the credential file before creating a new server-side key. + stored_credential(host)?; // A plain client for the non-RPC auth routes. let plain = Transport::new(host, Auth::None); let http = plain.http(); @@ -159,7 +161,7 @@ async fn whoami(host: &str, api_key: &str) -> Result { } pub async fn logout(host: &str) -> CliResult { - let Some(stored) = stored_credential(host) else { + let Some(stored) = stored_credential(host)? else { return fail(format!("no stored login for {host}")); }; // Best-effort server-side revoke, authenticated by the key being revoked. @@ -196,7 +198,7 @@ struct StatusJson<'a> { } pub async fn status(host: &str, json: bool) -> CliResult { - let key = resolve_api_key(host); + let key = resolve_api_key(host)?; let source = if env_api_key_set() { "ENGRAMS_API_KEY".to_string() } else { diff --git a/crates/engram-cli/src/main.rs b/crates/engram-cli/src/main.rs index 5ec35dc86..ae2d3574b 100644 --- a/crates/engram-cli/src/main.rs +++ b/crates/engram-cli/src/main.rs @@ -356,7 +356,7 @@ impl Ctx { /// pointer when no key is resolvable — every RPC verb calls through /// here, so the logged-out failure mode is one consistent message. fn clients(&self) -> CliResult { - let Some(key) = resolve_api_key(&self.host) else { + let Some(key) = resolve_api_key(&self.host)? else { return fail(format!( "not logged in to {} — run `engrams auth login` (or set ENGRAMS_API_KEY)", self.host diff --git a/deploy/dev/seed-buckets.sh b/deploy/dev/seed-buckets.sh index 77559f441..97ad192dc 100755 --- a/deploy/dev/seed-buckets.sh +++ b/deploy/dev/seed-buckets.sh @@ -17,6 +17,9 @@ set -euo pipefail +seed_output="$(mktemp)" +trap 'rm -f "$seed_output"' EXIT + EMULATOR="${STORAGE_EMULATOR_HOST:-http://localhost:4443}" S3_ENDPOINT="${ENGRAM_TEST_S3_ENDPOINT:-${ENGRAM_S3_ENDPOINT_URL:-}}" # Honor either env var so the script works in both contexts: @@ -55,7 +58,7 @@ seed_gcs() { # POST the bucket. The `name` field is what the SDK references; the # `location` and `storageClass` defaults match what the prod-shape # tooling expects but are otherwise irrelevant under the emulator. - HTTP_STATUS=$(curl -sw '%{http_code}' -o /tmp/seed-buckets.out \ + HTTP_STATUS=$(curl -sw '%{http_code}' -o "$seed_output" \ -X POST "${EMULATOR}/storage/v1/b?project=engram-dev" \ -H 'Content-Type: application/json' \ -d "{\"name\":\"${BUCKET}\"}" || true) @@ -69,7 +72,7 @@ seed_gcs() { ;; *) echo "seed-buckets: unexpected status ${HTTP_STATUS} from emulator:" >&2 - cat /tmp/seed-buckets.out >&2 + cat "$seed_output" >&2 exit 1 ;; esac diff --git a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml index 9c86d867c..9176a6ddd 100644 --- a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml +++ b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml @@ -1,9 +1,5 @@ {{- if .Values.operator.enabled -}} -# ADR 0044 K3: cluster-scoped permissions the rollout operator needs — -# read its CRs, patch the host-agent DaemonSet image, and list/delete its -# pods + cordon nodes for the drain-gated roll. Node + DaemonSet/Pod access -# is cluster-wide because the host fleet spans nodes; scope is otherwise -# minimal (no secrets, no create on workloads). +# Cluster resources used to observe fleets and cordon nodes. apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -17,6 +13,36 @@ rules: - apiGroups: ["engram.io"] resources: ["hostfleets/status"] verbs: ["get", "update", "patch"] + # Cordon/uncordon the node during its roll. + - apiGroups: [""] + resources: ["nodes"] + verbs: ["get", "list", "watch", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "hostfleet.operator.fullname" . }} + labels: + {{- include "hostfleet.operator.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "hostfleet.operator.fullname" . }} +subjects: + - kind: ServiceAccount + name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} +--- +# The host-agent DaemonSet and its pods. A HostFleet whose daemonSet is in +# another namespace gets Forbidden. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "hostfleet.operator.labels" . | nindent 4 }} +rules: # Patch the host-agent DaemonSet's image toward the CR. - apiGroups: ["apps"] resources: ["daemonsets"] @@ -25,20 +51,17 @@ rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch", "delete"] - # Cordon/uncordon the node during its roll. - - apiGroups: [""] - resources: ["nodes"] - verbs: ["get", "list", "watch", "patch"] --- apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding +kind: RoleBinding metadata: name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} labels: {{- include "hostfleet.operator.labels" . | nindent 4 }} roleRef: apiGroup: rbac.authorization.k8s.io - kind: ClusterRole + kind: Role name: {{ include "hostfleet.operator.fullname" . }} subjects: - kind: ServiceAccount diff --git a/justfile b/justfile index 457f0f20a..5ff63776d 100644 --- a/justfile +++ b/justfile @@ -10,7 +10,7 @@ # 0024). `just bake-demo` bakes the Claude image; `just pull-kernel` # fetches the right kernel. -set shell := ["bash", "-cu"] +set shell := ["bash", "-euo", "pipefail", "-c"] set dotenv-load := true # `just` with no args prints the recipe list.