Skip to main content

areev_core/
authz.rs

1//! Authorization primitives — principals, verbs, grants, and the host-side
2//! credential map.
3//!
4//! The model (design of record: `docs/cal-all-you-need-proposal.md`, D2–D4):
5//! *policy* (who may do what) lives **in the memory file** as grant grains,
6//! scoped per namespace; *credentials* (who is this caller) live host-side in
7//! a credential map that holds **no policy and no raw secrets** — tokens are
8//! referenced by SHA-256 or by env-var name. A memory with no grant grains
9//! grants nothing to anyone but the owner session (fail closed); the owner
10//! session — a local open with no principal asserted — is the implicit
11//! superuser, so the single-user path never meets any of this.
12//!
13//! This module is the shared vocabulary only. Building an [`AuthzSet`] from a
14//! file's grant grains is the store's job; enforcing it at dispatch is the
15//! facade's and the surfaces'.
16
17use crate::error::{AreevError, Result};
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20use std::fmt;
21
22/// The reserved namespace grant grains live in. The OMS 1.6 spec draft
23/// (§12.6) is the source of truth for this name — it follows the spec's
24/// `agent:identity` / `agent:recommendations` reserved-namespace precedent.
25pub const AUTHZ_NS: &str = "agent:authz";
26/// Reserved namespace for reproducible run and assembly manifests.
27pub const HARNESS_NS: &str = "agent:harness";
28/// Reserved namespace for grain attestations: one Observation per signed
29/// grain saying "author key K signed content hash H", linked to the grain by
30/// [`REL_ATTESTS`]. The signature is detached on purpose — the attested
31/// grain's bytes and address never change (`docs/grain-attestation-plan.md`).
32pub const ATTEST_NS: &str = "agent:attest";
33/// Relation from an attestation to the grain it attests.
34pub const REL_ATTESTS: &str = "mg:attests";
35/// Relation carried by a grant grain (OMS `PERMISSION` category).
36pub const REL_PERMITS: &str = "mg:permits";
37
38/// One operation class — the unit of granting, `GRANT SELECT`-style.
39///
40/// The string forms (`read`, `loop.review`, …) are the wire/CAL vocabulary;
41/// they appear in grant-grain objects and eventually in `GRANT` statements,
42/// so they are frozen once the spec ships.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum Verb {
45    Read,
46    Write,
47    Supersede,
48    Delete,
49    Erase,
50    LoopRun,
51    LoopReview,
52    LoopApply,
53    Admin,
54    /// D5 (governed-agents §6.8): start/resume/fork a workflow run —
55    /// Control-tier: it spends budgets and executes effects, so it is not
56    /// plain `write`.
57    RunExecute,
58    /// D5: answer a `requires_action` Client ask. This IS the approval
59    /// boundary — Control-tier, and the driver additionally refuses
60    /// responder == triggering principal on approval asks (separation of
61    /// duties, mirroring the loop's self-approval block).
62    RunRespond,
63    /// D5: cancel a run. Deliberately LOW-tier and broadly grantable — the
64    /// brake must never be blocked by missing privilege (the kill-switch
65    /// SLA depends on it).
66    RunCancel,
67}
68
69impl Verb {
70    /// Every verb, in canonical display order. Append-only, like error
71    /// codes: the string forms live in grant grains that replicate.
72    pub const ALL: [Verb; 12] = [
73        Verb::Read,
74        Verb::Write,
75        Verb::Supersede,
76        Verb::Delete,
77        Verb::Erase,
78        Verb::LoopRun,
79        Verb::LoopReview,
80        Verb::LoopApply,
81        Verb::Admin,
82        Verb::RunExecute,
83        Verb::RunRespond,
84        Verb::RunCancel,
85    ];
86
87    pub fn as_str(&self) -> &'static str {
88        match self {
89            Verb::Read => "read",
90            Verb::Write => "write",
91            Verb::Supersede => "supersede",
92            Verb::Delete => "delete",
93            Verb::Erase => "erase",
94            Verb::LoopRun => "loop.run",
95            Verb::LoopReview => "loop.review",
96            Verb::LoopApply => "loop.apply",
97            Verb::Admin => "admin",
98            Verb::RunExecute => "run.execute",
99            Verb::RunRespond => "run.respond",
100            Verb::RunCancel => "run.cancel",
101        }
102    }
103
104    pub fn parse(s: &str) -> Result<Verb> {
105        match s {
106            "read" => Ok(Verb::Read),
107            "write" => Ok(Verb::Write),
108            "supersede" => Ok(Verb::Supersede),
109            "delete" => Ok(Verb::Delete),
110            "erase" => Ok(Verb::Erase),
111            "loop.run" => Ok(Verb::LoopRun),
112            "loop.review" => Ok(Verb::LoopReview),
113            "loop.apply" => Ok(Verb::LoopApply),
114            "admin" => Ok(Verb::Admin),
115            "run.execute" => Ok(Verb::RunExecute),
116            "run.respond" => Ok(Verb::RunRespond),
117            "run.cancel" => Ok(Verb::RunCancel),
118            other => Err(AreevError::Validation(format!(
119                "unknown verb {other:?} — one of: read, write, supersede, delete, erase, \
120                 loop.run, loop.review, loop.apply, admin, run.execute, run.respond, \
121                 run.cancel"
122            ))),
123        }
124    }
125}
126
127impl fmt::Display for Verb {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(self.as_str())
130    }
131}
132
133/// A set of verbs allowed on a set of namespaces, inside one memory.
134/// The memory axis is implicit — a grant lives in the file it governs (D4).
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Grant {
137    pub verbs: Vec<Verb>,
138    /// Governed namespaces. `["*"]` (or empty) = every namespace.
139    pub namespaces: Vec<String>,
140}
141
142impl Grant {
143    pub fn covers(&self, verb: Verb, ns: &str) -> bool {
144        self.verbs.contains(&verb)
145            && (self.namespaces.is_empty()
146                || self.namespaces.iter().any(|n| n == "*" || n == ns))
147    }
148
149    /// The canonical object string a grant grain carries:
150    /// `read,write ON caller,shared` / `delete ON *`. Normative per OMS 1.6
151    /// §12.6: lowercase, comma-separated, **lexicographically sorted** verbs
152    /// and namespaces, duplicates dropped — so two implementations writing
153    /// the same grant produce the same content address.
154    pub fn to_object_string(&self) -> String {
155        let mut verbs: Vec<&str> = self.verbs.iter().map(Verb::as_str).collect();
156        verbs.sort_unstable();
157        verbs.dedup();
158        let ns = if self.namespaces.is_empty() {
159            "*".to_string()
160        } else {
161            let mut ns: Vec<&str> = self.namespaces.iter().map(String::as_str).collect();
162            ns.sort_unstable();
163            ns.dedup();
164            ns.join(",")
165        };
166        format!("{} ON {}", verbs.join(","), ns)
167    }
168
169    pub fn from_object_string(s: &str) -> Result<Grant> {
170        let (verbs_part, ns_part) = s.split_once(" ON ").ok_or_else(|| {
171            AreevError::Validation(format!(
172                "malformed grant object {s:?} — expected \"<verbs> ON <namespaces>\""
173            ))
174        })?;
175        let mut verbs = Vec::new();
176        for v in verbs_part.split(',') {
177            let v = Verb::parse(v.trim())?;
178            if !verbs.contains(&v) {
179                verbs.push(v);
180            }
181        }
182        if verbs.is_empty() {
183            return Err(AreevError::Validation(format!(
184                "grant object {s:?} names no verbs"
185            )));
186        }
187        let mut namespaces = Vec::new();
188        for n in ns_part.split(',') {
189            let n = n.trim();
190            if n.is_empty() {
191                return Err(AreevError::Validation(format!(
192                    "grant object {s:?} has an empty namespace"
193                )));
194            }
195            if !namespaces.iter().any(|x| x == n) {
196                namespaces.push(n.to_string());
197            }
198        }
199        Ok(Grant { verbs, namespaces })
200    }
201}
202
203/// The resolved rights of one session: a principal plus the grants that
204/// cover it. Every dispatch layer asks the same question:
205/// [`AuthzSet::check`].
206#[derive(Debug, Clone)]
207pub struct AuthzSet {
208    principal: String,
209    owner: bool,
210    grants: Vec<Grant>,
211}
212
213impl AuthzSet {
214    /// The implicit-superuser session: a local open with no principal
215    /// asserted (`root@localhost`). Every verb on every namespace.
216    pub fn owner(principal: impl Into<String>) -> Self {
217        AuthzSet {
218            principal: principal.into(),
219            owner: true,
220            grants: Vec::new(),
221        }
222    }
223
224    /// A restricted session: only what the grants cover. Zero grants =
225    /// nothing (fail closed).
226    pub fn restricted(principal: impl Into<String>, grants: Vec<Grant>) -> Self {
227        AuthzSet {
228            principal: principal.into(),
229            owner: false,
230            grants,
231        }
232    }
233
234    pub fn principal(&self) -> &str {
235        &self.principal
236    }
237
238    pub fn is_owner(&self) -> bool {
239        self.owner
240    }
241
242    pub fn allows(&self, verb: Verb, ns: &str) -> bool {
243        self.owner || self.grants.iter().any(|g| g.covers(verb, ns))
244    }
245
246    /// The one enforcement question. The refusal names the verb, the
247    /// resource, and the principal — the pieces a granting admin needs.
248    /// (Once `GRANT` parses, the message will also spell the statement that
249    /// fixes it — not before, to avoid pointing at unshipped syntax.)
250    pub fn check(&self, verb: Verb, ns: &str) -> Result<()> {
251        if self.allows(verb, ns) {
252            return Ok(());
253        }
254        Err(AreevError::AuthzDenied(format!(
255            "principal {} lacks {verb} on namespace {ns:?}",
256            self.principal
257        )))
258    }
259}
260
261/// The observer kind a principal label implies (`"agent"` / `"human"`),
262/// used for audit stamping wherever no credential record declares one. The
263/// answer always derives from the host-held label — never from statement or
264/// request text, which must not be able to claim humanity.
265pub fn observer_kind(principal: &str) -> &'static str {
266    for prefix in ["agent:", "bot:", "job:", "svc:", "engine:"] {
267        if principal.starts_with(prefix) {
268            return "agent";
269        }
270    }
271    "human"
272}
273
274/// A verifiable, non-disclosing reference to an erased identity, for audit
275/// targets: the first 16 hex of SHA-256 over the identity string.
276///
277/// **Why not the identity itself.** An audit grain is immutable, replicates,
278/// and lands in archives. Writing the raw identifier into it re-introduces
279/// exactly the reference the erasure just removed — the erased subject stays
280/// recallable from `agent:authz` forever, un-erasable by the subject
281/// selector (which never matches `subject:<id> ns:<ns>` as a partition key),
282/// and travels into every bundle and segment. That is a right-to-erasure
283/// failure hiding inside the accountability record.
284///
285/// A fingerprint keeps both properties: given a candidate identity anyone
286/// can recompute the digest and **verify** that a specific audit record is
287/// about that person (answering "prove you erased me"), but the log cannot
288/// be mined to enumerate who was erased. The human-readable reference — the
289/// ticket or request number — belongs in BECAUSE, which the operator
290/// controls and which names a *request*, not a data subject.
291///
292/// Truncated to 64 bits of digest: this is a correlation handle, not a
293/// security boundary (identity strings are low-entropy, so a determined
294/// attacker with a candidate list can always confirm guesses — which is the
295/// same property that makes verification work).
296pub fn subject_fingerprint(identity: &str) -> String {
297    let digest = Sha256::digest(identity.as_bytes());
298    hex_lower(&digest[..8])
299}
300
301/// Constant-time byte comparison — avoids leaking a bearer token through
302/// response timing. A length mismatch fails fast (token length is not secret).
303fn ct_eq(a: &[u8], b: &[u8]) -> bool {
304    if a.len() != b.len() {
305        return false;
306    }
307    let mut diff = 0u8;
308    for (x, y) in a.iter().zip(b.iter()) {
309        diff |= x ^ y;
310    }
311    diff == 0
312}
313
314fn hex_lower(bytes: &[u8]) -> String {
315    const HEX: &[u8; 16] = b"0123456789abcdef";
316    let mut out = String::with_capacity(bytes.len() * 2);
317    for b in bytes {
318        out.push(HEX[(b >> 4) as usize] as char);
319        out.push(HEX[(b & 0x0f) as usize] as char);
320    }
321    out
322}
323
324/// Build the Tier-2 audit Observation for one destructive execution — the
325/// accountability record (GDPR Art. 5(2)/30) that `areev audit export`
326/// emits.
327///
328/// **One builder, every surface.** CAL destruction, the CLI's
329/// `forget-subject`/`purge-older-than`, and anything else that destroys
330/// must produce byte-identical audit shapes, or the evidence export becomes
331/// a union of dialects. Note the deliberate asymmetry with REQ-ERASE-5: the
332/// *engine* (`Areev::forget_subject`) still writes no audit grain of its
333/// own — a library caller owns its own logging — but the surfaces a human
334/// or agent actually invokes are hosts, and hosts audit.
335///
336/// `target` describes what was destroyed in the surface's own vocabulary:
337/// `hash:<hex>` (a content address of already-deleted content — not identity
338/// material), `subject:<fp> ns:<ns>` where `<fp>` is a
339/// [`subject_fingerprint`] (**never** the raw identity — see that function
340/// for why), or `older_than:<n>d ns:<ns>` (an age, no identity at all).
341pub fn audit_observation(
342    principal: &str,
343    verb: &str,
344    target: &str,
345    because: Option<&str>,
346    count: usize,
347    now_ms: i64,
348) -> crate::types::Observation {
349    use std::sync::atomic::{AtomicU64, Ordering};
350    // Process-static: two identical erasures in the same millisecond must
351    // stay two records, not collapse into one content address.
352    static AUDIT_SEQ: AtomicU64 = AtomicU64::new(0);
353    let mut obs = crate::types::Observation {
354        observer_id: principal.to_string(),
355        observer_type: observer_kind(principal).to_string(),
356        subject: Some(target.to_string()),
357        object: Some(verb.to_string()),
358        observer_model: None,
359        frame_id: Some(format!(
360            "tier2:{now_ms}:{}",
361            AUDIT_SEQ.fetch_add(1, Ordering::Relaxed)
362        )),
363        sync_group: None,
364        observation_mode: None,
365        observation_scope: None,
366        compression_ratio: None,
367        common: Default::default(),
368    };
369    obs.common.namespace = Some(AUTHZ_NS.to_string());
370    obs.common.created_at = Some(now_ms);
371    obs.common.context = Some(serde_json::json!({
372        "audit": "tier2",
373        "verb": verb,
374        "target": target,
375        "because": because.unwrap_or(""),
376        "grains_erased": count,
377        // Names the scheme so a verifier knows how to recompute a subject
378        // fingerprint years later, without reading our source.
379        "subject_ref": "sha256-64/hex",
380    }));
381    obs
382}
383
384/// The prefix every Areev-minted bearer token carries.
385///
386/// Three jobs, all of which a bare random string cannot do: secret scanners
387/// (GitHub's, GitLab's, and every commercial one) can be taught a single
388/// regex for it; a human who finds one in a paste knows what it opens and
389/// who to tell; and the server can reject an obviously-malformed credential
390/// before it reaches the constant-time scan. Modelled on GitHub's `ghp_`.
391///
392/// It is deliberately NOT required — an operator's existing token keeps
393/// working — but [`token_is_minted`] is what the startup banner uses to warn
394/// that a credential's entropy is unknown.
395pub const TOKEN_PREFIX: &str = "areev_pat_";
396
397/// Whether `token` has the shape [`encode_token_body`] produces: the prefix plus at
398/// least 32 base32 characters (160 bits — the floor below which a digest in
399/// a shared file starts being worth grinding).
400///
401/// A `true` here means the entropy is known-good *because Areev generated
402/// it*. It is not a security check — an attacker can spell the prefix — it
403/// is an operator-hygiene signal, which is why nothing refuses on a `false`.
404pub fn token_is_minted(token: &str) -> bool {
405    match token.strip_prefix(TOKEN_PREFIX) {
406        Some(body) => {
407            body.len() >= 32 && body.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
408        }
409        None => false,
410    }
411}
412
413/// Render 32 random bytes as the token body. Split out from generation so
414/// the CSPRNG stays in the host that mints (the CLI) while the *format* —
415/// the thing every reader must agree on — lives here with its validator.
416///
417/// Base32-ish over `[a-z0-9]`: case-insensitive to transcribe, safe in a URL,
418/// a shell word, and a JSON string without escaping.
419pub fn encode_token_body(bytes: &[u8; 32]) -> String {
420    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
421    // 32 bytes = 256 bits → 51 full 5-bit groups (255 bits); the last bit is
422    // dropped rather than padded, leaving 255 bits of entropy in 51 chars.
423    let mut out = String::with_capacity(51);
424    let mut acc: u16 = 0;
425    let mut bits = 0u8;
426    for &b in bytes {
427        acc = (acc << 8) | b as u16;
428        bits += 8;
429        while bits >= 5 {
430            bits -= 5;
431            let idx = ((acc >> bits) & 0x1f) as usize;
432            out.push(ALPHABET[idx] as char);
433        }
434    }
435    out
436}
437
438/// The host-side credential map (`areev-auth.json`): tokens → principal
439/// names, nothing else. No verbs, no namespaces, no raw secrets — a token is
440/// referenced by its SHA-256 or by the env var that holds it, so the file is
441/// inert if stolen or synced.
442#[derive(Debug, Serialize, Deserialize)]
443#[serde(deny_unknown_fields)]
444pub struct CredentialMap {
445    pub version: u32,
446    #[serde(default)]
447    pub tokens: Vec<CredentialEntry>,
448    /// IdP group → principal (A2). The same job the `tokens` list already
449    /// does — map an external identifier onto a principal the FILE grants
450    /// rights to — for the axis SSO actually scales on: without it every
451    /// person behind the proxy needs their own grant grain, which is the
452    /// administrative burden SSO exists to remove.
453    ///
454    /// A group-derived principal is a ROLE, not a person. That is why it can
455    /// never answer a HITL approval, even under `--sso-approvals allow`:
456    /// "someone in engineering approved this" is not an audit record.
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub groups: Option<std::collections::BTreeMap<String, String>>,
459}
460
461#[derive(Debug, Serialize, Deserialize)]
462#[serde(deny_unknown_fields)]
463pub struct CredentialEntry {
464    /// Stable, operator-chosen name for THIS credential — not the principal.
465    ///
466    /// Two tokens for one principal (a laptop and a CI runner, or an old and
467    /// a new one mid-rotation) are otherwise indistinguishable: revoking one
468    /// means identifying a line by its digest, and no log line can ever name
469    /// which credential acted. The id appears on successful auth and in
470    /// `whoami`; it is **never** echoed on a failure, because a refused
471    /// secret must not confirm which credential it nearly matched.
472    ///
473    /// **Optional, with a derived fallback** ([`CredentialEntry::id`]) — an
474    /// `areev-auth.json` written before ids existed must keep working across
475    /// an upgrade. A console that refuses to start because a new field is
476    /// missing is a worse security outcome than an ugly default: it gets
477    /// fixed by rolling back.
478    #[serde(default, skip_serializing_if = "Option::is_none")]
479    pub id: Option<String>,
480    /// Free-text note for humans (`"CI runner, rotates quarterly"`).
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub label: Option<String>,
483    /// Lowercase hex SHA-256 of the bearer token.
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub sha256: Option<String>,
486    /// Name of the environment variable holding the bearer token.
487    #[serde(default, skip_serializing_if = "Option::is_none")]
488    pub env: Option<String>,
489    /// The principal this credential authenticates as.
490    pub principal: String,
491    /// Per-memory scope (the enterprise plane's rule): when set, this
492    /// credential authenticates ONLY on services whose memory label is in
493    /// the list — one auth file shared across server instances, each token
494    /// reaching only its memories. `None` = every memory (the common
495    /// single-memory deployment).
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub memories: Option<Vec<String>>,
498    /// Optional expiry (ISO-8601; `"2026-12-31T23:59:59Z"`). Past it, the
499    /// credential authenticates nobody — indistinguishably from an unknown
500    /// token, so an expired credential cannot be used to probe which ids
501    /// exist.
502    ///
503    /// Deliberately OPTIONAL. A mandatory lifetime would break a homelab
504    /// console at 3am for a threat model it does not have; `areev auth mint
505    /// --expires 90d` is the documented path for the deployments that want
506    /// one, and the startup banner names credentials expiring within 14 days.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub expires_at: Option<String>,
509}
510
511impl CredentialEntry {
512    /// This credential's effective id: the operator's `id` when set, else a
513    /// stable one derived from what identifies the credential anyway.
514    ///
515    /// Derivation is deliberately *not* positional (`token-0`, `token-1`):
516    /// an index shifts when an unrelated line is added, so `areev auth
517    /// revoke --id token-1` would eventually revoke the wrong credential —
518    /// the exact failure an id exists to prevent. A digest prefix and an
519    /// env-var name are both properties of the credential itself, so they
520    /// survive reordering.
521    pub fn id(&self) -> String {
522        match (self.id.as_deref(), &self.sha256, &self.env) {
523            (Some(id), _, _) => id.to_string(),
524            // Not a secret: it is a prefix of a digest the file already
525            // publishes in full, one line up.
526            (None, Some(h), _) => h.chars().take(8).collect::<String>().to_ascii_lowercase(),
527            (None, None, Some(var)) => format!("env:{var}"),
528            (None, None, None) => "unnamed".to_string(),
529        }
530    }
531
532    /// Expiry as epoch ms, or `None` when the entry never expires.
533    ///
534    /// An `expires_at` that does not parse is treated as **already expired**
535    /// (`Some(i64::MIN)`), not as "no expiry". `from_json` refuses such a map
536    /// outright so this should be unreachable — but if it ever is reached,
537    /// failing closed is the only safe reading of a lifetime nobody can
538    /// interpret.
539    fn expires_at_ms(&self) -> Option<i64> {
540        self.expires_at
541            .as_deref()
542            .map(|s| crate::time::iso8601_to_ms(s).unwrap_or(i64::MIN))
543    }
544
545    /// Whether this credential is expired at `now_ms`.
546    pub fn is_expired_at(&self, now_ms: i64) -> bool {
547        self.expires_at_ms().is_some_and(|exp| now_ms >= exp)
548    }
549}
550
551impl CredentialMap {
552    /// Parse and validate. Fail closed: unknown keys, a bad version, an
553    /// entry with both or neither credential form, or a malformed digest all
554    /// refuse the whole map.
555    pub fn from_json(s: &str) -> Result<CredentialMap> {
556        let map: CredentialMap = serde_json::from_str(s)
557            .map_err(|e| AreevError::AuthzConfigInvalid(format!("credential map: {e}")))?;
558        if map.version != 1 {
559            return Err(AreevError::AuthzConfigInvalid(format!(
560                "credential map: unsupported version {} (expected 1)",
561                map.version
562            )));
563        }
564        let mut seen_ids: Vec<String> = Vec::with_capacity(map.tokens.len());
565        for (i, t) in map.tokens.iter().enumerate() {
566            if t.principal.trim().is_empty() {
567                return Err(AreevError::AuthzConfigInvalid(format!(
568                    "credential map: entry {i} has an empty principal"
569                )));
570            }
571            // The id is what makes one credential revocable and one log line
572            // attributable. It may be derived, but it must be legible and
573            // unique — a duplicate makes `areev auth revoke --id` ambiguous,
574            // which is the one thing an id exists to prevent.
575            if let Some(explicit) = t.id.as_deref() {
576                if explicit.trim().is_empty() {
577                    return Err(AreevError::AuthzConfigInvalid(format!(
578                        "credential map: entry {i} ({}) has an empty \"id\" — omit the field \
579                         to get a derived one, or give it a name",
580                        t.principal
581                    )));
582                }
583                if !explicit
584                    .bytes()
585                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')
586                {
587                    return Err(AreevError::AuthzConfigInvalid(format!(
588                        "credential map: entry {i} id {explicit:?} must be alphanumeric with \
589                         -, _ or . (it is printed in logs and passed to `areev auth revoke`)"
590                    )));
591                }
592            }
593            let id = t.id();
594            if seen_ids.contains(&id) {
595                return Err(AreevError::AuthzConfigInvalid(format!(
596                    "credential map: duplicate id {id:?} — revoking it would be ambiguous, \
597                     which is the one thing an id exists to prevent"
598                )));
599            }
600            seen_ids.push(id.clone());
601            // An unparseable lifetime is refused at LOAD, not silently
602            // treated as "never expires" — the failure mode of a typo'd
603            // expiry must be a console that will not start, never a
604            // credential that outlives its intended window.
605            if let Some(raw) = &t.expires_at {
606                if crate::time::iso8601_to_ms(raw).is_none() {
607                    return Err(AreevError::AuthzConfigInvalid(format!(
608                        "credential map: entry {i} ({id}) has an unparseable \"expires_at\" \
609                         {raw:?} — expected ISO-8601, e.g. \"2026-12-31T23:59:59Z\""
610                    )));
611                }
612            }
613            match (&t.sha256, &t.env) {
614                (Some(_), Some(_)) | (None, None) => {
615                    return Err(AreevError::AuthzConfigInvalid(format!(
616                        "credential map: entry {i} ({}) must have exactly one of \
617                         \"sha256\" or \"env\"",
618                        t.principal
619                    )));
620                }
621                (Some(h), None) => {
622                    if h.len() != 64 || !h.chars().all(|c| c.is_ascii_hexdigit()) {
623                        return Err(AreevError::AuthzConfigInvalid(format!(
624                            "credential map: entry {i} ({}) sha256 must be 64 hex chars",
625                            t.principal
626                        )));
627                    }
628                }
629                (None, Some(v)) => {
630                    if v.trim().is_empty() {
631                        return Err(AreevError::AuthzConfigInvalid(format!(
632                            "credential map: entry {i} ({}) has an empty \"env\" variable name",
633                            t.principal
634                        )));
635                    }
636                }
637            }
638            if let Some(memories) = &t.memories {
639                if memories.is_empty() || memories.iter().any(|m| m.trim().is_empty()) {
640                    return Err(AreevError::AuthzConfigInvalid(format!(
641                        "credential map: entry {i} ({}) has an empty \"memories\" \
642                         scope — omit the field to grant every memory",
643                        t.principal
644                    )));
645                }
646            }
647        }
648        Ok(map)
649    }
650
651    /// Resolve a presented bearer token to its principal. The error carries
652    /// no part of the token — a refused secret must not leak into logs.
653    ///
654    /// Expiry is evaluated against the system clock; [`resolve_at`] takes the
655    /// instant explicitly for tests.
656    ///
657    /// [`resolve_at`]: Self::resolve_at
658    pub fn resolve(&self, presented: &str) -> Result<&str> {
659        self.resolve_at(presented, crate::time::now_ms())
660    }
661
662    /// [`resolve`](Self::resolve) at an explicit instant.
663    pub fn resolve_at(&self, presented: &str, now_ms: i64) -> Result<&str> {
664        self.entry_at(presented, now_ms).map(|t| t.principal.as_str())
665    }
666
667    /// The matching, unexpired entry for `presented` — the shared core of
668    /// every resolve path, so expiry and the empty-token rule cannot drift
669    /// between them.
670    fn entry_at(&self, presented: &str, now_ms: i64) -> Result<&CredentialEntry> {
671        // An empty presented token can never authenticate. Without this, an
672        // env-referenced credential whose variable is exported *empty*
673        // (`Environment=AREEV_BOT_TOKEN=` in a unit file, `export VAR=` in a
674        // wrapper) matches the empty string an `Authorization: Bearer `
675        // header parses to, and every caller becomes that principal.
676        if presented.is_empty() {
677            return Err(AreevError::AuthzTokenUnrecognized);
678        }
679        let digest = hex::encode(Sha256::digest(presented.as_bytes()));
680        // Constant-shape scan: every entry is examined whether or not an
681        // earlier one matched, so an EXPIRED credential is not even
682        // timing-distinguishable from an unknown one. (This is why expiry is
683        // filtered after the scan rather than short-circuiting inside it.)
684        let mut found: Option<&CredentialEntry> = None;
685        for t in &self.tokens {
686            let matched = match (&t.sha256, &t.env) {
687                (Some(h), None) => h.eq_ignore_ascii_case(&digest),
688                // The env var must actually hold a secret — an unset or
689                // empty variable authenticates nobody.
690                (None, Some(var)) => std::env::var(var)
691                    .is_ok_and(|v| !v.trim().is_empty() && ct_eq(v.as_bytes(), presented.as_bytes())),
692                _ => false,
693            };
694            if matched && found.is_none() {
695                found = Some(t);
696            }
697        }
698        match found {
699            Some(t) if !t.is_expired_at(now_ms) => Ok(t),
700            // Expired resolves exactly like unknown: same error, no mention
701            // of the id, so a stale credential cannot be used to enumerate
702            // which ids the map holds.
703            _ => Err(AreevError::AuthzTokenUnrecognized),
704        }
705    }
706
707    /// The credential id that authenticated `presented`, for the audit/log
708    /// line on a SUCCESSFUL auth. Never call this on a failure path.
709    pub fn resolve_id_at(&self, presented: &str, now_ms: i64) -> Option<String> {
710        self.entry_at(presented, now_ms).ok().map(|t| t.id())
711    }
712
713    /// Resolve a token FOR ONE MEMORY: like [`resolve`](Self::resolve), but
714    /// a credential carrying a `memories` scope only authenticates when
715    /// `memory` is listed. The refusal is indistinguishable from an unknown
716    /// token — a scoped credential must not confirm which memories exist.
717    pub fn resolve_for_memory(&self, presented: &str, memory: &str) -> Result<&str> {
718        self.resolve_for_memory_at(presented, memory, crate::time::now_ms())
719    }
720
721    /// [`resolve_for_memory`](Self::resolve_for_memory) at an explicit
722    /// instant.
723    pub fn resolve_for_memory_at(
724        &self,
725        presented: &str,
726        memory: &str,
727        now_ms: i64,
728    ) -> Result<&str> {
729        // Shares `entry_at` so the empty-token rule, the constant-shape scan
730        // and expiry cannot drift between the two resolve paths — the bug
731        // class where one caller honors an expiry the other ignores.
732        let t = self.entry_at(presented, now_ms)?;
733        match &t.memories {
734            Some(list) if !list.iter().any(|m| m == memory) => {
735                Err(AreevError::AuthzTokenUnrecognized)
736            }
737            _ => Ok(&t.principal),
738        }
739    }
740
741    /// The credential id that authenticated `presented` on `memory`, for the
742    /// success log line. `None` on any refusal.
743    pub fn resolve_id_for_memory_at(
744        &self,
745        presented: &str,
746        memory: &str,
747        now_ms: i64,
748    ) -> Option<String> {
749        let t = self.entry_at(presented, now_ms).ok()?;
750        match &t.memories {
751            Some(list) if !list.iter().any(|m| m == memory) => None,
752            _ => Some(t.id()),
753        }
754    }
755
756    /// Credentials expiring within `window_ms` of `now_ms` (and those already
757    /// expired), for the startup banner. Returns `(id, expires_at)` pairs.
758    ///
759    /// A console that only reports an expiry at the moment it starts refusing
760    /// is a console that reports it during an incident.
761    pub fn expiring_within(&self, now_ms: i64, window_ms: i64) -> Vec<(String, String)> {
762        self.tokens
763            .iter()
764            .filter_map(|t| {
765                let raw = t.expires_at.as_deref()?;
766                let exp = crate::time::iso8601_to_ms(raw)?;
767                (exp <= now_ms + window_ms).then_some((t.id(), raw.to_string()))
768            })
769            .collect()
770    }
771
772    /// The principal an IdP group maps to, if any (A2).
773    ///
774    /// Group names are compared case-insensitively: directories are
775    /// inconsistent about the case they emit (`Engineering` vs
776    /// `engineering`), and a mapping that silently misses because of it
777    /// fails *open* into whatever the identity alone was granted — which is
778    /// the wrong direction for an authorization lookup to be sloppy in.
779    pub fn principal_for_group(&self, group: &str) -> Option<&str> {
780        let g = group.trim();
781        self.groups.as_ref()?.iter().find_map(|(k, v)| {
782            k.eq_ignore_ascii_case(g).then_some(v.as_str())
783        })
784    }
785
786    /// Whether any credential authenticates as this principal — surfaces
787    /// that require a *known* principal name use this to refuse typos early.
788    pub fn knows_principal(&self, principal: &str) -> Result<()> {
789        if self.tokens.iter().any(|t| t.principal == principal) {
790            return Ok(());
791        }
792        Err(AreevError::AuthzUnknownPrincipal(principal.to_string()))
793    }
794}
795
796#[cfg(test)]
797mod tests {
798    use super::*;
799
800    #[test]
801    fn verbs_roundtrip_their_string_forms() {
802        for v in Verb::ALL {
803            assert_eq!(Verb::parse(v.as_str()).unwrap(), v);
804        }
805        assert!(Verb::parse("loop-run").is_err());
806        assert!(Verb::parse("").is_err());
807    }
808
809    #[test]
810    fn an_empty_env_credential_authenticates_nobody() {
811        // The variable name itself must be non-empty…
812        assert!(CredentialMap::from_json(
813            r#"{"version":1,"tokens":[{"env":"  ","principal":"agent:writer"}]}"#
814        )
815        .is_err());
816
817        // …and a variable exported EMPTY must not match the empty string an
818        // `Authorization: Bearer ` header parses to. Otherwise every caller
819        // becomes `agent:writer`.
820        std::env::set_var("AREEV_TEST_EMPTY_TOK", "");
821        let map = CredentialMap::from_json(
822            r#"{"version":1,"tokens":[{"env":"AREEV_TEST_EMPTY_TOK","principal":"agent:writer"}]}"#,
823        )
824        .unwrap();
825        assert!(map.resolve("").is_err(), "empty bearer must not authenticate");
826        assert!(map.resolve("anything").is_err());
827
828        // Unset behaves the same.
829        std::env::remove_var("AREEV_TEST_EMPTY_TOK");
830        assert!(map.resolve("").is_err());
831    }
832
833    #[test]
834    fn grant_object_string_roundtrips() {
835        let g = Grant {
836            verbs: vec![Verb::Read, Verb::Write],
837            namespaces: vec!["caller".into(), "shared".into()],
838        };
839        let s = g.to_object_string();
840        assert_eq!(s, "read,write ON caller,shared");
841        assert_eq!(Grant::from_object_string(&s).unwrap(), g);
842
843        let all = Grant { verbs: vec![Verb::Erase], namespaces: vec!["*".into()] };
844        assert_eq!(all.to_object_string(), "erase ON *");
845        assert_eq!(
846            Grant::from_object_string("erase ON *").unwrap().namespaces,
847            vec!["*".to_string()]
848        );
849
850        assert!(Grant::from_object_string("read caller").is_err());
851        assert!(Grant::from_object_string(" ON x").is_err());
852        assert!(Grant::from_object_string("read ON ").is_err());
853    }
854
855    #[test]
856    fn owner_allows_everything_restricted_fails_closed() {
857        let owner = AuthzSet::owner("user:local");
858        for v in Verb::ALL {
859            assert!(owner.check(v, "any-ns").is_ok());
860        }
861
862        let none = AuthzSet::restricted("agent:bot", Vec::new());
863        for v in Verb::ALL {
864            assert!(none.check(v, "caller").is_err(), "{v} must be refused");
865        }
866    }
867
868    #[test]
869    fn grants_cover_exactly_what_they_say() {
870        let set = AuthzSet::restricted(
871            "agent:bot",
872            vec![Grant {
873                verbs: vec![Verb::Read, Verb::Write],
874                namespaces: vec!["caller".into()],
875            }],
876        );
877        assert!(set.check(Verb::Read, "caller").is_ok());
878        assert!(set.check(Verb::Write, "caller").is_ok());
879        assert!(set.check(Verb::Write, "shared").is_err());
880        assert!(set.check(Verb::Delete, "caller").is_err());
881
882        let star = AuthzSet::restricted(
883            "job:sweep",
884            vec![Grant { verbs: vec![Verb::Erase], namespaces: vec!["*".into()] }],
885        );
886        assert!(star.check(Verb::Erase, "anything").is_ok());
887    }
888
889    #[test]
890    fn refusal_names_verb_namespace_and_principal_with_the_aut_code() {
891        let set = AuthzSet::restricted("agent:bot", Vec::new());
892        let err = set.check(Verb::Delete, "caller").unwrap_err();
893        assert_eq!(err.code(), "AUT-E001");
894        let msg = err.to_string();
895        for needle in ["delete", "caller", "agent:bot"] {
896            assert!(msg.contains(needle), "{msg:?} must name {needle}");
897        }
898    }
899
900    const MAP: &str = r#"{
901        "version": 1,
902        "tokens": [
903            { "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
904              "principal": "user:anna" },
905            { "env": "AREEV_TEST_BOT_TOKEN", "principal": "agent:bot" }
906        ]
907    }"#;
908
909    #[test]
910    fn credential_map_loads_and_resolves_by_sha256() {
911        let map = CredentialMap::from_json(MAP).unwrap();
912        // sha256("test") — the digest above.
913        assert_eq!(map.resolve("test").unwrap(), "user:anna");
914        assert!(map.knows_principal("user:anna").is_ok());
915        assert_eq!(
916            map.knows_principal("user:nobody").unwrap_err().code(),
917            "AUT-E002"
918        );
919    }
920
921    #[test]
922    fn credential_map_resolves_by_env_var() {
923        let map = CredentialMap::from_json(MAP).unwrap();
924        // Unique var name per test binary run; set before resolve.
925        std::env::set_var("AREEV_TEST_BOT_TOKEN", "s3cret");
926        assert_eq!(map.resolve("s3cret").unwrap(), "agent:bot");
927        std::env::remove_var("AREEV_TEST_BOT_TOKEN");
928    }
929
930    #[test]
931    fn unrecognized_token_error_never_echoes_the_secret() {
932        let map = CredentialMap::from_json(MAP).unwrap();
933        let err = map.resolve("super-secret-value").unwrap_err();
934        assert_eq!(err.code(), "AUT-E004");
935        assert!(!err.to_string().contains("super-secret-value"));
936    }
937
938    #[test]
939    fn credential_map_fails_closed() {
940        // Unknown key.
941        assert_eq!(
942            CredentialMap::from_json(r#"{"version":1,"tokens":[],"roles":{}}"#)
943                .unwrap_err()
944                .code(),
945            "AUT-E003"
946        );
947        // Wrong version.
948        assert!(CredentialMap::from_json(r#"{"version":2,"tokens":[]}"#).is_err());
949        // Both credential forms.
950        assert!(CredentialMap::from_json(
951            r#"{"version":1,"tokens":[{"sha256":"00","env":"X","principal":"p"}]}"#
952        )
953        .is_err());
954        // Neither form.
955        assert!(CredentialMap::from_json(
956            r#"{"version":1,"tokens":[{"principal":"p"}]}"#
957        )
958        .is_err());
959        // Malformed digest.
960        assert!(CredentialMap::from_json(
961            r#"{"version":1,"tokens":[{"sha256":"zz","principal":"p"}]}"#
962        )
963        .is_err());
964        // Empty principal.
965        assert!(CredentialMap::from_json(
966            r#"{"version":1,"tokens":[{"env":"X","principal":"  "}]}"#
967        )
968        .is_err());
969        // [A1] An id that cannot be printed or passed to `revoke`.
970        assert!(CredentialMap::from_json(
971            r#"{"version":1,"tokens":[{"env":"X","principal":"p","id":"has space"}]}"#
972        )
973        .is_err());
974        // [A1] Duplicate ids make revocation ambiguous.
975        assert!(CredentialMap::from_json(
976            r#"{"version":1,"tokens":[
977                {"env":"X","principal":"p","id":"dup"},
978                {"env":"Y","principal":"q","id":"dup"}
979            ]}"#
980        )
981        .is_err());
982        // [A1] A typo'd lifetime must refuse the map, never read as "never
983        // expires" — the failure mode of a bad expiry is a console that will
984        // not start, not a credential that outlives its window.
985        assert!(CredentialMap::from_json(
986            r#"{"version":1,"tokens":[{"env":"X","principal":"p","expires_at":"soon"}]}"#
987        )
988        .is_err());
989    }
990
991    /// [A1] A map written before ids existed still loads — and every entry
992    /// still gets a stable, non-positional id.
993    #[test]
994    fn pre_id_maps_load_and_derive_stable_ids() {
995        let map = CredentialMap::from_json(
996            r#"{"version":1,"tokens":[
997                {"sha256":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
998                 "principal":"user:a"},
999                {"env":"AREEV_LEGACY_TOK","principal":"user:b"}
1000            ]}"#,
1001        )
1002        .unwrap();
1003        assert_eq!(map.tokens[0].id(), "9f86d081");
1004        assert_eq!(map.tokens[1].id(), "env:AREEV_LEGACY_TOK");
1005
1006        // Non-positional: prepending an entry does not renumber the others,
1007        // which is what makes `revoke --id` safe.
1008        let grown = CredentialMap::from_json(
1009            r#"{"version":1,"tokens":[
1010                {"env":"AREEV_NEW_TOK","principal":"user:c"},
1011                {"sha256":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
1012                 "principal":"user:a"}
1013            ]}"#,
1014        )
1015        .unwrap();
1016        assert_eq!(grown.tokens[1].id(), "9f86d081");
1017    }
1018
1019    /// [A1] Expiry refuses indistinguishably from an unknown token, and one
1020    /// credential expiring leaves its principal's others alone.
1021    #[test]
1022    fn expired_credentials_refuse_like_unknown_ones() {
1023        let map = CredentialMap::from_json(
1024            r#"{"version":1,"tokens":[
1025                {"sha256":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
1026                 "principal":"user:a","id":"old","expires_at":"2026-01-01T00:00:00Z"},
1027                {"sha256":"fd61a03af4f77d870fc21e05e7e80678095c92d808cfb3b5c279ee04c74aca13",
1028                 "principal":"user:a","id":"new"}
1029            ]}"#,
1030        )
1031        .unwrap();
1032        let before = crate::time::iso8601_to_ms("2025-06-01T00:00:00Z").unwrap();
1033        let after = crate::time::iso8601_to_ms("2026-06-01T00:00:00Z").unwrap();
1034
1035        // sha256("test") is the first digest; sha256("test3") the second.
1036        assert_eq!(map.resolve_at("test", before).unwrap(), "user:a");
1037        assert_eq!(map.resolve_id_at("test", before).as_deref(), Some("old"));
1038
1039        // Past the expiry it is refused — with the SAME error an unknown
1040        // token gets, and without naming the id.
1041        let err = map.resolve_at("test", after).unwrap_err();
1042        assert_eq!(err.code(), map.resolve_at("never-issued", after).unwrap_err().code());
1043        assert!(!err.to_string().contains("old"), "must not name the id: {err}");
1044        assert!(map.resolve_id_at("test", after).is_none());
1045
1046        // The principal's OTHER credential is untouched — expiring one token
1047        // must not lock the human out of their own account.
1048        assert_eq!(map.resolve_at("test3", after).unwrap(), "user:a");
1049
1050        // And the same rule holds on the memory-scoped path.
1051        assert!(map.resolve_for_memory_at("test", "m", after).is_err());
1052        assert_eq!(map.resolve_for_memory_at("test3", "m", after).unwrap(), "user:a");
1053    }
1054
1055    /// [A1] The banner input: what is about to expire, before it does.
1056    #[test]
1057    fn expiring_within_reports_the_window() {
1058        let map = CredentialMap::from_json(
1059            r#"{"version":1,"tokens":[
1060                {"env":"A","principal":"p","id":"soon","expires_at":"2026-01-10T00:00:00Z"},
1061                {"env":"B","principal":"p","id":"later","expires_at":"2027-01-01T00:00:00Z"},
1062                {"env":"C","principal":"p","id":"never"}
1063            ]}"#,
1064        )
1065        .unwrap();
1066        let now = crate::time::iso8601_to_ms("2026-01-01T00:00:00Z").unwrap();
1067        let two_weeks = 14 * 86_400_000;
1068        let due: Vec<String> = map
1069            .expiring_within(now, two_weeks)
1070            .into_iter()
1071            .map(|(id, _)| id)
1072            .collect();
1073        assert_eq!(due, vec!["soon".to_string()]);
1074    }
1075
1076    /// [A1] The token format: recognizable to a scanner, and honest about
1077    /// what it does and does not prove.
1078    #[test]
1079    fn minted_token_shape_is_recognizable() {
1080        let body = encode_token_body(&[0u8; 32]);
1081        let token = format!("{TOKEN_PREFIX}{body}");
1082        assert!(token_is_minted(&token));
1083        assert!(token.starts_with("areev_pat_"));
1084        assert_eq!(body.len(), 51, "51 base32 chars = 255 bits");
1085
1086        // Distinct entropy → distinct tokens.
1087        let other = encode_token_body(&[1u8; 32]);
1088        assert_ne!(body, other);
1089
1090        // An operator's own token is not "minted" — that is a hygiene
1091        // signal, not an auth check, so nothing here refuses it.
1092        assert!(!token_is_minted("hunter2"));
1093        assert!(!token_is_minted("areev_pat_short"));
1094    }
1095}