Skip to main content

gitiverse_core/
policy.rs

1use wire_mesh_core::domain::revocation::RevocationCheck;
2use wire_mesh_core::domain::tokens::{TokenRejection, TokenVerdict, verify_capability_token};
3use wire_mesh_core::ports::{Clock, Identity};
4use wire_mesh_wire::tokens::{CapabilityScope, CoseSign1};
5
6use crate::ids::{ActorId, CAP_CI, CAP_MAINTAIN, CAP_READ, CAP_WRITE, RepoId};
7use crate::repo::RepoVisibility;
8
9/// Repository action being authorised.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum RepoAction {
12    Read,
13    Write,
14    Maintain,
15    Ci,
16}
17
18impl RepoAction {
19    /// Minimum capability verb required for this action.
20    #[must_use]
21    pub const fn capability(self) -> &'static str {
22        match self {
23            RepoAction::Read => CAP_READ,
24            RepoAction::Write => CAP_WRITE,
25            RepoAction::Maintain => CAP_MAINTAIN,
26            RepoAction::Ci => CAP_CI,
27        }
28    }
29}
30
31/// Why an access request succeeded.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum AccessGrant {
34    PublicRead,
35    Authority {
36        actor: ActorId,
37    },
38    Capability {
39        capability: String,
40        bearer: ActorId,
41        root_issuer: ActorId,
42        effective_expires: u64,
43    },
44}
45
46/// Why an access request was denied.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum AccessDenial {
49    MissingToken,
50    TokenRejected(TokenRejection),
51    UntrustedRootIssuer(ActorId),
52    WrongScope,
53    InsufficientCapability {
54        required: &'static str,
55        presented: String,
56    },
57}
58
59/// Outcome of repository access evaluation.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum AccessDecision {
62    Allow(AccessGrant),
63    Deny(AccessDenial),
64}
65
66impl AccessDecision {
67    #[must_use]
68    pub fn is_allowed(&self) -> bool {
69        matches!(self, AccessDecision::Allow(_))
70    }
71}
72
73/// Context required to evaluate an access check against repository visibility, authorities, revocation view, and clock.
74pub struct AccessContext<'a> {
75    pub repo_id: RepoId,
76    pub visibility: RepoVisibility,
77    pub authorities: &'a [ActorId],
78    pub identity: &'a dyn Identity,
79    pub clock: &'a dyn Clock,
80    pub revocations: &'a dyn RevocationCheck,
81}
82
83/// Builds the canonical capability scope for a specific repository (`kind = "repo"`, `path = "repo:<repo_id>"`).
84#[must_use]
85pub fn repo_scope(repo_id: &RepoId) -> CapabilityScope {
86    CapabilityScope {
87        kind: "repo".to_owned(),
88        path: Some(format!("repo:{repo_id}")),
89    }
90}
91
92/// Builds a wildcard repository scope (`kind = "repo"`, `path = None`) suitable as a delegable root over any repository.
93#[must_use]
94pub fn wildcard_repo_scope() -> CapabilityScope {
95    CapabilityScope {
96        kind: "repo".to_owned(),
97        path: None,
98    }
99}
100
101/// Checks whether a capability scope authorises operations on `repo_id`.
102#[must_use]
103pub fn scope_matches_repo(scope: &CapabilityScope, repo_id: &RepoId) -> bool {
104    if scope.validate().is_err() {
105        return false;
106    }
107    if !matches!(scope.kind.as_str(), "repo" | "gitiverse") {
108        return false;
109    }
110    match scope.path.as_deref() {
111        None | Some("*") => true,
112        Some(path) => {
113            path == repo_id.to_string()
114                || path == format!("repo:{repo_id}")
115                || path == format!("repo:{}", repo_id.to_hex())
116                || path == format!("/{repo_id}")
117        }
118    }
119}
120
121/// Checks whether a presented capability verb satisfies `action`.
122#[must_use]
123pub fn verb_satisfies(presented: &str, action: RepoAction) -> bool {
124    match action {
125        RepoAction::Read => matches!(presented, CAP_READ | CAP_WRITE | CAP_MAINTAIN),
126        RepoAction::Write => matches!(presented, CAP_WRITE | CAP_MAINTAIN),
127        RepoAction::Maintain => presented == CAP_MAINTAIN,
128        RepoAction::Ci => presented == CAP_CI,
129    }
130}
131
132/// Evaluates access for `action` on a repository, checking `RepoVisibility`, `RevocationCheck`, `verify_capability_token`, authority root trust, resource scope, and capability verb.
133pub async fn evaluate_access(
134    ctx: &AccessContext<'_>,
135    action: RepoAction,
136    caller: Option<ActorId>,
137    token: Option<&CoseSign1>,
138) -> AccessDecision {
139    let Some(token) = token else {
140        if let Some(actor) = caller
141            && ctx.authorities.contains(&actor)
142            && matches!(
143                action,
144                RepoAction::Read | RepoAction::Write | RepoAction::Maintain
145            )
146        {
147            return AccessDecision::Allow(AccessGrant::Authority { actor });
148        }
149        if action == RepoAction::Read && ctx.visibility == RepoVisibility::Public {
150            return AccessDecision::Allow(AccessGrant::PublicRead);
151        }
152        return AccessDecision::Deny(AccessDenial::MissingToken);
153    };
154
155    let expected_bearer = caller.map(|actor| *actor.as_device_id());
156    let verdict = verify_capability_token(
157        ctx.identity,
158        ctx.clock,
159        ctx.revocations,
160        token,
161        expected_bearer,
162    )
163    .await;
164
165    let (claims, effective_expires, root_issuer) = match verdict {
166        TokenVerdict::Valid {
167            claims,
168            effective_expires,
169            root_issuer,
170            ..
171        } => (claims, effective_expires, root_issuer),
172        TokenVerdict::Invalid(rejection) => {
173            return AccessDecision::Deny(AccessDenial::TokenRejected(rejection));
174        }
175    };
176
177    let root_actor = ActorId(root_issuer);
178    if !ctx.authorities.contains(&root_actor) {
179        return AccessDecision::Deny(AccessDenial::UntrustedRootIssuer(root_actor));
180    }
181
182    if !scope_matches_repo(&claims.scope, &ctx.repo_id) {
183        return AccessDecision::Deny(AccessDenial::WrongScope);
184    }
185
186    if !verb_satisfies(&claims.capability.0, action) {
187        return AccessDecision::Deny(AccessDenial::InsufficientCapability {
188            required: action.capability(),
189            presented: claims.capability.0,
190        });
191    }
192
193    AccessDecision::Allow(AccessGrant::Capability {
194        capability: claims.capability.0,
195        bearer: ActorId(claims.bearer),
196        root_issuer: root_actor,
197        effective_expires,
198    })
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use wire_mesh_core::adapters::NodeIdentity;
205    use wire_mesh_core::domain::mint::{
206        MintCapabilityToken, mint_capability_token, mint_revocation_entry,
207    };
208    use wire_mesh_core::domain::revocation::RevocationView;
209    use wire_mesh_wire::tokens::CapabilityVerb;
210
211    const NOW: u64 = 1_700_000_000_000;
212
213    struct FixedClock(u64);
214    impl Clock for FixedClock {
215        fn now_unix_ms(&self) -> u64 {
216            self.0
217        }
218    }
219
220    async fn mint_repo_token(
221        issuer: &NodeIdentity,
222        bearer: ActorId,
223        verb: &str,
224        scope: CapabilityScope,
225        token_id: Vec<u8>,
226    ) -> CoseSign1 {
227        mint_capability_token(MintCapabilityToken {
228            identity: issuer,
229            clock: &FixedClock(NOW),
230            token_id,
231            bearer: *bearer.as_device_id(),
232            capability: CapabilityVerb(verb.to_owned()),
233            scope,
234            expires: NOW + 60_000,
235            not_before: None,
236            delegations_remaining: Some(1),
237            parent: None,
238            conditions: None,
239            authorised_by: None,
240            grants_capability: None,
241            requests_capability: None,
242        })
243        .await
244        .unwrap()
245    }
246
247    #[tokio::test]
248    async fn public_and_private_read_access_obeys_visibility_and_tokens() {
249        let founder = NodeIdentity::generate_ed25519();
250        let reader = NodeIdentity::generate_ed25519();
251        let repo_id = RepoId::from_bytes([0xAA; 32]);
252        let authorities = [ActorId(*founder.device_id())];
253        let revocations = RevocationView::new();
254        let clock = FixedClock(NOW);
255
256        let public_ctx = AccessContext {
257            repo_id,
258            visibility: RepoVisibility::Public,
259            authorities: &authorities,
260            identity: &founder,
261            clock: &clock,
262            revocations: &revocations,
263        };
264        assert_eq!(
265            evaluate_access(&public_ctx, RepoAction::Read, None, None).await,
266            AccessDecision::Allow(AccessGrant::PublicRead)
267        );
268        assert_eq!(
269            evaluate_access(&public_ctx, RepoAction::Write, None, None).await,
270            AccessDecision::Deny(AccessDenial::MissingToken)
271        );
272
273        let private_ctx = AccessContext {
274            visibility: RepoVisibility::Private,
275            ..public_ctx
276        };
277        assert_eq!(
278            evaluate_access(&private_ctx, RepoAction::Read, None, None).await,
279            AccessDecision::Deny(AccessDenial::MissingToken)
280        );
281
282        let reader_id = ActorId(*reader.device_id());
283        let tok = mint_repo_token(
284            &founder,
285            reader_id,
286            CAP_READ,
287            repo_scope(&repo_id),
288            vec![1; 16],
289        )
290        .await;
291        assert!(
292            evaluate_access(&private_ctx, RepoAction::Read, Some(reader_id), Some(&tok))
293                .await
294                .is_allowed()
295        );
296        assert!(matches!(
297            evaluate_access(&private_ctx, RepoAction::Write, Some(reader_id), Some(&tok)).await,
298            AccessDecision::Deny(AccessDenial::InsufficientCapability { .. })
299        ));
300    }
301
302    #[tokio::test]
303    async fn scope_mismatch_untrusted_issuer_and_revocation_are_denied() {
304        let founder = NodeIdentity::generate_ed25519();
305        let stranger = NodeIdentity::generate_ed25519();
306        let worker = NodeIdentity::generate_es256();
307        let repo_id = RepoId::from_bytes([0x10; 32]);
308        let other_repo = RepoId::from_bytes([0x20; 32]);
309        let authorities = [ActorId(*founder.device_id())];
310        let clock = FixedClock(NOW);
311        let worker_id = ActorId(*worker.device_id());
312
313        let token_id = vec![9; 16];
314        let valid_tok = mint_repo_token(
315            &founder,
316            worker_id,
317            CAP_CI,
318            CapabilityScope {
319                kind: "repo".to_owned(),
320                path: Some("*".to_owned()),
321            },
322            token_id.clone(),
323        )
324        .await;
325        let wrong_scope_tok = mint_repo_token(
326            &founder,
327            worker_id,
328            CAP_WRITE,
329            repo_scope(&other_repo),
330            vec![2; 16],
331        )
332        .await;
333        let untrusted_tok = mint_repo_token(
334            &stranger,
335            worker_id,
336            CAP_MAINTAIN,
337            repo_scope(&repo_id),
338            vec![3; 16],
339        )
340        .await;
341
342        let mut revocations = RevocationView::new();
343        let ctx = AccessContext {
344            repo_id,
345            visibility: RepoVisibility::Private,
346            authorities: &authorities,
347            identity: &founder,
348            clock: &clock,
349            revocations: &revocations,
350        };
351
352        assert!(
353            evaluate_access(&ctx, RepoAction::Ci, Some(worker_id), Some(&valid_tok))
354                .await
355                .is_allowed()
356        );
357        // CI token cannot push code.
358        assert!(matches!(
359            evaluate_access(&ctx, RepoAction::Write, Some(worker_id), Some(&valid_tok)).await,
360            AccessDecision::Deny(AccessDenial::InsufficientCapability { .. })
361        ));
362        assert_eq!(
363            evaluate_access(
364                &ctx,
365                RepoAction::Write,
366                Some(worker_id),
367                Some(&wrong_scope_tok)
368            )
369            .await,
370            AccessDecision::Deny(AccessDenial::WrongScope)
371        );
372        assert_eq!(
373            evaluate_access(
374                &ctx,
375                RepoAction::Maintain,
376                Some(worker_id),
377                Some(&untrusted_tok)
378            )
379            .await,
380            AccessDecision::Deny(AccessDenial::UntrustedRootIssuer(ActorId(
381                *stranger.device_id()
382            )))
383        );
384
385        // Revoking the token must immediately deny access.
386        let entry = mint_revocation_entry(&founder, token_id.clone(), NOW)
387            .await
388            .unwrap();
389        revocations
390            .verify_and_insert(&entry, &founder)
391            .await
392            .unwrap();
393        let ctx_revoked = AccessContext {
394            repo_id,
395            visibility: RepoVisibility::Private,
396            authorities: &authorities,
397            identity: &founder,
398            clock: &clock,
399            revocations: &revocations,
400        };
401        assert!(matches!(
402            evaluate_access(
403                &ctx_revoked,
404                RepoAction::Ci,
405                Some(worker_id),
406                Some(&valid_tok)
407            )
408            .await,
409            AccessDecision::Deny(AccessDenial::TokenRejected(TokenRejection::Revoked { .. }))
410        ));
411    }
412
413    #[tokio::test]
414    async fn delegated_wildcard_to_repo_token_verifies_and_authorises() {
415        let founder = NodeIdentity::generate_ed25519();
416        let maintainer = NodeIdentity::generate_ed25519();
417        let contributor = NodeIdentity::generate_es256();
418        let repo_id = RepoId::from_bytes([0x55; 32]);
419        let authorities = [ActorId(*founder.device_id())];
420        let revocations = RevocationView::new();
421        let clock = FixedClock(NOW);
422
423        let root_write = mint_repo_token(
424            &founder,
425            ActorId(*maintainer.device_id()),
426            CAP_WRITE,
427            wildcard_repo_scope(),
428            vec![10; 16],
429        )
430        .await;
431        let delegated = mint_capability_token(MintCapabilityToken {
432            identity: &maintainer,
433            clock: &clock,
434            token_id: vec![11; 16],
435            bearer: *contributor.device_id(),
436            capability: CapabilityVerb(CAP_WRITE.to_owned()),
437            scope: repo_scope(&repo_id),
438            expires: NOW + 30_000,
439            not_before: None,
440            delegations_remaining: Some(0),
441            parent: Some(&root_write),
442            conditions: None,
443            authorised_by: None,
444            grants_capability: None,
445            requests_capability: None,
446        })
447        .await
448        .unwrap();
449
450        let ctx = AccessContext {
451            repo_id,
452            visibility: RepoVisibility::Private,
453            authorities: &authorities,
454            identity: &founder,
455            clock: &clock,
456            revocations: &revocations,
457        };
458        assert!(
459            evaluate_access(
460                &ctx,
461                RepoAction::Write,
462                Some(ActorId(*contributor.device_id())),
463                Some(&delegated)
464            )
465            .await
466            .is_allowed()
467        );
468    }
469
470    #[tokio::test]
471    async fn authenticated_authority_succeeds_without_token_except_for_ci() {
472        let founder = NodeIdentity::generate_es256();
473        let stranger = NodeIdentity::generate_es256();
474        let founder_id = ActorId(*founder.device_id());
475        let stranger_id = ActorId(*stranger.device_id());
476        let repo_id = RepoId::from_bytes([0x77; 32]);
477        let authorities = [founder_id];
478        let revocations = RevocationView::new();
479        let clock = FixedClock(NOW);
480        let ctx = AccessContext {
481            repo_id,
482            visibility: RepoVisibility::Private,
483            authorities: &authorities,
484            identity: &founder,
485            clock: &clock,
486            revocations: &revocations,
487        };
488
489        for action in [RepoAction::Read, RepoAction::Write, RepoAction::Maintain] {
490            assert_eq!(
491                evaluate_access(&ctx, action, Some(founder_id), None).await,
492                AccessDecision::Allow(AccessGrant::Authority { actor: founder_id })
493            );
494        }
495        assert_eq!(
496            evaluate_access(&ctx, RepoAction::Ci, Some(founder_id), None).await,
497            AccessDecision::Deny(AccessDenial::MissingToken)
498        );
499        assert_eq!(
500            evaluate_access(&ctx, RepoAction::Read, Some(stranger_id), None).await,
501            AccessDecision::Deny(AccessDenial::MissingToken)
502        );
503    }
504}