vta-service 0.10.0

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
//! REST routes for DID templates (global + context scope).
//!
//! Global-scope writes (`POST`, `PUT`, `DELETE` under `/did-templates`)
//! gate on [`SuperAdminAuth`]; reads and render accept any authenticated
//! caller via [`AuthClaims`].
//!
//! Context-scope routes (`/contexts/{id}/did-templates/...`) use
//! [`AuthClaims`] for every handler and delegate authz to the operations
//! layer, which accepts super admin OR admin-with-context for writes,
//! and any caller with context access for reads.

use std::collections::HashMap;

use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use serde::Deserialize;
use serde_json::Value;

use vta_sdk::did_templates::{DidTemplate, DidTemplateRecord, TemplateVars};
// Wire types canonically live in vta-sdk per
// `memory::feedback-wire-types-in-sdk`. The shapes that match the
// trust-task variants are re-exported under their legacy REST
// aliases; the Render request body diverges (REST takes `name` from
// the URL path, trust-task takes `name` in the payload) so the
// per-handler type stays local.
pub use vta_sdk::protocols::did_template_management::list::ListDidTemplatesResultBody as ListDidTemplatesResponse;
pub use vta_sdk::protocols::did_template_management::render::RenderDidTemplateResultBody as RenderDidTemplateResponse;

use crate::auth::{AuthClaims, SuperAdminAuth};
use crate::error::AppError;
use crate::operations;
use crate::server::AppState;

/// REST request body for `POST /did-templates/{name}/render` and the
/// context-scoped variant. `name` is in the URL path, so the body
/// carries only the caller variables. Distinct from the trust-task
/// `RenderDidTemplateBody` which carries `name` inline since the
/// envelope has no path component.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct RenderDidTemplateRequest {
    #[serde(default)]
    pub vars: HashMap<String, Value>,
}

/// `GET /did-templates` — list all global templates. Any authenticated caller.
#[utoipa::path(
    get, path = "/did-templates", tag = "did-templates",
    security(("bearer_jwt" = [])),
    responses(
        (status = 200, description = "DID templates", body = ListDidTemplatesResponse),
        (status = 401, description = "Missing or invalid bearer token"),
    ),
)]
pub async fn list_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
) -> Result<Json<ListDidTemplatesResponse>, AppError> {
    let templates =
        operations::did_templates::list_global(&state.did_templates_ks, &auth, "rest").await?;
    Ok(Json(ListDidTemplatesResponse { templates }))
}

/// `POST /did-templates` — create a global template. Super admin only.
#[utoipa::path(
    post, path = "/did-templates", tag = "did-templates",
    security(("bearer_jwt" = [])),
    request_body = DidTemplate,
    responses(
        (status = 201, description = "DID template created", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 403, description = "Caller is not a super admin"),
    ),
)]
pub async fn create_handler(
    auth: SuperAdminAuth,
    State(state): State<AppState>,
    Json(template): Json<DidTemplate>,
) -> Result<(StatusCode, Json<DidTemplateRecord>), AppError> {
    let record = operations::did_templates::create_global(
        &state.did_templates_ks,
        &state.audit_ks,
        &auth.0,
        template,
        "rest",
    )
    .await?;
    Ok((StatusCode::CREATED, Json(record)))
}

/// `GET /did-templates/{name}` — fetch one global template. Any authed caller.
#[utoipa::path(
    get, path = "/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("name" = String, Path, description = "Template name")),
    responses(
        (status = 200, description = "DID template", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn get_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> Result<Json<DidTemplateRecord>, AppError> {
    let record =
        operations::did_templates::get_global(&state.did_templates_ks, &auth, &name, "rest")
            .await?;
    Ok(Json(record))
}

/// `PUT /did-templates/{name}` — replace a global template. Super admin only.
#[utoipa::path(
    put, path = "/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("name" = String, Path, description = "Template name")),
    request_body = DidTemplate,
    responses(
        (status = 200, description = "DID template updated", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 403, description = "Caller is not a super admin"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn update_handler(
    auth: SuperAdminAuth,
    State(state): State<AppState>,
    Path(name): Path<String>,
    Json(template): Json<DidTemplate>,
) -> Result<Json<DidTemplateRecord>, AppError> {
    let record = operations::did_templates::update_global(
        &state.did_templates_ks,
        &state.audit_ks,
        &auth.0,
        &name,
        template,
        "rest",
    )
    .await?;
    Ok(Json(record))
}

/// `DELETE /did-templates/{name}` — delete a global template. Super admin only.
#[utoipa::path(
    delete, path = "/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("name" = String, Path, description = "Template name")),
    responses(
        (status = 204, description = "DID template deleted"),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 403, description = "Caller is not a super admin"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn delete_handler(
    auth: SuperAdminAuth,
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> Result<StatusCode, AppError> {
    operations::did_templates::delete_global(
        &state.did_templates_ks,
        &state.audit_ks,
        &auth.0,
        &name,
        "rest",
    )
    .await?;
    Ok(StatusCode::NO_CONTENT)
}

/// `POST /did-templates/{name}/render` — render a template with caller vars.
/// Any authenticated caller. Server injects ambient variables.
#[utoipa::path(
    post, path = "/did-templates/{name}/render", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("name" = String, Path, description = "Template name")),
    request_body = RenderDidTemplateRequest,
    responses(
        (status = 200, description = "Rendered DID document", body = RenderDidTemplateResponse),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn render_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path(name): Path<String>,
    Json(req): Json<RenderDidTemplateRequest>,
) -> Result<Json<RenderDidTemplateResponse>, AppError> {
    let mut caller_vars = TemplateVars::new();
    for (k, v) in req.vars {
        caller_vars.insert(k, v);
    }

    // Hold the read guard for the duration of render — it's purely CPU,
    // no network or storage writes, so we don't block writers meaningfully.
    // Cloning AppConfig (with its Arc/RwLock internals) on every render
    // request was the old behaviour; this avoids the per-request deep copy.
    let config_guard = state.config.read().await;
    let document = operations::did_templates::render_global(
        &state.did_templates_ks,
        &config_guard,
        &auth,
        &name,
        caller_vars,
        "rest",
    )
    .await?;
    Ok(Json(RenderDidTemplateResponse { document }))
}

// ── Context-scoped handlers ──────────────────────────────────────────

/// `GET /contexts/{id}/did-templates` — list context-scoped templates.
#[utoipa::path(
    get, path = "/contexts/{id}/did-templates", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("id" = String, Path, description = "Context identifier")),
    responses(
        (status = 200, description = "DID templates", body = ListDidTemplatesResponse),
        (status = 401, description = "Missing or invalid bearer token"),
    ),
)]
pub async fn list_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path(context_id): Path<String>,
) -> Result<Json<ListDidTemplatesResponse>, AppError> {
    let templates = operations::did_templates::list_context(
        &state.did_templates_ks,
        &auth,
        &context_id,
        "rest",
    )
    .await?;
    Ok(Json(ListDidTemplatesResponse { templates }))
}

/// `POST /contexts/{id}/did-templates` — create a context-scoped template.
#[utoipa::path(
    post, path = "/contexts/{id}/did-templates", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(("id" = String, Path, description = "Context identifier")),
    request_body = DidTemplate,
    responses(
        (status = 201, description = "DID template created", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
    ),
)]
pub async fn create_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path(context_id): Path<String>,
    Json(template): Json<DidTemplate>,
) -> Result<(StatusCode, Json<DidTemplateRecord>), AppError> {
    let record = operations::did_templates::create_context(
        &state.did_templates_ks,
        &state.contexts_ks,
        &state.audit_ks,
        &auth,
        &context_id,
        template,
        "rest",
    )
    .await?;
    Ok((StatusCode::CREATED, Json(record)))
}

/// `GET /contexts/{id}/did-templates/{name}` — fetch one context template.
#[utoipa::path(
    get, path = "/contexts/{id}/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(
        ("id" = String, Path, description = "Context identifier"),
        ("name" = String, Path, description = "Template name"),
    ),
    responses(
        (status = 200, description = "DID template", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn get_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path((context_id, name)): Path<(String, String)>,
) -> Result<Json<DidTemplateRecord>, AppError> {
    let record = operations::did_templates::get_context(
        &state.did_templates_ks,
        &auth,
        &context_id,
        &name,
        "rest",
    )
    .await?;
    Ok(Json(record))
}

/// `PUT /contexts/{id}/did-templates/{name}` — replace a context template.
#[utoipa::path(
    put, path = "/contexts/{id}/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(
        ("id" = String, Path, description = "Context identifier"),
        ("name" = String, Path, description = "Template name"),
    ),
    request_body = DidTemplate,
    responses(
        (status = 200, description = "DID template updated", body = DidTemplateRecord),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn update_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path((context_id, name)): Path<(String, String)>,
    Json(template): Json<DidTemplate>,
) -> Result<Json<DidTemplateRecord>, AppError> {
    let record = operations::did_templates::update_context(
        &state.did_templates_ks,
        &state.audit_ks,
        &auth,
        &context_id,
        &name,
        template,
        "rest",
    )
    .await?;
    Ok(Json(record))
}

/// `DELETE /contexts/{id}/did-templates/{name}` — remove a context template.
#[utoipa::path(
    delete, path = "/contexts/{id}/did-templates/{name}", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(
        ("id" = String, Path, description = "Context identifier"),
        ("name" = String, Path, description = "Template name"),
    ),
    responses(
        (status = 204, description = "DID template deleted"),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn delete_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path((context_id, name)): Path<(String, String)>,
) -> Result<StatusCode, AppError> {
    operations::did_templates::delete_context(
        &state.did_templates_ks,
        &state.audit_ks,
        &auth,
        &context_id,
        &name,
        "rest",
    )
    .await?;
    Ok(StatusCode::NO_CONTENT)
}

/// `POST /contexts/{id}/did-templates/{name}/render` — render a context template.
#[utoipa::path(
    post, path = "/contexts/{id}/did-templates/{name}/render", tag = "did-templates",
    security(("bearer_jwt" = [])),
    params(
        ("id" = String, Path, description = "Context identifier"),
        ("name" = String, Path, description = "Template name"),
    ),
    request_body = RenderDidTemplateRequest,
    responses(
        (status = 200, description = "Rendered DID document", body = RenderDidTemplateResponse),
        (status = 401, description = "Missing or invalid bearer token"),
        (status = 404, description = "Template not found"),
    ),
)]
pub async fn render_context_handler(
    auth: AuthClaims,
    State(state): State<AppState>,
    Path((context_id, name)): Path<(String, String)>,
    Json(req): Json<RenderDidTemplateRequest>,
) -> Result<Json<RenderDidTemplateResponse>, AppError> {
    let mut caller_vars = TemplateVars::new();
    for (k, v) in req.vars {
        caller_vars.insert(k, v);
    }

    // See render_handler above — render is CPU-only, so we hold the read
    // guard across the call rather than deep-cloning AppConfig per request.
    let config_guard = state.config.read().await;
    let document = operations::did_templates::render_context(
        &state.did_templates_ks,
        &state.contexts_ks,
        &config_guard,
        &auth,
        &context_id,
        &name,
        caller_vars,
        "rest",
    )
    .await?;
    Ok(Json(RenderDidTemplateResponse { document }))
}