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#[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#[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 Destination,
61 Checkpoint,
64 Authz,
67 KvLease,
74 KvFence,
78 Filter,
82 Session,
84 #[serde(other)]
92 Unrecognized,
93}
94
95pub const STREAM_RESOURCE_PREFIX: &str = "stream:";
98
99pub fn stream_resource(stream: &str) -> String {
101 format!("{STREAM_RESOURCE_PREFIX}{stream}")
102}
103
104pub 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
116pub 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#[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 #[default]
132 Deployment,
133 Stream,
136}
137
138impl Tenancy {
139 pub fn is_deployment(&self) -> bool {
140 *self == Self::Deployment
141 }
142}
143
144pub 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 _ => true,
156 }
157}
158
159pub 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
180fn 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#[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 #[serde(other)]
219 Unrecognized,
220}
221
222#[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 #[default]
243 All,
244 Literal,
246 Prefix,
248}
249
250#[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 pub fn all() -> Self {
263 Self::default()
264 }
265
266 pub fn literal(value: impl Into<String>) -> Self {
268 Self {
269 kind: ResourceKind::Literal,
270 value: value.into(),
271 }
272 }
273
274 pub fn prefix(value: impl Into<String>) -> Self {
276 Self {
277 kind: ResourceKind::Prefix,
278 value: value.into(),
279 }
280 }
281
282 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#[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#[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#[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
323pub fn validate_role_name(name: &str) -> Result<(), InvalidError> {
330 crate::validate::validate_safelisted_name("role name", name, MAX_ROLE_NAME_BYTES)
331}
332
333pub 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
354pub 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
373pub 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 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 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
432pub const ACTION_COUNT: usize = 5;
439
440pub fn action_index(feature: Feature, action: Action) -> usize {
445 feature as usize * ACTION_COUNT + action as usize
446}
447
448const _: () = {
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
466pub 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
487pub 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#[derive(Clone, Debug, Serialize, Deserialize)]
502#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
503pub struct WhoamiReq {
504 pub v: u32,
505}
506
507#[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#[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#[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#[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#[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#[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 pub revision: u64,
562}
563
564#[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#[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#[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 #[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#[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 Role(String),
609 Binding { user_id: u32 },
611 All,
613 Stream(String),
616}
617
618#[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#[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 RoleDefined(String),
637 RoleDeleted(String),
639 RolesBound { user_id: u32, roles: Vec<String> },
641 TenancySet(Tenancy),
643}
644
645#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub stream: Option<String>,
657}
658
659#[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
671#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
672#[non_exhaustive]
673pub enum AuthzReply {
674 Ok,
676 Whoami(WhoamiReply),
678 Roles(ListRolesReply),
680 Role(Option<Role>),
682 Bindings(BindingsReply),
684 History(AuthzHistoryReply),
686 Err(AuthzError),
687}
688
689#[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 #[error("invalid role name: {0}")]
702 InvalidName(String),
703 #[error("invalid grant: {0}")]
706 InvalidGrant(String),
707 #[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 #[error("refused by stream tenancy: {0}")]
718 TenancyViolation(String),
719 #[error("mutation id conflict: {0}")]
722 MutationConflict(String),
723 #[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 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 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 assert!(!delegated_allow(
985 &agent,
986 &user,
987 Feature::Kv,
988 Action::Read,
989 Some("private/x")
990 ));
991 assert!(!delegated_allow(
993 &agent,
994 &user,
995 Feature::Kv,
996 Action::Write,
997 Some("shared/x")
998 ));
999 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 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 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 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 assert!(!grants_allow(&[grant], Feature::Kv, Action::Read, None));
1083 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}