alkgit 0.1.0

Git smart protocol for the alk family: pkt-line substrates, protocol V2 serving (upload-pack/receive-pack), producer/consumer halves on alkcall channels, and the backend seam traits — the shipped alkstore+alkblobs composition is the alkgit-substrate crate (ADR-010/025)
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
//! The per-repo authorization policy (ADR-011 §3 as amended by
//! ADR-015 §2) and the authorized-repo marker (ADR-007 step 3).
//!
//! [`authorize`] is a pure function over the resolved record and the
//! alkcall [`Identity`] — no io, no async, no backend calls; it is the
//! one tested policy the wave-2 serving entries and the `git/repo/*`
//! op handlers both evaluate before any protocol byte / op action.
//! [`AuthorizedRepo`] is the marker the door/adapter constructs only
//! when the check passes: serving entries take it as their input, so
//! skipping the check is a type error, not a runtime log. The collapse
//! rule (unknown-repo ≡ unauthorized → the generic wire denial,
//! ADR-008/N-2) stays call-site business — nothing here maps errors.

use alkcall::core::Identity;

use crate::registry::{AccessAction, RepoRecord, Visibility};

/// The per-repo policy function (ADR-011 §3 as amended by ADR-015 §2).
///
/// - `read` on a `Public` repo → allowed for anyone, including
///   `None` (anonymous-first-class — ADR-007's operative clause).
/// - `read` on a `Private` repo → identity required with a read grant.
/// - `write` → identity required and a write-or-manage grant, on every
///   repo (push is always authenticated).
/// - `manage` → identity required plus a `manage` grant — no anonymous
///   path and no owner-bypass path.
///
/// Grant monotonicity is evaluated here; stored grant sets need not be
/// closed under it (backend.md §RepoRecord): a stored `manage` grant
/// satisfies `manage`, `write`, and `read` checks; a stored `write`
/// satisfies `write` and `read`; a stored `read` satisfies `read`.
pub fn authorize(record: &RepoRecord, identity: Option<&Identity>, action: AccessAction) -> bool {
    match action {
        AccessAction::Read if record.visibility == Visibility::Public => true,
        AccessAction::Read | AccessAction::Write | AccessAction::Manage => {
            identity_holds(record, identity, action)
        }
    }
}

/// The two-tier repo-op gate (ADR-015 §3): the `delete`/`update`/`get`
/// ops' handler-side rule — global admin scope **OR** `manage` grant.
///
/// Pure function over the resolved record and the alkcall [`Identity`];
/// the ops carry an empty `AccessControl::default()` and evaluate this
/// instead. A `None` identity is denied — `manage` requires identity
/// (ADR-015 §2) and no scope set exists to hold `git:admin`. The
/// generic FORBIDDEN denial is the op layer's mapping (unknown-repo and
/// not-authorized collapse there per ADR-008 — the caller resolved the
/// record before this gate ran). The two sources stay distinct
/// (ADR-015 §6): `git:admin` in `Identity.scopes` is platform-level
/// capability, the grant is per-repo record state.
pub fn authorize_repo_op(record: &RepoRecord, identity: Option<&Identity>) -> bool {
    match identity {
        None => false,
        Some(identity) => {
            identity.scopes.iter().any(|scope| scope == GIT_ADMIN_SCOPE)
                || authorize(record, Some(identity), AccessAction::Manage)
        }
    }
}

/// The platform admin scope that satisfies the op gate's scope tier
/// (ADR-015 §3).
pub const GIT_ADMIN_SCOPE: &str = "git:admin";

/// The authorized-repo marker (ADR-007 step 3; the marker
/// transport.md's session substrate layer places in the session
/// tuples, front-door-blind per ADR-002).
///
/// The door/adapter constructs it only after the ADR-007 resolve →
/// authorize sequence passes; the serving entries take it as input, so
/// a session cannot reach the transport layer unchecked — the check is
/// unskippable by types. The marker carries the session tuple's
/// authorization inputs: the resolved [`RepoRecord`] (the object the
/// backend traits key their calls on), the [`AccessAction`] the check
/// was evaluated for, and the checked identity view — the granted
/// identity id, `None` for an anonymous public-read session.
///
/// Constructed with [`AuthorizedRepo::authorize`]; the fields are
/// private and there is no other constructor or public path in — a
/// denied evaluation (anonymous on a private repo, an unidentified
/// write, a grant that does not satisfy the action) yields `None`, so
/// no unauthorized session value can exist at any type level.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthorizedRepo {
    record: RepoRecord,
    action: AccessAction,
    identity_id: Option<String>,
}

impl AuthorizedRepo {
    /// The marker's only constructor (ADR-007 step 3): runs the
    /// [`authorize`] policy evaluation over the already-resolved
    /// record, the checked identity, and the action the service
    /// selects — `Some` only when the check passes, `None` (the
    /// collapse-rule denial input, mapped at the serving entries)
    /// otherwise.
    pub fn authorize(
        record: RepoRecord,
        identity: Option<&Identity>,
        action: AccessAction,
    ) -> Option<Self> {
        if authorize(&record, identity, action) {
            Some(Self {
                record,
                action,
                identity_id: identity.map(|identity| identity.id.clone()),
            })
        } else {
            None
        }
    }

    /// The resolved record — the input for the backend trait calls
    /// (`&RepoRecord` on every object-storage method, ADR-018 §2).
    pub fn record(&self) -> &RepoRecord {
        &self.record
    }

    /// The action the authorization was evaluated for (the service's
    /// selected tier: read for fetch, write for push, manage for the
    /// op gate).
    pub fn action(&self) -> AccessAction {
        self.action
    }

    /// The granted identity id (`Identity.id`, ADR-011 §1) — `None`
    /// for an anonymous public-read session.
    pub fn identity_id(&self) -> Option<&str> {
        self.identity_id.as_deref()
    }
}

/// The grant side of the matrix: identity required, and the stored
/// grant set must satisfy the action under its monotonic expansion
/// (`AccessAction`'s variant order encodes the tier ranking — a stored
/// grant satisfies the action iff it ranks at or above it).
fn identity_holds(record: &RepoRecord, identity: Option<&Identity>, action: AccessAction) -> bool {
    let Some(identity) = identity else {
        return false;
    };
    let Some(held) = record.grants.get(&identity.id) else {
        return false;
    };
    held.iter().any(|grant| *grant >= action)
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    fn identity(id: &str) -> Identity {
        Identity {
            id: id.to_string(),
            scopes: Vec::new(),
            resources: HashMap::new(),
        }
    }

    fn record(visibility: Visibility, grants: &[(&str, &[AccessAction])]) -> RepoRecord {
        RepoRecord {
            repo_id: "alkdev/alkgit".to_string(),
            visibility,
            grants: grants
                .iter()
                .map(|(key, actions)| ((*key).to_string(), actions.to_vec()))
                .collect(),
        }
    }

    #[test]
    fn public_read_allows_anyone_including_anonymous() {
        let public = record(Visibility::Public, &[]);
        assert!(authorize(&public, None, AccessAction::Read));
        let no_grants = identity("u-7731");
        assert!(authorize(&public, Some(&no_grants), AccessAction::Read));
        let with_grants = record(
            Visibility::Public,
            &[("u-7731", &[AccessAction::Read, AccessAction::Write])],
        );
        assert!(authorize(
            &with_grants,
            Some(&no_grants),
            AccessAction::Read
        ));
    }

    #[test]
    fn public_write_is_authenticated_and_granted_on_public_repos_too() {
        let public_empty = record(Visibility::Public, &[]);
        assert!(!authorize(&public_empty, None, AccessAction::Write));
        let stranger = identity("stranger");
        assert!(!authorize(
            &public_empty,
            Some(&stranger),
            AccessAction::Write
        ));
        let public_read_only = record(Visibility::Public, &[("stranger", &[AccessAction::Read])]);
        assert!(!authorize(
            &public_read_only,
            Some(&stranger),
            AccessAction::Write
        ));
    }

    #[test]
    fn private_read_denies_anonymous_and_the_grantless() {
        let private = record(Visibility::Private, &[]);
        assert!(!authorize(&private, None, AccessAction::Read));
        let holder = identity("u-7731");
        assert!(!authorize(&private, Some(&holder), AccessAction::Read));
    }

    #[test]
    fn private_read_is_satisfied_by_every_grant_tier() {
        for actions in [
            &[AccessAction::Read][..],
            &[AccessAction::Write],
            &[AccessAction::Manage],
            &[AccessAction::Read, AccessAction::Write],
        ] {
            let private = record(Visibility::Private, &[("u-7731", actions)]);
            let holder = identity("u-7731");
            assert!(authorize(&private, Some(&holder), AccessAction::Read));
        }
    }

    #[test]
    fn private_read_denies_an_identity_without_an_entry() {
        let private = record(Visibility::Private, &[("other", &[AccessAction::Manage])]);
        let stranger = identity("u-7731");
        assert!(!authorize(&private, Some(&stranger), AccessAction::Read));
    }

    #[test]
    fn write_requires_a_write_or_manage_grant() {
        for visibility in [Visibility::Public, Visibility::Private] {
            let empty = record(visibility, &[]);
            let holder = identity("u-7731");
            assert!(!authorize(&empty, None, AccessAction::Write));
            assert!(!authorize(&empty, Some(&holder), AccessAction::Write));
            let read_only = record(visibility, &[("u-7731", &[AccessAction::Read])]);
            assert!(!authorize(&read_only, Some(&holder), AccessAction::Write));
        }
    }

    #[test]
    fn write_is_satisfied_by_write_and_manage_grants() {
        for visibility in [Visibility::Public, Visibility::Private] {
            for actions in [
                &[AccessAction::Write][..],
                &[AccessAction::Manage],
                &[AccessAction::Read, AccessAction::Write],
                &[
                    AccessAction::Read,
                    AccessAction::Write,
                    AccessAction::Manage,
                ],
            ] {
                let granted = record(visibility, &[("u-7731", actions)]);
                let holder = identity("u-7731");
                assert!(authorize(&granted, Some(&holder), AccessAction::Write));
            }
        }
    }

    #[test]
    fn manage_denies_anonymous_and_lower_tiers() {
        for visibility in [Visibility::Public, Visibility::Private] {
            let empty = record(visibility, &[]);
            let holder = identity("u-7731");
            assert!(!authorize(&empty, None, AccessAction::Manage));
            assert!(!authorize(&empty, Some(&holder), AccessAction::Manage));
            let lower = record(
                visibility,
                &[("u-7731", &[AccessAction::Read, AccessAction::Write])],
            );
            assert!(!authorize(&lower, Some(&holder), AccessAction::Manage));
        }
    }

    #[test]
    fn manage_requires_exactly_a_manage_grant() {
        for visibility in [Visibility::Public, Visibility::Private] {
            let granted = record(
                visibility,
                &[("u-7731", &[AccessAction::Read, AccessAction::Manage])],
            );
            let holder = identity("u-7731");
            assert!(authorize(&granted, Some(&holder), AccessAction::Manage));
            let write_only = record(visibility, &[("u-7731", &[AccessAction::Write])]);
            assert!(!authorize(&write_only, Some(&holder), AccessAction::Manage));
        }
    }

    #[test]
    fn stored_grant_sets_need_not_be_closed_under_monotonicity() {
        let sparse = record(Visibility::Private, &[("u-7731", &[AccessAction::Manage])]);
        let holder = identity("u-7731");
        assert!(authorize(&sparse, Some(&holder), AccessAction::Read));
        assert!(authorize(&sparse, Some(&holder), AccessAction::Write));
        assert!(authorize(&sparse, Some(&holder), AccessAction::Manage));
        let empty_entry = record(Visibility::Private, &[("u-7731", &[])]);
        assert!(!authorize(&empty_entry, Some(&holder), AccessAction::Read));
        assert!(!authorize(&empty_entry, Some(&holder), AccessAction::Write));
        assert!(!authorize(
            &empty_entry,
            Some(&holder),
            AccessAction::Manage
        ));
    }

    #[test]
    fn the_marker_is_constructible_only_through_the_checked_path() {
        let private = record(Visibility::Private, &[("u-7731", &[AccessAction::Write])]);
        let holder = identity("u-7731");
        let stranger = identity("stranger");
        assert_eq!(
            AuthorizedRepo::authorize(private.clone(), None, AccessAction::Read),
            None
        );
        assert_eq!(
            AuthorizedRepo::authorize(private.clone(), Some(&stranger), AccessAction::Read),
            None
        );
        assert_eq!(
            AuthorizedRepo::authorize(private.clone(), Some(&holder), AccessAction::Manage),
            None
        );
        assert!(
            AuthorizedRepo::authorize(private.clone(), Some(&holder), AccessAction::Read).is_some()
        );
        assert!(AuthorizedRepo::authorize(private, Some(&holder), AccessAction::Write).is_some());
    }

    #[test]
    fn the_marker_carries_the_checked_authorization_inputs() {
        let public = record(Visibility::Public, &[]);
        let anonymous = AuthorizedRepo::authorize(public.clone(), None, AccessAction::Read)
            .expect("anonymous public read passes");
        assert_eq!(anonymous.record(), &public);
        assert_eq!(anonymous.action(), AccessAction::Read);
        assert_eq!(anonymous.identity_id(), None);

        let private = record(Visibility::Private, &[("u-7731", &[AccessAction::Manage])]);
        let holder = identity("u-7731");
        let identified = AuthorizedRepo::authorize(private, Some(&holder), AccessAction::Write)
            .expect("the manage grant satisfies write");
        assert_eq!(identified.record().repo_id, "alkdev/alkgit");
        assert_eq!(identified.action(), AccessAction::Write);
        assert_eq!(identified.identity_id(), Some("u-7731"));
    }

    fn scoped(id: &str, scopes: &[&str]) -> Identity {
        Identity {
            id: id.to_string(),
            scopes: scopes.iter().map(|scope| (*scope).to_string()).collect(),
            resources: HashMap::new(),
        }
    }

    // The op-gate matrix (w4-ops-gate). Contract stamp: ADR-015 §3 —
    // admin scope OR manage grant; §2 — manage requires identity, no
    // anonymous path; §6 — scopes and grants are distinct sources.

    #[test]
    fn the_op_gate_denies_anonymous() {
        for visibility in [Visibility::Public, Visibility::Private] {
            assert!(!authorize_repo_op(&record(visibility, &[]), None));
            assert!(!authorize_repo_op(
                &record(visibility, &[("u-7731", &[AccessAction::Manage])]),
                None
            ));
        }
    }

    #[test]
    fn the_op_gate_denies_read_and_write_grants() {
        for actions in [
            &[AccessAction::Read][..],
            &[AccessAction::Write],
            &[AccessAction::Read, AccessAction::Write],
        ] {
            for visibility in [Visibility::Public, Visibility::Private] {
                let granted = record(visibility, &[("u-7731", actions)]);
                let holder = identity("u-7731");
                assert!(!authorize_repo_op(&granted, Some(&holder)));
            }
        }
    }

    #[test]
    fn the_op_gate_grants_a_manage_grant() {
        for visibility in [Visibility::Public, Visibility::Private] {
            let granted = record(visibility, &[("u-7731", &[AccessAction::Manage])]);
            let holder = identity("u-7731");
            assert!(authorize_repo_op(&granted, Some(&holder)));
        }
    }

    #[test]
    fn the_op_gate_grants_the_admin_scope_without_any_grant() {
        for visibility in [Visibility::Public, Visibility::Private] {
            let grantless = record(visibility, &[]);
            let admin = scoped("u-admin", &[GIT_ADMIN_SCOPE]);
            assert!(authorize_repo_op(&grantless, Some(&admin)));
        }
    }

    #[test]
    fn the_op_gate_grants_the_admin_scope_on_a_private_repo() {
        let private = record(Visibility::Private, &[]);
        let admin = scoped("u-admin", &[GIT_ADMIN_SCOPE]);
        assert!(authorize_repo_op(&private, Some(&admin)));
    }

    #[test]
    fn the_op_gate_other_scopes_do_not_satisfy_the_admin_scope() {
        let grantless = record(Visibility::Private, &[]);
        let repo_create = scoped("u-7731", &["git:repo:create"]);
        assert!(!authorize_repo_op(&grantless, Some(&repo_create)));
        let mixed = scoped("u-7731", &["git:repo:create", GIT_ADMIN_SCOPE]);
        assert!(authorize_repo_op(&grantless, Some(&mixed)));
    }

    #[test]
    fn the_op_gate_manage_grant_monotonicity_holds_through_the_composition() {
        // A sparse manage grant satisfies the manage check via
        // `authorize`'s existing monotonicity (ADR-015 §2) — the gate
        // adds no tier logic of its own.
        let sparse = record(
            Visibility::Private,
            &[("u-7731", &[AccessAction::Read, AccessAction::Manage])],
        );
        let holder = identity("u-7731");
        assert!(authorize_repo_op(&sparse, Some(&holder)));
        let via_authorize = authorize(&sparse, Some(&holder), AccessAction::Manage);
        assert!(via_authorize);
        assert_eq!(authorize_repo_op(&sparse, Some(&holder)), via_authorize);
    }

    #[test]
    fn the_op_gate_denies_an_empty_scopes_identity_on_a_grantless_record() {
        let grantless = record(Visibility::Private, &[]);
        let holder = identity("u-7731");
        assert!(!authorize_repo_op(&grantless, Some(&holder)));
    }

    #[test]
    fn the_admin_scope_is_platform_capability_the_grant_is_per_repo() {
        // ADR-015 §6: a grant on one record does not confer the gate
        // on another — the granted holder passes here, a grantless
        // record denies the same identity, while the scope tier is
        // repo-independent (tested above).
        let granted = record(Visibility::Private, &[("u-7731", &[AccessAction::Manage])]);
        let holder = identity("u-7731");
        assert!(authorize_repo_op(&granted, Some(&holder)));
        let grantless = record(Visibility::Private, &[]);
        assert!(!authorize_repo_op(&grantless, Some(&holder)));
    }
}