axond 0.3.25

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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! The `/admin/v1` error envelope: one closed vocabulary of machine-readable
//! codes, and nothing on the wire that a caller did not already know.
//!
//! Separate from [`GatewayError`](crate::error::GatewayError) on purpose. That
//! enum is the *inference* contract — its shape is what provider SDKs parse, and
//! its codes are part of the compatibility promise for `/v1` callers. An
//! administrative refusal answers different questions ("is my expected revision
//! current?", "does this deployment own durable state at all?") to a different
//! audience, and folding the two together would mean every new administrative
//! code widened the surface an inference SDK sees.
//!
//! Two properties are structural rather than conventional:
//!
//! **Nothing reaches the wire that was not already the caller's.** The
//! serialized body is built from [`AdminError::code`], a [`Display`] message
//! whose interpolated values are only revisions, resource references, and the
//! caller's own idempotency key, and an optional stable rule name. Backend text
//! — a DSN in a connection error, a driver's message, an identity provider's
//! response — is carried in [`AdminError::operator_detail`], which is never
//! serialized and exists to be logged. So redaction is a property of the type
//! rather than a filter someone has to remember to apply.
//!
//! **Every distinguishable outcome has its own code.** [`AdminError::CODES`] is
//! the whole vocabulary, asserted against the enum by a test, so a client can
//! branch on `stateful_mode_required` versus `revision_conflict` versus
//! `idempotency_key_reused` without parsing prose.
//!
//! [`Display`]: std::fmt::Display

use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;

use super::auth::AdminAuthError;
use crate::backends::control_plane::ControlPlaneError;
use crate::desired_state::{
    CanonicalError, ExpectedRevision, IdempotencyKey, InvalidIdempotencyKey, ResourceRef,
    RevisionId, ValidationError,
};

/// Why an administrative request was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AdminError {
    /// The caller could not be established as an administrative identity. The
    /// cause is a [`AdminAuthError`], deliberately not rendered into the
    /// message: which credential was wrong is not something an unauthenticated
    /// caller is told.
    #[error("administrative authentication failed")]
    Unauthenticated(#[source] AdminAuthError),
    /// The caller is a known administrator, but not for this action or scope.
    #[error("administrative authorization failed")]
    Forbidden(#[source] AdminAuthError),
    /// Human administration is OIDC, so an identity provider outage is an
    /// availability failure of its own — and the reason a stateful deployment is
    /// required to configure a breakglass credential.
    #[error("the identity provider could not be consulted")]
    IdentityProviderUnavailable,
    /// This deployment does not own durable state, so there is nothing for
    /// `/admin/v1` to administer. Returned without consulting any control-plane
    /// backend: a stateless deployment has none to consult.
    #[error("this deployment is stateless; /admin/v1 administers durable state in stateful mode")]
    StatefulModeRequired,
    #[error("an administrative mutation requires an `Idempotency-Key` header")]
    IdempotencyKeyRequired,
    #[error("the `Idempotency-Key` header is not a usable key: {0}")]
    IdempotencyKeyInvalid(#[source] InvalidIdempotencyKey),
    /// The key was already used to publish *different* desired state. Replaying
    /// the earlier revision would report a change that never happened.
    #[error("idempotency key `{key}` already published revision {published} with other state")]
    IdempotencyKeyReused {
        key: IdempotencyKey,
        published: RevisionId,
    },
    #[error("an administrative mutation requires an `X-Axond-Expected-Revision` header")]
    ExpectedRevisionRequired,
    #[error("the `X-Axond-Expected-Revision` header is neither `empty` nor a revision id")]
    ExpectedRevisionInvalid,
    /// Another administrator published first. The caller re-reads and rebuilds;
    /// it does not replay the same candidate.
    #[error("expected {expected} to be current, but the newest is {actual:?}")]
    RevisionConflict {
        expected: ExpectedRevision,
        actual: Option<RevisionId>,
    },
    /// The complete candidate is not valid desired state. `rule` is the stable
    /// name of the invariant that refused it and `reference` the resource it is
    /// about; the domain's own prose stays in `detail`, which is logged rather
    /// than returned, because a validation message interpolates values from the
    /// state being validated.
    #[error("the candidate revision is not valid desired state: {rule}")]
    ValidationFailed {
        rule: &'static str,
        reference: Option<ResourceRef>,
        detail: String,
    },
    #[error("{reference} is already published with different content; publish a new version")]
    ImmutableResourceVersion { reference: ResourceRef },
    #[error("revision {0} is not retained")]
    RevisionNotFound(RevisionId),
    /// Stored state does not add up. An operator alert, never masked as an
    /// outage, and never retried into one.
    #[error("stored control-plane state is unreadable")]
    RevisionUnreadable {
        revision: Option<RevisionId>,
        detail: String,
    },
    /// Intact storage this build declines to interpret. Cleared by a deployment,
    /// not by a retry, and not an integrity alert.
    #[error("stored revision {revision} is not compatible with this build")]
    RevisionIncompatible {
        revision: RevisionId,
        detail: String,
    },
    #[error("stored revision {revision} exceeds what this build reads")]
    RevisionTooLarge {
        revision: RevisionId,
        detail: String,
    },
    /// The control plane is unreachable. Administration is degraded; inference
    /// is not, because no request path consults it.
    #[error("the control plane is unavailable")]
    ControlPlaneUnavailable { detail: String },
    /// The control plane refused this replica's own credential or a policy the
    /// caller cannot influence.
    #[error("the control plane refused the operation")]
    ControlPlaneDenied { detail: String },
    #[error("the audit summary is empty, too long, or not printable")]
    AuditSummaryInvalid,
    #[error("the `X-Axond-Dry-Run` header must be `true` or `false`")]
    DryRunInvalid,
    #[error("a history request may ask for at most {max} revisions")]
    HistoryLimitInvalid { max: u32 },
    /// No such administrative route. Unlike `/v1`, where a `404` would be
    /// indistinguishable from a misconfigured `base_url`, an unknown
    /// `/admin/v1` path is a client error and says so in its own code.
    #[error("no such /admin/v1 route")]
    RouteNotFound,
    #[error("that method is not allowed on this /admin/v1 route")]
    MethodNotAllowed,
}

impl AdminError {
    /// Every code this surface can return, in the order the variants are
    /// declared. A test holds the two in step, so the vocabulary is reviewable
    /// as a list rather than by reading a `match`.
    pub const CODES: &'static [&'static str] = &[
        "admin_unauthenticated",
        "admin_forbidden",
        "identity_provider_unavailable",
        "stateful_mode_required",
        "idempotency_key_required",
        "idempotency_key_invalid",
        "idempotency_key_reused",
        "expected_revision_required",
        "expected_revision_invalid",
        "revision_conflict",
        "validation_failed",
        "immutable_resource_version",
        "revision_not_found",
        "revision_unreadable",
        "revision_incompatible",
        "revision_too_large",
        "control_plane_unavailable",
        "control_plane_denied",
        "audit_summary_invalid",
        "dry_run_invalid",
        "history_limit_invalid",
        "admin_route_not_found",
        "admin_method_not_allowed",
    ];

    pub const fn code(&self) -> &'static str {
        match self {
            Self::Unauthenticated(_) => "admin_unauthenticated",
            Self::Forbidden(_) => "admin_forbidden",
            Self::IdentityProviderUnavailable => "identity_provider_unavailable",
            Self::StatefulModeRequired => "stateful_mode_required",
            Self::IdempotencyKeyRequired => "idempotency_key_required",
            Self::IdempotencyKeyInvalid(_) => "idempotency_key_invalid",
            Self::IdempotencyKeyReused { .. } => "idempotency_key_reused",
            Self::ExpectedRevisionRequired => "expected_revision_required",
            Self::ExpectedRevisionInvalid => "expected_revision_invalid",
            Self::RevisionConflict { .. } => "revision_conflict",
            Self::ValidationFailed { .. } => "validation_failed",
            Self::ImmutableResourceVersion { .. } => "immutable_resource_version",
            Self::RevisionNotFound(_) => "revision_not_found",
            Self::RevisionUnreadable { .. } => "revision_unreadable",
            Self::RevisionIncompatible { .. } => "revision_incompatible",
            Self::RevisionTooLarge { .. } => "revision_too_large",
            Self::ControlPlaneUnavailable { .. } => "control_plane_unavailable",
            Self::ControlPlaneDenied { .. } => "control_plane_denied",
            Self::AuditSummaryInvalid => "audit_summary_invalid",
            Self::DryRunInvalid => "dry_run_invalid",
            Self::HistoryLimitInvalid { .. } => "history_limit_invalid",
            Self::RouteNotFound => "admin_route_not_found",
            Self::MethodNotAllowed => "admin_method_not_allowed",
        }
    }

    pub const fn status(&self) -> StatusCode {
        match self {
            Self::Unauthenticated(_) => StatusCode::UNAUTHORIZED,
            Self::Forbidden(_) => StatusCode::FORBIDDEN,
            // A precondition the caller *omitted* is not a malformed one: `428`
            // says "state what you expected", which is the fix, where `400`
            // would read as "your header was wrong".
            Self::ExpectedRevisionRequired => StatusCode::PRECONDITION_REQUIRED,
            Self::IdempotencyKeyRequired
            | Self::IdempotencyKeyInvalid(_)
            | Self::ExpectedRevisionInvalid
            | Self::ValidationFailed { .. }
            | Self::AuditSummaryInvalid
            | Self::DryRunInvalid
            | Self::HistoryLimitInvalid { .. } => StatusCode::BAD_REQUEST,
            Self::RevisionConflict { .. }
            | Self::IdempotencyKeyReused { .. }
            | Self::ImmutableResourceVersion { .. } => StatusCode::CONFLICT,
            Self::RevisionNotFound(_) | Self::RouteNotFound => StatusCode::NOT_FOUND,
            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
            // Stateless mode is not a failure and not a misconfiguration: the
            // surface is unimplemented *for this deployment*, which is what
            // `501` means.
            Self::StatefulModeRequired => StatusCode::NOT_IMPLEMENTED,
            Self::ControlPlaneUnavailable { .. } | Self::IdentityProviderUnavailable => {
                StatusCode::SERVICE_UNAVAILABLE
            }
            // Unreadable, incompatible, oversized, and refused storage are all
            // "this replica cannot serve the request, and retrying will not
            // change that": an operator acts, the caller does not.
            Self::RevisionUnreadable { .. }
            | Self::RevisionIncompatible { .. }
            | Self::RevisionTooLarge { .. }
            | Self::ControlPlaneDenied { .. } => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    /// Whether repeating the identical request could succeed without the caller
    /// changing anything.
    ///
    /// Only the two outages qualify. A conflict is explicitly *not* retryable:
    /// the caller must re-read the head and rebuild, and a client that retried
    /// the same candidate would be racing rather than converging.
    pub const fn retryable(&self) -> bool {
        matches!(
            self,
            Self::ControlPlaneUnavailable { .. } | Self::IdentityProviderUnavailable
        )
    }

    /// The operator-facing cause, for a log line. Never serialized: this is
    /// where a backend's own text — which may name a host, a DSN, or a driver
    /// internal — is kept out of a response.
    pub fn operator_detail(&self) -> Option<&str> {
        match self {
            Self::ValidationFailed { detail, .. }
            | Self::RevisionUnreadable { detail, .. }
            | Self::RevisionIncompatible { detail, .. }
            | Self::RevisionTooLarge { detail, .. }
            | Self::ControlPlaneUnavailable { detail }
            | Self::ControlPlaneDenied { detail } => Some(detail),
            _ => None,
        }
    }

    /// The stable name of the invariant a candidate broke, if this is a
    /// validation refusal.
    pub const fn rule(&self) -> Option<&'static str> {
        match self {
            Self::ValidationFailed { rule, .. } => Some(rule),
            _ => None,
        }
    }

    /// The revision this refusal is about, if it is about one.
    pub const fn revision(&self) -> Option<RevisionId> {
        match self {
            Self::RevisionNotFound(revision)
            | Self::RevisionIncompatible { revision, .. }
            | Self::RevisionTooLarge { revision, .. } => Some(*revision),
            Self::IdempotencyKeyReused { published, .. } => Some(*published),
            Self::RevisionUnreadable { revision, .. } => *revision,
            // A conflict names the head the caller has to re-read, in the
            // structured field rather than only in the prose.
            Self::RevisionConflict { actual, .. } => *actual,
            _ => None,
        }
    }

    /// The resource this refusal names, if it names one.
    pub const fn reference(&self) -> Option<ResourceRef> {
        match self {
            Self::ImmutableResourceVersion { reference } => Some(*reference),
            Self::ValidationFailed { reference, .. } => *reference,
            _ => None,
        }
    }

    /// The body a caller receives.
    pub fn envelope(&self) -> AdminErrorEnvelope {
        AdminErrorEnvelope {
            error: AdminErrorBody {
                code: self.code(),
                message: self.to_string(),
                retryable: self.retryable(),
                rule: self.rule(),
                resource: self.reference().map(|reference| reference.to_string()),
                revision: self.revision().map(|revision| revision.to_string()),
            },
        }
    }

    /// Translate a store failure into the administrative vocabulary.
    ///
    /// Exhaustive on purpose: a new [`ControlPlaneError`] variant must be given a
    /// code here rather than collapsing into a generic `500`, which is how
    /// "unreadable storage" and "unreachable storage" stop being
    /// distinguishable.
    pub fn from_control_plane(error: ControlPlaneError) -> Self {
        match error {
            ControlPlaneError::Unavailable { backend, message } => Self::ControlPlaneUnavailable {
                detail: format!("{backend}: {message}"),
            },
            ControlPlaneError::Conflict { expected, actual } => {
                Self::RevisionConflict { expected, actual }
            }
            ControlPlaneError::RevisionNotFound(revision) => Self::RevisionNotFound(revision),
            ControlPlaneError::Invalid(error) => Self::from(error),
            ControlPlaneError::ImmutableResourceVersion { reference } => {
                Self::ImmutableResourceVersion { reference }
            }
            ControlPlaneError::IdempotencyKeyReused { key, published } => {
                Self::IdempotencyKeyReused { key, published }
            }
            ControlPlaneError::Denied { backend, message } => Self::ControlPlaneDenied {
                detail: format!("{backend}: {message}"),
            },
            ControlPlaneError::Corrupt { revision, source } => Self::RevisionUnreadable {
                revision: Some(revision),
                detail: source.to_string(),
            },
            ControlPlaneError::CorruptStorage { detail } => Self::RevisionUnreadable {
                revision: None,
                detail,
            },
            ControlPlaneError::Incompatible { revision, source } => Self::RevisionIncompatible {
                revision,
                detail: source.to_string(),
            },
            ControlPlaneError::TooLarge { revision, limit } => Self::RevisionTooLarge {
                revision,
                detail: limit.to_string(),
            },
        }
    }
}

/// The stable rule name and the resource a validation failure is about.
///
/// A separate function rather than a method on [`ValidationError`] because the
/// naming is an *administrative protocol* commitment: the domain is free to
/// reword its messages, and these strings are not allowed to move with them.
fn validation_rule(error: &ValidationError) -> (&'static str, Option<ResourceRef>) {
    match error {
        ValidationError::Empty => ("empty_revision", None),
        ValidationError::DuplicateResourceVersion { reference } => {
            ("duplicate_resource_version", Some(*reference))
        }
        ValidationError::MultipleVersions { first, .. } => ("multiple_versions", Some(*first)),
        ValidationError::DuplicateSlug { first, .. } => ("duplicate_slug", Some(*first)),
        ValidationError::ScopeMismatch { reference, .. } => ("scope_mismatch", Some(*reference)),
        ValidationError::DanglingResourceReference { from, .. } => {
            ("dangling_resource_reference", Some(*from))
        }
        ValidationError::DanglingBlobReference { from, .. } => {
            ("dangling_blob_reference", Some(*from))
        }
        ValidationError::UnreferencedBlob { .. } => ("unreferenced_blob", None),
        ValidationError::CrossTenantReference { from, .. } => {
            ("cross_tenant_reference", Some(*from))
        }
        ValidationError::TenantScopedDependency { from, .. } => {
            ("tenant_scoped_dependency", Some(*from))
        }
        ValidationError::Tenancy(_) => ("tenancy", None),
        // #243's credential records validate by their own rules; the resource is
        // named by the inner error's message, and the material never is.
        ValidationError::Credential(_) => ("provider_credential", None),
        // #253's policy records validate by their own rules, and name the
        // resource they are about without quoting its body.
        ValidationError::Policy(policy) => ("policy", Some(policy.reference())),
        ValidationError::AuditMutationMismatch { .. } => ("audit_mutation_mismatch", None),
        ValidationError::Canonical(_) => ("not_canonical", None),
    }
}

impl From<ValidationError> for AdminError {
    fn from(error: ValidationError) -> Self {
        let (rule, reference) = validation_rule(&error);
        Self::ValidationFailed {
            rule,
            reference,
            detail: error.to_string(),
        }
    }
}

impl From<CanonicalError> for AdminError {
    /// State with no canonical form is invalid state, and the domain already says
    /// so: routing through [`ValidationError`] keeps one rule name for it rather
    /// than a second code that means the same thing.
    fn from(error: CanonicalError) -> Self {
        Self::from(ValidationError::from(error))
    }
}

impl From<ControlPlaneError> for AdminError {
    fn from(error: ControlPlaneError) -> Self {
        Self::from_control_plane(error)
    }
}

impl From<AdminAuthError> for AdminError {
    /// The authentication/authorization split is the error's own to make: only
    /// it knows whether the caller failed to establish an identity or failed to
    /// carry authority, and a `403` for the former would tell an anonymous
    /// caller that its credential was recognized.
    fn from(error: AdminAuthError) -> Self {
        if error.is_unavailable() {
            Self::IdentityProviderUnavailable
        } else if error.is_authorization() {
            Self::Forbidden(error)
        } else {
            Self::Unauthenticated(error)
        }
    }
}

/// The wire body of an administrative refusal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AdminErrorEnvelope {
    pub error: AdminErrorBody,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AdminErrorBody {
    /// The stable machine-readable code. Named `type` on the wire to match the
    /// inference envelope's shape, so one client-side error reader handles both.
    #[serde(rename = "type")]
    pub code: &'static str,
    pub message: String,
    /// Whether an identical retry could succeed. Explicit so a client does not
    /// infer it from the status code and retry a conflict.
    pub retryable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

impl IntoResponse for AdminError {
    fn into_response(self) -> Response {
        (self.status(), Json(self.envelope())).into_response()
    }
}