delegated 0.2.1

Minimal fail-closed capability-token evaluation core
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
//! Fail-closed capability evaluation and operation binding.

use crate::audit::AuditSink;
use crate::contracts::{MAX_IDENTIFIER_BYTES, validate_request};
use crate::crypto::{IssuerKeyResolver, verify_token};
use crate::models::{AuditEvent, Decision, OperationContext, RequestEnvelope, Violation};
use crate::revocation::TrustStateStore;
use chrono::{DateTime, Duration, Utc};
use serde_json::Value;
use std::io;

/// Default maximum accepted serialized request size: 64 KiB.
pub const DEFAULT_MAX_ENVELOPE_BYTES: usize = 64 * 1024;

/// Security limits applied by an [`Evaluator`].
#[derive(Debug, Clone, Copy)]
pub struct EvaluationConfig {
    /// Permitted clock skew for activation and expiry checks; capped at five minutes.
    pub clock_leeway: Duration,
    /// Maximum duration between token issuance and expiry.
    pub max_token_lifetime: Duration,
    /// Maximum serialized request size accepted before JSON parsing.
    pub max_envelope_bytes: usize,
}

impl Default for EvaluationConfig {
    fn default() -> Self {
        Self {
            clock_leeway: Duration::seconds(30),
            max_token_lifetime: Duration::hours(24),
            max_envelope_bytes: DEFAULT_MAX_ENVELOPE_BYTES,
        }
    }
}

/// Evaluates untrusted capability envelopes against trusted host operation facts.
pub struct Evaluator<'a> {
    issuer_keys: &'a dyn IssuerKeyResolver,
    trust_state: &'a dyn TrustStateStore,
    config: EvaluationConfig,
}

impl<'a> Evaluator<'a> {
    /// Creates an evaluator with conservative defaults, explicit issuer keys, and explicit state.
    pub fn new(
        issuer_keys: &'a dyn IssuerKeyResolver,
        trust_state: &'a dyn TrustStateStore,
    ) -> Self {
        Self {
            issuer_keys,
            trust_state,
            config: EvaluationConfig::default(),
        }
    }

    /// Replaces evaluation limits after validating their safe bounds.
    pub fn with_config(mut self, config: EvaluationConfig) -> Result<Self, Violation> {
        if config.clock_leeway < Duration::zero() || config.clock_leeway > Duration::minutes(5) {
            return Err(Violation::new(
                "configuration",
                "clock_leeway must be between zero and five minutes",
            ));
        }
        if config.max_token_lifetime <= Duration::zero() {
            return Err(Violation::new(
                "configuration",
                "max_token_lifetime must be positive",
            ));
        }
        if config.max_envelope_bytes == 0 {
            return Err(Violation::new(
                "configuration",
                "max_envelope_bytes must be positive",
            ));
        }
        self.config = config;
        Ok(self)
    }

    /// Evaluates an untrusted envelope against the operation the host will execute.
    pub fn evaluate(
        &self,
        raw_request: &[u8],
        operation: &OperationContext,
        now: DateTime<Utc>,
    ) -> (Decision, AuditEvent) {
        let result = self.evaluate_inner(raw_request, operation, now);
        match result {
            Ok(envelope) => {
                let decision = Decision::allow("authorized", "capability authorized operation");
                let event = audit_from_envelope(&envelope, operation, now, &decision);
                (decision, event)
            }
            Err(violation) => {
                let decision = Decision::deny(violation.stage, violation.reason.clone());
                let event = audit_from_raw(
                    raw_request,
                    operation,
                    now,
                    &decision,
                    self.config.max_envelope_bytes,
                );
                (decision, event)
            }
        }
    }

    /// Evaluation plus mandatory audit persistence. An audit write error is returned and
    /// callers must not execute the operation.
    pub fn evaluate_and_audit(
        &self,
        raw_request: &[u8],
        operation: &OperationContext,
        now: DateTime<Utc>,
        sink: &dyn AuditSink,
    ) -> io::Result<Decision> {
        let (decision, event) = self.evaluate(raw_request, operation, now);
        sink.write_event(&event)?;
        Ok(decision)
    }

    fn evaluate_inner(
        &self,
        raw_request: &[u8],
        operation: &OperationContext,
        now: DateTime<Utc>,
    ) -> Result<RequestEnvelope, Violation> {
        validate_operation(operation)?;
        if raw_request.len() > self.config.max_envelope_bytes {
            return Err(Violation::new(
                "normalize_request",
                format!(
                    "request exceeds the configured {} byte limit",
                    self.config.max_envelope_bytes
                ),
            ));
        }
        let envelope: RequestEnvelope = serde_json::from_slice(raw_request).map_err(|error| {
            Violation::new(
                "normalize_request",
                format!("request does not match the contract: {error}"),
            )
        })?;
        validate_request(&envelope)?;
        let token = &envelope.delegation_token;

        // Trust is established exclusively through a host-configured issuer key.
        verify_token(token, self.issuer_keys)?;

        if token.issued_at > now + self.config.clock_leeway {
            return Err(Violation::new(
                "validate_lifetime",
                "token is not active yet",
            ));
        }
        if token.expires_at <= now - self.config.clock_leeway {
            return Err(Violation::new("validate_lifetime", "token has expired"));
        }
        if token.expires_at - token.issued_at > self.config.max_token_lifetime {
            return Err(Violation::new(
                "validate_lifetime",
                "token lifetime exceeds the configured maximum",
            ));
        }

        let revoked = self
            .trust_state
            .is_token_revoked(&token.issuer, &token.token_id)
            .map_err(|error| state_error("token revocation lookup", error))?;
        if revoked {
            return Err(Violation::new("revocation", "token is revoked"));
        }
        let denied = self
            .trust_state
            .is_agent_denied(&token.issuer, &token.agent_id)
            .map_err(|error| state_error("agent deny lookup", error))?;
        if denied {
            return Err(Violation::new("revocation", "agent is denied"));
        }

        bind_operation(token, operation)?;

        // Consume only after all other checks pass. Invalid or unauthorized requests cannot
        // burn a valid nonce. The backend operation itself must be atomic.
        let fresh = self
            .trust_state
            .consume_nonce(&token.issuer, &token.nonce, now, token.expires_at)
            .map_err(|error| state_error("nonce consumption", error))?;
        if !fresh {
            return Err(Violation::new(
                "replay",
                "token nonce has already been consumed",
            ));
        }

        Ok(envelope)
    }
}

fn validate_operation(operation: &OperationContext) -> Result<(), Violation> {
    if !valid_operation_value(&operation.audience) || !valid_operation_value(&operation.action) {
        return Err(Violation::new(
            "operation_context",
            format!(
                "host audience and action must be trimmed and contain 1..={MAX_IDENTIFIER_BYTES} bytes"
            ),
        ));
    }
    if operation
        .resource
        .as_ref()
        .is_some_and(|value| !valid_operation_value(value))
    {
        return Err(Violation::new(
            "operation_context",
            format!("host resource must be trimmed and contain 1..={MAX_IDENTIFIER_BYTES} bytes"),
        ));
    }
    Ok(())
}

fn valid_operation_value(value: &str) -> bool {
    !value.is_empty() && value.len() <= MAX_IDENTIFIER_BYTES && value.trim().len() == value.len()
}

fn bind_operation(
    token: &crate::models::DelegationToken,
    operation: &OperationContext,
) -> Result<(), Violation> {
    if !token.audience.contains(&operation.audience) {
        return Err(Violation::new(
            "bind_operation",
            "audience is not authorized",
        ));
    }
    if !token.allowed_actions.contains(&operation.action) {
        return Err(Violation::new("bind_operation", "action is not authorized"));
    }
    if let Some(allowed) = &token.allowed_resources {
        let resource = operation.resource.as_ref().ok_or_else(|| {
            Violation::new(
                "bind_operation",
                "host resource is required by this constrained token",
            )
        })?;
        if !allowed.contains(resource) {
            return Err(Violation::new(
                "bind_operation",
                "resource is not authorized",
            ));
        }
    }
    if let Some(maximum) = token.max_delegation_depth {
        let actual = operation.delegation_depth.ok_or_else(|| {
            Violation::new(
                "bind_operation",
                "host delegation depth is required by this constrained token",
            )
        })?;
        if actual > maximum {
            return Err(Violation::new(
                "bind_operation",
                "delegation depth exceeds the token maximum",
            ));
        }
    }
    Ok(())
}

fn state_error(operation: &str, error: impl std::fmt::Display) -> Violation {
    Violation::new(
        "trust_state",
        format!("{operation} failed; denying request: {error}"),
    )
}

fn audit_from_envelope(
    envelope: &RequestEnvelope,
    operation: &OperationContext,
    now: DateTime<Utc>,
    decision: &Decision,
) -> AuditEvent {
    let token = &envelope.delegation_token;
    AuditEvent {
        occurred_at: now,
        allowed: decision.allowed,
        stage: decision.stage.clone(),
        reason: decision.reason.clone(),
        claims_verified: true,
        request_id: envelope.request_id.clone(),
        token_id: Some(token.token_id.clone()),
        issuer: Some(token.issuer.clone()),
        agent_id: Some(token.agent_id.clone()),
        delegator_id: Some(token.delegator_id.clone()),
        audience: operation.audience.clone(),
        action: operation.action.clone(),
        resource: operation.resource.clone(),
    }
}

fn audit_from_raw(
    raw: &[u8],
    operation: &OperationContext,
    now: DateTime<Utc>,
    decision: &Decision,
    max_envelope_bytes: usize,
) -> AuditEvent {
    let parsed: Option<Value> = (raw.len() <= max_envelope_bytes)
        .then(|| serde_json::from_slice(raw).ok())
        .flatten();
    let token = parsed
        .as_ref()
        .and_then(|value| value.get("delegation_token"));
    AuditEvent {
        occurred_at: now,
        allowed: false,
        stage: decision.stage.clone(),
        reason: decision.reason.clone(),
        claims_verified: false,
        request_id: parsed
            .as_ref()
            .and_then(|value| string_at(value, "request_id")),
        token_id: token.and_then(|value| string_at(value, "token_id")),
        issuer: token.and_then(|value| string_at(value, "issuer")),
        agent_id: token.and_then(|value| string_at(value, "agent_id")),
        delegator_id: token.and_then(|value| string_at(value, "delegator_id")),
        audience: operation.audience.clone(),
        action: operation.action.clone(),
        resource: operation.resource.clone(),
    }
}

fn string_at(value: &Value, key: &str) -> Option<String> {
    value.get(key)?.as_str().map(str::to_owned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, TimeZone, Utc};

    fn now() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0).single().unwrap()
    }

    #[test]
    fn evaluation_config_rejects_unsafe_limits() {
        let keys = crate::crypto::PinnedIssuerKeys::new();
        let state = crate::revocation::InMemoryTrustState::new();

        let too_much_leeway = EvaluationConfig {
            clock_leeway: Duration::minutes(6),
            ..EvaluationConfig::default()
        };
        assert!(
            Evaluator::new(&keys, &state)
                .with_config(too_much_leeway)
                .is_err()
        );

        let zero_lifetime = EvaluationConfig {
            max_token_lifetime: Duration::zero(),
            ..EvaluationConfig::default()
        };
        assert!(
            Evaluator::new(&keys, &state)
                .with_config(zero_lifetime)
                .is_err()
        );

        let zero_bytes = EvaluationConfig {
            max_envelope_bytes: 0,
            ..EvaluationConfig::default()
        };
        assert!(
            Evaluator::new(&keys, &state)
                .with_config(zero_bytes)
                .is_err()
        );
    }

    #[test]
    fn validate_operation_rejects_blank_or_untrimmed_values() {
        assert!(validate_operation(&OperationContext::new("", "calendar.create")).is_err());
        assert!(validate_operation(&OperationContext::new("calendar-api", "")).is_err());
        assert!(
            validate_operation(
                &OperationContext::new("calendar-api", "calendar.create").with_resource(" bad")
            )
            .is_err()
        );
    }

    #[test]
    fn audit_from_raw_marks_claims_unverified_and_preserves_operation() {
        let operation = OperationContext::new("calendar-api", "calendar.create")
            .with_resource("calendar:alice");
        let decision = Decision::deny("normalize_request", "bad request");
        let raw = br#"{"request_id":"req-1","delegation_token":{"token_id":"tok-1","issuer":"issuer.example","agent_id":"agent:bad","delegator_id":"user:bob"}}"#;
        let event = audit_from_raw(raw, &operation, now(), &decision, 1024);
        assert!(!event.allowed);
        assert!(!event.claims_verified);
        assert_eq!(event.request_id.as_deref(), Some("req-1"));
        assert_eq!(event.token_id.as_deref(), Some("tok-1"));
        assert_eq!(event.audience, "calendar-api");
        assert_eq!(event.resource.as_deref(), Some("calendar:alice"));
    }
}