axond 0.3.7

Axond — a stateless, single-binary, self-hosted AI gateway: one place for provider keys, model routing, usage, and telemetry.
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
//! Mutations: who changed desired state, under what expectation, and the audit
//! event the change carries.
//!
//! A mutation is the unit an administrator submits and the unit an audit trail
//! records. Three properties are typed rather than conventional:
//!
//! - **Every change has an actor.** [`Actor`] has no "unknown" variant, so a
//!   durable mutation without attribution is unconstructible rather than
//!   discovered later in an audit review.
//! - **Every change states what it expected.** [`ExpectedRevision`] is required,
//!   so concurrent administrators get a typed conflict instead of last-write-wins
//!   (#141's "concurrent writers cannot lose updates").
//! - **Every change is safe to retry.** [`IdempotencyKey`] plus the candidate's
//!   checksum makes a retry replay its own outcome, and makes a *reused* key
//!   carrying different state a refusal — see
//!   [`RevisionCandidate`](super::revision::RevisionCandidate).
//!
//! The audit event is part of the mutation rather than a separate call, because
//! it has to commit in the mutation's own transaction: an audit trail that can be
//! half-written is not an audit trail.

use std::time::SystemTime;

use super::canonical::{Canonical, CanonicalValue};
use super::ids::{AuditEventId, MutationId, RevisionId};
use super::resource::{ResourceRef, ResourceScope};

/// Who performed a mutation.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Actor {
    /// An OIDC-authenticated human, identified by issuer-scoped subject: a
    /// subject is only unique within its issuer, so storing it without the
    /// issuer would merge two people from two identity providers.
    Human { issuer: String, subject: String },
    /// The static bootstrap breakglass operator. Distinct from a human on
    /// purpose: "someone used breakglass" is the thing an auditor looks for.
    Breakglass,
    /// The gateway itself — a background catalogue refresh, for example.
    ///
    /// Owned rather than `&'static str` because an audit row read back out of a
    /// durable store has to produce this without leaking.
    System { component: String },
}

impl Canonical for Actor {
    fn canonical(&self) -> CanonicalValue {
        match self {
            Self::Human { issuer, subject } => CanonicalValue::map([
                ("kind", CanonicalValue::string("human")),
                ("issuer", CanonicalValue::string(issuer.clone())),
                ("subject", CanonicalValue::string(subject.clone())),
            ]),
            Self::Breakglass => {
                CanonicalValue::map([("kind", CanonicalValue::string("breakglass"))])
            }
            Self::System { component } => CanonicalValue::map([
                ("kind", CanonicalValue::string("system")),
                ("component", CanonicalValue::string(component.clone())),
            ]),
        }
    }
}

impl std::fmt::Display for Actor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Human { issuer, subject } => write!(f, "human {subject} @ {issuer}"),
            Self::Breakglass => f.write_str("breakglass"),
            Self::System { component } => write!(f, "system {component}"),
        }
    }
}

/// What a mutation did, independent of which resource kinds it touched.
///
/// Generic verbs rather than one variant per resource kind: a new resource kind
/// must not require a new mutation kind, and an audit reader should be able to
/// filter "every deletion" without enumerating kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MutationKind {
    Create,
    Update,
    Delete,
    /// Credential or key rotation: an update, but the one an auditor greps for.
    Rotate,
    /// Republication of an earlier revision's desired state.
    Rollback,
}

impl MutationKind {
    pub const ALL: &'static [Self] = &[
        Self::Create,
        Self::Update,
        Self::Delete,
        Self::Rotate,
        Self::Rollback,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Update => "update",
            Self::Delete => "delete",
            Self::Rotate => "rotate",
            Self::Rollback => "rollback",
        }
    }
}

impl Canonical for MutationKind {
    fn canonical(&self) -> CanonicalValue {
        CanonicalValue::string(self.as_str())
    }
}

/// A caller-supplied deduplication token.
///
/// A retry carrying the same key *and* the same desired state must return the
/// original outcome rather than publishing a second revision; the same key with
/// different desired state is a refusal, never a silent replay of a revision the
/// caller did not describe.
///
/// The token carries no scope of its own, so a durable implementation must dedupe
/// within the *authenticated caller's* scope and expire records rather than
/// retaining them forever: a global, immortal namespace would let one
/// administrator's `retry-1` replay or block another's. Two callers submitting the
/// same string are two independent writes.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IdempotencyKey(String);

/// Why an idempotency key was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum InvalidIdempotencyKey {
    #[error("an idempotency key must not be empty")]
    Empty,
    #[error("idempotency key is {length} characters, over the {max}-character limit")]
    TooLong { length: usize, max: usize },
    #[error("an idempotency key must be printable ASCII")]
    Unprintable,
}

impl IdempotencyKey {
    pub const MAX_LEN: usize = 200;

    /// Validate a caller-supplied key.
    ///
    /// Bounded and printable because it is a durable map key and appears in error
    /// messages and logs: an unbounded or control-character-bearing token is a
    /// storage and log-injection problem, not a client convenience.
    pub fn parse(input: &str) -> Result<Self, InvalidIdempotencyKey> {
        if input.is_empty() {
            return Err(InvalidIdempotencyKey::Empty);
        }
        if input.len() > Self::MAX_LEN {
            return Err(InvalidIdempotencyKey::TooLong {
                length: input.len(),
                max: Self::MAX_LEN,
            });
        }
        if !input
            .bytes()
            .all(|byte| byte.is_ascii_graphic() || byte == b' ')
        {
            return Err(InvalidIdempotencyKey::Unprintable);
        }
        Ok(Self(input.to_owned()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for IdempotencyKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// The revision a writer believes is current.
///
/// Explicit rather than "whatever is current", so two administrators editing
/// concurrently get a typed conflict instead of a silent last-write-wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpectedRevision {
    /// The store has never published a revision.
    Empty,
    /// This exact revision must still be the newest.
    Exactly(RevisionId),
}

impl ExpectedRevision {
    /// Whether `newest` satisfies this expectation.
    ///
    /// One function so every implementation — the oracle, #165's Postgres
    /// `WHERE` clause — agrees on what "expected" means, including the case a
    /// store must never treat as a match: expecting an empty control plane when
    /// one already has revisions.
    pub fn matches(self, newest: Option<RevisionId>) -> bool {
        match (self, newest) {
            (Self::Empty, None) => true,
            (Self::Exactly(expected), Some(actual)) => expected == actual,
            _ => false,
        }
    }
}

impl std::fmt::Display for ExpectedRevision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => f.write_str("an empty control plane"),
            Self::Exactly(revision) => write!(f, "{revision}"),
        }
    }
}

/// One administrative change, whatever number of resources it touched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mutation {
    pub id: MutationId,
    pub actor: Actor,
    pub kind: MutationKind,
    /// The narrowest scope the change applies to, for authorization and audit
    /// filtering.
    pub scope: ResourceScope,
    pub idempotency_key: IdempotencyKey,
    pub submitted_at: SystemTime,
}

impl Canonical for Mutation {
    fn canonical(&self) -> CanonicalValue {
        CanonicalValue::map([
            ("id", CanonicalValue::string(self.id.to_string())),
            ("actor", self.actor.canonical()),
            ("kind", self.kind.canonical()),
            ("scope", self.scope.canonical()),
            (
                "idempotency_key",
                CanonicalValue::string(self.idempotency_key.as_str()),
            ),
        ])
    }
}

/// The audit event a mutation carries.
///
/// It records the mutation's *intent* — actor, verb, target, human summary — and
/// is written in the mutation's own transaction. The desired state itself is not
/// duplicated here: the revision is the state, and this event is why it changed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditEvent {
    pub id: AuditEventId,
    pub mutation: MutationId,
    pub actor: Actor,
    pub kind: MutationKind,
    /// The resource version the change centred on, when there is one. A mutation
    /// that only deletes has no new version to point at.
    pub target: Option<ResourceRef>,
    pub summary: String,
    pub recorded_at: SystemTime,
}

impl Canonical for AuditEvent {
    fn canonical(&self) -> CanonicalValue {
        let mut fields = vec![
            ("id", CanonicalValue::string(self.id.to_string())),
            (
                "mutation",
                CanonicalValue::string(self.mutation.to_string()),
            ),
            ("actor", self.actor.canonical()),
            ("kind", self.kind.canonical()),
            ("summary", CanonicalValue::string(self.summary.clone())),
        ];
        // Absent means absent: there is no null, so an event without a target
        // omits the field rather than carrying a second spelling of "none".
        if let Some(target) = &self.target {
            fields.push(("target", target.canonical()));
        }
        CanonicalValue::map(fields)
    }
}

#[cfg(test)]
mod tests {
    use super::super::ids::{ResourceId, Uuid7};
    use super::super::resource::{ResourceKind, ResourceVersionNumber};
    use super::*;

    fn revision(seed: u64) -> RevisionId {
        RevisionId::new(Uuid7::from_parts(seed, 0, seed).unwrap())
    }

    fn mutation_id(seed: u64) -> MutationId {
        MutationId::new(Uuid7::from_parts(seed, 0, seed).unwrap())
    }

    #[test]
    fn an_expectation_matches_only_the_state_it_describes() {
        let first = revision(1);
        let second = revision(2);

        assert!(ExpectedRevision::Empty.matches(None));
        assert!(!ExpectedRevision::Empty.matches(Some(first)));
        assert!(ExpectedRevision::Exactly(first).matches(Some(first)));
        assert!(!ExpectedRevision::Exactly(first).matches(Some(second)));
        assert!(
            !ExpectedRevision::Exactly(first).matches(None),
            "expecting a revision an empty control plane does not have must not match"
        );
    }

    #[test]
    fn an_expectation_explains_itself() {
        assert_eq!(
            ExpectedRevision::Empty.to_string(),
            "an empty control plane"
        );
        let first = revision(1);
        assert_eq!(
            ExpectedRevision::Exactly(first).to_string(),
            first.to_string()
        );
    }

    #[test]
    fn idempotency_keys_are_bounded_printable_tokens() {
        assert_eq!(
            IdempotencyKey::parse("retry-1").unwrap().as_str(),
            "retry-1"
        );
        assert_eq!(
            IdempotencyKey::parse("retry 1").unwrap().to_string(),
            "retry 1"
        );
        assert_eq!(IdempotencyKey::parse(""), Err(InvalidIdempotencyKey::Empty));
        assert_eq!(
            IdempotencyKey::parse(&"k".repeat(IdempotencyKey::MAX_LEN + 1)),
            Err(InvalidIdempotencyKey::TooLong {
                length: IdempotencyKey::MAX_LEN + 1,
                max: IdempotencyKey::MAX_LEN
            })
        );
        for input in ["retry\n1", "retry\t1", "retry\u{0}"] {
            assert_eq!(
                IdempotencyKey::parse(input),
                Err(InvalidIdempotencyKey::Unprintable)
            );
        }
        // Keys are compared exactly: no trimming, no case folding, because a
        // client's token is the client's.
        assert_ne!(
            IdempotencyKey::parse("retry-1").unwrap(),
            IdempotencyKey::parse("Retry-1").unwrap()
        );
    }

    #[test]
    fn actors_are_distinguishable_and_issuer_scoped() {
        let one = Actor::Human {
            issuer: "https://idp.example".to_owned(),
            subject: "u-1".to_owned(),
        };
        let other = Actor::Human {
            issuer: "https://other.example".to_owned(),
            subject: "u-1".to_owned(),
        };
        assert_ne!(one, other, "a subject is unique only within its issuer");
        assert_ne!(one.checksum().unwrap(), other.checksum().unwrap());
        assert_ne!(
            Actor::Breakglass.checksum().unwrap(),
            Actor::System {
                component: "breakglass".to_owned()
            }
            .checksum()
            .unwrap(),
            "breakglass is not a component that happens to be named breakglass"
        );
        assert_eq!(one.to_string(), "human u-1 @ https://idp.example");
    }

    #[test]
    fn mutation_kinds_have_distinct_canonical_forms() {
        let checksums: std::collections::BTreeSet<_> = MutationKind::ALL
            .iter()
            .map(|kind| kind.checksum().unwrap())
            .collect();
        assert_eq!(checksums.len(), MutationKind::ALL.len());
    }

    #[test]
    fn an_audit_event_omits_an_absent_target_rather_than_nulling_it() {
        let event = AuditEvent {
            id: AuditEventId::new(Uuid7::from_parts(5, 0, 5).unwrap()),
            mutation: mutation_id(4),
            actor: Actor::Breakglass,
            kind: MutationKind::Delete,
            target: None,
            summary: "retired the alias".to_owned(),
            recorded_at: SystemTime::UNIX_EPOCH,
        };
        let targeted = AuditEvent {
            target: Some(ResourceRef::new(
                ResourceKind::Alias,
                ResourceId::new(Uuid7::from_parts(6, 0, 6).unwrap()),
                ResourceVersionNumber::FIRST,
            )),
            ..event.clone()
        };
        assert_ne!(event.checksum().unwrap(), targeted.checksum().unwrap());
        // `recorded_at` is deliberately outside the canonical form: when a row
        // was written is not part of what was decided.
        let later = AuditEvent {
            recorded_at: SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(60),
            ..event.clone()
        };
        assert_eq!(event.checksum().unwrap(), later.checksum().unwrap());
    }

    #[test]
    fn a_mutation_canonicalizes_its_attribution_but_not_its_clock() {
        let mutation = Mutation {
            id: mutation_id(3),
            actor: Actor::System {
                component: "catalog-refresh".to_owned(),
            },
            kind: MutationKind::Update,
            scope: ResourceScope::Deployment,
            idempotency_key: IdempotencyKey::parse("refresh-1").unwrap(),
            submitted_at: SystemTime::UNIX_EPOCH,
        };
        let later = Mutation {
            submitted_at: SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1),
            ..mutation.clone()
        };
        assert_eq!(mutation.checksum().unwrap(), later.checksum().unwrap());

        let other_actor = Mutation {
            actor: Actor::Breakglass,
            ..mutation.clone()
        };
        assert_ne!(
            mutation.checksum().unwrap(),
            other_actor.checksum().unwrap()
        );
    }
}