vta-service 0.38.0

Service for Verifiable Trust Agents operating in 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
//! Contexts slice trust-task handlers.
//!
//! Mirrors the legacy REST `/contexts/*` routes. Auth: any
//! authenticated caller for list/get; admin for update-did;
//! super-admin for create/update/preview-delete/delete.

use super::helpers::TrustTaskOutcome;
use serde_json::Value;
use trust_tasks_rs::TrustTask;
use vta_sdk::protocols::context_management::create::CreateContextBody;
use vta_sdk::protocols::context_management::delete::{DeleteContextBody, DeleteContextPreviewBody};
use vta_sdk::protocols::context_management::get::GetContextBody;
use vta_sdk::protocols::context_management::list::ListContextsBody;
use vta_sdk::protocols::context_management::update::UpdateContextBody;
use vta_sdk::protocols::context_management::update_did::UpdateContextDidBody;

use crate::auth::AuthClaims;
use crate::operations;
use crate::server::AppState;

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

/// The task's own slug, read off the document rather than written down, so an
/// extended code can only ever name the task that emitted it.
fn slug_from_doc(doc: &TrustTask<Value>) -> String {
    doc.type_uri
        .to_string()
        .strip_prefix("https://trusttasks.org/spec/")
        .and_then(|rest| rest.rsplit_once('/'))
        .map(|(slug, _ver)| slug.to_string())
        .unwrap_or_else(|| "vta/contexts/delete".to_string())
}

fn ext(slug: &str, local: &str) -> trust_tasks_rs::TrustTaskCode {
    trust_tasks_rs::TrustTaskCode::new_extended(slug, local)
        .expect("contexts extended code is grammar-valid")
}

/// Reject a context operation with the error code its own specification
/// declares.
///
/// One function for the whole family, because the slug is read off the
/// document: the same match answers `vta/contexts/get:notFound`,
/// `vta/contexts/update:notFound`, `vta/contexts/create:parentNotFound` and
/// `vta/contexts/delete:notEmpty` depending only on which task is being
/// served. A per-handler mapping would be six copies of this, and the sixth
/// would be the one that drifts.
fn reject_context_error(
    doc: &TrustTask<Value>,
    e: operations::contexts::ContextError,
) -> TrustTaskOutcome {
    use operations::contexts::ContextError;
    let slug = slug_from_doc(doc);
    match e {
        // Deliberately says nothing about whether the id exists. That is the
        // point of the code: `vta/contexts/get` states that it "does not
        // distinguish 'does not exist' from 'exists but not yours'", and a
        // message that distinguished them would put back exactly what the
        // conflation removes.
        ContextError::Unreachable => reject_with_code(
            doc,
            ext(&slug, "notFound"),
            "no context with that id is reachable by this caller",
            None,
        ),
        ContextError::ParentUnreachable => reject_with_code(
            doc,
            ext(&slug, "parentNotFound"),
            "no context with that parent id is reachable by this caller",
            None,
        ),
        ContextError::NotEmpty(holds) => reject_with_code(
            doc,
            ext(&slug, "notEmpty"),
            format!(
                "context holds {}; retry with force to delete the whole subtree, or preview it \
                 first",
                holds.summary()
            ),
            // The counts machine-readably, so a consumer can decide without
            // parsing the sentence above. `subContexts` is the one that
            // changes what the operator is agreeing to.
            Some(serde_json::json!({
                "subContexts": holds.sub_contexts,
                "keys": holds.keys,
                "webvhDids": holds.webvh_dids,
                "aclEntries": holds.acl_entries,
                "didTemplates": holds.did_templates,
            })),
        ),
        ContextError::Other(e) => app_error_to_reject(doc, e),
    }
}

/// Handler for `spec/vta/contexts/list/1.0`.
pub(super) async fn handle_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: ListContextsBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::contexts::list_contexts(&state.contexts_ks, auth, TRANSPORT_TRUST_TASK).await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/create/1.0`. Super-admin only.
pub(super) async fn handle_create(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // Admin role required; `create_context` enforces the finer gate (super-admin
    // for a top-level context, admin-of-parent for a sub-context).
    if let Err(e) = auth.require_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: CreateContextBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let audit_id = req.id.clone();
    match operations::contexts::create_context(
        &state.contexts_ks,
        auth,
        &req.id,
        req.name,
        req.description,
        req.parent,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => {
            // A context is the isolation boundary every key, DID and app-state
            // record hangs off. Creating one is creating a new compartment, and
            // "when did this appear, and who made it" is a question the trail
            // has to answer.
            if let Err(e) = crate::audit::record_with_detail(
                &state.audit_sink,
                "contexts.create",
                &auth.did,
                Some(&audit_id),
                "success",
                Some(TRANSPORT_TRUST_TASK),
                Some(&audit_id),
                None,
            )
            .await
            {
                tracing::warn!(error = %e, "audit record failed for contexts.create");
            }
            success_response(&doc, body)
        }
        Err(e) => reject_context_error(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/get/1.0`.
pub(super) async fn handle_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: GetContextBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::contexts::get_context_op(
        &state.contexts_ks,
        auth,
        &req.id,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => reject_context_error(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/secrets/1.0` — the private keys of a context's own DID.
///
/// **`KeyExport`, and only for a context the caller may act in** (VTI-VTA-003). Releasing a
/// DID's keys is an export, so it is gated on the capability `keys/export-secret` also
/// requires, which only `admin` derives — the operator of a context's DID is an admin scoped
/// to that context. The scope check still applies on top: an admin of one context reaches
/// no other context's keys.
///
/// Both checks live in [`operations::export::get_context_secrets`] rather than here, so a
/// second entry point cannot acquire a different set of them. A refusal rides out as
/// `permissionDenied` carrying the command that fixes it, which the SDK surfaces as
/// `VtaError::Forbidden` on every transport.
pub(super) async fn handle_secrets(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: vta_sdk::protocols::context_management::secrets::GetContextSecretsBody =
        match parse_payload(&doc) {
            Ok(r) => r,
            Err(resp) => return resp,
        };
    let deps = operations::export::ExportDeps {
        keys_ks: &state.keys_ks,
        contexts_ks: &state.contexts_ks,
        imported_ks: &state.imported_ks,
        audit: &state.audit_sink,
        acl_ks: &state.acl_ks,
        #[cfg(feature = "webvh")]
        webvh_ks: &state.webvh_ks,
        seed_store: &state.seed_store,
    };
    match operations::export::get_context_secrets(&deps, auth, &req.id, TRANSPORT_TRUST_TASK).await
    {
        // The spec's response is lowerCamelCase (SPEC §4.10); `DidSecretsBundle` is the
        // internal snake_case form, shared with the on-disk export. The conversion is the
        // boundary between them.
        Ok(bundle) => success_response(
            &doc,
            vta_sdk::protocols::context_management::secrets::ContextSecretsResultBody::from(bundle),
        ),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/update/1.0`. Super-admin only.
pub(super) async fn handle_update(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: UpdateContextBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::contexts::update_context(
        &state.contexts_ks,
        auth,
        &req.id,
        operations::contexts::UpdateContextParams {
            name: req.name,
            did: req.did,
            description: req.description,
            context_policy: req.context_policy,
        },
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => reject_context_error(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/update-did/1.0`. Admin only.
pub(super) async fn handle_update_did(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: UpdateContextDidBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::contexts::update_context_did(
        &state.contexts_ks,
        auth,
        &req.id,
        req.did,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => reject_context_error(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/preview-delete/1.0`. Super-admin only.
pub(super) async fn handle_preview_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // Admin role; the operation enforces access to the context or an ancestor.
    if let Err(e) = auth.require_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: DeleteContextPreviewBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::contexts::preview_delete_context(
        &state.contexts_ks,
        &state.keys_ks,
        &state.acl_ks,
        &state.did_templates_ks,
        #[cfg(feature = "webvh")]
        &state.webvh_ks,
        auth,
        &req.id,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => reject_context_error(&doc, e),
    }
}

/// Handler for `spec/vta/contexts/delete/1.0`. Admin role; the operation
/// enforces access to the context or an ancestor (folder authority) and
/// cascades the subtree with `force`.
pub(super) async fn handle_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_admin() {
        return app_error_to_reject(&doc, e);
    }
    // Step-up (context/delete floor) is enforced centrally by the PDP gate.
    let req: DeleteContextBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ks = operations::keyspaces_from_app_state(state);
    // A context's DIDs are deleted through the full webvh path, which needs a
    // resolver to reach their hosting servers. Without one the deletion is
    // *refused* for a context that holds DIDs rather than dropping their local
    // records — see `ContextDidCleanup`.
    #[cfg(feature = "webvh")]
    let outcome = {
        let vta_did = state.config.read().await.vta_did.clone();
        match state.did_resolver.as_ref() {
            Some(did_resolver) => {
                let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
                let cleanup = operations::contexts::ContextDidCleanup {
                    deps: &deps,
                    vta_did: vta_did.as_deref(),
                };
                operations::contexts::delete_context(
                    &ks,
                    auth,
                    &req.id,
                    req.force,
                    TRANSPORT_TRUST_TASK,
                    Some(&cleanup),
                )
                .await
            }
            None => {
                operations::contexts::delete_context(
                    &ks,
                    auth,
                    &req.id,
                    req.force,
                    TRANSPORT_TRUST_TASK,
                    None,
                )
                .await
            }
        }
    };
    #[cfg(not(feature = "webvh"))]
    let outcome =
        operations::contexts::delete_context(&ks, auth, &req.id, req.force, TRANSPORT_TRUST_TASK)
            .await;

    match outcome {
        Ok(body) => success_response(&doc, body),
        Err(e) => reject_context_error(&doc, e),
    }
}

#[cfg(test)]
mod secrets_gate_tests {
    use super::*;
    use crate::acl::Role;
    use crate::test_support::build_signing_test_app_state;
    use serde_json::json;
    use trust_tasks_rs::TypeUri;
    use vti_common::acl::{AclEntry, store_acl_entry};

    /// VTI-VTA-003 over the Trust Task transport — which REST, DIDComm and TSP
    /// all dispatch into: the refusal is `permissionDenied` (the SDK maps it to
    /// `VtaError::Forbidden`), and the fix command survives in the message.
    #[tokio::test]
    async fn vti_vta_003_refusal_is_permission_denied_and_names_the_fix() {
        let (state, _dir) = build_signing_test_app_state().await;
        let did = "did:key:zRoomHost";
        store_acl_entry(
            &state.acl_ks,
            &AclEntry::new(did, Role::Application, "did:key:zRoot")
                .with_contexts(vec!["rooms".to_string()]),
        )
        .await
        .expect("store the caller's entry");
        let auth = AuthClaims {
            did: did.into(),
            role: Role::Application,
            allowed_contexts: vec!["rooms".to_string()],
            session_id: "test-session".into(),
            access_expires_at: 0,
            issued_at: 0,
            amr: Vec::new(),
            acr: String::new(),
        };
        let uri: TypeUri = vta_sdk::trust_tasks::TASK_CONTEXTS_SECRETS_1_0
            .parse()
            .expect("contexts/secrets uri");
        let doc = TrustTask::new(
            format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            uri,
            json!({ "id": "rooms" }),
        );

        let out = handle_secrets(&state, &auth, doc).await;
        let body: Value = serde_json::from_slice(&out.body).expect("response is JSON");
        assert_eq!(
            body.pointer("/payload/code").and_then(Value::as_str),
            Some("permissionDenied"),
            "{body}"
        );
        let message = body.to_string();
        assert!(
            message.contains(
                "pnm acl change-role --did did:key:zRoomHost --from application --to admin"
            ),
            "the fix command must reach the caller: {message}"
        );
    }
}