boatramp-core 0.2.5

Core domain types, streaming storage trait, pluggable KV, and content-addressed deploys for boatramp
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Cedar-based control-plane authorization (the `authz` feature).
//!
//! Generates a Cedar [`PolicySet`] from the operator-editable [`AuthzPolicy`] and
//! decides each request with `Authorizer::is_authorized` over transient,
//! per-request entities, preserving the exact RBAC semantics of [`AuthzPolicy::rights_for`] +
//! [`RightSet::allows`](boatramp_types::authz::RightSet::allows) — enforced by the
//! differential test at the bottom of this module (the faithfulness gate).
//!
//! Model:
//! - **Principal** = `BR::Principal::"self"`, a member of one `BR::Role::"<name>"`
//!   group per granted role, carrying a `<role>_sites : Set<String>` attribute for
//!   every target-scoped role (the raw grant targets — a `"<project>/<site>"` for a
//!   site role, a bare `"<project>"` for a project role; always present, possibly empty).
//! - **Resource** = `BR::<Resource>::"<id>"`. The two target-scoped resources carry
//!   attributes the scoping guards read: `BR::Site` a `name` (the full `project/site`)
//!   and a `project` (its project segment); `BR::Project` a `name` (the project).
//! - **Action** = `BR::Action::"<action>"` with `read`/`write`/`deploy` parented to
//!   `admin`, so an `admin` grant (`action in [BR::Action::"admin"]`) covers every
//!   action — mirroring `Right::satisfies`' "granted Admin ⇒ any action".
//! - **Target scoping**, mirroring `target_matches`: a `RoleTarget` template guards on
//!   `principal.<role>_sites.contains(resource.name)` (exact `project/site` or project);
//!   a `ProjectWildcard` template (a project role's per-site right) guards on
//!   `…contains(resource.project)`, matching every site whose project segment is granted;
//!   an `AnyTarget` template emits no `when` (a global wildcard).
//!
//! Default-deny throughout: any entity/request construction error yields `false`.

use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::str::FromStr;

use cedar_policy::{
    Authorizer, Context, Decision, Entities, Entity, EntityId, EntityTypeName, EntityUid,
    PolicySet, Request, RestrictedExpression,
};

use boatramp_types::authz::{Action, AuthzPolicy, GrantedRole, Resource, Right, TargetScope};

/// The Cedar namespace for all boatramp authorization entities.
const NS: &str = "BR";

/// Error compiling an [`AuthzPolicy`] into a Cedar [`PolicySet`].
#[derive(Debug, thiserror::Error)]
pub enum CedarError {
    /// A role name is not a safe Cedar identifier (`[A-Za-z_][A-Za-z0-9_]*`); it
    /// would break the generated policy text (both the `Role::"<name>"` literal and
    /// the `<name>_sites` attribute path). Rejected on compile, deny-safe.
    #[error("unsafe role name: {0:?}")]
    RoleName(String),
    /// The generated policy text failed to parse — an internal generator bug.
    #[error("policy generation failed: {0}")]
    Policy(String),
}

/// A compiled Cedar authorizer generated from an [`AuthzPolicy`].
pub struct CompiledCedar {
    policies: PolicySet,
    authorizer: Authorizer,
    /// Roles carrying at least one target-scoped template — the principal gets a
    /// `<role>_sites` attribute for each (always present, possibly empty), so the
    /// site-scoping `when` guards never hit a missing attribute.
    scoped_roles: Vec<String>,
}

impl CompiledCedar {
    /// Compile an [`AuthzPolicy`] into a Cedar [`PolicySet`].
    ///
    /// Rejects role names that are not safe Cedar identifiers (they would allow
    /// injection into the generated policy text). The generated text is parsed eagerly so a
    /// generator bug surfaces here rather than at authorize time.
    pub fn compile(policy: &AuthzPolicy) -> Result<Self, CedarError> {
        for name in policy.roles.keys() {
            if !is_safe_ident(name) {
                return Err(CedarError::RoleName(name.clone()));
            }
        }
        let text = generate_policy_text(policy);
        let policies = PolicySet::from_str(&text)
            .map_err(|e| CedarError::Policy(format!("{e}\n--- text ---\n{text}")))?;
        let scoped_roles = policy
            .roles
            .iter()
            .filter(|(_, templates)| templates.iter().any(|t| t.scope.is_targeted()))
            .map(|(name, _)| name.clone())
            .collect();
        Ok(Self {
            policies,
            authorizer: Authorizer::new(),
            scoped_roles,
        })
    }

    /// Decide whether a principal holding `roles` may perform `required`.
    ///
    /// Default-deny: any entity/request construction error yields `false`.
    pub fn authorize(&self, roles: &[GrantedRole], required: &Right) -> bool {
        matches!(self.decide(roles, required), Ok(Decision::Allow))
    }

    /// The fallible core of [`authorize`](Self::authorize): build the per-request
    /// entities + request and run the authorizer. Kept private but exercised
    /// directly (unwrapped) by the differential test so construction bugs are loud.
    fn decide(&self, roles: &[GrantedRole], required: &Right) -> Result<Decision, Box<dyn Error>> {
        let principal_uid = uid("Principal", "self");
        let action_uid = uid("Action", required.action.as_str());
        let (resource_uid, resource) = resource_entity(required)?;
        let principal = principal_entity(&principal_uid, roles, &self.scoped_roles)?;

        let mut entities: Vec<Entity> = vec![principal, resource];
        entities.extend(action_entities()?);
        // Empty group entities for each granted role, so `principal in Role::"x"`
        // resolves against a known (leaf) entity rather than a dangling reference.
        for r in roles {
            if is_safe_ident(&r.name) {
                entities.push(Entity::new(
                    uid("Role", &r.name),
                    HashMap::new(),
                    HashSet::new(),
                )?);
            }
        }
        let entities = Entities::from_entities(entities, None)?;

        let request = Request::new(
            principal_uid,
            action_uid,
            resource_uid,
            Context::empty(),
            None,
        )?;
        Ok(self
            .authorizer
            .is_authorized(&request, &self.policies, &entities)
            .decision())
    }
}

/// Generate the Cedar policy text for an [`AuthzPolicy`]: one `permit` per role ×
/// right-template. Role names are pre-validated by [`is_safe_ident`], so the
/// `Role::"<name>"` literal and `<name>_sites` attribute path are injection-safe.
fn generate_policy_text(policy: &AuthzPolicy) -> String {
    let mut out = String::new();
    for (role, templates) in &policy.roles {
        for t in templates {
            let action = action_scope(t.action);
            let resource_ty = resource_type(t.resource);
            let guard = match t.scope {
                // Bind the request's target to the role's granted targets, mirroring
                // `target_matches(Some(g), required)`. `Set::contains` is Cedar set
                // membership (`in` is entity-hierarchy membership — wrong here). The
                // granted set holds the raw grant target (a `"<project>/<site>"` for a
                // site role, or a bare `"<project>"` for a project role).
                TargetScope::RoleTarget => {
                    format!(" when {{ principal.{role}_sites.contains(resource.name) }}")
                }
                // A project role's per-site right: match the request's site by its
                // *project* segment against the granted project names, mirroring the
                // `"<project>/*"` wildcard in `target_matches`. Reads the Site
                // resource's `project` attribute (only Site permits use this scope).
                TargetScope::ProjectWildcard => {
                    format!(" when {{ principal.{role}_sites.contains(resource.project) }}")
                }
                // Wildcard grant: matches any resource of that type.
                TargetScope::AnyTarget => String::new(),
            };
            out.push_str(&format!(
                "permit(principal in {NS}::Role::\"{role}\", {action}, resource is {NS}::{resource_ty}){guard};\n"
            ));
        }
    }
    out
}

/// The action clause for a permit. `Admin` is the superuser action: `action in
/// [admin]` matches any request action, because `read`/`write`/`deploy` are
/// parented to `admin` in the per-request action entities — mirroring
/// `Right::satisfies`' "granted Admin ⇒ satisfies any action".
fn action_scope(action: Action) -> String {
    match action {
        Action::Admin => format!("action in [{NS}::Action::\"admin\"]"),
        other => format!("action == {NS}::Action::\"{}\"", other.as_str()),
    }
}

/// The Cedar entity type name (CamelCase) for a [`Resource`].
fn resource_type(resource: Resource) -> &'static str {
    match resource {
        Resource::Site => "Site",
        Resource::Project => "Project",
        Resource::Blobs => "Blobs",
        Resource::Tokens => "Tokens",
        Resource::Certs => "Certs",
        Resource::Cache => "Cache",
        Resource::System => "System",
    }
}

/// Build the principal entity: its `Role::"<name>"` group memberships (parents) and
/// one `<role>_sites` set attribute per target-scoped role in the policy (the site
/// names it holds that role on — always present so the `when` guards never fault).
fn principal_entity(
    principal_uid: &EntityUid,
    roles: &[GrantedRole],
    scoped_roles: &[String],
) -> Result<Entity, Box<dyn Error>> {
    let mut parents: HashSet<EntityUid> = HashSet::new();
    for r in roles {
        if is_safe_ident(&r.name) {
            parents.insert(uid("Role", &r.name));
        }
    }
    let mut attrs: HashMap<String, RestrictedExpression> = HashMap::new();
    for role in scoped_roles {
        let sites = roles
            .iter()
            .filter(|r| &r.name == role)
            .filter_map(|r| r.target.as_ref())
            .map(|t| RestrictedExpression::new_string(t.clone()));
        attrs.insert(
            format!("{role}_sites"),
            RestrictedExpression::new_set(sites),
        );
    }
    Ok(Entity::new(principal_uid.clone(), attrs, parents)?)
}

/// Build the resource entity for a required right. The two target-scoped resources
/// carry attributes the scoping guards read: `Site` is keyed by its full
/// `"<project>/<site>"` target and carries both `name` (the full target, for a site
/// grant) and `project` (its project segment, for a project-wildcard grant); `Project`
/// is keyed + `name`-attributed by the project. Other resources are global singletons
/// keyed by their type term, needing no attributes.
fn resource_entity(required: &Right) -> Result<(EntityUid, Entity), Box<dyn Error>> {
    let ty = resource_type(required.resource);
    let (id, attrs) = match required.resource {
        Resource::Site => {
            let name = required.target.clone().unwrap_or_default();
            let project = boatramp_types::authz::project_of(&name).to_string();
            let mut a = HashMap::new();
            a.insert(
                "name".to_string(),
                RestrictedExpression::new_string(name.clone()),
            );
            a.insert(
                "project".to_string(),
                RestrictedExpression::new_string(project),
            );
            (name, a)
        }
        Resource::Project => {
            let name = required.target.clone().unwrap_or_default();
            let mut a = HashMap::new();
            a.insert(
                "name".to_string(),
                RestrictedExpression::new_string(name.clone()),
            );
            (name, a)
        }
        other => (other.as_str().to_string(), HashMap::new()),
    };
    let entity_uid = uid(ty, &id);
    let entity = Entity::new(entity_uid.clone(), attrs, HashSet::new())?;
    Ok((entity_uid, entity))
}

/// The four action entities with the superuser hierarchy: `read`/`write`/`deploy`
/// each parent to `admin`, so an `action in [admin]` permit matches them all.
fn action_entities() -> Result<Vec<Entity>, Box<dyn Error>> {
    let admin = uid("Action", "admin");
    let mut out = Vec::with_capacity(4);
    out.push(Entity::new(admin.clone(), HashMap::new(), HashSet::new())?);
    for a in ["read", "write", "deploy"] {
        let parents = HashSet::from([admin.clone()]);
        out.push(Entity::new(uid("Action", a), HashMap::new(), parents)?);
    }
    Ok(out)
}

/// Construct a `BR::<type_name>::"<id>"` entity uid. The type name is a fixed
/// literal (always valid); the id is arbitrary text handled by the infallible
/// [`EntityId::new`].
fn uid(type_name: &str, id: &str) -> EntityUid {
    let tn =
        EntityTypeName::from_str(&format!("{NS}::{type_name}")).expect("static Cedar type name");
    EntityUid::from_type_name_and_id(tn, EntityId::new(id))
}

/// Whether `s` is a safe Cedar identifier (`[A-Za-z_][A-Za-z0-9_]*`). Role names
/// must satisfy this: they appear both as a `Role::"<name>"` string literal and,
/// for scoped roles, as the `<name>_sites` attribute path in generated policy text.
fn is_safe_ident(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

#[cfg(test)]
mod tests {
    use super::*;
    use boatramp_types::authz::{RightSet, RightTemplate};
    use std::collections::BTreeMap;

    /// The differential faithfulness gate: for every (roleset, required) pair,
    /// the Cedar decision must equal the pure-Rust oracle
    /// `policy.rights_for(roles).allows(required)`.
    fn assert_faithful(policy: &AuthzPolicy, rolesets: &[Vec<GrantedRole>]) {
        let cedar = CompiledCedar::compile(policy).expect("compile");
        let targets = [
            None,
            Some("blog".to_string()),
            Some("shop".to_string()),
            // Project-qualified site targets + bare project targets (0.2.0), so the
            // gate covers `Resource::Project` and the project-wildcard site scope.
            Some("acme".to_string()),
            Some("acme/blog".to_string()),
            Some("acme/shop".to_string()),
            Some("other/blog".to_string()),
            // A literal `*` target: the wildcard is the *absence* of a target
            // (`None`), so a grant/required of the string `*` must be treated
            // literally by both engines (a resource named `*` can't be created).
            Some("*".to_string()),
            Some("acme/*".to_string()),
        ];
        for roles in rolesets {
            let expected_set: RightSet = policy.rights_for(roles);
            for &resource in &Resource::ALL {
                for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
                    for target in &targets {
                        let required = Right::new(resource, target.clone(), action);
                        let oracle = expected_set.allows(&required);
                        // Unwrap `decide` so a construction bug panics loudly with
                        // the offending inputs instead of silently denying.
                        let got = cedar.decide(roles, &required).expect("cedar decide")
                            == Decision::Allow;
                        assert_eq!(
                            got, oracle,
                            "mismatch: roles={roles:?} required={required:?} (cedar={got} oracle={oracle})"
                        );
                    }
                }
            }
        }
    }

    fn default_rolesets() -> Vec<Vec<GrantedRole>> {
        vec![
            vec![],
            vec![GrantedRole::global("admin")],
            vec![GrantedRole::global("operator")],
            // Scoped roles granted globally (no target): RoleTarget templates
            // contribute nothing; only their AnyTarget templates (e.g. Blobs) apply.
            vec![GrantedRole::global("publisher")],
            vec![GrantedRole::global("deployer")],
            vec![GrantedRole::global("viewer")],
            // Scoped roles bound to a site.
            vec![GrantedRole::scoped("publisher", "blog")],
            vec![GrantedRole::scoped("publisher", "shop")],
            vec![GrantedRole::scoped("deployer", "blog")],
            vec![GrantedRole::scoped("viewer", "blog")],
            // Multiple instances of the same scoped role → the site set has 2 members.
            vec![
                GrantedRole::scoped("publisher", "blog"),
                GrantedRole::scoped("publisher", "shop"),
            ],
            // Mixed roles.
            vec![
                GrantedRole::scoped("publisher", "blog"),
                GrantedRole::scoped("viewer", "shop"),
            ],
            vec![
                GrantedRole::scoped("deployer", "blog"),
                GrantedRole::global("operator"),
            ],
            // Unknown role → grants nothing (rights_for skips it).
            vec![GrantedRole::global("ghost")],
            vec![
                GrantedRole::global("ghost"),
                GrantedRole::scoped("viewer", "blog"),
            ],
            // Project roles (0.2.0): the tenant boundary + project-wildcard site scope
            // must match the oracle across every (resource, action, target).
            vec![GrantedRole::scoped("project_admin", "acme")],
            vec![GrantedRole::scoped("project_publisher", "acme")],
            vec![GrantedRole::scoped("project_viewer", "acme")],
            vec![GrantedRole::global("project_admin")], // no target → contributes only Blobs
            // A project-qualified site role alongside a project role.
            vec![
                GrantedRole::scoped("publisher", "acme/blog"),
                GrantedRole::scoped("project_viewer", "acme"),
            ],
            // Two projects at once — coverage must stay scoped to each.
            vec![
                GrantedRole::scoped("project_admin", "acme"),
                GrantedRole::scoped("project_viewer", "other"),
            ],
            // A grant target of the literal string `*` is NOT a global wildcard:
            // both engines must treat it as matching only a resource named `*`
            // (the pure oracle previously over-granted here — the gate now covers it).
            vec![GrantedRole::scoped("publisher", "*")],
            vec![GrantedRole::scoped("project_admin", "*")],
        ]
    }

    #[test]
    fn cedar_matches_oracle_default_policy() {
        assert_faithful(&AuthzPolicy::default_policy(), &default_rolesets());
    }

    #[test]
    fn cedar_matches_oracle_custom_policy() {
        // A second, hand-rolled policy to vary the *policy* dimension (not just
        // roles/required): a scoped editor (Site read+write) and a global auditor.
        let mut roles: BTreeMap<String, Vec<RightTemplate>> = BTreeMap::new();
        roles.insert(
            "editor".to_string(),
            vec![
                RightTemplate::scoped(Resource::Site, Action::Read),
                RightTemplate::scoped(Resource::Site, Action::Write),
            ],
        );
        roles.insert(
            "auditor".to_string(),
            vec![
                RightTemplate::any(Resource::System, Action::Read),
                RightTemplate::any(Resource::Tokens, Action::Read),
            ],
        );
        // A role that is BOTH scoped (Site) and global (Certs admin) — exercises a
        // role with mixed template scopes.
        roles.insert(
            "sitelead".to_string(),
            vec![
                RightTemplate::scoped(Resource::Site, Action::Admin),
                RightTemplate::any(Resource::Certs, Action::Admin),
            ],
        );
        let policy = AuthzPolicy {
            version: boatramp_types::SCHEMA_VERSION,
            roles,
        };
        let rolesets = vec![
            vec![],
            vec![GrantedRole::scoped("editor", "blog")],
            vec![GrantedRole::global("editor")], // scoped role, no target → nothing
            vec![GrantedRole::global("auditor")],
            vec![GrantedRole::scoped("sitelead", "blog")],
            vec![GrantedRole::global("sitelead")], // Certs admin applies; Site does not
            vec![
                GrantedRole::scoped("editor", "blog"),
                GrantedRole::global("auditor"),
            ],
            vec![
                GrantedRole::scoped("sitelead", "shop"),
                GrantedRole::scoped("editor", "blog"),
            ],
        ];
        assert_faithful(&policy, &rolesets);
    }

    #[test]
    fn compile_rejects_unsafe_role_name() {
        for bad in [
            "has space",
            "quote\"inject",
            "dash-role",
            "dot.role",
            "",
            "1leading",
        ] {
            let mut roles: BTreeMap<String, Vec<RightTemplate>> = BTreeMap::new();
            roles.insert(
                bad.to_string(),
                vec![RightTemplate::any(Resource::System, Action::Read)],
            );
            let policy = AuthzPolicy {
                version: boatramp_types::SCHEMA_VERSION,
                roles,
            };
            assert!(
                matches!(
                    CompiledCedar::compile(&policy),
                    Err(CedarError::RoleName(_))
                ),
                "expected rejection of role name {bad:?}"
            );
        }
    }

    #[test]
    fn admin_is_superuser_across_actions() {
        let cedar = CompiledCedar::compile(&AuthzPolicy::default_policy()).unwrap();
        let admin = [GrantedRole::global("admin")];
        for &resource in &Resource::ALL {
            for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
                let target = matches!(resource, Resource::Site).then(|| "any-site".to_string());
                let required = Right::new(resource, target, action);
                assert!(
                    cedar.authorize(&admin, &required),
                    "admin denied {required:?}"
                );
            }
        }
    }

    #[test]
    fn publisher_scoped_to_its_site_only() {
        let cedar = CompiledCedar::compile(&AuthzPolicy::default_policy()).unwrap();
        let roles = [GrantedRole::scoped("publisher", "blog")];
        // Its own site: write allowed.
        assert!(cedar.authorize(
            &roles,
            &Right::new(Resource::Site, Some("blog".into()), Action::Write)
        ));
        // A different site: denied.
        assert!(!cedar.authorize(
            &roles,
            &Right::new(Resource::Site, Some("shop".into()), Action::Write)
        ));
        // Blob deploy (AnyTarget) allowed regardless of site.
        assert!(cedar.authorize(&roles, &Right::new(Resource::Blobs, None, Action::Deploy)));
        // System admin denied.
        assert!(!cedar.authorize(&roles, &Right::new(Resource::System, None, Action::Admin)));
    }
}