vti-common 0.10.5

Shared server-side infrastructure for VTA and VTC services
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
use std::sync::Arc;

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum_extra::TypedHeader;
use axum_extra::headers::Authorization;
use axum_extra::headers::authorization::Bearer;
use tracing::warn;

use crate::acl::Role;
use crate::auth::jwt::JwtKeys;
use crate::auth::session::{SessionState, get_session};
use crate::error::AppError;
use crate::store::KeyspaceHandle;

/// Trait that each service's `AppState` implements to provide the data
/// needed by the auth extractors.
pub trait AuthState: Clone + Send + Sync + 'static {
    fn jwt_keys(&self) -> Option<&Arc<JwtKeys>>;
    fn sessions_ks(&self) -> &KeyspaceHandle;
}

/// Extracted from a valid JWT Bearer token on protected routes.
///
/// Add this as a handler parameter to require authentication:
/// ```ignore
/// async fn handler(_auth: AuthClaims, ...) { }
/// ```
#[derive(Debug, Default, Clone)]
pub struct AuthClaims {
    pub did: String,
    pub role: Role,
    pub allowed_contexts: Vec<String>,
    /// JWT `session_id` claim. Carried through so handlers can do
    /// session-targeted operations (sign-out, refresh-token
    /// rotation) without re-decoding the JWT.
    pub session_id: String,
    /// JWT `exp` claim — Unix-second expiry. Surfaced so
    /// `whoami`-style endpoints can return the access-token
    /// lifetime without re-decoding.
    pub access_expires_at: u64,
    /// Authentication Methods References per [RFC 8176]. Mirrors
    /// `Claims.amr` from the bearer JWT. Handlers gating sensitive
    /// operations check this to decide whether a step-up is needed.
    pub amr: Vec<String>,
    /// Authentication Context Class Reference per OIDC Core §2.
    /// Typical values: `"aal1"` / `"aal2"` / `"aal3"`. Handlers gating
    /// step-up read this directly.
    pub acr: String,
}

/// Name of the admin UX session cookie set by the VTC's
/// `POST /v1/auth/admin-login` + `POST /v1/auth/passkey-login/finish`
/// flows. When the `Authorization: Bearer` header is absent,
/// [`AuthClaims`] falls back to reading a JWT out of this cookie.
/// The cookie is set with `Path=/; SameSite=Strict; Secure; HttpOnly`
/// so the browser sends it on `/v1/*` API calls; `HttpOnly` keeps
/// JS on any path from reading it, and `SameSite=Strict` blocks
/// cross-site CSRF.
pub const ADMIN_SESSION_COOKIE: &str = "vtc_admin_session";

impl<S: AuthState> FromRequestParts<S> for AuthClaims {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // Try `Authorization: Bearer <jwt>` first. Programmatic
        // clients (cnm-cli, DIDComm bridges, the existing
        // `/v1/auth/` flow) all use this path.
        let bearer_token = TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state)
            .await
            .ok()
            .map(|TypedHeader(auth)| auth.token().to_string());

        // Fall back to the admin session cookie (Phase 5 M5.2.3).
        // Set by `POST /v1/auth/admin-login`; carries the same JWT
        // as the bearer path.
        let token: String = match bearer_token {
            Some(t) => t,
            None => match cookie_token(parts, ADMIN_SESSION_COOKIE) {
                Some(t) => t,
                None => {
                    warn!(
                        "auth rejected: no Authorization header and no {ADMIN_SESSION_COOKIE} cookie"
                    );
                    return Err(AppError::Unauthorized(
                        "missing or invalid Authorization header".into(),
                    ));
                }
            },
        };
        let token = token.as_str();

        // Decode and validate JWT
        let jwt_keys = state
            .jwt_keys()
            .ok_or_else(|| AppError::Unauthorized("auth not configured".into()))?;

        let claims = jwt_keys.decode(token)?;

        // Verify session exists and is authenticated
        let session = get_session(state.sessions_ks(), &claims.session_id)
            .await?
            .ok_or_else(|| {
                warn!(session_id = %claims.session_id, "auth rejected: session not found");
                AppError::Unauthorized("session not found".into())
            })?;

        if session.state != SessionState::Authenticated {
            warn!(session_id = %claims.session_id, "auth rejected: session not in authenticated state");
            return Err(AppError::Unauthorized("session not authenticated".into()));
        }

        let role = Role::parse(&claims.role)?;

        Ok(AuthClaims {
            did: claims.sub,
            role,
            allowed_contexts: claims.contexts,
            session_id: claims.session_id,
            access_expires_at: claims.exp,
            amr: claims.amr,
            acr: claims.acr,
        })
    }
}

impl AuthClaims {
    /// **UNSAFE**: Synthesize a super-admin claim with no wire-level
    /// verification. Only for **on-host offline CLI** invocations — the
    /// trust boundary is the OS process, not the network.
    ///
    /// Feature-gated behind `cli-synthesis` so this function is physically
    /// absent from enclave and server-only builds. Any caller compiles
    /// iff the feature is on; calling this from a route handler is a bug
    /// that the type system can't catch (the resulting `AuthClaims` is
    /// indistinguishable from a legitimate one), so the name loudly marks
    /// the footgun.
    ///
    /// The trust model: a process that can execute the VTA binary AND
    /// read the keystore + seed store is already trusted by the OS to
    /// act as the VTA itself. Offline CLIs that mutate state (mint keys,
    /// seal bundles, export admin credentials) pre-date any over-the-
    /// wire authentication, so wire-level claims can't gate them. The
    /// caller-supplied `channel` is recorded in the audit log so misuse
    /// can be traced back to the specific CLI path.
    ///
    /// Downstream hardening (tracked as review item 9 follow-up):
    /// - Require an operator-side credential (env var / local config
    ///   pointing at a key in the ACL) before synthesizing.
    /// - Audit-log process identity (`uid`, `pid`, `cwd`) alongside
    ///   `channel` so a forensic investigator can distinguish
    ///   operator-intentional runs from lateral-movement abuse.
    ///
    /// The sentinel DID format `"cli:<channel>"` (not `did:*`) is
    /// deliberate — it doesn't round-trip through DID resolution and
    /// can't be confused with a real caller DID in log correlation.
    #[cfg(feature = "cli-synthesis")]
    pub fn unsafe_local_cli_super_admin(channel: &str) -> Self {
        Self {
            did: format!("cli:{channel}"),
            role: Role::Admin,
            allowed_contexts: Vec::new(),
            // CLI synthesis bypasses the session store entirely.
            // The sentinel session_id matches the DID format and
            // `access_expires_at: 0` makes the synthesized claim
            // visibly "no real expiry" to any log scraper.
            session_id: format!("cli:{channel}"),
            access_expires_at: 0,
            // CLI synthesis is a process-local trust boundary; the auth
            // method is the OS user, not a wire factor. Surface `"cli"`
            // in amr so a downstream auditor distinguishes synthesized
            // claims from real authenticated sessions.
            amr: vec!["cli".to_string()],
            acr: String::new(),
        }
    }

    /// Returns `true` if the caller is an admin with unrestricted access
    /// (empty `allowed_contexts`).
    pub fn is_super_admin(&self) -> bool {
        self.role == Role::Admin && self.allowed_contexts.is_empty()
    }

    /// Returns `true` if the caller has access to the given context — as a super
    /// admin, or because one of their `allowed_contexts` is `context_id` itself
    /// **or an ancestor of it** (folder-level authority: admin of a parent
    /// context covers the whole subtree).
    ///
    /// Ancestry is the segment-aware
    /// [`is_ancestor_or_self`](crate::context_path::is_ancestor_or_self) — a
    /// pure, store-free check over the verified JWT's contexts. For today's flat
    /// (single-segment, childless) contexts this is identical to the previous
    /// exact match.
    pub fn has_context_access(&self, context_id: &str) -> bool {
        self.is_super_admin()
            || self
                .allowed_contexts
                .iter()
                .any(|allowed| crate::context_path::is_ancestor_or_self(allowed, context_id))
    }

    /// Check that the caller has access to the given context.
    ///
    /// Admins with an empty `allowed_contexts` list have unrestricted access.
    pub fn require_context(&self, context_id: &str) -> Result<(), AppError> {
        if self.has_context_access(context_id) {
            return Ok(());
        }
        Err(AppError::Forbidden(format!(
            "no access to context: {context_id}"
        )))
    }

    /// If the caller has exactly one allowed context, return it.
    pub fn default_context(&self) -> Option<&str> {
        if self.allowed_contexts.len() == 1 {
            Some(&self.allowed_contexts[0])
        } else {
            None
        }
    }

    /// Require at least Reader role (all roles except Monitor).
    ///
    /// Use for read-only endpoints that access business data (keys, contexts, DIDs).
    /// Monitor can only see metrics and health.
    pub fn require_read(&self) -> Result<(), AppError> {
        if self.role == Role::Monitor {
            return Err(AppError::Forbidden("reader role or higher required".into()));
        }
        Ok(())
    }

    /// Require at least Application role (Admin, Initiator, or Application).
    ///
    /// Use for write operations: signing, cache writes, and other actions that
    /// produce artifacts or modify state.
    pub fn require_write(&self) -> Result<(), AppError> {
        if matches!(self.role, Role::Admin | Role::Initiator | Role::Application) {
            return Ok(());
        }
        Err(AppError::Forbidden(
            "application role or higher required".into(),
        ))
    }

    /// Require the caller to have Admin role.
    pub fn require_admin(&self) -> Result<(), AppError> {
        if self.role == Role::Admin {
            return Ok(());
        }
        Err(AppError::Forbidden("admin role required".into()))
    }

    /// Require the caller to have Admin or Initiator role.
    pub fn require_manage(&self) -> Result<(), AppError> {
        if self.role == Role::Admin || self.role == Role::Initiator {
            return Ok(());
        }
        Err(AppError::Forbidden(
            "admin or initiator role required".into(),
        ))
    }

    /// Require the caller to be a super admin (Admin + unrestricted).
    pub fn require_super_admin(&self) -> Result<(), AppError> {
        if self.is_super_admin() {
            return Ok(());
        }
        Err(AppError::Forbidden("super admin required".into()))
    }
}

/// Extractor that requires the caller to have Admin or Initiator role.
///
/// Use on endpoints that manage ACL entries and other management tasks:
/// ```ignore
/// async fn handler(auth: ManageAuth, ...) { }
/// ```
#[derive(Debug, Clone)]
pub struct ManageAuth(pub AuthClaims);

impl<S: AuthState> FromRequestParts<S> for ManageAuth {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let claims = AuthClaims::from_request_parts(parts, state).await?;

        match claims.role {
            Role::Admin | Role::Initiator => Ok(ManageAuth(claims)),
            _ => {
                warn!(did = %claims.did, role = %claims.role, "auth rejected: admin or initiator role required");
                Err(AppError::Forbidden(
                    "admin or initiator role required".into(),
                ))
            }
        }
    }
}

/// Extractor that requires the caller to have Admin role.
///
/// Use on endpoints that modify configuration, create/delete keys, etc.:
/// ```ignore
/// async fn handler(auth: AdminAuth, ...) { }
/// ```
#[derive(Debug, Clone)]
pub struct AdminAuth(pub AuthClaims);

impl<S: AuthState> FromRequestParts<S> for AdminAuth {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let claims = AuthClaims::from_request_parts(parts, state).await?;

        match claims.role {
            Role::Admin => Ok(AdminAuth(claims)),
            _ => {
                warn!(did = %claims.did, role = %claims.role, "auth rejected: admin role required");
                Err(AppError::Forbidden("admin role required".into()))
            }
        }
    }
}

/// Extractor that requires a **stepped-up** session (JWT `acr == "aal2"`).
///
/// Use on routes that demand a second factor beyond the base DID
/// challenge-response (`aal1`) — typical examples: ACL edits,
/// key rotation, backup export, anything that lets an attacker
/// with a leaked `aal1` token pivot to a long-lived foothold.
///
/// ```ignore
/// async fn rotate_keys(auth: StepUpAuth, ...) { /* aal2 enforced */ }
/// ```
///
/// A request with a lower `acr` is rejected with
/// [`AppError::StepUpRequired`] (403 + body
/// `{ "error": "step_up_required", "requiredAcr": "aal2" }`). The
/// wallet uses that signal to trigger a passkey-login or
/// VTA-approval ceremony — distinct from a generic `forbidden`
/// it would get from a role gate.
///
/// **Trust model**: the gate reads `acr` from the JWT claims the
/// `AuthClaims` extractor already verified (signature, expiry,
/// session existence). Step-up tokens are stateless during their
/// access-window; the canonical refresh handler preserves `acr`
/// across rotation. If a step-up access-token leaks, the only
/// brake is the short access-token TTL (or [`M2`] — shorter TTL
/// when `acr=aal2`).
#[derive(Debug, Clone)]
pub struct StepUpAuth(pub AuthClaims);

impl<S: AuthState> FromRequestParts<S> for StepUpAuth {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let claims = AuthClaims::from_request_parts(parts, state).await?;

        if claims.acr == "aal2" {
            Ok(StepUpAuth(claims))
        } else {
            warn!(
                did = %claims.did,
                acr = %claims.acr,
                "auth rejected: step-up (aal2) required",
            );
            Err(AppError::StepUpRequired(
                "operation requires a stepped-up (aal2) session".into(),
            ))
        }
    }
}

/// Extractor that requires the caller to be a super admin (Admin role with
/// empty `allowed_contexts`).
///
/// Use on endpoints that only unrestricted administrators should access,
/// such as creating/deleting contexts or modifying global configuration:
/// ```ignore
/// async fn handler(auth: SuperAdminAuth, ...) { }
/// ```
#[derive(Debug, Clone)]
pub struct SuperAdminAuth(pub AuthClaims);

impl<S: AuthState> FromRequestParts<S> for SuperAdminAuth {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let claims = AuthClaims::from_request_parts(parts, state).await?;

        if !claims.is_super_admin() {
            warn!(did = %claims.did, "auth rejected: super admin required");
            return Err(AppError::Forbidden("super admin required".into()));
        }

        Ok(SuperAdminAuth(claims))
    }
}

/// Extractor that requires the caller to have at least Application role
/// (Admin, Initiator, or Application).
///
/// Use on endpoints that perform write operations — signing, cache writes,
/// and other actions that produce artifacts or modify state:
/// ```ignore
/// async fn handler(auth: WriteAuth, ...) { }
/// ```
#[derive(Debug, Clone)]
pub struct WriteAuth(pub AuthClaims);

impl<S: AuthState> FromRequestParts<S> for WriteAuth {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let claims = AuthClaims::from_request_parts(parts, state).await?;

        match claims.role {
            Role::Admin | Role::Initiator | Role::Application => Ok(WriteAuth(claims)),
            _ => {
                warn!(did = %claims.did, role = %claims.role, "auth rejected: application role or higher required");
                Err(AppError::Forbidden(
                    "application role or higher required".into(),
                ))
            }
        }
    }
}

/// Pull a named cookie value off the request `Cookie` headers.
/// Returns `None` when the cookie isn't present. Does **not**
/// percent-decode — cookie values minted by the VTC's admin-login
/// flow are JWTs (base64url + dots), which are ASCII-safe.
fn cookie_token(parts: &Parts, name: &str) -> Option<String> {
    parts
        .headers
        .get_all(axum::http::header::COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|s| s.split(';'))
        .map(|s| s.trim())
        .find_map(|kv| {
            let (k, v) = kv.split_once('=')?;
            (k == name).then(|| v.to_string())
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn has_context_access_grants_the_subtree_to_a_parent_admin() {
        // A context admin scoped to `acme/eng` (not super-admin — the list is
        // non-empty), so ancestry applies.
        let claims = AuthClaims {
            role: Role::Admin,
            allowed_contexts: vec!["acme/eng".into()],
            ..Default::default()
        };
        assert!(!claims.is_super_admin());

        // Self + every descendant.
        assert!(claims.has_context_access("acme/eng"));
        assert!(claims.has_context_access("acme/eng/team-a"));
        assert!(claims.has_context_access("acme/eng/team-a/squad-1"));

        // NOT the parent, a sibling, or a prefix-confusion look-alike.
        assert!(!claims.has_context_access("acme"));
        assert!(!claims.has_context_access("acme/ops"));
        assert!(!claims.has_context_access("acme/engineering"));

        assert!(claims.require_context("acme/eng/team-a").is_ok());
        assert!(claims.require_context("acme/ops").is_err());
    }

    #[test]
    fn flat_context_grant_is_exact_match_only() {
        // A single-segment grant with no sub-contexts behaves exactly as before.
        let claims = AuthClaims {
            role: Role::Reader,
            allowed_contexts: vec!["prod-mediator".into()],
            ..Default::default()
        };
        assert!(claims.has_context_access("prod-mediator"));
        assert!(!claims.has_context_access("prod-mediator-2"));
        assert!(!claims.has_context_access("other"));
    }

    #[cfg(feature = "cli-synthesis")]
    #[test]
    fn local_cli_synthesizes_super_admin_with_channel_sentinel() {
        let claims = AuthClaims::unsafe_local_cli_super_admin("provision-integration");
        assert_eq!(claims.did, "cli:provision-integration");
        assert_eq!(claims.role, Role::Admin);
        assert!(claims.allowed_contexts.is_empty());
        assert!(claims.is_super_admin());
    }

    #[cfg(feature = "cli-synthesis")]
    #[test]
    fn local_cli_grants_any_context_access() {
        let claims = AuthClaims::unsafe_local_cli_super_admin("keys-bundle");
        // Super-admin has access to every context — enforced elsewhere
        // but assert it explicitly here so a future refactor that
        // breaks the invariant gets caught.
        assert!(claims.has_context_access("any-context"));
        assert!(claims.has_context_access("another"));
        claims
            .require_context("prod-mediator")
            .expect("super-admin passes require_context");
    }

    #[cfg(feature = "cli-synthesis")]
    #[test]
    fn local_cli_did_sentinel_cannot_be_confused_with_real_did() {
        // The `cli:<channel>` format must not round-trip as a
        // `did:*` URI — otherwise audit-log correlation would muddle
        // CLI-synthesized claims with real caller identities.
        let claims = AuthClaims::unsafe_local_cli_super_admin("context-reprovision");
        assert!(!claims.did.starts_with("did:"));
        assert!(claims.did.starts_with("cli:"));
    }

    #[cfg(feature = "cli-synthesis")]
    #[test]
    fn local_cli_channel_embedded_in_did() {
        // Audit-log grep'ability: each synthesis records its `channel`
        // distinctly so forensic investigation can attribute CLI
        // actions to the specific code path that ran them.
        let a = AuthClaims::unsafe_local_cli_super_admin("provision-integration");
        let b = AuthClaims::unsafe_local_cli_super_admin("keys-bundle");
        assert_ne!(a.did, b.did);
    }
}