engenho-control-types 0.53.130

engenho-control-types — the central types of engenho's non-Kubernetes control plane, DERIVED at build time from spec/engenho-control.openapi.yaml: the schema types, the closed OperationId + CATALOG (authority tier, confirm gate, CLI spelling per operation), per-operation typed requests, and the transport-agnostic EngenhoControl trait every transport serves.
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! engenho-control-types — the central types of engenho's control plane.
//!
//! Everything a transport, the CLI, or the MCP server needs to speak the
//! control API is DERIVED at build time from the one authored spec,
//! `spec/engenho-control.openapi.yaml` (see `build.rs` and
//! `docs/CONTROL-PLANE.md`):
//!
//! * [`types`] — every `components.schemas` entry (typify).
//! * [`OperationId`] + [`CATALOG`] — every operation with its method, path,
//!   authority tier, confirm gate and CLI spelling, from the spec's
//!   `x-engenho-*` extensions.
//! * [`ops`] — one marker type and one typed `…Request` per operation, each
//!   [`Operation`] binding marker → request → response, and the
//!   [`EngenhoControl`] trait with one method per operation.
//!
//! Hand-written here: only the glue that is not a schema — the principal,
//! the error type, the HTTP rendering helpers, and the catalog row types.

#![forbid(unsafe_code)]

use std::future::Future;
use std::pin::Pin;

use serde::Serialize;
use serde::de::DeserializeOwned;

/// Every `components.schemas` type of the spec, generated by typify.
#[allow(
    clippy::all,
    clippy::pedantic,
    missing_docs,
    unused_imports,
    irrefutable_let_patterns
)]
pub mod types {
    include!(concat!(env!("OUT_DIR"), "/types.rs"));
}

#[allow(clippy::all, clippy::pedantic)]
mod catalog {
    use crate::{
        CliSpelling, ConfirmGate, HttpMethod, MediaType, OperationSpec, ParamLocation, ParamSpec,
    };
    include!(concat!(env!("OUT_DIR"), "/catalog.rs"));
}
pub use catalog::{CATALOG, OperationId};

/// One marker type and one typed request per operation, plus
/// [`EngenhoControl`] and the [`ops::visit`] dispatch.
#[allow(clippy::all, clippy::pedantic)]
pub mod ops {
    include!(concat!(env!("OUT_DIR"), "/ops.rs"));
}
pub use ops::{EngenhoControl, OperationVisitor, visit};

pub use types::{AuthorityTier, ReinitOp};

/// SPKI pins and the rustls verifiers of the remote control plane (feature
/// `tls`).
#[cfg(feature = "tls")]
pub mod pin;

/// The spec, byte for byte as authored — served by `GET /v1/spec`.
pub const SPEC_YAML: &str = include_str!("../../spec/engenho-control.openapi.yaml");

/// The API version string every `hello` answers with.
pub const API_VERSION: &str = "engenho.control/v1";

/// A boxed, `Send` future — what [`Operation::invoke`] returns so a router
/// can dispatch any operation through one generic path.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

// ── the catalog row ─────────────────────────────────────────────────────────

/// The HTTP method of an operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HttpMethod {
    /// `GET` — exactly the observe-tier operations.
    Get,
    /// `PUT`.
    Put,
    /// `POST`.
    Post,
    /// `DELETE`.
    Delete,
    /// `PATCH`.
    Patch,
}

impl HttpMethod {
    /// The method's wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Put => "PUT",
            Self::Post => "POST",
            Self::Delete => "DELETE",
            Self::Patch => "PATCH",
        }
    }
}

/// How an operation relates to the destructive-confirmation handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConfirmGate {
    /// Not confirm-gated.
    None,
    /// Executes this re-initialization; the request must carry the
    /// `Engenho-Confirmation` header and a `confirm_phrase`.
    Executes(ReinitOp),
    /// Issues a challenge (`createConfirmation`).
    Issue,
    /// Consumes a challenge without executing (`cancelConfirmation`).
    Cancel,
}

/// The `engenho ctl <resource> <verb>` spelling of an operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CliSpelling {
    /// The noun (`runtime`, `config`, …).
    pub resource: &'static str,
    /// The verb (`show`, `set`, …).
    pub verb: &'static str,
}

/// One operation's row, read from the spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperationSpec {
    /// Which operation.
    pub id: OperationId,
    /// Its HTTP method.
    pub method: HttpMethod,
    /// Its path template (`/v1/children/{child}`), as the spec spells it.
    pub path: &'static str,
    /// Its one tag.
    pub tag: &'static str,
    /// The authority a caller needs.
    pub tier: AuthorityTier,
    /// The response carries secret material (never an MCP tool).
    pub sensitive: bool,
    /// Its relation to the confirmation handshake.
    pub gate: ConfirmGate,
    /// Its CLI spelling.
    pub cli: CliSpelling,
    /// The status of its success response.
    pub success_status: u16,
    /// Its parameters: the path item's, then its own, in spec order.
    pub params: &'static [ParamSpec],
    /// Whether it takes a JSON request body.
    pub body: bool,
    /// The media type of its success body.
    pub response_media: MediaType,
}

/// Where a parameter travels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParamLocation {
    /// A `{name}` segment of the path.
    Path,
    /// A query pair.
    Query,
    /// A header.
    Header,
}

/// One parameter of an operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ParamSpec {
    /// Its name, as the spec (and the wire) spells it.
    pub name: &'static str,
    /// Where it travels.
    pub location: ParamLocation,
    /// Whether the operation refuses a request without it.
    pub required: bool,
    /// How its text becomes a typed value.
    pub kind: wire::Kind,
}

/// The media type of a success body.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MediaType {
    /// `application/json`.
    Json,
    /// `application/yaml` text (the spec itself).
    Yaml,
}

impl MediaType {
    /// The `Content-Type` value.
    #[must_use]
    pub const fn content_type(self) -> &'static str {
        match self {
            Self::Json => "application/json",
            Self::Yaml => "application/yaml",
        }
    }
}

impl OperationId {
    /// The operation a request names, and its decoded path parameters —
    /// `None` when no operation has that method and path.
    #[must_use]
    pub fn route(method: &str, path: &str) -> Option<(Self, Vec<(String, String)>)> {
        let segments: Vec<&str> = path.trim_end_matches('/').split('/').collect();
        CATALOG.iter().find_map(|row| {
            if !row.method.as_str().eq_ignore_ascii_case(method) {
                return None;
            }
            let template: Vec<&str> = row.path.split('/').collect();
            if template.len() != segments.len() {
                return None;
            }
            let mut params = Vec::new();
            for (want, got) in template.iter().zip(&segments) {
                match want.strip_prefix('{').and_then(|w| w.strip_suffix('}')) {
                    Some(name) => params.push((name.to_string(), wire::decode_segment(got)?)),
                    None if want == got => {}
                    None => return None,
                }
            }
            Some((row.id, params))
        })
    }
}

// ── operations ──────────────────────────────────────────────────────────────

/// Binds an operation's marker type to its request and response, and
/// dispatches it into an [`EngenhoControl`] — the one generic path every
/// transport and client uses.
pub trait Operation: Send + Sync + 'static {
    /// Which operation.
    const ID: OperationId;
    /// Every input of the operation.
    type Request: wire::OperationRequest + Send + 'static;
    /// Its success body.
    type Response: Serialize + DeserializeOwned + Send + 'static;
    /// Call the operation on `ctl` as `by`.
    fn invoke<'a>(
        ctl: &'a dyn EngenhoControl,
        by: &'a Principal,
        req: Self::Request,
    ) -> BoxFuture<'a, Result<Self::Response, ControlError>>;
}

// ── the principal ───────────────────────────────────────────────────────────

/// Who is calling, as the transport proved it.
///
/// ★ `Serialize` only — there is no `Deserialize`, so a peer can never send
/// one: authority does not flow in over the wire. A transport mints a
/// principal from what the kernel (peer credentials) or the TLS handshake
/// (pinned SPKI) attested, plus the grant its policy derived from that.
///
/// ```compile_fail
/// let _p: engenho_control_types::Principal = serde_json::from_str("{}").unwrap();
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Principal {
    attested: types::AttestedView,
    declared: types::DeclaredView,
    grant: types::GrantView,
}

impl Principal {
    /// Mint a principal. Call this only from a transport, with facts the
    /// kernel or the TLS handshake attested — never from request content.
    #[must_use]
    pub fn mint(
        attested: types::AttestedView,
        declared: types::DeclaredView,
        grant: types::GrantView,
    ) -> Self {
        Self {
            attested,
            declared,
            grant,
        }
    }

    /// What was attested.
    #[must_use]
    pub fn attested(&self) -> &types::AttestedView {
        &self.attested
    }

    /// What the caller declared about itself (never authority).
    #[must_use]
    pub fn declared(&self) -> &types::DeclaredView {
        &self.declared
    }

    /// The grant: the entitled tier and the effective (ceilinged) tier.
    #[must_use]
    pub fn grant(&self) -> &types::GrantView {
        &self.grant
    }

    /// The tier this request may act at.
    #[must_use]
    pub fn effective(&self) -> AuthorityTier {
        self.grant.effective
    }

    /// The wire view recorded in overrides and audit records.
    #[must_use]
    pub fn view(&self) -> types::PrincipalView {
        types::PrincipalView {
            attested: self.attested.clone(),
            declared: self.declared.clone(),
        }
    }
}

// ── errors ──────────────────────────────────────────────────────────────────

/// Why an operation did not produce its success body — the spec's two error
/// bodies, in kotae's vocabulary.
#[derive(Debug, Clone, PartialEq)]
pub enum ControlError {
    /// Understood and refused; the reason names what would be accepted.
    Refused(types::Refusal),
    /// The daemon could not answer; conclude nothing about the subject.
    Blind(types::Blind),
}

impl ControlError {
    /// A refusal with no `legal` alternatives.
    #[must_use]
    pub fn refused(reason: types::RefusalReason, because: impl Into<String>) -> Self {
        Self::Refused(types::Refusal {
            outcome: types::RefusalOutcome::Refused,
            reason,
            because: because.into(),
            legal: Vec::new(),
        })
    }

    /// A refusal that names what would be accepted instead.
    #[must_use]
    pub fn refused_with(
        reason: types::RefusalReason,
        because: impl Into<String>,
        legal: Vec<String>,
    ) -> Self {
        Self::Refused(types::Refusal {
            outcome: types::RefusalOutcome::Refused,
            reason,
            because: because.into(),
            legal,
        })
    }

    /// A blind answer.
    #[must_use]
    pub fn blind(reason: types::BlindReason, because: impl Into<String>) -> Self {
        Self::Blind(types::Blind {
            outcome: types::BlindOutcome::Blind,
            reason,
            because: because.into(),
        })
    }

    /// The HTTP status this error is served with. Total over
    /// [`types::RefusalReason`], so a new reason cannot ship without one.
    #[must_use]
    pub const fn status(&self) -> u16 {
        use types::RefusalReason as R;
        match self {
            Self::Blind(_) => 503,
            Self::Refused(r) => match r.reason {
                R::UnknownOperation => 404,
                R::InsufficientAuthority
                | R::ConfirmationRequired
                | R::ConfirmationMismatch
                | R::ConfirmationExpired => 403,
                R::PreconditionFailed
                | R::RuntimeRunning
                | R::RuntimeNotRunning
                | R::RuntimeNotFailed
                | R::RuntimeNotStopped
                | R::LifecycleBusy
                | R::Wedged
                | R::RespawnRefused => 409,
                R::UnknownLeaf
                | R::NotOverridableLeaf
                | R::InvalidValue
                | R::ConfigRejected
                | R::Unsupported => 422,
            },
        }
    }
}

impl std::fmt::Display for ControlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Refused(r) => write!(f, "refused ({}): {}", r.reason, r.because),
            Self::Blind(b) => write!(f, "blind ({}): {}", b.reason, b.because),
        }
    }
}

impl std::error::Error for ControlError {}

// ── HTTP rendering ──────────────────────────────────────────────────────────

/// Rendering operations to, and parsing them from, HTTP pieces. Every
/// generated `…Request` implements [`wire::OperationRequest`] through these.
pub mod wire {
    use serde::Serialize;
    use serde::de::DeserializeOwned;
    use serde_json::Value;

    use crate::HttpMethod;

    /// Converts an operation's typed request to and from HTTP pieces.
    pub trait OperationRequest: Sized {
        /// Render into the HTTP pieces a client sends.
        fn to_http(&self) -> HttpRequest;
        /// Parse from the HTTP pieces a server received.
        ///
        /// # Errors
        /// A missing or malformed parameter or body.
        fn from_http(parts: &HttpParts) -> Result<Self, BadRequest>;
    }

    /// The pieces of an HTTP request, as a client renders them.
    #[derive(Debug, Clone, PartialEq)]
    pub struct HttpRequest {
        /// The method.
        pub method: HttpMethod,
        /// The concrete path, parameters substituted and percent-encoded.
        pub path: String,
        /// Query pairs.
        pub query: Vec<(&'static str, String)>,
        /// Header pairs.
        pub headers: Vec<(&'static str, String)>,
        /// The JSON body, if the operation has one.
        pub body: Option<Value>,
    }

    /// The pieces of an HTTP request, as a server received them.
    #[derive(Debug, Clone, Default, PartialEq)]
    pub struct HttpParts {
        /// Path parameters, by the spec's template name (decoded).
        pub path_params: Vec<(String, String)>,
        /// Query pairs (decoded).
        pub query: Vec<(String, String)>,
        /// Headers.
        pub headers: Vec<(String, String)>,
        /// The parsed JSON body.
        pub body: Option<Value>,
    }

    impl HttpParts {
        /// A path parameter by template name.
        #[must_use]
        pub fn path_param(&self, name: &str) -> Option<&str> {
            self.path_params
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.as_str())
        }

        /// A query parameter.
        #[must_use]
        pub fn query_param(&self, name: &str) -> Option<&str> {
            self.query
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.as_str())
        }

        /// A header, matched case-insensitively.
        #[must_use]
        pub fn header(&self, name: &str) -> Option<&str> {
            self.headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case(name))
                .map(|(_, v)| v.as_str())
        }
    }

    /// Why a request could not be parsed into its operation's typed request.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum BadRequest {
        /// A required parameter (or the body) is absent.
        Missing(&'static str),
        /// A parameter did not parse into its type.
        Parameter {
            /// Which parameter.
            name: &'static str,
            /// Why.
            detail: String,
        },
        /// The body did not deserialize into its type.
        Body(String),
    }

    impl std::fmt::Display for BadRequest {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Missing(name) => write!(f, "missing required {name}"),
                Self::Parameter { name, detail } => write!(f, "parameter {name}: {detail}"),
                Self::Body(detail) => write!(f, "body: {detail}"),
            }
        }
    }

    impl std::error::Error for BadRequest {}

    /// How a parameter's raw text becomes JSON before serde types it.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Kind {
        /// A string (or a string enum, or a pattern-constrained string).
        Text,
        /// An unsigned integer.
        Integer,
        /// A boolean.
        Boolean,
    }

    /// Render a typed parameter value as its wire text.
    ///
    /// # Panics
    /// Never for spec types: every one serializes to a scalar.
    #[must_use]
    pub fn render<T: Serialize>(v: &T) -> String {
        match serde_json::to_value(v).expect("spec parameter types serialize") {
            Value::String(s) => s,
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            other => other.to_string(),
        }
    }

    /// Parse a parameter's wire text into its typed value.
    ///
    /// # Errors
    /// The text is not a valid value of the parameter's type.
    pub fn parse<T: DeserializeOwned>(
        name: &'static str,
        kind: Kind,
        raw: &str,
    ) -> Result<T, BadRequest> {
        let bad = |detail: String| BadRequest::Parameter { name, detail };
        let value = match kind {
            Kind::Text => Value::String(raw.to_string()),
            Kind::Integer => {
                Value::Number(raw.parse::<u64>().map_err(|e| bad(e.to_string()))?.into())
            }
            Kind::Boolean => Value::Bool(raw.parse::<bool>().map_err(|e| bad(e.to_string()))?),
        };
        serde_json::from_value(value).map_err(|e| bad(e.to_string()))
    }

    /// Percent-decode one path segment; `None` when it is not valid
    /// percent-encoding of UTF-8.
    #[must_use]
    pub fn decode_segment(s: &str) -> Option<String> {
        let bytes = s.as_bytes();
        let mut out = Vec::with_capacity(bytes.len());
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'%' {
                let hex = s.get(i + 1..i + 3)?;
                out.push(u8::from_str_radix(hex, 16).ok()?);
                i += 3;
            } else {
                out.push(bytes[i]);
                i += 1;
            }
        }
        String::from_utf8(out).ok()
    }

    /// Percent-encode one path segment (everything outside RFC 3986's
    /// unreserved set).
    #[must_use]
    pub fn encode_segment(s: &str) -> String {
        use std::fmt::Write as _;
        let mut out = String::with_capacity(s.len());
        for b in s.bytes() {
            if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
                out.push(char::from(b));
            } else {
                // Writing to a String cannot fail.
                let _ = write!(out, "%{b:02X}");
            }
        }
        out
    }
}