gitiverse-core 0.3.0

Core domain identities, repository manifests, signed refs, capability access policy, and canonical CBOR protocol types for gitiverse
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
use wire_mesh_core::domain::revocation::RevocationCheck;
use wire_mesh_core::domain::tokens::{TokenRejection, TokenVerdict, verify_capability_token};
use wire_mesh_core::ports::{Clock, Identity};
use wire_mesh_wire::tokens::{CapabilityScope, CoseSign1};

use crate::ids::{ActorId, CAP_CI, CAP_MAINTAIN, CAP_READ, CAP_WRITE, RepoId};
use crate::repo::RepoVisibility;

/// Repository action being authorised.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RepoAction {
    Read,
    Write,
    Maintain,
    Ci,
}

impl RepoAction {
    /// Minimum capability verb required for this action.
    #[must_use]
    pub const fn capability(self) -> &'static str {
        match self {
            RepoAction::Read => CAP_READ,
            RepoAction::Write => CAP_WRITE,
            RepoAction::Maintain => CAP_MAINTAIN,
            RepoAction::Ci => CAP_CI,
        }
    }
}

/// Why an access request succeeded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessGrant {
    PublicRead,
    Authority {
        actor: ActorId,
    },
    Capability {
        capability: String,
        bearer: ActorId,
        root_issuer: ActorId,
        effective_expires: u64,
    },
}

/// Why an access request was denied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessDenial {
    MissingToken,
    TokenRejected(TokenRejection),
    UntrustedRootIssuer(ActorId),
    WrongScope,
    InsufficientCapability {
        required: &'static str,
        presented: String,
    },
}

/// Outcome of repository access evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessDecision {
    Allow(AccessGrant),
    Deny(AccessDenial),
}

impl AccessDecision {
    #[must_use]
    pub fn is_allowed(&self) -> bool {
        matches!(self, AccessDecision::Allow(_))
    }
}

/// Context required to evaluate an access check against repository visibility, authorities, revocation view, and clock.
pub struct AccessContext<'a> {
    pub repo_id: RepoId,
    pub visibility: RepoVisibility,
    pub authorities: &'a [ActorId],
    pub identity: &'a dyn Identity,
    pub clock: &'a dyn Clock,
    pub revocations: &'a dyn RevocationCheck,
}

/// Builds the canonical capability scope for a specific repository (`kind = "repo"`, `path = "repo:<repo_id>"`).
#[must_use]
pub fn repo_scope(repo_id: &RepoId) -> CapabilityScope {
    CapabilityScope {
        kind: "repo".to_owned(),
        path: Some(format!("repo:{repo_id}")),
    }
}

/// Builds a wildcard repository scope (`kind = "repo"`, `path = None`) suitable as a delegable root over any repository.
#[must_use]
pub fn wildcard_repo_scope() -> CapabilityScope {
    CapabilityScope {
        kind: "repo".to_owned(),
        path: None,
    }
}

/// Checks whether a capability scope authorises operations on `repo_id`.
#[must_use]
pub fn scope_matches_repo(scope: &CapabilityScope, repo_id: &RepoId) -> bool {
    if scope.validate().is_err() {
        return false;
    }
    if !matches!(scope.kind.as_str(), "repo" | "gitiverse") {
        return false;
    }
    match scope.path.as_deref() {
        None | Some("*") => true,
        Some(path) => {
            path == repo_id.to_string()
                || path == format!("repo:{repo_id}")
                || path == format!("repo:{}", repo_id.to_hex())
                || path == format!("/{repo_id}")
        }
    }
}

/// Checks whether a presented capability verb satisfies `action`.
#[must_use]
pub fn verb_satisfies(presented: &str, action: RepoAction) -> bool {
    match action {
        RepoAction::Read => matches!(presented, CAP_READ | CAP_WRITE | CAP_MAINTAIN),
        RepoAction::Write => matches!(presented, CAP_WRITE | CAP_MAINTAIN),
        RepoAction::Maintain => presented == CAP_MAINTAIN,
        RepoAction::Ci => presented == CAP_CI,
    }
}

/// Evaluates access for `action` on a repository, checking `RepoVisibility`, `RevocationCheck`, `verify_capability_token`, authority root trust, resource scope, and capability verb.
pub async fn evaluate_access(
    ctx: &AccessContext<'_>,
    action: RepoAction,
    caller: Option<ActorId>,
    token: Option<&CoseSign1>,
) -> AccessDecision {
    let Some(token) = token else {
        if let Some(actor) = caller
            && ctx.authorities.contains(&actor)
            && matches!(
                action,
                RepoAction::Read | RepoAction::Write | RepoAction::Maintain
            )
        {
            return AccessDecision::Allow(AccessGrant::Authority { actor });
        }
        if action == RepoAction::Read && ctx.visibility == RepoVisibility::Public {
            return AccessDecision::Allow(AccessGrant::PublicRead);
        }
        return AccessDecision::Deny(AccessDenial::MissingToken);
    };

    let expected_bearer = caller.map(|actor| *actor.as_device_id());
    let verdict = verify_capability_token(
        ctx.identity,
        ctx.clock,
        ctx.revocations,
        token,
        expected_bearer,
    )
    .await;

    let (claims, effective_expires, root_issuer) = match verdict {
        TokenVerdict::Valid {
            claims,
            effective_expires,
            root_issuer,
            ..
        } => (claims, effective_expires, root_issuer),
        TokenVerdict::Invalid(rejection) => {
            return AccessDecision::Deny(AccessDenial::TokenRejected(rejection));
        }
    };

    let root_actor = ActorId(root_issuer);
    if !ctx.authorities.contains(&root_actor) {
        return AccessDecision::Deny(AccessDenial::UntrustedRootIssuer(root_actor));
    }

    if !scope_matches_repo(&claims.scope, &ctx.repo_id) {
        return AccessDecision::Deny(AccessDenial::WrongScope);
    }

    if !verb_satisfies(&claims.capability.0, action) {
        return AccessDecision::Deny(AccessDenial::InsufficientCapability {
            required: action.capability(),
            presented: claims.capability.0,
        });
    }

    AccessDecision::Allow(AccessGrant::Capability {
        capability: claims.capability.0,
        bearer: ActorId(claims.bearer),
        root_issuer: root_actor,
        effective_expires,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use wire_mesh_core::adapters::NodeIdentity;
    use wire_mesh_core::domain::mint::{
        MintCapabilityToken, mint_capability_token, mint_revocation_entry,
    };
    use wire_mesh_core::domain::revocation::RevocationView;
    use wire_mesh_wire::tokens::CapabilityVerb;

    const NOW: u64 = 1_700_000_000_000;

    struct FixedClock(u64);
    impl Clock for FixedClock {
        fn now_unix_ms(&self) -> u64 {
            self.0
        }
    }

    async fn mint_repo_token(
        issuer: &NodeIdentity,
        bearer: ActorId,
        verb: &str,
        scope: CapabilityScope,
        token_id: Vec<u8>,
    ) -> CoseSign1 {
        mint_capability_token(MintCapabilityToken {
            identity: issuer,
            clock: &FixedClock(NOW),
            token_id,
            bearer: *bearer.as_device_id(),
            capability: CapabilityVerb(verb.to_owned()),
            scope,
            expires: NOW + 60_000,
            not_before: None,
            delegations_remaining: Some(1),
            parent: None,
            conditions: None,
            authorised_by: None,
            grants_capability: None,
            requests_capability: None,
        })
        .await
        .unwrap()
    }

    #[tokio::test]
    async fn public_and_private_read_access_obeys_visibility_and_tokens() {
        let founder = NodeIdentity::generate_ed25519();
        let reader = NodeIdentity::generate_ed25519();
        let repo_id = RepoId::from_bytes([0xAA; 32]);
        let authorities = [ActorId(*founder.device_id())];
        let revocations = RevocationView::new();
        let clock = FixedClock(NOW);

        let public_ctx = AccessContext {
            repo_id,
            visibility: RepoVisibility::Public,
            authorities: &authorities,
            identity: &founder,
            clock: &clock,
            revocations: &revocations,
        };
        assert_eq!(
            evaluate_access(&public_ctx, RepoAction::Read, None, None).await,
            AccessDecision::Allow(AccessGrant::PublicRead)
        );
        assert_eq!(
            evaluate_access(&public_ctx, RepoAction::Write, None, None).await,
            AccessDecision::Deny(AccessDenial::MissingToken)
        );

        let private_ctx = AccessContext {
            visibility: RepoVisibility::Private,
            ..public_ctx
        };
        assert_eq!(
            evaluate_access(&private_ctx, RepoAction::Read, None, None).await,
            AccessDecision::Deny(AccessDenial::MissingToken)
        );

        let reader_id = ActorId(*reader.device_id());
        let tok = mint_repo_token(
            &founder,
            reader_id,
            CAP_READ,
            repo_scope(&repo_id),
            vec![1; 16],
        )
        .await;
        assert!(
            evaluate_access(&private_ctx, RepoAction::Read, Some(reader_id), Some(&tok))
                .await
                .is_allowed()
        );
        assert!(matches!(
            evaluate_access(&private_ctx, RepoAction::Write, Some(reader_id), Some(&tok)).await,
            AccessDecision::Deny(AccessDenial::InsufficientCapability { .. })
        ));
    }

    #[tokio::test]
    async fn scope_mismatch_untrusted_issuer_and_revocation_are_denied() {
        let founder = NodeIdentity::generate_ed25519();
        let stranger = NodeIdentity::generate_ed25519();
        let worker = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x10; 32]);
        let other_repo = RepoId::from_bytes([0x20; 32]);
        let authorities = [ActorId(*founder.device_id())];
        let clock = FixedClock(NOW);
        let worker_id = ActorId(*worker.device_id());

        let token_id = vec![9; 16];
        let valid_tok = mint_repo_token(
            &founder,
            worker_id,
            CAP_CI,
            CapabilityScope {
                kind: "repo".to_owned(),
                path: Some("*".to_owned()),
            },
            token_id.clone(),
        )
        .await;
        let wrong_scope_tok = mint_repo_token(
            &founder,
            worker_id,
            CAP_WRITE,
            repo_scope(&other_repo),
            vec![2; 16],
        )
        .await;
        let untrusted_tok = mint_repo_token(
            &stranger,
            worker_id,
            CAP_MAINTAIN,
            repo_scope(&repo_id),
            vec![3; 16],
        )
        .await;

        let mut revocations = RevocationView::new();
        let ctx = AccessContext {
            repo_id,
            visibility: RepoVisibility::Private,
            authorities: &authorities,
            identity: &founder,
            clock: &clock,
            revocations: &revocations,
        };

        assert!(
            evaluate_access(&ctx, RepoAction::Ci, Some(worker_id), Some(&valid_tok))
                .await
                .is_allowed()
        );
        // CI token cannot push code.
        assert!(matches!(
            evaluate_access(&ctx, RepoAction::Write, Some(worker_id), Some(&valid_tok)).await,
            AccessDecision::Deny(AccessDenial::InsufficientCapability { .. })
        ));
        assert_eq!(
            evaluate_access(
                &ctx,
                RepoAction::Write,
                Some(worker_id),
                Some(&wrong_scope_tok)
            )
            .await,
            AccessDecision::Deny(AccessDenial::WrongScope)
        );
        assert_eq!(
            evaluate_access(
                &ctx,
                RepoAction::Maintain,
                Some(worker_id),
                Some(&untrusted_tok)
            )
            .await,
            AccessDecision::Deny(AccessDenial::UntrustedRootIssuer(ActorId(
                *stranger.device_id()
            )))
        );

        // Revoking the token must immediately deny access.
        let entry = mint_revocation_entry(&founder, token_id.clone(), NOW)
            .await
            .unwrap();
        revocations
            .verify_and_insert(&entry, &founder)
            .await
            .unwrap();
        let ctx_revoked = AccessContext {
            repo_id,
            visibility: RepoVisibility::Private,
            authorities: &authorities,
            identity: &founder,
            clock: &clock,
            revocations: &revocations,
        };
        assert!(matches!(
            evaluate_access(
                &ctx_revoked,
                RepoAction::Ci,
                Some(worker_id),
                Some(&valid_tok)
            )
            .await,
            AccessDecision::Deny(AccessDenial::TokenRejected(TokenRejection::Revoked { .. }))
        ));
    }

    #[tokio::test]
    async fn delegated_wildcard_to_repo_token_verifies_and_authorises() {
        let founder = NodeIdentity::generate_ed25519();
        let maintainer = NodeIdentity::generate_ed25519();
        let contributor = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x55; 32]);
        let authorities = [ActorId(*founder.device_id())];
        let revocations = RevocationView::new();
        let clock = FixedClock(NOW);

        let root_write = mint_repo_token(
            &founder,
            ActorId(*maintainer.device_id()),
            CAP_WRITE,
            wildcard_repo_scope(),
            vec![10; 16],
        )
        .await;
        let delegated = mint_capability_token(MintCapabilityToken {
            identity: &maintainer,
            clock: &clock,
            token_id: vec![11; 16],
            bearer: *contributor.device_id(),
            capability: CapabilityVerb(CAP_WRITE.to_owned()),
            scope: repo_scope(&repo_id),
            expires: NOW + 30_000,
            not_before: None,
            delegations_remaining: Some(0),
            parent: Some(&root_write),
            conditions: None,
            authorised_by: None,
            grants_capability: None,
            requests_capability: None,
        })
        .await
        .unwrap();

        let ctx = AccessContext {
            repo_id,
            visibility: RepoVisibility::Private,
            authorities: &authorities,
            identity: &founder,
            clock: &clock,
            revocations: &revocations,
        };
        assert!(
            evaluate_access(
                &ctx,
                RepoAction::Write,
                Some(ActorId(*contributor.device_id())),
                Some(&delegated)
            )
            .await
            .is_allowed()
        );
    }

    #[tokio::test]
    async fn authenticated_authority_succeeds_without_token_except_for_ci() {
        let founder = NodeIdentity::generate_es256();
        let stranger = NodeIdentity::generate_es256();
        let founder_id = ActorId(*founder.device_id());
        let stranger_id = ActorId(*stranger.device_id());
        let repo_id = RepoId::from_bytes([0x77; 32]);
        let authorities = [founder_id];
        let revocations = RevocationView::new();
        let clock = FixedClock(NOW);
        let ctx = AccessContext {
            repo_id,
            visibility: RepoVisibility::Private,
            authorities: &authorities,
            identity: &founder,
            clock: &clock,
            revocations: &revocations,
        };

        for action in [RepoAction::Read, RepoAction::Write, RepoAction::Maintain] {
            assert_eq!(
                evaluate_access(&ctx, action, Some(founder_id), None).await,
                AccessDecision::Allow(AccessGrant::Authority { actor: founder_id })
            );
        }
        assert_eq!(
            evaluate_access(&ctx, RepoAction::Ci, Some(founder_id), None).await,
            AccessDecision::Deny(AccessDenial::MissingToken)
        );
        assert_eq!(
            evaluate_access(&ctx, RepoAction::Read, Some(stranger_id), None).await,
            AccessDecision::Deny(AccessDenial::MissingToken)
        );
    }
}