vcon-server 0.4.16

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
//! The admin tools, for operator keys: the same work as the `/admin/`
//! routes. Tenants records each outcome, and a refusal before Tenants is
//! recorded in the admin log by the gate, as the routes record theirs.

use rmcp::model::JsonObject;
use serde::Deserialize;
use serde_json::{Value, json};

use super::{Hints, Outcome, Running, Server, Spec, arguments, budget, fence, tool};
use crate::access::{Caller, Scopes};
use crate::api::{self, Problem};
use crate::audit::{Action, Actor, AuditQuery};
use crate::ids::{KeyId, TenantId};
use crate::retention::Retention;
use crate::tenants::{KeyInfo, KeyLife, Removal, TenantError, TenantInfo};

/// The admin tools.
pub(super) fn specs() -> Vec<Spec> {
    let read = Hints {
        read_only: true,
        idempotent: true,
        ..Hints::NONE
    };
    let erase = Hints {
        destructive: true,
        ..Hints::NONE
    };
    vec![
        spec::<TenantCreateArgs>(
            "admin_tenant_create",
            "Makes a tenant with this name (1 to 128 characters) and, if given, its own \
             retention period (such as 7y, 18m or 90d; the server default when left out or \
             null), and returns its id.",
            Hints::NONE,
            Action::TenantCreate,
            tenant_create,
        ),
        spec::<PageArgs>(
            "admin_tenant_list",
            "Returns every tenant, by name: its id, its name between untrusted-vcon-data \
             markers, its own retention period (null for the server default) and its \
             metadata level for Parquet exports; from cursor, within max_bytes, with \
             next_cursor when more follow.",
            read,
            Action::TenantList,
            tenant_list,
        ),
        spec::<TenantRetentionArgs>(
            "admin_tenant_retention",
            "Sets the tenant's own retention period, or with null returns it to the server \
             default, and returns the tenant's id and its period.",
            Hints {
                idempotent: true,
                ..Hints::NONE
            },
            Action::TenantRetention,
            tenant_retention,
        ),
        spec::<TenantRemoveArgs>(
            "admin_tenant_remove",
            "Removes a tenant that keeps no vCon, or with force one that does unless a vCon \
             of it is under a legal hold, destroying its keys and data, and returns its id.",
            erase,
            Action::TenantRemove,
            tenant_remove,
        ),
        spec::<KeyCreateArgs>(
            "admin_key_create",
            "Makes a key for the tenant holding these scopes (write, read, delete, legal, \
             audit, tenant_admin) with this label, and returns its id, its token and its \
             expiry. The token is returned this once; only its hash is kept. The key expires \
             in 90 days, or in expires_in_days days (1 to 365), or never with no_expiry.",
            Hints::NONE,
            Action::KeyCreate,
            key_create,
        ),
        spec::<KeyListArgs>(
            "admin_key_list",
            "Returns the tenant's keys, oldest first: each id, tenant, scopes, label between \
             untrusted-vcon-data markers, and times made, revoked, of expiry and of last use (RFC \
             3339, null for a time the key does not have); never a token. From cursor, within max_bytes, with next_cursor when more follow.",
            read,
            Action::KeyList,
            key_list,
        ),
        spec::<KeyRevokeArgs>(
            "admin_key_revoke",
            "Revokes the key with this id, so its next request is refused, and returns the \
             id; a key already revoked answers the same.",
            Hints {
                destructive: true,
                idempotent: true,
                ..Hints::NONE
            },
            Action::KeyRevoke,
            key_revoke,
        ),
        spec::<AuditArgs>(
            "admin_audit_read",
            "Returns records of the admin log after the sequence number after (0, the \
             default, is the start), oldest first, at most limit of them (1 to 10000, default \
             1000), within max_bytes: each record as audit export --admin writes it, and \
             next_cursor, the seq of the last record returned.",
            Hints {
                read_only: true,
                ..Hints::NONE
            },
            Action::AuditRead,
            audit_read,
        ),
    ]
}

fn spec<A: rmcp::schemars::JsonSchema + 'static>(
    name: &'static str,
    description: &'static str,
    hints: Hints,
    action: Action,
    run: super::Run,
) -> Spec {
    Spec {
        tool: tool::<A>(name, description, hints),
        action,
        run,
    }
}

/// A tenant's id, or the refusal the admin routes give a malformed one:
/// unknown-tenant.
fn tenant_id(text: &str) -> Result<TenantId, Outcome> {
    TenantId::parse(text).ok_or(Outcome::Refused(Problem::Tenant(TenantError::NotFound)))
}

/// A retention period as text, null for the server default.
fn period(text: Option<&str>) -> Result<Option<Retention>, Outcome> {
    text.map(|t| Retention::parse(t).ok_or(Outcome::Arguments))
        .transpose()
}

/// What Tenants refused or failed, as the admin routes answer it.
fn answered(error: TenantError) -> Outcome {
    Outcome::Answered(Problem::Tenant(error))
}

/// A page of `rows` from `cursor`, a row index an earlier page gave, under
/// `key`, fitting `room`, with the provenance sentence.
fn rows_page(
    key: &str,
    rows: &[Value],
    cursor: Option<&str>,
    room: usize,
) -> Result<Value, Outcome> {
    let start = cursor
        .map(|c| c.parse::<usize>().map_err(|_| Outcome::Arguments))
        .transpose()?
        .unwrap_or(0);
    let rows = rows.get(start..).ok_or(Outcome::Arguments)?;
    let page = |n: usize| {
        json!({
            key: rows[..n],
            "truncated": n < rows.len(),
            "next_cursor": (n < rows.len()).then(|| (start + n).to_string()),
            "provenance": fence::PROVENANCE,
        })
    };
    let n = budget::rows_that_fit(rows.len(), |n| budget::size(&page(n)) <= room);
    Ok(page(n))
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct TenantCreateArgs {
    /// The tenant's name: 1 to 128 characters, no control character, no white
    /// space at either end.
    name: String,
    /// Its own retention period, such as 7y, 18m or 90d; the server default
    /// when left out or null.
    retention: Option<String>,
}

fn tenant_create<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: TenantCreateArgs = arguments(args)?;
        let retention = period(args.retention.as_deref())?;
        let tenants = server.app.tenants.clone();
        let id =
            api::blocking(move || tenants.create(Actor::Key(caller.key), &args.name, retention))
                .await
                .map_err(answered)?;
        Ok(json!({"id": id.to_string()}))
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct PageArgs {
    /// The next_cursor a previous page gave.
    cursor: Option<String>,
    /// The most bytes the result may hold; the server's ceiling applies.
    max_bytes: Option<u64>,
}

fn tenant_list<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: PageArgs = arguments(args)?;
        let room = budget::resolve(args.max_bytes, server.app.mcp.response_bytes);
        let tenants = server.app.tenants.clone();
        let listed = api::blocking(move || tenants.list(Actor::Key(caller.key)))
            .await
            .map_err(answered)?;
        let rows: Vec<Value> = listed
            .iter()
            .map(|t: &TenantInfo| {
                let mut row = t.to_json();
                row["name"] = fence::fence_field(&t.name).into();
                row
            })
            .collect();
        rows_page("tenants", &rows, args.cursor.as_deref(), room)
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct TenantRetentionArgs {
    /// The tenant's id.
    id: String,
    /// The period, such as 7y, 18m or 90d, or null for the server default;
    /// it must be given.
    retention: Value,
}

fn tenant_retention<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: TenantRetentionArgs = arguments(args)?;
        let retention = match &args.retention {
            Value::Null => None,
            Value::String(text) => period(Some(text))?,
            _ => return Err(Outcome::Arguments),
        };
        let id = tenant_id(&args.id)?;
        let tenants = server.app.tenants.clone();
        api::blocking(move || tenants.set_retention(Actor::Key(caller.key), id, retention))
            .await
            .map_err(answered)?;
        Ok(json!({"id": id.to_string(), "retention": retention.map(|r| r.to_string())}))
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct TenantRemoveArgs {
    /// The tenant's id.
    id: String,
    /// Remove it even while it keeps vCons; a legal hold still refuses.
    force: Option<bool>,
}

fn tenant_remove<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: TenantRemoveArgs = arguments(args)?;
        let id = tenant_id(&args.id)?;
        // Nothing over the network overrides a legal hold.
        let removal = if args.force == Some(true) {
            Removal::Force
        } else {
            Removal::Empty
        };
        let tenants = server.app.tenants.clone();
        api::blocking(move || tenants.remove(Actor::Key(caller.key), id, removal))
            .await
            .map_err(answered)?;
        Ok(json!({"id": id.to_string()}))
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct KeyCreateArgs {
    /// The tenant the key belongs to.
    tenant: String,
    /// The scopes it holds: write, read, delete, legal, audit, tenant_admin.
    scopes: Vec<String>,
    /// Who holds the key.
    label: String,
    /// The days until the key expires, from 1 to 365; 90 when absent.
    #[serde(default)]
    expires_in_days: Option<i64>,
    /// True for a key that never expires, where the configuration allows
    /// one.
    #[serde(default)]
    no_expiry: Option<bool>,
}

fn key_create<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: KeyCreateArgs = arguments(args)?;
        let tenant = tenant_id(&args.tenant)?;
        let scopes = Scopes::named(&args.scopes)
            .ok_or(Outcome::Refused(Problem::Tenant(TenantError::BadScopes)))?;
        let life = KeyLife::asked(args.expires_in_days, args.no_expiry);
        let tenants = server.app.tenants.clone();
        let made = api::blocking(move || {
            tenants.create_key_for(
                Actor::Key(caller.key),
                Some(tenant),
                scopes,
                &args.label,
                life,
            )
        })
        .await
        .map_err(answered)?;
        made.to_json()
            .ok_or(Outcome::Refused(Problem::Tenant(TenantError::Io)))
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct KeyListArgs {
    /// The tenant whose keys to list.
    tenant: String,
    /// The next_cursor a previous page gave.
    cursor: Option<String>,
    /// The most bytes the result may hold; the server's ceiling applies.
    max_bytes: Option<u64>,
}

fn key_list<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: KeyListArgs = arguments(args)?;
        let tenant = tenant_id(&args.tenant)?;
        let room = budget::resolve(args.max_bytes, server.app.mcp.response_bytes);
        let tenants = server.app.tenants.clone();
        let keys = api::blocking(move || tenants.list_keys(Actor::Key(caller.key), Some(tenant)))
            .await
            .map_err(answered)?;
        let rows: Vec<Value> = keys
            .iter()
            .map(|k: &KeyInfo| {
                let mut row = k.to_json()?;
                row["label"] = fence::fence_field(&k.label).into();
                Some(row)
            })
            .collect::<Option<_>>()
            .ok_or_else(|| answered(TenantError::Io))?;
        rows_page("keys", &rows, args.cursor.as_deref(), room)
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct KeyRevokeArgs {
    /// The key's id.
    id: String,
}

fn key_revoke<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: KeyRevokeArgs = arguments(args)?;
        let id = KeyId::parse(&args.id).ok_or(Outcome::Refused(Problem::UnknownKey))?;
        let tenants = server.app.tenants.clone();
        api::blocking(move || tenants.revoke_key(Actor::Key(caller.key), id))
            .await
            .map_err(|error| match error {
                TenantError::NotFound => Outcome::Answered(Problem::UnknownKey),
                error => answered(error),
            })?;
        Ok(json!({"id": id.to_string()}))
    })
}

#[derive(Debug, Clone, Deserialize, rmcp::schemars::JsonSchema)]
#[schemars(crate = "rmcp::schemars")]
#[serde(deny_unknown_fields)]
pub(super) struct AuditArgs {
    /// Records after this sequence number; 0 when left out.
    after: Option<u64>,
    /// How many records at most: 1 to 10000, 1000 when left out.
    limit: Option<u64>,
    /// The most bytes the result may hold; the server's ceiling applies.
    max_bytes: Option<u64>,
}

fn audit_read<'a>(server: &'a Server, caller: Caller, args: JsonObject) -> Running<'a> {
    Box::pin(async move {
        let args: AuditArgs = arguments(args)?;
        let query = AuditQuery::new(args.after, args.limit)
            .map_err(|_| Outcome::Refused(Problem::BadQuery))?;
        let room = budget::resolve(args.max_bytes, server.app.mcp.response_bytes);
        let tenants = server.app.tenants.clone();
        let lines = api::blocking(move || tenants.audit_page(Actor::Key(caller.key), &query))
            .await
            .map_err(answered)?;
        super::audit::records(lines, room)
    })
}