vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! `VtcAclEntry` — the VTC's per-DID auth-gate record.
//!
//! Two things live on one entry, and they are independent
//! (`docs/05-design-notes/vtc-admin-roles.md` §6):
//!
//! - the **community role** ([`super::VtcRole`]: `member`, `moderator`,
//!   `issuer`, `admin`, `custom:*`) — what the subject's membership is, the
//!   role its credentials name. It confers no administrative power on its own.
//! - the **administrative authority** ([`AdminAuthority`]): an administrative
//!   role (a ceiling), an explicit act scope, the capabilities held, an approve
//!   scope and the capabilities it may approve. Every axis is stated
//!   (`acl/_shared/0.2` CONVENTIONS §4); none has a default.
//!
//! Authorization is one question, [`VtcAclEntry::can`]. Nothing reads the
//! shape of a list to decide anything: there are no context lists on a VTC
//! entry (**VTI-VTC-010**), so the empty-list trap the VTA guards against
//! (#746, #769, #770) does not exist here.
//!
//! ## Wire shape
//!
//! Stored under `acl:<did>` in the `acl` keyspace. The administrative axes are
//! flattened into the row (`adminRole`, `act`, `capabilities`, `approve`,
//! `approveCapabilities`). A row written before role-based administration —
//! with `allowed_contexts` and no `act` — does not decode, and so confers
//! nothing: rollout is net-new (`vtc-admin-roles.md` §9), and a backup brings
//! its rows across through [`super::migrate`].

use serde::{Deserialize, Serialize};
use vti_common::error::AppError;
use vti_common::store::KeyspaceHandle;

use super::VtcRole;
pub use super::capability::AdminAuthority;
use super::capability::{CapRef, Capability, ResourceQualifier};

/// One ACL entry. 1:1 with a [`crate::members::Member`] row by
/// DID, but kept in a separate keyspace because the auth path
/// reads ACL rows on every request and shouldn't pay the cost of
/// loading the richer Member metadata.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VtcAclEntry {
    pub did: String,
    /// The community role: what the subject's membership is. Not authority.
    pub role: VtcRole,
    pub label: Option<String>,
    /// The administrative authority, every axis explicit.
    #[serde(flatten)]
    pub admin: AdminAuthority,
    /// The granter whose authority this entry was delegated from and is
    /// bounded by (`acl/_shared/0.2` `delegatedBy`, **VTI-ACL-071**). Absent on
    /// an entry derived from no granter: the first administrator, an
    /// operator-written recovery entry, a member admitted by a join.
    #[serde(default)]
    pub delegated_by: Option<String>,
    pub created_at: u64,
    pub created_by: String,
    /// Unix-epoch seconds of the last mutation, and who made it.
    ///
    /// `#[serde(default)]` because an entry that has never been modified has
    /// none; this is provenance, not authority.
    #[serde(default)]
    pub updated_at: Option<u64>,
    #[serde(default)]
    pub updated_by: Option<String>,
    /// Unix-epoch seconds at which this entry expires and should be
    /// pruned by the background sweeper. `None` is permanent.
    #[serde(default)]
    pub expires_at: Option<u64>,
    /// Capabilities held on one of the community's resources — a git
    /// namespace or repository — each a delegation of its own
    /// (**VTI-ACL-035 – 037**, [`super::resource_grant`]). Absent and empty are
    /// the same: no resource grants.
    #[serde(
        default,
        rename = "resourceGrants",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub resource_grants: Vec<super::resource_grant::ResourceGrant>,
    /// Whether the subject set `label` itself (**VTI-ACL-052** item 2). The
    /// label confers no authority (VTI-ACL-001), so a subject may change it on
    /// its own entry; what it can do is mislead, so wherever the label is
    /// shown to another party it is shown as self-set. Cleared whenever
    /// anyone else sets the label; carried by every write that leaves it as
    /// it is. Provenance, not authority: absent on every row written before
    /// it existed, which reads as `false`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub label_set_by_subject: bool,
    /// Set while a **cooling-off** reduction of this entry is open
    /// (`vtc-action-list.md` §8.2, VTI-APV-019): from the moment it is raised
    /// until it lands or is cancelled, the entry authorizes nothing —
    /// [`Self::can`], [`Self::can_any`] and [`Self::can_approve`] all answer
    /// `false` — while the row itself is untouched, so cancelling restores it
    /// exactly. Never stored on the row: read beside it at load from the
    /// marker the action list keeps ([`super::storage::get_acl_entry`],
    /// [`crate::admin_actions`]).
    #[serde(skip)]
    pub suspension: Option<Suspension>,
}

/// A suspension pending a reduction's cooling-off (`vtc-action-list.md` §8.2):
/// which action holds it and when that action lands.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Suspension {
    pub action_id: String,
    /// Unix-epoch seconds at which the reduction lands.
    pub lands_at: u64,
    /// The administrator who asked for the reduction.
    pub requester: String,
}

impl Suspension {
    /// When it lands, as RFC 3339.
    pub fn lands_at_rfc3339(&self) -> String {
        chrono::DateTime::from_timestamp(self.lands_at as i64, 0)
            .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
            .unwrap_or_else(|| self.lands_at.to_string())
    }

    /// The refusal every privileged act of a suspended entry gets: what holds
    /// it, and until when.
    pub fn refusal(&self, did: &str) -> AppError {
        AppError::Forbidden(self.message(did))
    }

    /// [`Self::refusal`]'s text.
    pub fn message(&self, did: &str) -> String {
        format!(
            "{did} is suspended pending its removal: a reduction of this entry is cooling off \
             (action {}, requested by {}, lands {}), and until it lands or is cancelled the \
             entry authorizes nothing (VTI-APV-019). You can still sign in and see the action \
             (vtc/admin/actions/show)",
            self.action_id,
            self.requester,
            self.lands_at_rfc3339(),
        )
    }
}

impl VtcAclEntry {
    /// A fresh entry with community role `role` and administrative authority
    /// `admin`, created now by `created_by`.
    pub fn new(
        did: impl Into<String>,
        role: VtcRole,
        admin: AdminAuthority,
        created_by: impl Into<String>,
    ) -> Self {
        Self {
            did: did.into(),
            role,
            label: None,
            admin,
            delegated_by: None,
            created_at: vti_common::auth::session::now_epoch(),
            created_by: created_by.into(),
            updated_at: None,
            updated_by: None,
            expires_at: None,
            resource_grants: Vec::new(),
            label_set_by_subject: false,
            suspension: None,
        }
    }

    /// **The** authorization question (**VTI-ACL-030**, **-036**): may this
    /// entry exercise `cap` on `resource` (`None` = community-wide), now?
    ///
    /// An expired entry can do nothing (**VTI-ACL-004**), and a qualified
    /// capability confers nothing without this live entry for the same subject
    /// — it is a member of the entry, not a right held beside it.
    ///
    /// The entry's resource grants answer too: a git right held on a
    /// namespace or repository is this entry's capability at that qualifier
    /// (phase C3, **VTI-VTC-020**).
    pub fn can(&self, cap: Capability, resource: Option<&ResourceQualifier>) -> bool {
        self.suspension.is_none()
            && !self.is_expired(vti_common::auth::session::now_epoch())
            && (self.admin.can(cap, resource) || self.resource_grant_confers(cap, resource))
    }

    /// Whether one of this entry's live resource grants confers `cap` at
    /// `resource`. Expiry of the entry itself is the caller's.
    fn resource_grant_confers(
        &self,
        cap: Capability,
        resource: Option<&ResourceQualifier>,
    ) -> bool {
        let now = chrono::Utc::now();
        self.resource_grants
            .iter()
            .any(|g| g.is_live(now) && g.confers(cap, resource))
    }

    /// Whether this is a non-member's entry: the `application` community role,
    /// which exists only to hold resource grants (the bridge, an external
    /// signer) and is never a membership.
    pub fn is_application(&self) -> bool {
        self.role == VtcRole::Application
    }

    /// [`Self::can`] at any qualifier — the gate on a read that spans every
    /// resource of the capability's kind.
    pub fn can_any(&self, cap: Capability) -> bool {
        let now = chrono::Utc::now();
        self.suspension.is_none()
            && !self.is_expired(vti_common::auth::session::now_epoch())
            && (self.admin.can_any(cap)
                || self
                    .resource_grants
                    .iter()
                    .any(|g| g.is_live(now) && g.confers(cap, Some(&g.resource))))
    }

    /// Whether this live entry holds `wanted` at a covering qualifier.
    pub fn holds(&self, wanted: &CapRef) -> bool {
        self.can(wanted.capability, wanted.resource.as_ref())
    }

    /// May this live entry approve an action needing `wanted`
    /// (**VTI-ACL-040**)? Independent of what it may do.
    pub fn can_approve(&self, wanted: &CapRef) -> bool {
        self.suspension.is_none()
            && !self.is_expired(vti_common::auth::session::now_epoch())
            && self.admin.can_approve(wanted)
    }

    /// Whether a cooling-off reduction of this entry is open, so that it
    /// authorizes nothing until it lands or is cancelled ([`Self::suspension`]).
    pub fn is_suspended(&self) -> bool {
        self.suspension.is_some()
    }

    /// Whether this live entry holds an administrative role of any kind —
    /// what console sign-in admits. A suspended entry still does: it signs in
    /// to see why, and every act it would take is refused by [`Self::can`].
    pub fn is_administrator(&self) -> bool {
        !self.is_expired(vti_common::auth::session::now_epoch()) && self.admin.is_administrator()
    }

    /// Whether this is a live `community-admin` holding `vtc.roles.assign`
    /// unqualified — the holders the attrition guard keeps at least one of.
    pub fn is_community_admin(&self) -> bool {
        matches!(
            self.admin.admin_role,
            Some(super::capability::AdminRole::CommunityAdmin)
        ) && self.can(Capability::RolesAssign, None)
    }

    /// The capabilities this entry holds, as `cap[@resource]` strings — what an
    /// audit row or an operator display names. Empty when it may not act.
    ///
    /// Resource grants are listed as the capability references they answer
    /// for (`git.repo.manage@git-repo:…`), a maintainer's or creator's grade
    /// included as `cap/grade@resource` so a display never reads one as the
    /// capability in full.
    pub fn capability_list(&self) -> Vec<String> {
        let mut out: Vec<String> = if self.admin.act.is_all() {
            self.admin.effective().iter().map(CapRef::display).collect()
        } else {
            Vec::new()
        };
        let now = chrono::Utc::now();
        out.extend(
            self.resource_grants
                .iter()
                .filter(|g| g.is_live(now))
                .map(|g| match g.grade {
                    Some(super::resource_grant::RepoGrade::Own) | None => g.cap_ref().display(),
                    Some(_) => g.display(),
                }),
        );
        out
    }

    /// Returns `true` once this entry has passed its
    /// `expires_at`. Permanent entries (`None`) never expire.
    pub fn is_expired(&self, now_unix: u64) -> bool {
        match self.expires_at {
            Some(deadline) => now_unix >= deadline,
            None => false,
        }
    }
}

/// Decode a `VtcAclEntry` from raw bytes. Public so the
/// [`super::storage`] helpers + pagination callers can reuse the
/// same decode path without duplicating the JSON tax.
pub(crate) fn decode(bytes: &[u8]) -> Result<VtcAclEntry, AppError> {
    serde_json::from_slice(bytes)
        .map_err(|e| AppError::Internal(format!("VtcAclEntry decode: {e}")))
}

/// Iterate `acl:<did>` rows, decoding each into a `VtcAclEntry`.
/// Helper for `list_acl_entries` + paginated walkers.
pub(crate) async fn iter(ks: &KeyspaceHandle) -> Result<Vec<VtcAclEntry>, AppError> {
    let raw = ks.prefix_iter_raw(b"acl:".to_vec()).await?;
    let mut out = Vec::with_capacity(raw.len());
    for (_k, v) in raw {
        match decode(&v) {
            Ok(entry) => out.push(entry),
            Err(err) => {
                tracing::warn!(error = %err, "skipping unparseable acl entry");
            }
        }
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::acl::capability::{AdminRole, VtcActScope};
    use serde_json::json;

    #[test]
    fn is_expired_returns_false_for_permanent_entries() {
        let entry = sample_entry(None);
        assert!(!entry.is_expired(u64::MAX));
    }

    #[test]
    fn is_expired_returns_true_after_deadline() {
        let entry = sample_entry(Some(100));
        assert!(!entry.is_expired(50));
        assert!(entry.is_expired(101));
    }

    #[test]
    fn round_trip_through_json() {
        let entry = sample_entry(Some(200));
        let bytes = serde_json::to_vec(&entry).unwrap();
        let parsed = decode(&bytes).unwrap();
        assert_eq!(parsed, entry);
    }

    /// Net-new rollout (`vtc-admin-roles.md` §9): a row in the old shape —
    /// `allowed_contexts`, no `act` — does not decode, so it confers nothing.
    /// Nothing is derived from the absence of the explicit axes
    /// (VTI-ACL-006…008).
    #[test]
    fn a_pre_role_row_does_not_decode() {
        let legacy = json!({
            "did": "did:key:zAdmin",
            "role": "admin",
            "label": null,
            "allowed_contexts": [],
            "created_at": 0,
            "created_by": "did:key:vtc-install"
        });
        assert!(decode(&serde_json::to_vec(&legacy).unwrap()).is_err());
    }

    #[test]
    fn custom_role_round_trips() {
        let mut entry = sample_entry(None);
        entry.role = VtcRole::custom("editor").unwrap();
        entry.label = Some("badge holder".into());
        let bytes = serde_json::to_vec(&entry).unwrap();
        let parsed = decode(&bytes).unwrap();
        assert_eq!(parsed.role, VtcRole::Custom("editor".into()));
        assert_eq!(parsed, entry);
    }

    /// The community role confers nothing: an `admin` community role with no
    /// administrative authority can do nothing (VTI-ACL-010).
    #[test]
    fn the_community_role_is_not_authority() {
        let mut e = sample_entry(None);
        e.role = VtcRole::Admin;
        for c in Capability::ALL {
            assert!(!e.can(c, None));
        }
        assert!(!e.is_administrator());
    }

    /// An expired entry can do nothing, whatever it holds (VTI-ACL-004).
    #[test]
    fn an_expired_entry_can_do_nothing() {
        let mut e = sample_entry(Some(1));
        e.admin = AdminAuthority::community_admin();
        assert!(!e.can(Capability::RolesAssign, None));
        assert!(!e.is_administrator());
        e.expires_at = None;
        assert!(e.can(Capability::RolesAssign, None));
        assert!(e.is_community_admin());
    }

    #[test]
    fn a_moderator_is_an_administrator_but_not_a_community_admin() {
        let mut e = sample_entry(None);
        e.admin = AdminAuthority::for_role(AdminRole::Moderator);
        assert!(e.is_administrator());
        assert!(!e.is_community_admin());
        assert_eq!(e.admin.act, VtcActScope::All);
    }

    /// A suspended entry authorizes nothing, whatever it holds, and keeps
    /// what it holds (`vtc-action-list.md` §8.2).
    #[test]
    fn a_suspended_entry_authorizes_nothing() {
        let mut e = sample_entry(None);
        e.admin = AdminAuthority::community_admin();
        assert!(e.can(Capability::RolesAssign, None));
        e.suspension = Some(Suspension {
            action_id: "act-1".into(),
            lands_at: 1,
            requester: "did:key:zOther".into(),
        });
        for c in Capability::ALL {
            assert!(!e.can(c, None), "{c:?}");
            assert!(!e.can_any(c), "{c:?}");
            assert!(!e.can_approve(&CapRef::all(c)), "{c:?}");
        }
        // Still an administrator by its row: it may sign in and see why.
        assert!(e.is_administrator());
        assert_eq!(e.admin, AdminAuthority::community_admin());
        // Never written to the row.
        let bytes = serde_json::to_vec(&e).unwrap();
        assert!(decode(&bytes).unwrap().suspension.is_none());
    }

    fn sample_entry(expires_at: Option<u64>) -> VtcAclEntry {
        VtcAclEntry {
            did: "did:key:zSomeMember".into(),
            role: VtcRole::Member,
            label: None,
            admin: AdminAuthority::none(),
            delegated_by: None,
            created_at: 42,
            created_by: "did:key:vtc-install".into(),
            updated_at: None,
            updated_by: None,
            expires_at,
            resource_grants: Vec::new(),
            label_set_by_subject: false,
            suspension: None,
        }
    }
}