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
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
//! `vtc/admin/invites/{create,list,revoke}/0.1` — admin onboarding.
//!
//! Mirrors the `vtc admin invite` CLI, from the running daemon. Each is a
//! signed document served by the spine on every transport
//! (`trust_tasks::admin_tasks`); none has a REST route.
//!
//! - `create` mints a fresh single-use install URL for `did`, ensuring an
//!   `Admin` ACL grant exists first (so the new admin can actually log in
//!   once they claim the passkey). Writing that grant confers unrestricted
//!   authority, so it takes the inviter's passkey gesture bound to the
//!   invite and another unrestricted admin's consent.
//! - `list` lists every persisted install-token row with a derived status
//!   (`issued` / `consumed` / `expired`).
//! - `revoke` removes an invite by deleting its install-token row.

use std::sync::Arc;

use axum::http::StatusCode;
use chrono::{DateTime, Duration as ChronoDuration, Utc};
use serde::{Deserialize, Serialize};
use tracing::info;
use uuid::Uuid;
use vti_common::audit::{AdminInviteData, AuditEvent};
use vti_common::auth::extractor::AuthClaims;
use vti_common::error::AppError;

use crate::acl::{VtcAclEntry, VtcRole, get_acl_entry, store_acl_entry};
use crate::auth::session::now_epoch;
use crate::error::TaskError;
use crate::install::{
    INSTALL_TOKEN_DEFAULT_TTL_SECS, InstallTokenSigner, InstallTokenState, claim_secret,
    mint_install_token,
};
use crate::server::AppState;

// ---------------------------------------------------------------------------
// Wire shapes
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct CreateInviteRequest {
    /// Admin DID the install URL grants a passkey for.
    pub did: String,
    /// Token TTL in seconds. Defaults to
    /// [`INSTALL_TOKEN_DEFAULT_TTL_SECS`] (15 minutes) when omitted.
    /// Cap at 24 h to keep stale invites from accumulating in the
    /// keyspace.
    #[serde(default)]
    pub ttl_seconds: Option<u64>,
    /// Operator-supplied label for the ACL entry if one needs to be
    /// created. Ignored when the ACL entry already exists.
    #[serde(default)]
    pub label: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct CreateInviteResponse {
    /// `jti` of the minted install token — also the key the GET +
    /// DELETE surfaces use.
    pub jti: String,
    /// Clickable install URL pointing at the admin SPA's install
    /// page on this daemon's `public_url`.
    pub install_url: String,
    /// Out-of-band claim code the invitee must type alongside the
    /// URL to complete the ceremony. Returned **once** — the
    /// daemon stores only its Argon2id hash, so a lost code
    /// requires re-minting the invite. The operator delivers URL
    /// and code through separate channels.
    pub claim_code: String,
    /// Wall-clock expiry for the token.
    pub expires_at: DateTime<Utc>,
    /// `true` when the call also wrote the ACL entry; `false` when
    /// the target DID was already an admin (idempotent).
    pub acl_entry_created: bool,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct InviteSummary {
    pub jti: String,
    pub status: InviteStatus,
    /// Admin DID the invite was minted for. `None` only on
    /// legacy rows persisted before the field landed (those are
    /// safe to clean up via revoke). New invites always carry it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_did: Option<String>,
    /// `Issued` token expiry. `None` for `Consumed` rows (the
    /// state machine clears the timing data on transition).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    /// `Consumed` rows record the wall-clock at which the
    /// ceremony succeeded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consumed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
#[derive(utoipa::ToSchema)]
pub enum InviteStatus {
    Issued,
    Consumed,
    Expired,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct ListInvitesResponse {
    pub invites: Vec<InviteSummary>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct RevokeInviteResponse {
    pub jti: String,
}

// ---------------------------------------------------------------------------
// POST handler
// ---------------------------------------------------------------------------

/// The longest an invite may live.
pub(crate) const MAX_TTL_SECONDS: u64 = 24 * 60 * 60;

/// `vtc/admin/invites/create:ttlTooLong` — `ttlSeconds` exceeds the 24-hour
/// maximum.
pub const CREATE_INVITE_ERR_TTL_TOO_LONG: &str =
    trust_tasks_rs::specs::vtc::admin::invites::create::v0_1::error_codes::TTL_TOO_LONG.code;
/// `vtc/admin/invites/revoke:notFound` — no invite with that `jti`.
pub const REVOKE_INVITE_ERR_NOT_FOUND: &str =
    trust_tasks_rs::specs::vtc::admin::invites::revoke::v0_1::error_codes::NOT_FOUND.code;

/// What [`check_invite`] decided, carried to [`commit_invite`] once the
/// caller has settled whatever the invite costs.
#[derive(Debug)]
pub(crate) struct InvitePlan {
    ttl_seconds: u64,
    /// `true` when the invited DID holds no ACL entry, so the invite writes an
    /// **unrestricted** admin entry for it: a grant of unrestricted authority,
    /// which costs what one costs on `acl/grant` — the caller's passkey gesture
    /// bound to this invite, and another unrestricted admin's consent
    /// (VTI-APV-014). The caller settles both before [`commit_invite`].
    pub(crate) grants_admin: bool,
}

/// Every check that decides whether `actor` may invite `req.did`, before the
/// invite costs anything.
pub(crate) async fn check_invite(
    state: &AppState,
    actor: &AuthClaims,
    req: &CreateInviteRequest,
) -> Result<InvitePlan, TaskError> {
    if !req.did.starts_with("did:") {
        return Err(AppError::Validation(format!(
            "did must start with 'did:' (got '{}')",
            req.did
        ))
        .into());
    }

    let ttl_seconds = req.ttl_seconds.unwrap_or(INSTALL_TOKEN_DEFAULT_TTL_SECS);
    let out_of_range = || {
        AppError::Validation(format!(
            "ttl_seconds must be between 1 and {MAX_TTL_SECONDS}",
        ))
    };
    // Only the upper bound is declared (`ttlTooLong`); a zero TTL is the same
    // 400 without a code.
    if ttl_seconds > MAX_TTL_SECONDS {
        return Err(TaskError::declared(
            CREATE_INVITE_ERR_TTL_TOO_LONG,
            out_of_range(),
        ));
    }
    if ttl_seconds == 0 {
        return Err(out_of_range().into());
    }

    // The grant below makes a community administrator with the full ceiling.
    // Inviting one is granting one (vtc.roles.assign, design §4 "admin
    // invites"), bounded by the inviter's own entry like any grant
    // (VTI-ACL-071, VTI-ACL-053): only a caller who could have granted it with
    // acl/grant may invite it.
    let inviter = crate::acl::get_acl_entry(&state.acl_ks, &actor.did)
        .await?
        .ok_or_else(|| AppError::Forbidden(format!("{} has no ACL entry", actor.did)))?;
    let mut invited = VtcAclEntry::new(
        req.did.clone(),
        VtcRole::Admin,
        crate::acl::AdminAuthority::community_admin(),
        actor.did.clone(),
    );
    invited.expires_at = None;
    if let Err(refusal) =
        crate::acl::granting::check_write(&inviter, &invited, crate::auth::session::now_epoch())
    {
        return Err(AppError::Forbidden(format!(
            "inviting an administrator grants a community administrator: {refusal}"
        ))
        .into());
    }

    require_install_signer(state)?;
    require_public_url(state).await?;
    require_vtc_did(state).await?;

    // Ensure the target DID has an Admin ACL grant. Mirrors the CLI:
    // idempotent — leaves a pre-existing grant untouched (we don't downgrade
    // non-Admin DIDs here, since that would mean a separate role change is
    // needed first).
    let grants_admin = match get_acl_entry(&state.acl_ks, &req.did).await? {
        Some(existing) if existing.is_community_admin() => false,
        Some(_) => {
            return Err(AppError::Conflict(format!(
                "did {} already has a non-admin ACL grant; revoke it first \
                 (acl/revoke) before inviting",
                req.did
            ))
            .into());
        }
        None => true,
    };
    Ok(InvitePlan {
        ttl_seconds,
        grants_admin,
    })
}

/// Mint the invite [`check_invite`] planned, writing the admin entry it
/// grants. The caller has already settled the gesture and the consent a
/// granting invite costs.
pub(crate) async fn commit_invite(
    state: &AppState,
    actor: &AuthClaims,
    req: CreateInviteRequest,
    plan: InvitePlan,
) -> Result<CreateInviteResponse, TaskError> {
    let InvitePlan {
        ttl_seconds,
        grants_admin,
    } = plan;
    let signer = require_install_signer(state)?;
    let base_url = require_public_url(state).await?;
    let vtc_did = require_vtc_did(state).await?;

    let acl_entry_created = if grants_admin {
        // Re-read under the commit: an entry written for this DID since the
        // check must not be overwritten by an unrestricted admin row.
        if get_acl_entry(&state.acl_ks, &req.did).await?.is_some() {
            return Err(AppError::Conflict(format!(
                "did {} gained an ACL entry while this invite was being approved; send it again",
                req.did
            ))
            .into());
        }
        let label = req
            .label
            .clone()
            .unwrap_or_else(|| "admin invite (web)".into());
        let entry = VtcAclEntry {
            did: req.did.clone(),
            role: VtcRole::Admin,
            label: Some(label),
            admin: crate::acl::AdminAuthority::community_admin(),
            // A grant is a delegation (vtc-admin-roles.md §6.3).
            delegated_by: Some(actor.did.clone()),
            created_at: now_epoch(),
            created_by: format!("admin-ui/{}", env!("CARGO_PKG_VERSION")),
            updated_at: None,
            updated_by: None,
            expires_at: None,
            resource_grants: Vec::new(),
            label_set_by_subject: false,
            suspension: None,
        };
        store_acl_entry(&state.acl_ks, &entry).await?;
        true
    } else {
        false
    };

    let minted = mint_install_token(signer.as_ref(), &vtc_did, &req.did, ttl_seconds)?;
    let claim_code = claim_secret::generate();
    // Argon2id hashing is CPU-bound (~50–200 ms); keep it off the async REST
    // runtime so a burst of invite mints doesn't stall other requests (P0.10).
    let claim_code_hash = {
        let claim_code = claim_code.clone();
        tokio::task::spawn_blocking(move || claim_secret::hash(&claim_code))
            .await
            .map_err(|e| AppError::Internal(format!("claim-secret hash task failed: {e}")))??
    };
    let expires_at = Utc::now() + ChronoDuration::seconds(ttl_seconds as i64);
    state
        .install_store
        .record_issued(
            &minted.jti,
            minted.cnonce_bytes,
            *minted.ephemeral_signing_key,
            expires_at,
            Some(claim_code_hash),
            Some(req.did.clone()),
        )
        .await?;
    crate::admin_actions::record_effect(state).await;

    let install_url = format!(
        "{}/admin/install?token={}",
        base_url.trim_end_matches('/'),
        minted.jwt
    );

    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                &actor.did,
                Some(&req.did),
                AuditEvent::AdminInviteCreated(AdminInviteData {
                    jti: minted.jti.to_string(),
                    admin_did: Some(req.did.clone()),
                }),
            )
            .await?;
    }

    info!(
        target_did = %req.did,
        jti = %minted.jti,
        ttl_seconds,
        "admin invite minted"
    );

    Ok(CreateInviteResponse {
        jti: minted.jti.to_string(),
        install_url,
        claim_code,
        expires_at,
        acl_entry_created,
    })
}

// ---------------------------------------------------------------------------
// GET handler
// ---------------------------------------------------------------------------

/// `vtc/admin/invites/list/0.1`.
pub(crate) async fn list_invites(state: &AppState) -> Result<ListInvitesResponse, AppError> {
    let now = Utc::now();
    let mut invites: Vec<InviteSummary> = state
        .install_store
        .list_tokens()
        .await?
        .into_iter()
        .map(|(jti, state)| summarise(jti, state, now))
        .collect();
    // Stable order — newest issued/consumed first by timestamp,
    // then jti for tie-breaking. Falls through to jti for rows
    // missing both timestamps.
    invites.sort_by(|a, b| {
        let a_ts = a.consumed_at.or(a.expires_at);
        let b_ts = b.consumed_at.or(b.expires_at);
        b_ts.cmp(&a_ts).then_with(|| a.jti.cmp(&b.jti))
    });
    Ok(ListInvitesResponse { invites })
}

// ---------------------------------------------------------------------------
// DELETE handler
// ---------------------------------------------------------------------------

/// `vtc/admin/invites/revoke/0.1`, by `actor`.
pub(crate) async fn revoke_invite(
    state: &AppState,
    actor: &str,
    jti_str: &str,
) -> Result<RevokeInviteResponse, TaskError> {
    let jti = jti_str
        .parse::<Uuid>()
        .map_err(|_| AppError::Validation(format!("invalid jti: '{jti_str}'")))?;

    // Both live (`Issued`) and terminal (`Consumed` / expired
    // `Issued`) rows are eligible for deletion. The original design
    // refused `Consumed` "to preserve the audit trail" but the
    // audit trail lives in the `CommunityInstalled` audit envelope,
    // not in the install_store row — keeping spent rows around just
    // accumulates clutter in the invites list with no security
    // benefit. 404 only when the row is genuinely absent.
    //
    // That is a divergence from `vtc/admin/invites/revoke/0.1`, which refuses
    // a consumed row with `alreadyConsumed`; the admin UI's "Remove" action on
    // consumed rows depends on it (#1600 leaves the code baselined).
    let not_found = || {
        TaskError::declared(
            REVOKE_INVITE_ERR_NOT_FOUND,
            AppError::NotFound(format!("no invite for jti {jti}")),
        )
    };
    let existed = state.install_store.get_token(&jti).await?;
    if existed.is_none() {
        return Err(not_found());
    }

    if !state.install_store.delete_token(&jti).await? {
        // Token vanished between the peek and the delete — another
        // admin raced us. Surface as NotFound so the caller sees
        // the same outcome they would on a stale jti.
        return Err(not_found());
    }

    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                actor,
                None,
                AuditEvent::AdminInviteRevoked(AdminInviteData {
                    jti: jti.to_string(),
                    admin_did: None,
                }),
            )
            .await?;
    }

    info!(%jti, "admin invite removed");

    Ok(RevokeInviteResponse {
        jti: jti.to_string(),
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn summarise(jti: Uuid, state: InstallTokenState, now: DateTime<Utc>) -> InviteSummary {
    match state {
        InstallTokenState::Issued { exp, admin_did, .. } => {
            let status = if exp < now {
                InviteStatus::Expired
            } else {
                InviteStatus::Issued
            };
            InviteSummary {
                jti: jti.to_string(),
                status,
                target_did: admin_did,
                expires_at: Some(exp),
                consumed_at: None,
            }
        }
        InstallTokenState::Consumed { at, admin_did } => InviteSummary {
            jti: jti.to_string(),
            status: InviteStatus::Consumed,
            target_did: admin_did,
            expires_at: None,
            consumed_at: Some(at),
        },
    }
}

fn require_install_signer(state: &AppState) -> Result<&Arc<InstallTokenSigner>, AppError> {
    state
        .install_signer
        .as_ref()
        .ok_or_else(|| AppError::ServiceError {
            status: StatusCode::SERVICE_UNAVAILABLE,
            message: "install signer not configured (run setup first)".into(),
        })
}

async fn require_public_url(state: &AppState) -> Result<String, AppError> {
    state
        .config
        .read()
        .await
        .public_url
        .clone()
        .ok_or_else(|| AppError::ServiceError {
            status: StatusCode::SERVICE_UNAVAILABLE,
            message: "public_url not configured; cannot build install URL".into(),
        })
}

async fn require_vtc_did(state: &AppState) -> Result<String, AppError> {
    state
        .config
        .read()
        .await
        .vtc_did
        .clone()
        .ok_or_else(|| AppError::ServiceError {
            status: StatusCode::SERVICE_UNAVAILABLE,
            message: "vtc_did not configured (run setup first)".into(),
        })
}