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