vta-service 0.24.1

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! The room group slice — `spec/rooms/keys/{key-package,welcome,commit,open}`.
//!
//! How a group reaches a key-holding agent, and what it does once it has one. The
//! orchestration is [`crate::operations::room_groups`]; this is the dispatch surface.
//!
//! # Four tasks, four different gates
//!
//! Deliberately not one gate applied four times, because these are four different acts:
//!
//! | | authorized by |
//! |---|---|
//! | `key-package` | an invitation — minting retains a private key, so a VTA that minted for anyone is one anyone can fill |
//! | `welcome` | that same invitation, **consumed** |
//! | `commit` | the group itself — MLS authenticates the committer as a member of the group we already hold |
//! | `open` | [`Capability::RoomOpen`] |
//!
//! Only the last is a capability, and that asymmetry is the point. The first three are
//! *inbound* — a room's owner reaching this VTA — and an ACL of ours has no opinion about
//! who a room's owner is. The fourth is our own principal's agent asking us to decrypt, and
//! that is exactly what a capability is for.
//!
//! # Every request type here is generated
//!
//! `rooms/keys/{key-package,welcome,commit}` merged upstream in
//! `trustoverip/dtgwg-trust-tasks-tf#355` and released in `trust-tasks-rs` 0.17.8, so none
//! of the four needs a hand-written request body. Only the responses are local, because a
//! handler returns a struct rather than a `Value`.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use trust_tasks_rs::TrustTask;
use vti_common::acl::Capability;

use crate::audit;
use crate::auth::AuthClaims;
use crate::operations::{room_groups, room_invitation};
use crate::server::AppState;

use super::helpers::{
    TRANSPORT_TRUST_TASK, TrustTaskOutcome, app_error_to_reject, parse_payload, success_response,
};

/// How long an unused KeyPackage's private half is retained.
///
/// Bounded because the private half *is* retained key material: a caller that minted and
/// never joined has left a key behind, and one that minted repeatedly has left a pile.
const KEY_PACKAGE_LIFETIME_SECS: u64 = 7 * 24 * 60 * 60;

// ─── Response types ──────────────────────────────────────────────────────
//
// Requests come from the generated bindings; only the responses are written
// here, and only because a handler returns a struct rather than a `Value`.

/// `rooms/keys/key-package/0.1#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyPackageResponse {
    pub key_package: String,
    pub expires_at: String,
}

/// `rooms/keys/welcome/0.1#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WelcomeResponse {
    pub epoch: u64,
}

/// `rooms/keys/commit/0.1#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommitResponse {
    pub epoch: u64,
}

// ─── Handlers ────────────────────────────────────────────────────────────

/// `rooms/keys/key-package/0.1`.
pub(super) async fn handle_key_package(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: trust_tasks_rs::specs::rooms::keys::key_package::v0_1::Payload =
        match parse_payload(&doc) {
            Ok(r) => r,
            Err(resp) => return resp,
        };

    // Minting retains a private key against a Welcome that may never come, so it is not
    // free and is not offered unconditionally.
    if let Err(e) =
        require_invitation(state, req.invitation.as_deref(), &req.room_id, &auth.did).await
    {
        return app_error_to_reject(&doc, e);
    }

    let minted = match room_groups::mint_key_package(
        &state.room_groups_ks,
        &req.room_id,
        &auth.did,
        KEY_PACKAGE_LIFETIME_SECS,
        now(),
    )
    .await
    {
        Ok(m) => m,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    record(state, "rooms.keys.key-package", auth, &req.room_id).await;
    success_response(
        &doc,
        KeyPackageResponse {
            key_package: minted.key_package,
            expires_at: rfc3339(minted.expires_at),
        },
    )
}

/// `rooms/keys/welcome/0.1`.
pub(super) async fn handle_welcome(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: trust_tasks_rs::specs::rooms::keys::welcome::v0_1::Payload = match parse_payload(&doc)
    {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    // The load-bearing gate. A Welcome carries a group's secrets; without a matching
    // invitation this VTA would be accepting key material for a room nobody agreed to join.
    let invitation =
        match require_invitation(state, req.invitation.as_deref(), &req.room_id, &auth.did).await {
            Ok(i) => i,
            Err(e) => return app_error_to_reject(&doc, e),
        };

    let welcome = match decode_b64(&req.welcome, "welcome") {
        Ok(b) => b,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    let epoch = match room_groups::join(
        &state.room_groups_ks,
        &req.room_id,
        invitation.subject(),
        &welcome,
        now(),
    )
    .await
    {
        Ok(e) => e,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    // Consumed only after the join succeeded. Burning it on a Welcome that then failed to
    // process would strand the member: the invitation is spent and they are not in.
    if let Err(e) = room_groups::consume_invitation(
        &state.room_invitations_ks,
        invitation.credential_id(),
        &req.room_id,
        now(),
    )
    .await
    {
        return app_error_to_reject(&doc, e);
    }

    record(state, "rooms.keys.welcome", auth, &req.room_id).await;
    success_response(&doc, WelcomeResponse { epoch })
}

/// `rooms/keys/commit/0.1`.
pub(super) async fn handle_commit(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: trust_tasks_rs::specs::rooms::keys::commit::v0_1::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let commit = match decode_b64(&req.commit, "commit") {
        Ok(b) => b,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    // No gate of ours. MLS authenticates the committer as a member of the group we already
    // hold, and an ACL here would be this service deciding who may commit to a room it is
    // not part of — the mistake the whole family is arranged to avoid.
    let epoch = match room_groups::apply_commit(
        &state.room_groups_ks,
        &req.room_id,
        &commit,
        u64::from(req.epoch),
        now(),
    )
    .await
    {
        Ok(e) => e,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    record(state, "rooms.keys.commit", auth, &req.room_id).await;
    success_response(&doc, CommitResponse { epoch })
}

/// `rooms/keys/seal/0.1`.
///
/// The mirror of [`handle_open`], and gated on the same capability for the same reason:
/// `RoomOpen` governs a principal's room records, and sealing one is acting on them.
///
/// Note what this returns and what it does not. It hands back ciphertext; it does not store
/// anything and does not reach the room's host. A caller that wanted the record written must
/// present its own authority there, which is the separation that keeps this VTA out of the
/// decision about what a room contains.
pub(super) async fn handle_seal(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(r) = super::helpers::require_capability(
        state,
        auth,
        &doc,
        Capability::RoomOpen,
        "sealing a room record",
    )
    .await
    {
        return r;
    }

    let req: trust_tasks_rs::specs::rooms::keys::seal::v0_1::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let plaintext = match base64::Engine::decode(
        &base64::engine::general_purpose::URL_SAFE_NO_PAD,
        &req.plaintext,
    ) {
        Ok(b) => b,
        Err(e) => {
            return app_error_to_reject(
                &doc,
                vti_common::error::AppError::Validation(format!("plaintext is not base64url: {e}")),
            );
        }
    };

    let sealed = match room_groups::seal_record(
        &state.room_groups_ks,
        &req.room_id,
        &req.key,
        req.version,
        &plaintext,
    )
    .await
    {
        Ok(s) => s,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    record(state, "rooms.keys.seal", auth, &req.room_id).await;
    success_response(
        &doc,
        serde_json::json!({
            "sealed": {
                "ciphertext": sealed.ciphertext,
                "nonce": sealed.nonce,
                "epoch": sealed.epoch,
            }
        }),
    )
}

/// `rooms/keys/list/0.1`.
///
/// Which rooms this VTA can open, and how far back each reads.
///
/// Gated on `RoomOpen` because that is the capability the answer is *about*: an agent that
/// may not open a principal's rooms has no business enumerating them, and the list is the
/// principal's room membership as key custody sees it — more than any single room operation
/// discloses.
pub(super) async fn handle_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(r) = super::helpers::require_capability(
        state,
        auth,
        &doc,
        Capability::RoomOpen,
        "listing the rooms this VTA holds keys for",
    )
    .await
    {
        return r;
    }

    let rooms = match room_groups::list_rooms(&state.room_groups_ks).await {
        Ok(r) => r,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    record(state, "rooms.keys.list", auth, "").await;
    success_response(&doc, serde_json::json!({ "rooms": rooms }))
}

/// `rooms/keys/chain/0.1`.
///
/// The principal hands this VTA the room's epoch key chain, so it can open records sealed
/// before the principal joined.
///
/// # Gated on `RoomOpen`, and that is the whole of the authorization
///
/// The specification's entitlement is *being this key holder's own principal* — not a
/// credential the room issued. Fetching these rungs from a host took a room-issued `read`
/// chain; handing them on takes none, because this VTA is not being asked to believe
/// anything about the room. It is being handed material it will verify by trying to use it.
///
/// `RoomOpen` is the right capability because it is the one that governs *reading a room's
/// records*, and this extends how far back that reaches. Gating it on anything wider would
/// grant more than the task needs; on `Sign`, as the oracle's own docs argue, strictly more.
pub(super) async fn handle_chain(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(r) = super::helpers::require_capability(
        state,
        auth,
        &doc,
        Capability::RoomOpen,
        "extending a room's readable history",
    )
    .await
    {
        return r;
    }

    let req: trust_tasks_rs::specs::rooms::keys::chain::v0_1::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    // Converted rather than clamped: an epoch outside `u32` is a malformed rung, and
    // saturating it to `u32::MAX` would store one under an epoch nobody will ever ask for —
    // a delivery that reports success and extends nothing.
    let links: Result<Vec<vti_rooms::wire::EpochLink>, _> = req
        .links
        .iter()
        .map(|l| {
            u32::try_from(l.epoch).map(|epoch| vti_rooms::wire::EpochLink {
                epoch,
                wrapped: l.wrapped.clone(),
                nonce: l.nonce.clone(),
            })
        })
        .collect();
    let links = match links {
        Ok(l) => l,
        Err(_) => {
            return app_error_to_reject(
                &doc,
                vti_common::error::AppError::Validation(
                    "an epoch link names an epoch outside the representable range".into(),
                ),
            );
        }
    };

    let (earliest, stored) =
        match room_groups::store_links(&state.room_groups_ks, &req.room_id, links, now()).await {
            Ok(r) => r,
            Err(e) => return app_error_to_reject(&doc, e),
        };

    record(state, "rooms.keys.chain", auth, &req.room_id).await;
    success_response(
        &doc,
        serde_json::json!({
            "roomId": req.room_id,
            "earliestReadableEpoch": earliest,
            "stored": stored,
        }),
    )
}

/// Everything the gated signer needs, gathered from the running service.
///
/// A copy of `room_owner`'s rather than a shared one: the two modules sign as
/// different identities and the struct is the argument list, not the policy.
fn signing_context<'a>(
    state: &'a AppState,
    auth: &'a AuthClaims,
) -> crate::operations::room_issuance::SigningContext<'a> {
    crate::operations::room_issuance::SigningContext {
        keys_ks: &state.keys_ks,
        imported_ks: &state.imported_ks,
        internal_ks: &state.internal_ks,
        contexts_ks: &state.contexts_ks,
        acl_ks: &state.acl_ks,
        seed_store: &state.seed_store,
        auth,
    }
}

/// `rooms/keys/backfill/0.1` — fetch the chain from the host and keep it.
///
/// Three hops folded into one, performed by the party that can perform all three:
/// mint a presentation, ask the host for the rungs, store what comes back. The
/// member could do the first and third and not the second — a browser reaches its
/// own agent and no third party — which is the whole reason this task exists.
///
/// **The presentation is minted for this VTA's own DID**, not the caller's, and
/// that is load-bearing rather than incidental. `room_oracle::present` attenuates
/// the principal's authority to whichever agent is named, and a host binds the
/// presentation to the DID that signed the request envelope. This VTA is what
/// signs the outbound document, so a presentation minted for anyone else is one
/// the host is right to refuse — and the refusal would read as the member lacking
/// authority rather than as an agent presenting somebody else's grant.
pub(super) async fn handle_backfill(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(r) = super::helpers::require_capability(
        state,
        auth,
        &doc,
        Capability::RoomOpen,
        "fetching a room's readable history",
    )
    .await
    {
        return r;
    }

    let req: trust_tasks_rs::specs::rooms::keys::backfill::v0_1::Payload = match parse_payload(&doc)
    {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let vta_did = match state.config.read().await.vta_did.clone() {
        Some(d) => d,
        None => {
            return app_error_to_reject(
                &doc,
                vti_common::error::AppError::Validation(
                    "this agent has no DID of its own, so it cannot present to a host as itself"
                        .into(),
                ),
            );
        }
    };
    let Some(resolver) = state.did_resolver.clone() else {
        return app_error_to_reject(
            &doc,
            vti_common::error::AppError::Validation(
                "this agent has no DID resolver configured, so it cannot find the host".into(),
            ),
        );
    };

    // `read`, and only `read`. Reading the room and reading the parts of it
    // written earlier are the same act, so they take the same grant; asking for
    // more would hand the host authority the operation never needed.
    let minted = match crate::operations::room_oracle::present(
        state,
        auth,
        &vta_did,
        &req.room_id,
        "read",
        Some(req.host.as_str()),
        None,
    )
    .await
    {
        Ok(m) => m,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    let mut payload = serde_json::json!({
        "roomId": req.room_id,
        "presentation": minted.presentation,
    });
    if let Some(from) = req.from_epoch {
        payload["fromEpoch"] = serde_json::json!(u64::from(from));
    }
    if let Some(limit) = req.limit {
        payload["limit"] = serde_json::json!(u64::from(limit));
    }

    let key = format!("{vta_did}#key-0");
    let reply = match crate::operations::room_host::send_room_task(
        signing_context(state, auth),
        &resolver,
        &req.host,
        &key,
        &vta_did,
        &key,
        vti_rooms::wire::ROOMS_EPOCH_CHAIN_TYPE,
        &format!("{}#response", vti_rooms::wire::ROOMS_EPOCH_CHAIN_TYPE),
        payload,
    )
    .await
    {
        Ok(v) => v,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    let links: Vec<vti_rooms::wire::EpochLink> =
        match serde_json::from_value(reply.get("links").cloned().unwrap_or(Value::Array(vec![]))) {
            Ok(l) => l,
            Err(e) => {
                return app_error_to_reject(
                    &doc,
                    vti_common::error::AppError::Internal(format!(
                        "room host `{}` served rungs this agent cannot read: {e}",
                        req.host
                    )),
                );
            }
        };
    let fetched = links.len();

    // Nothing served is a real answer rather than an error — the host holds no
    // rungs below what this agent already reads — and it needs no special case:
    // `store_links` with an empty delivery stores nothing and still walks what
    // is held, which is the reach this must report either way.
    let (earliest, stored) =
        match room_groups::store_links(&state.room_groups_ks, &req.room_id, links, now()).await {
            Ok(r) => r,
            Err(e) => return app_error_to_reject(&doc, e),
        };

    record(state, "rooms.keys.backfill", auth, &req.room_id).await;
    success_response(
        &doc,
        serde_json::json!({
            "roomId": req.room_id,
            "earliestReadableEpoch": earliest,
            "fetched": fetched,
            "stored": stored,
        }),
    )
}

/// `rooms/keys/open/0.1`.
pub(super) async fn handle_open(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(r) = super::helpers::require_capability(
        state,
        auth,
        &doc,
        Capability::RoomOpen,
        "opening a room record",
    )
    .await
    {
        return r;
    }

    let req: trust_tasks_rs::specs::rooms::keys::open::v0_1::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let plaintext = match room_groups::open_record(
        &state.room_groups_ks,
        &req.room_id,
        &req.key,
        u64::from(req.version),
        &req.sealed.ciphertext,
        &req.sealed.nonce,
        u32::try_from(u64::from(req.sealed.epoch)).unwrap_or(u32::MAX),
    )
    .await
    {
        Ok(p) => p,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    record(state, "rooms.keys.open", auth, &req.room_id).await;
    success_response(
        &doc,
        serde_json::json!({
            "plaintext": base64::Engine::encode(
                &base64::engine::general_purpose::URL_SAFE_NO_PAD,
                &plaintext,
            )
        }),
    )
}

// ─── Shared ──────────────────────────────────────────────────────────────

/// Verify the invitation, and refuse if it is missing, bad, or already spent.
async fn require_invitation(
    state: &AppState,
    encoded: Option<&str>,
    room_id: &str,
    member_did: &str,
) -> Result<room_invitation::VerifiedInvitation, vti_common::error::AppError> {
    let encoded = encoded.ok_or_else(|| {
        vti_common::error::AppError::Validation(format!(
            "no invitation presented for room `{room_id}`; joining a room is a two-party \
             act and the invitation is the other party's half"
        ))
    })?;

    let keys = vti_rooms_dtg::DataIntegrityKeys(state.trust_task_vm_resolver());
    let invitation = room_invitation::verify(encoded, room_id, member_did, &keys).await?;

    if room_invitation::is_consumed(&state.room_invitations_ks, invitation.credential_id()).await? {
        return Err(vti_common::error::AppError::Conflict(format!(
            "invitation `{}` has already been used",
            invitation.credential_id()
        )));
    }
    Ok(invitation)
}

fn decode_b64(s: &str, what: &str) -> Result<Vec<u8>, vti_common::error::AppError> {
    use base64::Engine as _;
    base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(s.trim())
        .map_err(|e| vti_common::error::AppError::Validation(format!("decode the {what}: {e}")))
}

fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn rfc3339(unix_seconds: u64) -> String {
    chrono::DateTime::from_timestamp(unix_seconds as i64, 0)
        .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).expect("epoch is in range"))
        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// Audit one group operation.
///
/// Every one of these is consequential: joining a room, advancing its keys, or opening one
/// of its records. "Which agent got into which room, and when" is the sentence an incident
/// review needs, and none of it is reconstructible from anywhere else.
pub(super) async fn record(state: &AppState, action: &str, auth: &AuthClaims, room_id: &str) {
    if let Err(e) = audit::record(
        &state.audit_sink,
        action,
        &auth.did,
        Some(room_id),
        "success",
        Some(TRANSPORT_TRUST_TASK),
        None,
    )
    .await
    {
        tracing::error!(error = %e, action, "failed to record a room-group audit entry");
    }
}