aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-runtime / src / approved_auth.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Approval authentication for the proposer hook (#249, part A). |
| 17 | //! |
| 18 | //! An [`crate::approved::ApprovedProposal`] carries `approval_mac`: an |
| 19 | //! HMAC-SHA256, keyed by the approval desk key, over the canonical binding of |
| 20 | //! every field the approval covers ([`ApprovalIdentity`]). The daemon holds |
| 21 | //! the same key (`<compose dir>/approval-desk.key`) and recomputes the MAC; |
| 22 | //! any field the caller changes (trace, request, approval id, approver, path, |
| 23 | //! content, approved proposal digest) or a MAC made with another key is |
| 24 | //! refused `PROPOSAL_REFUSED Unauthenticated`. |
| 25 | //! |
| 26 | //! What the MAC proves: the holder of the desk key approved exactly these |
| 27 | //! fields. It does not prove which human pressed approve; the desk (the |
| 28 | //! INTERPLANE host's approval continuation, host-only) names the approver and |
| 29 | //! the MAC stops anyone without the key from changing that name. Caller text |
| 30 | //! (model output, tool arguments, request JSON) is never approval: it cannot |
| 31 | //! carry a valid MAC without the key. |
| 32 | //! |
| 33 | //! Why a key and not the existing operator `authorization` grant: grant |
| 34 | //! records are `ComposeNote`s any same-user socket caller can append, so |
| 35 | //! "bound to a grant" would be caller text in two steps; the aien-mcp |
| 36 | //! `ApprovalGrant` lives in the INTERPLANE process memory and the daemon |
| 37 | //! cannot check it. The key is the smallest thing that separates "the desk |
| 38 | //! approved" from "the caller says it was approved". |
| 39 | //! |
| 40 | //! Key rules (checked on every load, so a replaced key takes effect at once): |
| 41 | //! a regular file (never a symlink, opened `O_NOFOLLOW`), owned by this |
| 42 | //! process's effective uid, no group or other permission bits, 64 hex digits. |
| 43 | //! The key is never printed, logged, recorded or reported; only |
| 44 | //! [`DeskKey::id`] (first 16 hex digits of sha256 of the key) is. |
| 45 | //! The compose home must not overlap the workspace the proposal targets (the |
| 46 | //! model-facing tools read inside the workspace), else `Confinement`. |
| 47 | //! |
| 48 | //! Rotation: replacing the key file makes every MAC made with the old key |
| 49 | //! fail (`Unauthenticated`), including approvals issued but not yet |
| 50 | //! submitted; the desk must approve again. Records already written keep the |
| 51 | //! old `desk_key_id`. Loss of the key: the daemon refuses every approved |
| 52 | //! proposal (`NoDesk`) until an operator creates a new one |
| 53 | //! (`aien compose desk-key`). |
| 54 | //! |
| 55 | //! Limit: the OS user stays the outer boundary. A process running as the |
| 56 | //! daemon's user that can read the compose home can read the key. |
| 57 | use aien_omega_compose::hex; |
| 58 | use serde_json::{Map, Value}; |
| 59 | use sha2::{Digest, Sha256}; |
| 60 | use std::io::{Read, Write}; |
| 61 | use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; |
| 62 | use std::path::{Path, PathBuf}; |
| 63 | |
| 64 | /// Version tag inside every binding. |
| 65 | pub const APPROVAL_BINDING_VERSION: &str = "aien.approval.v2"; |
| 66 | /// File name of the desk key inside the compose home. |
| 67 | pub const DESK_KEY_FILE: &str = "approval-desk.key"; |
| 68 | |
| 69 | const REFUSED: &str = crate::approved::REFUSED; |
| 70 | |
| 71 | fn refuse(name: &str, why: impl std::fmt::Display) -> String { |
| 72 | format!("{REFUSED} {name}: {why}") |
| 73 | } |
| 74 | |
| 75 | /// The fields one approval covers. `desk_key_id` names the key that |
| 76 | /// authenticated it; it is not caller input (the daemon fills it from the key |
| 77 | /// it holds). |
| 78 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 79 | pub struct ApprovalIdentity { |
| 80 | pub trace_id: String, |
| 81 | pub request_id: String, |
| 82 | pub approval_id: String, |
| 83 | pub approver: String, |
| 84 | pub path: String, |
| 85 | pub content_sha256: String, |
| 86 | pub approved_proposal_sha256: String, |
| 87 | pub desk_key_id: String, |
| 88 | /// The canonical absolute workspace the approval is for (476ca4 c17): the |
| 89 | /// effect can land only here. The daemon canonicalises the submitted |
| 90 | /// workspace and binds that, so a valid approval presented with another |
| 91 | /// workspace fails the MAC (Unauthenticated, nothing consumed). |
| 92 | pub workspace: String, |
| 93 | } |
| 94 | |
| 95 | impl ApprovalIdentity { |
| 96 | /// The identity of `p` for the canonical `workspace` under the desk key |
| 97 | /// `desk_key_id`. |
| 98 | pub fn of(p: &crate::approved::ApprovedProposal, workspace: &str, desk_key_id: &str) -> Self { |
| 99 | Self { |
| 100 | trace_id: p.trace_id.clone(), |
| 101 | request_id: p.request_id.clone(), |
| 102 | approval_id: p.approval_id.clone(), |
| 103 | approver: p.approver.clone(), |
| 104 | path: p.path.clone(), |
| 105 | content_sha256: p.content_sha256.clone(), |
| 106 | approved_proposal_sha256: p.approved_proposal_sha256.clone(), |
| 107 | desk_key_id: desk_key_id.to_string(), |
| 108 | workspace: workspace.to_string(), |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// The canonical absolute workspace path (symlinks resolved), as bound. |
| 114 | pub fn canonical_workspace(workspace: &Path) -> Result<String, String> { |
| 115 | let c = std::fs::canonicalize(workspace) |
| 116 | .map_err(|e| format!("workspace {}: {e}", workspace.display()))?; |
| 117 | c.to_str() |
| 118 | .map(str::to_string) |
| 119 | .ok_or_else(|| format!("workspace {} is not UTF-8", c.display())) |
| 120 | } |
| 121 | |
| 122 | /// Canonical binding: compact JSON, keys in sorted order, of the nine |
| 123 | /// identity fields plus `"v": APPROVAL_BINDING_VERSION`. |
| 124 | pub fn binding_bytes(id: &ApprovalIdentity) -> Vec<u8> { |
| 125 | // serde_json's Map is a BTreeMap here (no preserve_order feature), so |
| 126 | // keys serialize sorted; inserted sorted anyway. |
| 127 | let mut m = Map::new(); |
| 128 | for (k, v) in [ |
| 129 | ("approval_id", &id.approval_id), |
| 130 | ("approved_proposal_sha256", &id.approved_proposal_sha256), |
| 131 | ("approver", &id.approver), |
| 132 | ("content_sha256", &id.content_sha256), |
| 133 | ("desk_key_id", &id.desk_key_id), |
| 134 | ("path", &id.path), |
| 135 | ("request_id", &id.request_id), |
| 136 | ("trace_id", &id.trace_id), |
| 137 | ("workspace", &id.workspace), |
| 138 | ] { |
| 139 | m.insert(k.into(), Value::String(v.clone())); |
| 140 | } |
| 141 | m.insert("v".into(), Value::String(APPROVAL_BINDING_VERSION.into())); |
| 142 | Value::Object(m).to_string().into_bytes() |
| 143 | } |
| 144 | |
| 145 | /// What the requirements MAC covers: a domain tag, the approval binding and |
| 146 | /// the requirement goal (a missing goal and an empty goal differ). |
| 147 | fn requirements_bytes(id: &ApprovalIdentity, goal: Option<&str>, base: Option<&str>) -> Vec<u8> { |
| 148 | // v2 adds the sha256 of the file the bytes replace (or "absent"); v1 is the |
| 149 | // binding of an approval whose requirements do not depend on the prior file. |
| 150 | let mut m = if base.is_some() { |
| 151 | b"aien.requirements.v2\0".to_vec() |
| 152 | } else { |
| 153 | b"aien.requirements.v1\0".to_vec() |
| 154 | }; |
| 155 | m.extend(binding_bytes(id)); |
| 156 | m.push(0); |
| 157 | match goal { |
| 158 | None => m.push(0), |
| 159 | Some(g) => { |
| 160 | m.push(1); |
| 161 | m.extend(g.as_bytes()); |
| 162 | } |
| 163 | } |
| 164 | if let Some(b) = base { |
| 165 | m.push(0); |
| 166 | m.extend(b.as_bytes()); |
| 167 | } |
| 168 | m |
| 169 | } |
| 170 | |
| 171 | /// The durable replay key of an approval: sha256 (hex) of its binding. |
| 172 | pub fn approval_key(id: &ApprovalIdentity) -> String { |
| 173 | hex(&Sha256::digest(binding_bytes(id))) |
| 174 | } |
| 175 | |
| 176 | /// HMAC-SHA256 (RFC 2104) over sha2; no extra dependency. |
| 177 | pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] { |
| 178 | const B: usize = 64; |
| 179 | let mut k = [0u8; B]; |
| 180 | if key.len() > B { |
| 181 | k[..32].copy_from_slice(&Sha256::digest(key)); |
| 182 | } else { |
| 183 | k[..key.len()].copy_from_slice(key); |
| 184 | } |
| 185 | let mut ipad = [0x36u8; B]; |
| 186 | let mut opad = [0x5cu8; B]; |
| 187 | for i in 0..B { |
| 188 | ipad[i] ^= k[i]; |
| 189 | opad[i] ^= k[i]; |
| 190 | } |
| 191 | let inner = Sha256::new() |
| 192 | .chain_update(ipad) |
| 193 | .chain_update(msg) |
| 194 | .finalize(); |
| 195 | let out = Sha256::new() |
| 196 | .chain_update(opad) |
| 197 | .chain_update(inner) |
| 198 | .finalize(); |
| 199 | let mut r = [0u8; 32]; |
| 200 | r.copy_from_slice(&out); |
| 201 | r |
| 202 | } |
| 203 | |
| 204 | /// Equal length and equal bytes, without an early exit. |
| 205 | fn ct_eq(a: &[u8], b: &[u8]) -> bool { |
| 206 | if a.len() != b.len() { |
| 207 | return false; |
| 208 | } |
| 209 | a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 |
| 210 | } |
| 211 | |
| 212 | fn unhex32(s: &str) -> Option<[u8; 32]> { |
| 213 | let s = s.trim_end_matches('\n'); |
| 214 | // Canonical form only: 64 lowercase hex digits. |
| 215 | if s.len() != 64 |
| 216 | || !s |
| 217 | .bytes() |
| 218 | .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) |
| 219 | { |
| 220 | return None; |
| 221 | } |
| 222 | let mut out = [0u8; 32]; |
| 223 | for (i, o) in out.iter_mut().enumerate() { |
| 224 | *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; |
| 225 | } |
| 226 | Some(out) |
| 227 | } |
| 228 | |
| 229 | /// Path of the desk key in a compose home. |
| 230 | pub fn desk_key_path(compose_dir: &Path) -> PathBuf { |
| 231 | compose_dir.join(DESK_KEY_FILE) |
| 232 | } |
| 233 | |
| 234 | /// The approval desk key. `Debug` shows only the id; the bytes are zeroed on drop. |
| 235 | pub struct DeskKey { |
| 236 | key: [u8; 32], |
| 237 | id: String, |
| 238 | } |
| 239 | |
| 240 | impl std::fmt::Debug for DeskKey { |
| 241 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 242 | write!(f, "DeskKey {{ id: {} }}", self.id) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | impl Drop for DeskKey { |
| 247 | fn drop(&mut self) { |
| 248 | for b in self.key.iter_mut() { |
| 249 | // SAFETY: a valid, aligned &mut u8. |
| 250 | unsafe { std::ptr::write_volatile(b, 0) }; |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | fn euid() -> u32 { |
| 256 | // SAFETY: geteuid has no preconditions and cannot fail. |
| 257 | unsafe { libc::geteuid() } |
| 258 | } |
| 259 | |
| 260 | impl DeskKey { |
| 261 | fn from_bytes(key: [u8; 32]) -> Self { |
| 262 | let id = hex(&Sha256::digest(key))[..16].to_string(); |
| 263 | Self { key, id } |
| 264 | } |
| 265 | |
| 266 | /// Load and check the key file (see the module rules). Errors are |
| 267 | /// `PROPOSAL_REFUSED NoDesk: ...` and never contain key bytes. |
| 268 | pub fn load(path: &Path) -> Result<Self, String> { |
| 269 | let nodesk = |why: String| refuse("NoDesk", format!("{}: {why}", path.display())); |
| 270 | let lmeta = std::fs::symlink_metadata(path).map_err(|e| nodesk(e.to_string()))?; |
| 271 | if lmeta.file_type().is_symlink() { |
| 272 | return Err(nodesk("is a symlink".into())); |
| 273 | } |
| 274 | let f = std::fs::OpenOptions::new() |
| 275 | .read(true) |
| 276 | .custom_flags(libc::O_NOFOLLOW) |
| 277 | .open(path) |
| 278 | .map_err(|e| nodesk(e.to_string()))?; |
| 279 | // Checks on the opened file, not the path (no swap in between). |
| 280 | let m = f.metadata().map_err(|e| nodesk(e.to_string()))?; |
| 281 | if !m.file_type().is_file() { |
| 282 | return Err(nodesk("not a regular file".into())); |
| 283 | } |
| 284 | if m.uid() != euid() { |
| 285 | return Err(nodesk(format!( |
| 286 | "owned by uid {}, not this process's uid {}", |
| 287 | m.uid(), |
| 288 | euid() |
| 289 | ))); |
| 290 | } |
| 291 | if m.mode() & 0o077 != 0 { |
| 292 | return Err(nodesk(format!( |
| 293 | "mode {:o} gives group or other access (must be 0600 or stricter)", |
| 294 | m.mode() & 0o777 |
| 295 | ))); |
| 296 | } |
| 297 | let mut s = String::new(); |
| 298 | f.take(256) |
| 299 | .read_to_string(&mut s) |
| 300 | .map_err(|e| nodesk(e.to_string()))?; |
| 301 | let key = unhex32(&s).ok_or_else(|| nodesk("not 64 hex digits".into()))?; |
| 302 | s.replace_range(.., &"0".repeat(s.len())); |
| 303 | Ok(Self::from_bytes(key)) |
| 304 | } |
| 305 | |
| 306 | /// Create a new key file (exclusive create, mode 0600, `O_NOFOLLOW`) from |
| 307 | /// /dev/urandom. Refuses when the file exists: rotation is delete + create |
| 308 | /// by the operator, never an overwrite here. |
| 309 | pub fn create(path: &Path) -> Result<Self, String> { |
| 310 | let mut key = [0u8; 32]; |
| 311 | std::fs::File::open("/dev/urandom") |
| 312 | .and_then(|mut r| r.read_exact(&mut key)) |
| 313 | .map_err(|e| format!("desk key: /dev/urandom: {e}"))?; |
| 314 | if let Some(parent) = path.parent() { |
| 315 | std::fs::create_dir_all(parent) |
| 316 | .map_err(|e| format!("desk key: {}: {e}", parent.display()))?; |
| 317 | } |
| 318 | let mut f = std::fs::OpenOptions::new() |
| 319 | .write(true) |
| 320 | .create_new(true) |
| 321 | .mode(0o600) |
| 322 | .custom_flags(libc::O_NOFOLLOW) |
| 323 | .open(path) |
| 324 | .map_err(|e| format!("desk key: create {}: {e}", path.display()))?; |
| 325 | // umask can only remove bits; set 0600 explicitly anyway. |
| 326 | f.set_permissions(std::fs::Permissions::from_mode(0o600)) |
| 327 | .and_then(|_| f.write_all(format!("{}\n", hex(&key)).as_bytes())) |
| 328 | .and_then(|_| f.sync_all()) |
| 329 | .map_err(|e| format!("desk key: write {}: {e}", path.display()))?; |
| 330 | Ok(Self::from_bytes(key)) |
| 331 | } |
| 332 | |
| 333 | /// First 16 hex digits of sha256(key): names the key, reveals nothing usable. |
| 334 | pub fn id(&self) -> &str { |
| 335 | &self.id |
| 336 | } |
| 337 | |
| 338 | /// The MAC (hex) the desk attaches to `id`'s binding. |
| 339 | pub fn mac(&self, id: &ApprovalIdentity) -> String { |
| 340 | hex(&hmac_sha256(&self.key, &binding_bytes(id))) |
| 341 | } |
| 342 | |
| 343 | /// Desk side: the MAC for a proposal under this key, for `workspace` |
| 344 | /// (canonicalised here as the daemon will). |
| 345 | pub fn sign(&self, p: &crate::approved::ApprovedProposal, workspace: &Path) -> String { |
| 346 | let ws = canonical_workspace(workspace).unwrap_or_else(|_| workspace.display().to_string()); |
| 347 | self.mac(&ApprovalIdentity::of(p, &ws, &self.id)) |
| 348 | } |
| 349 | |
| 350 | /// The MAC (hex) over the approval binding AND the bound requirements |
| 351 | /// (`p.requirements`, empty when None). A separate MAC so the identity |
| 352 | /// binding and its known-answer vector stay unchanged. |
| 353 | pub fn sign_requirements( |
| 354 | &self, |
| 355 | p: &crate::approved::ApprovedProposal, |
| 356 | workspace: &Path, |
| 357 | ) -> String { |
| 358 | let ws = canonical_workspace(workspace).unwrap_or_else(|_| workspace.display().to_string()); |
| 359 | let id = ApprovalIdentity::of(p, &ws, &self.id); |
| 360 | hex(&hmac_sha256( |
| 361 | &self.key, |
| 362 | &requirements_bytes( |
| 363 | &id, |
| 364 | p.requirements.as_deref(), |
| 365 | p.requirements_base.as_deref(), |
| 366 | ), |
| 367 | )) |
| 368 | } |
| 369 | |
| 370 | /// Desk side: set both MACs of `p` (the identity MAC and the requirements MAC). |
| 371 | pub fn seal(&self, p: &mut crate::approved::ApprovedProposal, workspace: &Path) { |
| 372 | p.approval_mac = self.sign(p, workspace); |
| 373 | p.requirements_mac = self.sign_requirements(p, workspace); |
| 374 | } |
| 375 | |
| 376 | /// Daemon side: Ok(identity) only when `p.approval_mac` is this key's MAC |
| 377 | /// over `p`'s binding; else `PROPOSAL_REFUSED Unauthenticated`. |
| 378 | pub fn authenticate( |
| 379 | &self, |
| 380 | p: &crate::approved::ApprovedProposal, |
| 381 | workspace: &Path, |
| 382 | ) -> Result<ApprovalIdentity, String> { |
| 383 | let ws = canonical_workspace(workspace).map_err(|e| refuse("Unauthenticated", e))?; |
| 384 | let id = ApprovalIdentity::of(p, &ws, &self.id); |
| 385 | let want = hmac_sha256(&self.key, &binding_bytes(&id)); |
| 386 | let got = unhex32(&p.approval_mac); |
| 387 | match got { |
| 388 | Some(g) if ct_eq(&g, &want) => { |
| 389 | let want_r = hmac_sha256( |
| 390 | &self.key, |
| 391 | &requirements_bytes( |
| 392 | &id, |
| 393 | p.requirements.as_deref(), |
| 394 | p.requirements_base.as_deref(), |
| 395 | ), |
| 396 | ); |
| 397 | match unhex32(&p.requirements_mac) { |
| 398 | Some(r) if ct_eq(&r, &want_r) => Ok(id), |
| 399 | _ => Err(refuse( |
| 400 | "Unauthenticated", |
| 401 | format!( |
| 402 | "requirements_mac is not the approval desk's (key {}) MAC over the bound requirements", |
| 403 | self.id |
| 404 | ), |
| 405 | )), |
| 406 | } |
| 407 | } |
| 408 | _ => Err(refuse( |
| 409 | "Unauthenticated", |
| 410 | format!( |
| 411 | "approval_mac is not the approval desk's (key {}) MAC over these fields", |
| 412 | self.id |
| 413 | ), |
| 414 | )), |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// Version tag of the `ComposeAuthorize` binding (sovereign-core #297). |
| 420 | pub const AUTHORIZE_BINDING_VERSION: &str = "aien.authorize.v1"; |
| 421 | |
| 422 | /// Everything one operator `ComposeAuthorize` covers. `path`, |
| 423 | /// `content_sha256` and `workspace` are the daemon's own commit-record values |
| 424 | /// on the verifying side; the signer computes the same from its report. |
| 425 | /// `nonce` makes each authorize unique: the daemon records it in the grant and |
| 426 | /// refuses a second grant for the same nonce. |
| 427 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 428 | pub struct AuthorizeBinding { |
| 429 | pub cx_promotion: u64, |
| 430 | pub proposal_sha256: String, |
| 431 | pub path: String, |
| 432 | pub content_sha256: String, |
| 433 | pub workspace: String, |
| 434 | pub approver: String, |
| 435 | pub constraints: Vec<u64>, |
| 436 | pub nonce: String, |
| 437 | pub desk_key_id: String, |
| 438 | } |
| 439 | |
| 440 | /// Canonical bytes of an authorize binding: a domain tag, then compact JSON |
| 441 | /// with sorted keys. The domain tag keeps it apart from every approval MAC. |
| 442 | pub fn authorize_binding_bytes(b: &AuthorizeBinding) -> Vec<u8> { |
| 443 | let mut m = Map::new(); |
| 444 | for (k, v) in [ |
| 445 | ("approver", &b.approver), |
| 446 | ("content_sha256", &b.content_sha256), |
| 447 | ("desk_key_id", &b.desk_key_id), |
| 448 | ("nonce", &b.nonce), |
| 449 | ("path", &b.path), |
| 450 | ("proposal_sha256", &b.proposal_sha256), |
| 451 | ("workspace", &b.workspace), |
| 452 | ] { |
| 453 | m.insert(k.into(), Value::String(v.clone())); |
| 454 | } |
| 455 | m.insert("cx_promotion".into(), Value::from(b.cx_promotion)); |
| 456 | m.insert("constraints".into(), Value::from(b.constraints.clone())); |
| 457 | m.insert("v".into(), Value::String(AUTHORIZE_BINDING_VERSION.into())); |
| 458 | let mut out = b"aien.authorize.mac\0".to_vec(); |
| 459 | out.extend(Value::Object(m).to_string().into_bytes()); |
| 460 | out |
| 461 | } |
| 462 | |
| 463 | impl DeskKey { |
| 464 | /// Desk side: the MAC (hex) for one authorize. `desk_key_id` is filled |
| 465 | /// from this key, whatever `b` carries. |
| 466 | pub fn sign_authorize(&self, b: &AuthorizeBinding) -> String { |
| 467 | let mut b = b.clone(); |
| 468 | b.desk_key_id = self.id.clone(); |
| 469 | hex(&hmac_sha256(&self.key, &authorize_binding_bytes(&b))) |
| 470 | } |
| 471 | |
| 472 | /// Daemon side: `Ok(())` only when `mac` is this key's MAC over `b`. |
| 473 | pub fn verify_authorize(&self, b: &AuthorizeBinding, mac: &str) -> Result<(), String> { |
| 474 | let mut b = b.clone(); |
| 475 | b.desk_key_id = self.id.clone(); |
| 476 | let want = hmac_sha256(&self.key, &authorize_binding_bytes(&b)); |
| 477 | match unhex32(mac) { |
| 478 | Some(g) if ct_eq(&g, &want) => Ok(()), |
| 479 | _ => Err(format!( |
| 480 | "authorize_mac is not the approval desk's (key {}) MAC over this proposal, path, content, workspace, approver and nonce", |
| 481 | self.id |
| 482 | )), |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /// Refuse when the compose home and the workspace overlap (either inside the |
| 488 | /// other): the model-facing tools read inside the workspace, and the desk key |
| 489 | /// and the journal must stay out of their reach. |
| 490 | pub fn check_confinement(compose_dir: &Path, workspace: &Path) -> Result<(), String> { |
| 491 | let c = std::fs::canonicalize(compose_dir).map_err(|e| { |
| 492 | refuse( |
| 493 | "Confinement", |
| 494 | format!("compose home {}: {e}", compose_dir.display()), |
| 495 | ) |
| 496 | })?; |
| 497 | let w = std::fs::canonicalize(workspace).map_err(|e| { |
| 498 | refuse( |
| 499 | "Confinement", |
| 500 | format!("workspace {}: {e}", workspace.display()), |
| 501 | ) |
| 502 | })?; |
| 503 | if c.starts_with(&w) || w.starts_with(&c) { |
| 504 | return Err(refuse( |
| 505 | "Confinement", |
| 506 | format!( |
| 507 | "compose home {} and workspace {} overlap; the approval desk refuses to run", |
| 508 | c.display(), |
| 509 | w.display() |
| 510 | ), |
| 511 | )); |
| 512 | } |
| 513 | Ok(()) |
| 514 | } |
| 515 | |
| 516 | #[cfg(test)] |
| 517 | mod tests { |
| 518 | use super::*; |
| 519 | |
| 520 | #[test] |
| 521 | fn hmac_matches_rfc4231_case_2() { |
| 522 | // RFC 4231 test case 2. |
| 523 | let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?"); |
| 524 | assert_eq!( |
| 525 | hex(&mac), |
| 526 | "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" |
| 527 | ); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn binding_is_sorted_compact_json() { |
| 532 | let id = ApprovalIdentity { |
| 533 | trace_id: "t".into(), |
| 534 | request_id: "r".into(), |
| 535 | approval_id: "a".into(), |
| 536 | approver: "p".into(), |
| 537 | path: "N.md".into(), |
| 538 | content_sha256: "c".into(), |
| 539 | approved_proposal_sha256: "s".into(), |
| 540 | desk_key_id: "k".into(), |
| 541 | workspace: "/w".into(), |
| 542 | }; |
| 543 | assert_eq!( |
| 544 | String::from_utf8(binding_bytes(&id)).unwrap(), |
| 545 | r#"{"approval_id":"a","approved_proposal_sha256":"s","approver":"p","content_sha256":"c","desk_key_id":"k","path":"N.md","request_id":"r","trace_id":"t","v":"aien.approval.v2","workspace":"/w"}"# |
| 546 | ); |
| 547 | } |
| 548 | |
| 549 | #[test] |
| 550 | fn ct_eq_and_unhex() { |
| 551 | assert!(ct_eq(b"ab", b"ab")); |
| 552 | assert!(!ct_eq(b"ab", b"ac")); |
| 553 | assert!(!ct_eq(b"ab", b"abc")); |
| 554 | assert!(unhex32(&"0".repeat(63)).is_none()); |
| 555 | assert!(unhex32(&"zz".repeat(32)).is_none()); |
| 556 | assert_eq!(unhex32(&"ff".repeat(32)), Some([0xff; 32])); |
| 557 | assert!(unhex32(&"FF".repeat(32)).is_none()); |
| 558 | assert!(unhex32(&format!(" {}", "f".repeat(63))).is_none()); |
| 559 | } |
| 560 | } |