crtx-store 0.1.0

SQLite persistence: migrations, repositories, transactions.
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Temporal authority timeline repository.

use chrono::{DateTime, Utc};
use cortex_core::{
    revalidate_temporal_authority, KeyLifecycleState, PolicyContribution, PolicyDecision,
    PolicyOutcome, TemporalAuthorityEvidence, TemporalAuthorityReport, TrustTier,
};
use rusqlite::{params, OptionalExtension, Row};

use crate::{Pool, StoreError, StoreResult};

/// Required contributor rule id documenting that an operator attested the
/// proposed key state transition (ADR 0019 §3, ADR 0026 §4).
pub const KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID: &str = "authority.key_state.attested_by_operator";
/// Required contributor rule id documenting that the trust tier gate composed
/// into the decision for this key state mutation (ADR 0019, ADR 0026 §4).
pub const KEY_STATE_TRUST_TIER_GATE_RULE_ID: &str = "authority.key_state.trust_tier_gate";
/// Required contributor rule id documenting that an operator attested the
/// principal trust tier promotion or downgrade (ADR 0019 §3, ADR 0026 §4).
pub const PRINCIPAL_STATE_ATTESTED_BY_OPERATOR_RULE_ID: &str =
    "authority.principal_state.attested_by_operator";
/// Required contributor rule id documenting that the trust tier gate composed
/// into the decision for this principal trust mutation (ADR 0019, ADR 0026 §4).
pub const PRINCIPAL_STATE_TRUST_TIER_GATE_RULE_ID: &str =
    "authority.principal_state.trust_tier_gate";
/// Required contributor rule id documenting that the proposed principal tier
/// is supported by a fresh tier promotion attestation (ADR 0019 §1, ADR 0026
/// §4). `BreakGlass` MUST NOT substitute for this contributor.
pub const PRINCIPAL_STATE_TIER_PROMOTION_ATTESTATION_RULE_ID: &str =
    "authority.principal_state.tier_promotion_attestation";

/// Key lifecycle timeline row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyTimelineRecord {
    /// Key identifier.
    pub key_id: String,
    /// Principal bound to this key at the effective time.
    pub principal_id: String,
    /// Key lifecycle state.
    pub state: KeyLifecycleState,
    /// Effective time for this state.
    pub effective_at: DateTime<Utc>,
    /// Optional reason such as compromise/offboarding.
    pub reason: Option<String>,
    /// Optional audit row reference.
    pub audit_ref: Option<String>,
}

/// Principal trust timeline row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrincipalTimelineRecord {
    /// Principal identifier.
    pub principal_id: String,
    /// Trust tier effective from this row.
    pub trust_tier: TrustTier,
    /// Effective time for this state.
    pub effective_at: DateTime<Utc>,
    /// Optional trust review deadline.
    pub trust_review_due_at: Option<DateTime<Utc>>,
    /// Optional principal removal time.
    pub removed_at: Option<DateTime<Utc>>,
    /// Optional audit row reference.
    pub audit_ref: Option<String>,
}

/// Query for temporal authority revalidation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemporalAuthorityQuery {
    /// Key identifier carried by the attestation.
    pub key_id: String,
    /// Signed event/audit time.
    pub event_time: DateTime<Utc>,
    /// Verification time.
    pub now: DateTime<Utc>,
    /// Minimum trust tier required for current use.
    pub minimum_trust_tier: TrustTier,
}

/// Repository for authority timelines.
#[derive(Debug)]
pub struct AuthorityRepo<'a> {
    pool: &'a Pool,
}

impl<'a> AuthorityRepo<'a> {
    /// Creates an authority repository over an open SQLite connection.
    #[must_use]
    pub const fn new(pool: &'a Pool) -> Self {
        Self { pool }
    }

    /// Append a key lifecycle timeline row through the ADR 0026 enforcement
    /// lattice.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this key-state mutation
    /// and MUST satisfy:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing.
    /// 2. The composition includes contributors for both
    ///    [`KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID`] and
    ///    [`KEY_STATE_TRUST_TIER_GATE_RULE_ID`]. The repo refuses callers that
    ///    skipped composition.
    /// 3. Per ADR 0026 §4, the operator attestation contributor MUST be
    ///    [`PolicyOutcome::Allow`] even when the final decision is
    ///    `BreakGlass`. Break-glass never substitutes for operator attestation
    ///    at the key-state authority root.
    /// 4. The proposed [`KeyTimelineRecord::state`] is consistent with the
    ///    principal's current trust tier visible in the timeline. Activating a
    ///    new key for a principal that is below
    ///    [`TrustTier::Verified`] is refused.
    pub fn append_key_state(
        &self,
        record: &KeyTimelineRecord,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_policy_final_outcome(policy, "authority.key_state")?;
        require_contributor_rule(policy, KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID)?;
        require_contributor_rule(policy, KEY_STATE_TRUST_TIER_GATE_RULE_ID)?;
        require_attestation_not_break_glassed(
            policy,
            KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID,
            "authority.key_state",
        )?;

        if matches!(record.state, KeyLifecycleState::Active) {
            self.reject_active_key_for_undertrust_principal(record)?;
        }

        self.pool.execute(
            "INSERT INTO authority_key_timeline (
                key_id, principal_id, state, effective_at, reason, audit_ref
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6);",
            params![
                record.key_id,
                record.principal_id,
                key_state_wire(record.state),
                record.effective_at.to_rfc3339(),
                record.reason,
                record.audit_ref,
            ],
        )?;
        Ok(())
    }

    /// Append a principal trust timeline row through the ADR 0026 enforcement
    /// lattice.
    ///
    /// Same envelope as [`Self::append_key_state`] plus the
    /// [`PRINCIPAL_STATE_TIER_PROMOTION_ATTESTATION_RULE_ID`] contributor.
    /// ADR 0026 §4 is a hard wall: `BreakGlass` MUST NOT substitute for the
    /// tier promotion attestation. The repo enforces that the attestation
    /// contributor is `Allow` even when the final decision is `BreakGlass`.
    pub fn append_principal_state(
        &self,
        record: &PrincipalTimelineRecord,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_policy_final_outcome(policy, "authority.principal_state")?;
        require_contributor_rule(policy, PRINCIPAL_STATE_ATTESTED_BY_OPERATOR_RULE_ID)?;
        require_contributor_rule(policy, PRINCIPAL_STATE_TRUST_TIER_GATE_RULE_ID)?;
        require_contributor_rule(policy, PRINCIPAL_STATE_TIER_PROMOTION_ATTESTATION_RULE_ID)?;
        require_attestation_not_break_glassed(
            policy,
            PRINCIPAL_STATE_ATTESTED_BY_OPERATOR_RULE_ID,
            "authority.principal_state",
        )?;
        require_attestation_not_break_glassed(
            policy,
            PRINCIPAL_STATE_TIER_PROMOTION_ATTESTATION_RULE_ID,
            "authority.principal_state",
        )?;

        self.pool.execute(
            "INSERT INTO authority_principal_timeline (
                principal_id, trust_tier, effective_at, trust_review_due_at, removed_at, audit_ref
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6);",
            params![
                record.principal_id,
                trust_tier_wire(record.trust_tier),
                record.effective_at.to_rfc3339(),
                record.trust_review_due_at.map(|value| value.to_rfc3339()),
                record.removed_at.map(|value| value.to_rfc3339()),
                record.audit_ref,
            ],
        )?;
        Ok(())
    }

    fn reject_active_key_for_undertrust_principal(
        &self,
        record: &KeyTimelineRecord,
    ) -> StoreResult<()> {
        let current_trust = self.principal_state_at(&record.principal_id, record.effective_at)?;
        match current_trust {
            Some(state) if state.trust_tier < TrustTier::Verified => {
                Err(StoreError::Validation(format!(
                    "authority.key_state preflight: refuse to activate key `{}` for principal `{}` while current trust tier `{:?}` is below `Verified`",
                    record.key_id, record.principal_id, state.trust_tier,
                )))
            }
            // Unknown principal: caller must register the trust state first.
            None => Err(StoreError::Validation(format!(
                "authority.key_state preflight: refuse to activate key `{}` for principal `{}` without a current trust tier row",
                record.key_id, record.principal_id,
            ))),
            Some(_) => Ok(()),
        }
    }

    /// Revalidate a key's authority at event time and for current use.
    pub fn revalidate(
        &self,
        query: &TemporalAuthorityQuery,
    ) -> StoreResult<TemporalAuthorityReport> {
        let key_at_event = self.key_state_at(&query.key_id, query.event_time)?;
        let current_key_state = self.key_state_at(&query.key_id, query.now)?;
        let key_activated_at = self.key_state_effective_at(
            &query.key_id,
            KeyLifecycleState::Active,
            query.event_time,
        )?;
        let key_retired_at =
            self.key_state_effective_at(&query.key_id, KeyLifecycleState::Retired, query.now)?;
        let key_revoked_at =
            self.key_state_effective_at(&query.key_id, KeyLifecycleState::Revoked, query.now)?;
        let principal_id = key_at_event
            .as_ref()
            .or(current_key_state.as_ref())
            .map(|record| record.principal_id.clone());
        let trust_at_event = match principal_id.as_deref() {
            Some(principal_id) => self.principal_state_at(principal_id, query.event_time)?,
            None => None,
        };
        let current_trust = match principal_id.as_deref() {
            Some(principal_id) => self.principal_state_at(principal_id, query.now)?,
            None => None,
        };

        Ok(revalidate_temporal_authority(TemporalAuthorityEvidence {
            key_id: query.key_id.clone(),
            principal_id,
            event_time: query.event_time,
            now: query.now,
            key_activated_at,
            key_retired_at,
            key_revoked_at,
            trust_tier_at_event_time: trust_at_event.as_ref().map(|record| record.trust_tier),
            current_trust_tier: current_trust.as_ref().map(|record| record.trust_tier),
            current_trust_tier_effective_at: current_trust
                .as_ref()
                .map(|record| record.effective_at),
            minimum_trust_tier: query.minimum_trust_tier,
            principal_removed_at: current_trust.as_ref().and_then(|record| record.removed_at),
            trust_review_due_at: current_trust
                .as_ref()
                .and_then(|record| record.trust_review_due_at),
        }))
    }

    fn key_state_at(
        &self,
        key_id: &str,
        at: DateTime<Utc>,
    ) -> StoreResult<Option<KeyTimelineRecord>> {
        let row = self
            .pool
            .query_row(
                "SELECT key_id, principal_id, state, effective_at, reason, audit_ref
                 FROM authority_key_timeline
                 WHERE key_id = ?1 AND effective_at <= ?2
                 ORDER BY effective_at DESC, state DESC
                 LIMIT 1;",
                params![key_id, at.to_rfc3339()],
                key_timeline_row,
            )
            .optional()?;

        row.map(TryInto::try_into).transpose()
    }

    fn key_state_effective_at(
        &self,
        key_id: &str,
        state: KeyLifecycleState,
        at: DateTime<Utc>,
    ) -> StoreResult<Option<DateTime<Utc>>> {
        let value = self
            .pool
            .query_row(
                "SELECT effective_at
                 FROM authority_key_timeline
                 WHERE key_id = ?1 AND state = ?2 AND effective_at <= ?3
                 ORDER BY effective_at DESC
                 LIMIT 1;",
                params![key_id, key_state_wire(state), at.to_rfc3339()],
                |row| row.get::<_, String>(0),
            )
            .optional()?;

        value.as_deref().map(parse_utc).transpose()
    }

    fn principal_state_at(
        &self,
        principal_id: &str,
        at: DateTime<Utc>,
    ) -> StoreResult<Option<PrincipalTimelineRecord>> {
        let row = self
            .pool
            .query_row(
                "SELECT principal_id, trust_tier, effective_at, trust_review_due_at, removed_at, audit_ref
                 FROM authority_principal_timeline
                 WHERE principal_id = ?1 AND effective_at <= ?2
                 ORDER BY effective_at DESC
                 LIMIT 1;",
                params![principal_id, at.to_rfc3339()],
                principal_timeline_row,
            )
            .optional()?;

        row.map(TryInto::try_into).transpose()
    }
}

#[derive(Debug)]
struct KeyTimelineRow {
    key_id: String,
    principal_id: String,
    state: String,
    effective_at: String,
    reason: Option<String>,
    audit_ref: Option<String>,
}

fn key_timeline_row(row: &Row<'_>) -> rusqlite::Result<KeyTimelineRow> {
    Ok(KeyTimelineRow {
        key_id: row.get(0)?,
        principal_id: row.get(1)?,
        state: row.get(2)?,
        effective_at: row.get(3)?,
        reason: row.get(4)?,
        audit_ref: row.get(5)?,
    })
}

impl TryFrom<KeyTimelineRow> for KeyTimelineRecord {
    type Error = StoreError;

    fn try_from(row: KeyTimelineRow) -> StoreResult<Self> {
        Ok(Self {
            key_id: row.key_id,
            principal_id: row.principal_id,
            state: parse_key_state(&row.state)?,
            effective_at: parse_utc(&row.effective_at)?,
            reason: row.reason,
            audit_ref: row.audit_ref,
        })
    }
}

#[derive(Debug)]
struct PrincipalTimelineRow {
    principal_id: String,
    trust_tier: String,
    effective_at: String,
    trust_review_due_at: Option<String>,
    removed_at: Option<String>,
    audit_ref: Option<String>,
}

fn principal_timeline_row(row: &Row<'_>) -> rusqlite::Result<PrincipalTimelineRow> {
    Ok(PrincipalTimelineRow {
        principal_id: row.get(0)?,
        trust_tier: row.get(1)?,
        effective_at: row.get(2)?,
        trust_review_due_at: row.get(3)?,
        removed_at: row.get(4)?,
        audit_ref: row.get(5)?,
    })
}

impl TryFrom<PrincipalTimelineRow> for PrincipalTimelineRecord {
    type Error = StoreError;

    fn try_from(row: PrincipalTimelineRow) -> StoreResult<Self> {
        Ok(Self {
            principal_id: row.principal_id,
            trust_tier: parse_trust_tier(&row.trust_tier)?,
            effective_at: parse_utc(&row.effective_at)?,
            trust_review_due_at: row
                .trust_review_due_at
                .as_deref()
                .map(parse_utc)
                .transpose()?,
            removed_at: row.removed_at.as_deref().map(parse_utc).transpose()?,
            audit_ref: row.audit_ref,
        })
    }
}

fn require_policy_final_outcome(policy: &PolicyDecision, surface: &str) -> StoreResult<()> {
    match policy.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        PolicyOutcome::Quarantine | PolicyOutcome::Reject => Err(StoreError::Validation(format!(
            "{surface} preflight: composed policy outcome {:?} blocks authority-root mutation",
            policy.final_outcome,
        ))),
    }
}

fn require_contributor_rule(policy: &PolicyDecision, rule_id: &str) -> StoreResult<()> {
    let contains_rule = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .any(|contribution| contribution.rule_id.as_str() == rule_id);
    if contains_rule {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "policy decision missing required contributor `{rule_id}`; caller skipped ADR 0026 composition",
        )))
    }
}

fn require_attestation_not_break_glassed(
    policy: &PolicyDecision,
    rule_id: &str,
    surface: &str,
) -> StoreResult<()> {
    // ADR 0026 §4: BreakGlass MUST NOT substitute for required attestation at
    // an authority root. The attestation contributor must itself have voted
    // `Allow` regardless of how the rest of the composition resolved.
    let attestation = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| contribution.rule_id.as_str() == rule_id)
        .ok_or_else(|| {
            StoreError::Validation(format!(
                "{surface} preflight: required attestation contributor `{rule_id}` is absent from the policy decision",
            ))
        })?;
    if attestation.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "{surface} preflight: attestation contributor `{rule_id}` returned {:?}; ADR 0026 §4 forbids BreakGlass substituting for attestation",
            attestation.outcome,
        )))
    }
}

/// Build a `PolicyDecision` that satisfies [`AuthorityRepo::append_key_state`]
/// inputs for the happy path. Intended for tests and fixtures only.
///
/// Production callers MUST compose
/// [`KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID`] and
/// [`KEY_STATE_TRUST_TIER_GATE_RULE_ID`] from real attestation evidence and
/// real trust-tier state. This helper is exposed unconditionally because
/// integration test crates outside `cortex-store` need the same fixture
/// shape; the `_test_allow` suffix is the contract that documents intent.
#[must_use]
pub fn key_state_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                KEY_STATE_ATTESTED_BY_OPERATOR_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator attestation present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                KEY_STATE_TRUST_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: trust tier gate satisfied",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a `PolicyDecision` that satisfies
/// [`AuthorityRepo::append_principal_state`] inputs for the happy path.
/// Intended for tests and fixtures only; see
/// [`key_state_policy_decision_test_allow`] for the production-caller
/// contract.
#[must_use]
pub fn principal_state_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                PRINCIPAL_STATE_ATTESTED_BY_OPERATOR_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator attestation present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                PRINCIPAL_STATE_TRUST_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: trust tier gate satisfied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                PRINCIPAL_STATE_TIER_PROMOTION_ATTESTATION_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: tier promotion attestation present",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

fn parse_utc(value: &str) -> StoreResult<DateTime<Utc>> {
    Ok(DateTime::parse_from_rfc3339(value)?.with_timezone(&Utc))
}

fn key_state_wire(state: KeyLifecycleState) -> &'static str {
    match state {
        KeyLifecycleState::Active => "active",
        KeyLifecycleState::Retired => "retired",
        KeyLifecycleState::Revoked => "revoked",
    }
}

fn parse_key_state(value: &str) -> StoreResult<KeyLifecycleState> {
    match value {
        "active" => Ok(KeyLifecycleState::Active),
        "retired" => Ok(KeyLifecycleState::Retired),
        "revoked" => Ok(KeyLifecycleState::Revoked),
        other => Err(StoreError::Validation(format!(
            "unknown key lifecycle state `{other}`"
        ))),
    }
}

fn trust_tier_wire(tier: TrustTier) -> &'static str {
    match tier {
        TrustTier::Untrusted => "untrusted",
        TrustTier::Observed => "observed",
        TrustTier::Verified => "verified",
        TrustTier::Operator => "operator",
    }
}

fn parse_trust_tier(value: &str) -> StoreResult<TrustTier> {
    match value {
        "untrusted" => Ok(TrustTier::Untrusted),
        "observed" => Ok(TrustTier::Observed),
        "verified" => Ok(TrustTier::Verified),
        "operator" => Ok(TrustTier::Operator),
        other => Err(StoreError::Validation(format!(
            "unknown trust tier `{other}`"
        ))),
    }
}