Skip to main content

laser_wire/
authz.rs

1use crate::codes::*;
2use crate::error::InvalidError;
3use crate::limits::{MAX_AUTHZ_MUTATION_ID_BYTES, MAX_ROLE_NAME_BYTES};
4use serde::{Deserialize, Serialize};
5
6/// Whether a grant permits or forbids. `Deny` always wins over `Allow`.
7#[derive(
8    Clone,
9    Copy,
10    Debug,
11    Default,
12    PartialEq,
13    Eq,
14    Serialize,
15    Deserialize,
16    strum::Display,
17    strum::EnumString,
18    strum::VariantArray,
19)]
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[strum(serialize_all = "snake_case")]
22#[serde(rename_all = "snake_case")]
23#[non_exhaustive]
24pub enum Effect {
25    #[default]
26    Allow,
27    Deny,
28}
29
30/// The managed surface a grant applies to. Maps to the command bands, so a grant
31/// on `Kv` is orthogonal to one on `Projection`.
32#[derive(
33    Clone,
34    Copy,
35    Debug,
36    PartialEq,
37    Eq,
38    Hash,
39    Serialize,
40    Deserialize,
41    strum::Display,
42    strum::EnumString,
43    strum::VariantArray,
44)]
45#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
46#[strum(serialize_all = "snake_case")]
47#[serde(rename_all = "snake_case")]
48#[non_exhaustive]
49pub enum Feature {
50    Kv,
51    Memory,
52    Projection,
53    Fork,
54    Graph,
55    Query,
56    Agent,
57    Workflow,
58    /// Retired with lakehouse destinations. Kept so the action mask positions
59    /// of the features after it stay fixed.
60    Destination,
61    /// Retired with lakehouse destinations. Kept so the action mask positions
62    /// of the features after it stay fixed.
63    Checkpoint,
64    /// Administration of the authorization layer itself (defining roles and
65    /// binding them). Gated by `authz:admin`, never derived from a command code.
66    Authz,
67    /// Lease lifecycle in a coordination namespace: acquire, renew, and release
68    /// (`kv_lease:admin`), including delegated acquisition for another subject.
69    /// Split from [`Feature::Kv`] so a state writer's `kv:write` grant never
70    /// implies lease control. The action vocabulary stays the shared
71    /// read/write/delete/admin set (every action widens the coarse mask by one
72    /// bit per feature, so features split, actions do not grow).
73    KvLease,
74    /// Presenting a fence on a fenced compare-and-swap (`kv_fence:read`): the
75    /// right to validate against a coordination namespace's lease and fence
76    /// rows without any right to mutate them.
77    KvFence,
78    /// The saved consumer-filter catalog: browse (`read`), register, revise, and
79    /// describe (`write`), archive and drop (`delete`), and group bindings or
80    /// revision pause/resume (`admin`). Filtered reads themselves need only native source permission.
81    Filter,
82    /// Managed reads of one stream's agent sessions.
83    Session,
84    /// A feature name a newer peer used that this build does not know. An unknown
85    /// `feature` string decodes here instead of failing the whole grant set, and
86    /// it matches no request (requests only ever carry a known feature), so an
87    /// unrecognized capability is inert: default-deny, never a silent allow.
88    /// Displays as `unrecognized` (a Display that panicked would let one foreign
89    /// grant crash any UI that renders a grant set), and the string parses back
90    /// into this same deny sink.
91    #[serde(other)]
92    Unrecognized,
93}
94
95/// The prefix of a resource name scoped to one stream, `stream:<name>` or
96/// `stream:<name>/<local>`.
97pub const STREAM_RESOURCE_PREFIX: &str = "stream:";
98
99/// The resource name of `stream` itself.
100pub fn stream_resource(stream: &str) -> String {
101    format!("{STREAM_RESOURCE_PREFIX}{stream}")
102}
103
104/// The name of the managed resource `local` inside `stream`,
105/// `stream:<stream>/<local>`. A `local` that already starts with `stream:` is
106/// returned unchanged, so scoping is idempotent and a caller-scoped name is
107/// never scoped twice.
108pub fn scoped_resource(stream: &str, local: &str) -> String {
109    if local.starts_with(STREAM_RESOURCE_PREFIX) {
110        local.to_owned()
111    } else {
112        format!("{STREAM_RESOURCE_PREFIX}{stream}/{local}")
113    }
114}
115
116/// The stream and local part of a scoped resource name. `None` for a bare name,
117/// for the stream resource itself, and for a name with an empty stream or local
118/// part. Stream names never contain `/`, so the first `/` ends the stream.
119pub fn split_scoped_resource(name: &str) -> Option<(&str, &str)> {
120    let (stream, local) = name.strip_prefix(STREAM_RESOURCE_PREFIX)?.split_once('/')?;
121    (!stream.is_empty() && !local.is_empty()).then_some((stream, local))
122}
123
124/// How a deployment scopes its managed resources, as its replicated
125/// authorization state records it.
126#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
128#[serde(rename_all = "snake_case")]
129pub enum Tenancy {
130    /// One deployment-wide namespace. Every grant pattern is accepted.
131    #[default]
132    Deployment,
133    /// Each stream is an account. A role may allow access inside one stream
134    /// only, and the root role is bound to root alone.
135    Stream,
136}
137
138impl Tenancy {
139    pub fn is_deployment(&self) -> bool {
140        *self == Self::Deployment
141    }
142}
143
144/// Whether an allow grant reaches resources in more than one stream: a
145/// whole-feature grant, or a prefix that is not inside one `stream:<name>/`.
146/// A deny grant only narrows access, so it never spans.
147pub fn grant_spans_streams(grant: &Grant) -> bool {
148    if grant.effect == Effect::Deny {
149        return false;
150    }
151    match grant.resource.kind {
152        ResourceKind::Literal => false,
153        ResourceKind::Prefix => prefix_stream(&grant.resource.value).is_none(),
154        // A whole-feature grant, and any pattern kind this build does not know.
155        _ => true,
156    }
157}
158
159/// The one stream every allow grant of a role stays inside, which its audit
160/// events are attributed to. `None` when a grant reaches more than one stream
161/// or none, or when the role allows nothing.
162pub fn grants_stream(grants: &[Grant]) -> Option<String> {
163    let mut streams = grants
164        .iter()
165        .filter(|grant| grant.effect == Effect::Allow)
166        .map(|grant| match grant.resource.kind {
167            ResourceKind::Literal => split_scoped_resource(&grant.resource.value)
168                .map(|(stream, _)| stream)
169                .or_else(|| grant.resource.value.strip_prefix(STREAM_RESOURCE_PREFIX))
170                .filter(|stream| !stream.is_empty() && !stream.contains('/')),
171            ResourceKind::Prefix => prefix_stream(&grant.resource.value),
172            _ => None,
173        });
174    let first = streams.next()??;
175    streams
176        .all(|stream| stream == Some(first))
177        .then(|| first.to_owned())
178}
179
180/// The one stream a prefix stays inside, if any.
181fn prefix_stream(prefix: &str) -> Option<&str> {
182    if let Some((stream, _local)) = split_scoped_resource(prefix) {
183        return Some(stream);
184    }
185    prefix
186        .strip_prefix(STREAM_RESOURCE_PREFIX)?
187        .strip_suffix('/')
188        .filter(|stream| !stream.is_empty() && !stream.contains('/'))
189}
190
191/// The verb a grant permits, derived from the command code by [`feature_action`].
192#[derive(
193    Clone,
194    Copy,
195    Debug,
196    PartialEq,
197    Eq,
198    Hash,
199    Serialize,
200    Deserialize,
201    strum::Display,
202    strum::EnumString,
203    strum::VariantArray,
204)]
205#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
206#[strum(serialize_all = "snake_case")]
207#[serde(rename_all = "snake_case")]
208#[non_exhaustive]
209pub enum Action {
210    Read,
211    Write,
212    Delete,
213    Admin,
214    /// An action name a newer peer used that this build does not know. Decodes
215    /// here rather than failing the grant set, and matches no request, so an
216    /// unrecognized action is inert: default-deny. Displays as `unrecognized`
217    /// and parses back into this same deny sink, never a panic.
218    #[serde(other)]
219    Unrecognized,
220}
221
222/// How a [`ResourcePattern`] matches a request's resource selector.
223#[derive(
224    Clone,
225    Copy,
226    Debug,
227    Default,
228    PartialEq,
229    Eq,
230    Serialize,
231    Deserialize,
232    strum::Display,
233    strum::EnumString,
234    strum::VariantArray,
235)]
236#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
237#[strum(serialize_all = "snake_case")]
238#[serde(rename_all = "snake_case")]
239#[non_exhaustive]
240pub enum ResourceKind {
241    /// The whole feature, ignoring `value` (the absent-pattern default).
242    #[default]
243    All,
244    /// One exact resource name.
245    Literal,
246    /// Every resource name under a prefix.
247    Prefix,
248}
249
250/// A resource selector on a grant: literal, prefixed, or the whole feature.
251#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
253pub struct ResourcePattern {
254    #[serde(default)]
255    pub kind: ResourceKind,
256    #[serde(default, skip_serializing_if = "String::is_empty")]
257    pub value: String,
258}
259
260impl ResourcePattern {
261    /// The whole-feature pattern.
262    pub fn all() -> Self {
263        Self::default()
264    }
265
266    /// An exact-name pattern.
267    pub fn literal(value: impl Into<String>) -> Self {
268        Self {
269            kind: ResourceKind::Literal,
270            value: value.into(),
271        }
272    }
273
274    /// A prefix pattern (every name under `value`).
275    pub fn prefix(value: impl Into<String>) -> Self {
276        Self {
277            kind: ResourceKind::Prefix,
278            value: value.into(),
279        }
280    }
281
282    /// Whether `resource` (the selector decoded from a request) matches. An
283    /// unkeyed request (`None`) matches only a whole-feature pattern.
284    pub fn matches(&self, resource: Option<&str>) -> bool {
285        match (self.kind, resource) {
286            (ResourceKind::All, _) => true,
287            (ResourceKind::Literal, Some(r)) => r == self.value,
288            (ResourceKind::Prefix, Some(r)) => r.starts_with(&self.value),
289            (_, None) => false,
290        }
291    }
292}
293
294/// One capability grant: an effect on a `feature:action`, optionally scoped to a
295/// resource pattern.
296#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
298pub struct Grant {
299    pub effect: Effect,
300    pub feature: Feature,
301    pub action: Action,
302    #[serde(default)]
303    pub resource: ResourcePattern,
304}
305
306/// A named set of grants, bound to users. A user's effective capability is the
307/// union of the grants of every bound role, minus any matching deny.
308#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
309#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
310pub struct Role {
311    pub name: String,
312    pub grants: Vec<Grant>,
313}
314
315/// The roles bound to one user (by the server-stamped `user_id`).
316#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
317#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
318pub struct RoleBinding {
319    pub user_id: u32,
320    pub roles: Vec<String>,
321}
322
323/// The canonical role-name rule, shared by the SDK, the server, and the
324/// console so a name accepted by one tier is never rejected by the next. A
325/// valid name is non-empty, at most [`MAX_ROLE_NAME_BYTES`] bytes, and made
326/// only of ASCII letters, digits, `-`, `_`, and `.`. Enforced on define and
327/// bind, never on replay: a journaled role loads regardless, so tightening the
328/// rule cannot strand existing state.
329pub fn validate_role_name(name: &str) -> Result<(), InvalidError> {
330    crate::validate::validate_safelisted_name("role name", name, MAX_ROLE_NAME_BYTES)
331}
332
333/// The role definition rule: a valid name and grants only on features some
334/// request is authorized against. `memory`, `agent` and `workflow` have no
335/// command that checks them, and a feature this build does not know is never
336/// matched, so a grant on one would be stored and change nothing. Enforced on
337/// define, never on replay.
338pub fn validate_role(role: &Role) -> Result<(), InvalidError> {
339    validate_role_name(&role.name)?;
340    match role.grants.iter().find(|grant| {
341        matches!(
342            grant.feature,
343            Feature::Memory | Feature::Agent | Feature::Workflow | Feature::Unrecognized
344        )
345    }) {
346        Some(grant) => Err(InvalidError::new(format!(
347            "no request is authorized against the `{}` feature, so a grant on it has no effect",
348            grant.feature
349        ))),
350        None => Ok(()),
351    }
352}
353
354/// The canonical authorization mutation id rule: non-empty, at most
355/// [`MAX_AUTHZ_MUTATION_ID_BYTES`] bytes of ASCII letters, digits and `-`.
356pub fn validate_mutation_id(mutation_id: &str) -> Result<(), InvalidError> {
357    if mutation_id.is_empty() || mutation_id.len() > MAX_AUTHZ_MUTATION_ID_BYTES {
358        return Err(InvalidError::new(format!(
359            "mutation id must be 1 to {MAX_AUTHZ_MUTATION_ID_BYTES} bytes"
360        )));
361    }
362    if !mutation_id
363        .bytes()
364        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
365    {
366        return Err(InvalidError::new(
367            "mutation id may hold only ASCII letters, digits and '-'",
368        ));
369    }
370    Ok(())
371}
372
373/// The `(feature, action)` a managed command code authorizes against. `None` for
374/// a code with no capability semantics (hello, backend hello, client metadata,
375/// batch, and the authz band itself), which is gated another way.
376pub fn feature_action(code: u32) -> Option<(Feature, Action)> {
377    let pair = match code {
378        AGDX_QUERY_CODE => (Feature::Query, Action::Read),
379        AGDX_GET_PROJECTION_CODE
380        | AGDX_LIST_PROJECTIONS_CODE
381        | AGDX_GET_SCHEMA_CODE
382        | AGDX_LIST_SCHEMAS_CODE
383        | AGDX_DECODE_RECORD_CODE => (Feature::Projection, Action::Read),
384        AGDX_REGISTER_SCHEMA_CODE => (Feature::Projection, Action::Admin),
385        AGDX_KV_GET_CODE | AGDX_KV_SCAN_CODE | AGDX_KV_NAMESPACES_CODE | AGDX_KV_EXISTS_CODE => {
386            (Feature::Kv, Action::Read)
387        }
388        // A fenced CAS additionally requires `kv_fence:read` on its
389        // coordination namespace ([`crate::kv::KvCasFenced::fence_namespace`]).
390        // This map carries the primary target-namespace grant and the enforcer
391        // checks the fence grant beside it.
392        AGDX_KV_SET_CODE
393        | AGDX_KV_CAS_CODE
394        | AGDX_KV_CAS_FENCED_CODE
395        | AGDX_KV_PATCH_CODE
396        | AGDX_KV_EXPIRE_CODE
397        | AGDX_KV_COPY_CODE
398        | AGDX_KV_MOVE_CODE => (Feature::Kv, Action::Write),
399        // Lease lifecycle is its own feature: a `kv:write` grant on a
400        // namespace must never imply acquiring, renewing, or releasing the
401        // lease that fences it. `admin` is the house action for a surface's
402        // privileged op (`projection:admin`, `fork:admin`), so lease control
403        // is `kv_lease:admin`, distinct from `kv:admin` by the feature alone.
404        AGDX_KV_LEASE_CODE | AGDX_KV_LEASE_RENEW_CODE | AGDX_KV_RELEASE_CODE => {
405            (Feature::KvLease, Action::Admin)
406        }
407        AGDX_KV_DELETE_CODE | AGDX_KV_DELETE_MANY_CODE => (Feature::Kv, Action::Delete),
408        AGDX_FORK_LIST_CODE => (Feature::Fork, Action::Read),
409        AGDX_FORK_CREATE_CODE | AGDX_FORK_PUT_CODE => (Feature::Fork, Action::Write),
410        AGDX_FORK_PROMOTE_CODE => (Feature::Fork, Action::Admin),
411        AGDX_FORK_DELETE_CODE => (Feature::Fork, Action::Delete),
412        AGDX_GRAPH_QUERY_CODE | AGDX_GRAPH_NEIGHBORS_CODE => (Feature::Graph, Action::Read),
413        AGDX_GRAPH_UPSERT_CODE => (Feature::Graph, Action::Write),
414        AGDX_SESSION_GET_CODE
415        | AGDX_SESSION_LIST_CODE
416        | AGDX_SESSION_EVENTS_CODE
417        | AGDX_SESSION_STATE_CODE
418        | AGDX_SESSION_LINKS_CODE
419        | AGDX_SESSION_SOURCES_CODE
420        | AGDX_SESSION_CHANGES_CODE => (Feature::Session, Action::Read),
421        AGDX_GET_FILTER_CODE
422        | AGDX_LIST_FILTERS_CODE
423        | AGDX_LIST_FILTER_REVISIONS_CODE
424        | AGDX_GET_FILTER_BINDING_CODE
425        | AGDX_LIST_FILTER_BINDINGS_CODE
426        | AGDX_FILTER_OPERATION_CODE => (Feature::Filter, Action::Read),
427        _ => return None,
428    };
429    Some(pair)
430}
431
432/// The number of [`Action`] variants (including the `Unrecognized` catch-all):
433/// the stride of the shared coarse-capability bitmask layout ([`action_index`]).
434/// The stride must cover every action so one feature's last action bit never
435/// collides with the next feature's first. Keep the action set minimal: every
436/// added action costs one mask bit per feature, so new capability semantics
437/// split into a feature (a fresh row) rather than an action (a wider stride).
438pub const ACTION_COUNT: usize = 5;
439
440/// The bit index of a `(feature, action)` in the coarse-capability bitmask, a
441/// pure function shared by every enforcer so the streaming server and the managed backend cannot drift.
442/// `Feature`/`Action` are `VariantArray` enums, so the ordinal is stable per wire
443/// revision.
444pub fn action_index(feature: Feature, action: Action) -> usize {
445    feature as usize * ACTION_COUNT + action as usize
446}
447
448// The coarse-capability bitmask every enforcer shares is a `u128` (widened
449// from `u64` when the kv_lease/kv_fence feature split pushed the grid past 64),
450// so every `(feature, action)` bit index must fit in 128 bits. Adding features
451// or actions past that ceiling is a compile error here, not a silent runtime
452// aliasing of two distinct capabilities onto one bit. `ACTION_COUNT` must also
453// stay the true `Action` variant count, or `action_index`'s stride would skip
454// or overlap rows.
455const _: () = {
456    assert!(
457        <Action as strum::VariantArray>::VARIANTS.len() == ACTION_COUNT,
458        "ACTION_COUNT must equal the number of Action variants"
459    );
460    assert!(
461        <Feature as strum::VariantArray>::VARIANTS.len() * ACTION_COUNT <= 128,
462        "authz coarse-capability bitmask overflow: Feature count * ACTION_COUNT exceeds 128 bits"
463    );
464};
465
466/// Whether `grants` permit `(feature, action)` on `resource`, deny-wins. An
467/// empty set permits nothing (there is no allow to match). `resource` is the
468/// selector decoded from a request, or `None` for an unkeyed op.
469pub fn grants_allow(
470    grants: &[Grant],
471    feature: Feature,
472    action: Action,
473    resource: Option<&str>,
474) -> bool {
475    let mut allowed = false;
476    for grant in grants {
477        if grant.feature == feature && grant.action == action && grant.resource.matches(resource) {
478            match grant.effect {
479                Effect::Deny => return false,
480                Effect::Allow => allowed = true,
481            }
482        }
483    }
484    allowed
485}
486
487/// The on-behalf-of check: an agent acting for a user is permitted an op only
488/// when both its own grants and the invoking user's grants permit it. The agent
489/// can never exceed the user who invoked it (permission intersection).
490pub fn delegated_allow(
491    agent: &[Grant],
492    user: &[Grant],
493    feature: Feature,
494    action: Action,
495    resource: Option<&str>,
496) -> bool {
497    grants_allow(agent, feature, action, resource) && grants_allow(user, feature, action, resource)
498}
499
500/// Request the caller's own effective capabilities.
501#[derive(Clone, Debug, Serialize, Deserialize)]
502#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
503pub struct WhoamiReq {
504    pub v: u32,
505}
506
507/// The caller's bound roles and their flattened grants.
508#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
510pub struct WhoamiReply {
511    pub v: u32,
512    pub roles: Vec<String>,
513    pub grants: Vec<Grant>,
514}
515
516/// Request to list roles, optionally filtered. Absent filters list every role,
517/// the same bounded-registry browse as `ListProjections`.
518#[derive(Clone, Debug, Serialize, Deserialize)]
519#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
520pub struct ListRolesReq {
521    pub v: u32,
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub name_prefix: Option<String>,
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub search: Option<String>,
526}
527
528/// Every matching role with its full grant set.
529#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
530#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
531pub struct ListRolesReply {
532    pub v: u32,
533    pub roles: Vec<Role>,
534}
535
536/// Request one role by name.
537#[derive(Clone, Debug, Serialize, Deserialize)]
538#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
539pub struct GetRoleReq {
540    pub v: u32,
541    pub name: String,
542}
543
544/// Request one user's bound role names.
545#[derive(Clone, Debug, Serialize, Deserialize)]
546#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
547pub struct GetBindingsReq {
548    pub v: u32,
549    pub user_id: u32,
550}
551
552/// One user's bound role names and the binding revision they were read at.
553#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
554#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
555pub struct BindingsReply {
556    pub v: u32,
557    pub roles: Vec<String>,
558    /// The revision of the binding the roles were read from, the value a
559    /// [`BindRolesReq::expect_revision`] names to replace exactly this binding.
560    /// Zero for a user that was never bound.
561    pub revision: u64,
562}
563
564/// Define or replace a role (upsert, carries the full grant set).
565#[derive(Clone, Debug, Serialize, Deserialize)]
566#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
567pub struct DefineRoleReq {
568    pub v: u32,
569    pub role: Role,
570    #[serde(default, skip_serializing_if = "Option::is_none")]
571    pub mutation_id: Option<String>,
572}
573
574/// Delete a role by name.
575#[derive(Clone, Debug, Serialize, Deserialize)]
576#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
577pub struct DeleteRoleReq {
578    pub v: u32,
579    pub name: String,
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    pub mutation_id: Option<String>,
582}
583
584/// Bind roles to a user (replace the user's whole role set).
585#[derive(Clone, Debug, Serialize, Deserialize)]
586#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
587pub struct BindRolesReq {
588    pub v: u32,
589    pub user_id: u32,
590    pub roles: Vec<String>,
591    /// Compare-and-swap precondition: apply only if the binding's current
592    /// revision equals this. Absent means an unconditional replace (the prior
593    /// behavior), so a caller opts into optimistic concurrency. A mismatch fails
594    /// with [`AuthzError::Conflict`]. Skip-none, so a request without it stays
595    /// byte-identical.
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    pub expect_revision: Option<u64>,
598    #[serde(default, skip_serializing_if = "Option::is_none")]
599    pub mutation_id: Option<String>,
600}
601
602/// Which authorization subject an [`AuthzHistoryReq`] reads the change log of.
603#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
604#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
605#[serde(rename_all = "snake_case")]
606pub enum AuthzSubject {
607    /// One role by name.
608    Role(String),
609    /// One user's bindings.
610    Binding { user_id: u32 },
611    /// Every authorization change.
612    All,
613    /// Every change attributed to one stream: roles whose grants stay inside
614    /// it and bindings of such roles. What a stream's owner may audit.
615    Stream(String),
616}
617
618/// Read the authorization change history for a subject, paged by revision. The
619/// audit surface the first compliance conversation opens: who granted what, when.
620#[derive(Clone, Debug, Serialize, Deserialize)]
621#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
622pub struct AuthzHistoryReq {
623    pub v: u32,
624    pub subject: AuthzSubject,
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub after_revision: Option<u64>,
627    pub limit: u32,
628}
629
630/// What an [`AuthzEvent`] recorded.
631#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
632#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
633#[serde(rename_all = "snake_case")]
634pub enum AuthzEventKind {
635    /// A role was defined or replaced.
636    RoleDefined(String),
637    /// A role was deleted.
638    RoleDeleted(String),
639    /// A user's role set was rebound.
640    RolesBound { user_id: u32, roles: Vec<String> },
641    /// The deployment's tenancy was set.
642    TenancySet(Tenancy),
643}
644
645/// One recorded authorization change: its revision, who made it, when, and what.
646#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
647#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
648pub struct AuthzEvent {
649    pub revision: u64,
650    pub actor: String,
651    pub at_micros: u64,
652    pub op: AuthzEventKind,
653    /// The stream the change is attributed to, see [`grants_stream`]. Absent
654    /// for a change that concerns no single stream.
655    #[serde(default, skip_serializing_if = "Option::is_none")]
656    pub stream: Option<String>,
657}
658
659/// A page of authorization change history.
660#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
662pub struct AuthzHistoryReply {
663    pub v: u32,
664    pub events: Vec<AuthzEvent>,
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub next_after_revision: Option<u64>,
667}
668
669/// Reply to any authorization command, shaped per request.
670#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
671#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
672#[non_exhaustive]
673pub enum AuthzReply {
674    /// A mutating command applied (`define_role`, `delete_role`, `bind_roles`).
675    Ok,
676    /// `whoami`: the caller's effective capabilities.
677    Whoami(WhoamiReply),
678    /// `list_roles`: every matching role.
679    Roles(ListRolesReply),
680    /// `get_role`: the role with the requested name, or `None`.
681    Role(Option<Role>),
682    /// `get_bindings`: one user's bound role names.
683    Bindings(BindingsReply),
684    /// `history`: a page of the authorization change log.
685    History(AuthzHistoryReply),
686    Err(AuthzError),
687}
688
689/// An authorization command failure.
690#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
691#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
692#[non_exhaustive]
693pub enum AuthzError {
694    #[error("authz not supported: {0}")]
695    Unsupported(String),
696    #[error("unauthorized")]
697    Unauthorized,
698    #[error("unknown role: {0}")]
699    UnknownRole(String),
700    /// A define or bind named a role that fails [`validate_role_name`].
701    #[error("invalid role name: {0}")]
702    InvalidName(String),
703    /// A define granted a feature no request is authorized against, see
704    /// [`validate_role`]. Nothing applied.
705    #[error("invalid grant: {0}")]
706    InvalidGrant(String),
707    /// A compare-and-swap bind lost the precondition: the binding's current
708    /// revision is not the one the request expected, so a concurrent admin got
709    /// there first. The caller re-reads and retries.
710    #[error("revision conflict: current is {current_revision}")]
711    Conflict { current_revision: u64 },
712    #[error("unsupported authz op version (expected {expected}, got {got})")]
713    Version { expected: u32, got: u32 },
714    /// A grant refused because it reaches past one stream while the server
715    /// runs with stream tenancy, for example a wildcard or a prefix spanning
716    /// streams.
717    #[error("refused by stream tenancy: {0}")]
718    TenancyViolation(String),
719    /// The mutation id already names a different request of the same account.
720    /// Nothing applied. A new operation needs a new mutation id.
721    #[error("mutation id conflict: {0}")]
722    MutationConflict(String),
723    /// No receipt capacity is free for a new mutation id inside the replay
724    /// window. Nothing applied. Retrying the same request later may succeed.
725    #[error("authorization receipt capacity exhausted: {0}")]
726    ResourceLimit(String),
727}
728
729#[cfg(all(test, feature = "cbor"))]
730mod tests {
731    use super::*;
732
733    #[test]
734    fn given_grants_on_unenforced_features_when_a_role_is_validated_then_should_refuse_them() {
735        let grant = |feature| Grant {
736            effect: Effect::Allow,
737            feature,
738            action: Action::Read,
739            resource: ResourcePattern::all(),
740        };
741        let role = |grants| Role {
742            name: "reader".to_owned(),
743            grants,
744        };
745        for feature in [
746            Feature::Memory,
747            Feature::Agent,
748            Feature::Workflow,
749            Feature::Unrecognized,
750        ] {
751            assert!(
752                validate_role(&role(vec![grant(Feature::Kv), grant(feature)])).is_err(),
753                "{feature}"
754            );
755        }
756        validate_role(&role(vec![grant(Feature::Kv), grant(Feature::Session)]))
757            .expect("enforced features validate");
758        assert!(
759            validate_role(&Role {
760                name: "bad name".to_owned(),
761                grants: Vec::new(),
762            })
763            .is_err()
764        );
765    }
766
767    #[test]
768    fn given_role_grants_when_attributed_then_should_name_one_stream_or_none() {
769        let allow = |kind: ResourceKind, value: &str| Grant {
770            effect: Effect::Allow,
771            feature: Feature::Kv,
772            action: Action::Read,
773            resource: ResourcePattern {
774                kind,
775                value: value.to_owned(),
776            },
777        };
778        assert_eq!(
779            grants_stream(&[
780                allow(ResourceKind::Prefix, "stream:acme/"),
781                allow(ResourceKind::Literal, "stream:acme/cart"),
782            ]),
783            Some("acme".to_owned())
784        );
785        assert_eq!(
786            grants_stream(&[
787                allow(ResourceKind::Prefix, "stream:acme/"),
788                allow(ResourceKind::Literal, "stream:other/cart"),
789            ]),
790            None
791        );
792        assert_eq!(grants_stream(&[allow(ResourceKind::All, "")]), None);
793        assert_eq!(
794            grants_stream(&[allow(ResourceKind::Prefix, "stream:acme")]),
795            None
796        );
797        assert_eq!(grants_stream(&[]), None);
798    }
799
800    #[test]
801    fn given_a_tenancy_event_when_round_tripped_then_should_keep_it_and_spanning_should_follow_the_pattern()
802     {
803        let event = AuthzEventKind::TenancySet(Tenancy::Stream);
804        let bytes = crate::framing::encode_named(&event).expect("encodes");
805        assert_eq!(
806            crate::framing::decode_named::<AuthzEventKind>(&bytes).expect("decodes"),
807            event
808        );
809        let allow = |resource| Grant {
810            effect: Effect::Allow,
811            feature: Feature::Kv,
812            action: Action::Read,
813            resource,
814        };
815        assert!(grant_spans_streams(&allow(ResourcePattern::all())));
816        assert!(grant_spans_streams(&allow(ResourcePattern::prefix(
817            "orders"
818        ))));
819        assert!(!grant_spans_streams(&allow(ResourcePattern::prefix(
820            "stream:a/"
821        ))));
822        assert!(!grant_spans_streams(&allow(ResourcePattern::literal("x"))));
823        for spanning in [
824            ResourcePattern::prefix("stream:"),
825            ResourcePattern::prefix("stream:acme"),
826            ResourcePattern::prefix("stream:/notes"),
827            ResourcePattern::prefix("acme/"),
828            ResourcePattern::prefix(""),
829        ] {
830            assert!(
831                grant_spans_streams(&allow(spanning.clone())),
832                "{spanning:?} reaches more than one stream"
833            );
834        }
835        for inside in [
836            ResourcePattern::literal("stream:acme"),
837            ResourcePattern::literal("stream:acme/notes"),
838            ResourcePattern::prefix("stream:acme/agent."),
839        ] {
840            assert!(
841                !grant_spans_streams(&allow(inside.clone())),
842                "{inside:?} stays inside one stream"
843            );
844        }
845        assert!(!grant_spans_streams(&Grant {
846            effect: Effect::Deny,
847            ..allow(ResourcePattern::all())
848        }));
849        assert!(Tenancy::default().is_deployment());
850    }
851    use crate::framing::{decode_named, encode_named};
852
853    #[test]
854    fn given_a_tenancy_violation_when_round_tripped_then_should_keep_the_reason() {
855        let reply = AuthzReply::Err(AuthzError::TenancyViolation("prefix acme".to_owned()));
856        let back: AuthzReply =
857            decode_named(&encode_named(&reply).expect("reply serializes")).expect("deserializes");
858        assert!(matches!(
859            back,
860            AuthzReply::Err(AuthzError::TenancyViolation(reason)) if reason == "prefix acme"
861        ));
862    }
863
864    #[test]
865    fn given_a_local_name_when_scoped_then_should_prefix_the_stream() {
866        assert_eq!(
867            scoped_resource("acme", "agent.keys"),
868            "stream:acme/agent.keys"
869        );
870        assert_eq!(scoped_resource("acme", "a/b"), "stream:acme/a/b");
871    }
872
873    #[test]
874    fn given_a_scoped_name_when_scoped_again_then_should_return_it_unchanged() {
875        let scoped = scoped_resource("acme", "sessions");
876        assert_eq!(scoped_resource("acme", &scoped), scoped);
877        assert_eq!(
878            scoped_resource("other", "stream:acme/sessions"),
879            "stream:acme/sessions"
880        );
881    }
882
883    #[test]
884    fn given_scoped_names_when_split_then_should_return_stream_and_local_part() {
885        assert_eq!(
886            split_scoped_resource("stream:acme/agent.keys"),
887            Some(("acme", "agent.keys"))
888        );
889        assert_eq!(
890            split_scoped_resource("stream:acme/a/b"),
891            Some(("acme", "a/b"))
892        );
893        assert_eq!(
894            split_scoped_resource(&scoped_resource("acme", "graph")),
895            Some(("acme", "graph"))
896        );
897    }
898
899    #[test]
900    fn given_unscoped_names_when_split_then_should_return_none() {
901        assert_eq!(split_scoped_resource("agent.keys"), None);
902        assert_eq!(split_scoped_resource("stream:acme"), None);
903        assert_eq!(split_scoped_resource("stream:/local"), None);
904        assert_eq!(split_scoped_resource("stream:acme/"), None);
905        assert_eq!(split_scoped_resource("streams:acme/local"), None);
906    }
907
908    #[test]
909    fn given_a_role_when_round_tripped_then_should_preserve_grants() {
910        let role = Role {
911            name: "kv-reader".to_string(),
912            grants: vec![
913                Grant {
914                    effect: Effect::Allow,
915                    feature: Feature::Kv,
916                    action: Action::Read,
917                    resource: ResourcePattern::prefix("agent-abc/"),
918                },
919                Grant {
920                    effect: Effect::Deny,
921                    feature: Feature::Kv,
922                    action: Action::Read,
923                    resource: ResourcePattern::literal("agent-abc/secret"),
924                },
925            ],
926        };
927        let bytes = encode_named(&role).expect("role serializes");
928        let back: Role = decode_named(&bytes).expect("role deserializes");
929        assert_eq!(back, role);
930    }
931
932    #[test]
933    fn given_role_names_when_validated_then_should_enforce_charset_and_length() {
934        assert!(validate_role_name("kv-reader").is_ok());
935        assert!(validate_role_name("ops.admin_2").is_ok());
936        assert!(validate_role_name(&"r".repeat(MAX_ROLE_NAME_BYTES)).is_ok());
937        assert!(validate_role_name("").is_err(), "empty");
938        assert!(validate_role_name("bad name").is_err(), "space");
939        assert!(validate_role_name("rĂ´le").is_err(), "non-ascii");
940        assert!(validate_role_name(&"r".repeat(MAX_ROLE_NAME_BYTES + 1)).is_err());
941    }
942
943    #[test]
944    fn given_a_resource_pattern_when_matched_then_should_honor_its_kind() {
945        assert!(ResourcePattern::all().matches(Some("anything")));
946        assert!(ResourcePattern::all().matches(None));
947        assert!(ResourcePattern::literal("ns").matches(Some("ns")));
948        assert!(!ResourcePattern::literal("ns").matches(Some("ns2")));
949        assert!(ResourcePattern::prefix("agent-").matches(Some("agent-abc")));
950        assert!(!ResourcePattern::prefix("agent-").matches(Some("other")));
951        // Unkeyed requests are whole-surface operations, so scoped grants must
952        // not widen to them.
953        assert!(!ResourcePattern::literal("ns").matches(None));
954        assert!(!ResourcePattern::prefix("agent-").matches(None));
955    }
956
957    #[test]
958    fn given_delegation_when_checked_then_agent_is_intersected_with_the_user() {
959        let allow = |feature, action, resource| Grant {
960            effect: Effect::Allow,
961            feature,
962            action,
963            resource,
964        };
965        // Agent may read+write kv anywhere. The user it acts for may only read kv
966        // under `shared/`. The intersection permits only what BOTH allow.
967        let agent = vec![
968            allow(Feature::Kv, Action::Read, ResourcePattern::all()),
969            allow(Feature::Kv, Action::Write, ResourcePattern::all()),
970        ];
971        let user = vec![allow(
972            Feature::Kv,
973            Action::Read,
974            ResourcePattern::prefix("shared/"),
975        )];
976        assert!(delegated_allow(
977            &agent,
978            &user,
979            Feature::Kv,
980            Action::Read,
981            Some("shared/x")
982        ));
983        // Outside the user's prefix: agent alone would allow, the user does not.
984        assert!(!delegated_allow(
985            &agent,
986            &user,
987            Feature::Kv,
988            Action::Read,
989            Some("private/x")
990        ));
991        // The user cannot write at all, so the agent cannot write on its behalf.
992        assert!(!delegated_allow(
993            &agent,
994            &user,
995            Feature::Kv,
996            Action::Write,
997            Some("shared/x")
998        ));
999        // An empty grant set permits nothing.
1000        assert!(!grants_allow(&[], Feature::Kv, Action::Read, None));
1001    }
1002
1003    #[test]
1004    fn given_a_command_code_when_classified_then_should_map_to_feature_and_action() {
1005        assert_eq!(
1006            feature_action(AGDX_KV_GET_CODE),
1007            Some((Feature::Kv, Action::Read))
1008        );
1009        assert_eq!(
1010            feature_action(AGDX_KV_SET_CODE),
1011            Some((Feature::Kv, Action::Write))
1012        );
1013        assert_eq!(
1014            feature_action(AGDX_KV_DELETE_CODE),
1015            Some((Feature::Kv, Action::Delete))
1016        );
1017        // Lease lifecycle is its own feature at the shared admin action, so a
1018        // `kv:write` grant can never acquire, renew, or release.
1019        assert_eq!(
1020            feature_action(AGDX_KV_LEASE_CODE),
1021            Some((Feature::KvLease, Action::Admin))
1022        );
1023        assert_eq!(
1024            feature_action(AGDX_KV_LEASE_RENEW_CODE),
1025            Some((Feature::KvLease, Action::Admin))
1026        );
1027        assert_eq!(
1028            feature_action(AGDX_KV_RELEASE_CODE),
1029            Some((Feature::KvLease, Action::Admin))
1030        );
1031        assert_eq!(
1032            feature_action(AGDX_KV_CAS_FENCED_CODE),
1033            Some((Feature::Kv, Action::Write))
1034        );
1035        assert_eq!(
1036            feature_action(AGDX_REGISTER_SCHEMA_CODE),
1037            Some((Feature::Projection, Action::Admin))
1038        );
1039        assert_eq!(
1040            feature_action(AGDX_QUERY_CODE),
1041            Some((Feature::Query, Action::Read))
1042        );
1043        assert_eq!(
1044            feature_action(AGDX_GRAPH_UPSERT_CODE),
1045            Some((Feature::Graph, Action::Write))
1046        );
1047        // No capability semantics: hello, batch, and the authz band self-gate.
1048        assert_eq!(feature_action(AGDX_HELLO_CODE), None);
1049        assert_eq!(feature_action(AGDX_BATCH_CODE), None);
1050        assert_eq!(feature_action(AGDX_AUTHZ_WHOAMI_CODE), None);
1051        assert_eq!(feature_action(AGDX_CONTROL_PUBLISH_CODE), None);
1052    }
1053
1054    #[test]
1055    fn given_feature_action_pairs_when_indexed_then_should_fit_a_u128_mask() {
1056        use strum::VariantArray;
1057        let mut seen = std::collections::HashSet::new();
1058        for &feature in Feature::VARIANTS {
1059            for &action in Action::VARIANTS {
1060                let index = action_index(feature, action);
1061                assert!(index < 128, "index {index} must fit a u128 mask");
1062                assert!(seen.insert(index), "index {index} collided");
1063            }
1064        }
1065        assert_eq!(action_index(Feature::Destination, Action::Read), 40);
1066        assert_eq!(action_index(Feature::Checkpoint, Action::Admin), 48);
1067        assert_eq!(action_index(Feature::Session, Action::Read), 70);
1068    }
1069
1070    #[test]
1071    fn given_an_unknown_feature_or_action_when_decoded_then_should_be_unrecognized_and_deny() {
1072        // A grant naming a feature and action a newer peer added decodes to the
1073        // Unrecognized catch-all rather than failing the whole grant set.
1074        let json = r#"{"effect":"allow","feature":"quantum","action":"teleport","resource":{"kind":"all"}}"#;
1075        let grant: Grant =
1076            serde_json::from_str(json).expect("an unknown feature/action still decodes");
1077        assert_eq!(grant.feature, Feature::Unrecognized);
1078        assert_eq!(grant.action, Action::Unrecognized);
1079        // An unrecognized capability matches no real request (requests are only
1080        // ever classified into known features and actions by `feature_action`),
1081        // so it is inert: default-deny, never a silent allow.
1082        assert!(!grants_allow(&[grant], Feature::Kv, Action::Read, None));
1083        // Displaying the deny sink must never panic (a panicking Display let one
1084        // foreign grant crash a UI rendering a grant set) and the string parses
1085        // back into the same sink.
1086        assert_eq!(Feature::Unrecognized.to_string(), "unrecognized");
1087        assert_eq!(Action::Unrecognized.to_string(), "unrecognized");
1088        assert_eq!("unrecognized".parse(), Ok(Feature::Unrecognized));
1089        assert_eq!("unrecognized".parse(), Ok(Action::Unrecognized));
1090    }
1091
1092    #[test]
1093    fn given_an_authz_reply_when_round_tripped_then_should_preserve_the_variant() {
1094        let reply = AuthzReply::Whoami(WhoamiReply {
1095            v: AUTHZ_OP_VERSION,
1096            roles: vec!["admin".to_string()],
1097            grants: vec![Grant {
1098                effect: Effect::Allow,
1099                feature: Feature::Kv,
1100                action: Action::Write,
1101                resource: ResourcePattern::all(),
1102            }],
1103        });
1104        let bytes = encode_named(&reply).expect("reply serializes");
1105        let back: AuthzReply = decode_named(&bytes).expect("reply deserializes");
1106        assert_eq!(back, reply);
1107    }
1108}