Skip to main content

subc_protocol/
config.rs

1//! Optional module config-gate control bodies.
2//!
3//! A module opts in by listing [`CONFIG_REVIEW_OP`] in HELLO `control_ops`, not
4//! by changing its manifest. Send these operations only after HELLO_ACK advertises
5//! [`CONFIG_GATE_CAPABILITY`]. Without it a module keeps its existing file reader;
6//! with it, a refusal must never cause a fallback to unapproved files.
7//!
8//! These standalone bodies leave the existing exhaustive session enums alone.
9//! Extension fields are ignored on read. Unknown policy strings preserve their
10//! spelling but grant no authority. All calls use channel 0; failures use
11//! [`crate::ErrorBody`], not a successful reply with an empty configuration.
12
13use std::collections::BTreeMap;
14
15use base64::{engine::general_purpose::STANDARD, Engine as _};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18pub use subc_config::{Digest, FieldChange, Layer};
19
20pub const CONFIG_GATE_CAPABILITY: &str = "config.gate";
21pub const CONFIG_REVIEW_OP: &str = "config.review";
22pub const CONFIG_DECLARE_OP: &str = "config.declare";
23pub const CONFIG_GET_OP: &str = "config.get";
24pub const CONFIG_APPLIED_OP: &str = "config.applied";
25pub const CONFIG_CHANGED_OP: &str = "config.changed";
26
27macro_rules! op_tag {
28    ($name:ident, $wire:literal) => {
29        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30        enum $name {
31            #[serde(rename = $wire)]
32            Op,
33        }
34    };
35}
36op_tag!(ReviewOp, "config.review");
37op_tag!(DeclareOp, "config.declare");
38op_tag!(GetOp, "config.get");
39op_tag!(AppliedOp, "config.applied");
40op_tag!(ChangedOp, "config.changed");
41
42macro_rules! open_string_enum {
43    ($(#[$meta:meta])* $name:ident { $($variant:ident => $wire:literal),+ $(,)? }) => {
44        $(#[$meta])*
45        #[non_exhaustive]
46        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47        #[serde(from = "String", into = "String")]
48        pub enum $name {
49            $($variant,)+
50            /// A future spelling, retained for diagnostics but never authority.
51            Unknown(String),
52        }
53        impl $name {
54            pub fn as_str(&self) -> &str {
55                match self {
56                    $(Self::$variant => $wire,)+
57                    Self::Unknown(value) => value,
58                }
59            }
60        }
61        impl From<String> for $name {
62            fn from(value: String) -> Self {
63                match value.as_str() {
64                    $($wire => Self::$variant,)+
65                    _ => Self::Unknown(value),
66                }
67            }
68        }
69        impl From<$name> for String {
70            fn from(value: $name) -> Self { value.as_str().to_owned() }
71        }
72    };
73}
74pub(crate) use open_string_enum;
75
76open_string_enum! {
77    /// Snapshot layer identity. An unknown layer must not be merged or delivered.
78    ConfigLayer {
79        Default => "default", User => "user", Workspace => "workspace", Project => "project"
80    }
81}
82impl ConfigLayer {
83    pub fn known_layer(&self) -> Option<Layer> {
84        match self {
85            Self::Default => Some(Layer::Default),
86            Self::User => Some(Layer::User),
87            Self::Workspace => Some(Layer::Workspace),
88            Self::Project => Some(Layer::Project),
89            Self::Unknown(_) => None,
90        }
91    }
92}
93
94open_string_enum! {
95    /// Delivery status. An unknown status must not be treated as an active view.
96    ConfigStatus {
97        Unstamped => "unstamped", Pending => "pending", Active => "active",
98        Failed => "failed", Gated => "gated"
99    }
100}
101impl ConfigStatus {
102    pub fn is_active(&self) -> bool {
103        matches!(self, Self::Active)
104    }
105}
106
107open_string_enum! {
108    /// Only an explicit ACK acknowledges a complete generation, including readiness.
109    ConfigApplyResult { Ack => "ack", Nack => "nack" }
110}
111impl ConfigApplyResult {
112    /// Unknown results have the same fail-closed disposition as a NACK.
113    pub fn is_ack(&self) -> bool {
114        matches!(self, Self::Ack)
115    }
116}
117
118/// Immutable raw input, never an instruction to open a mutable path.
119///
120/// Exactly one of `path` and `proposal_id` identifies the input; the daemon
121/// validates that location against the approved declaration. `bytes` and `digest`
122/// are either both present or both absent (a missing file, not an empty file).
123/// Bytes serialize as canonical RFC 4648 padded base64. Decoding checks both the
124/// encoding and the SHA-256 of the exact bytes, including BOMs and line endings.
125#[non_exhaustive]
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(try_from = "SnapshotWire")]
128pub struct ConfigLayerSnapshot {
129    pub module_id: String,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub project_id: Option<String>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub workspace_id: Option<String>,
134    pub layer: ConfigLayer,
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub path: Option<String>,
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub proposal_id: Option<String>,
139    #[serde(
140        serialize_with = "serialize_bytes",
141        skip_serializing_if = "Option::is_none"
142    )]
143    pub bytes: Option<Vec<u8>>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub digest: Option<Digest>,
146}
147
148impl ConfigLayerSnapshot {
149    /// Snapshot a file or its absence. An empty byte slice is a present file.
150    pub fn file(
151        module_id: impl Into<String>,
152        layer: ConfigLayer,
153        path: impl Into<String>,
154        bytes: Option<Vec<u8>>,
155    ) -> Self {
156        let digest = bytes.as_deref().map(subc_config::raw_digest);
157        Self {
158            module_id: module_id.into(),
159            project_id: None,
160            workspace_id: None,
161            layer,
162            path: Some(path.into()),
163            proposal_id: None,
164            bytes,
165            digest,
166        }
167    }
168}
169
170fn serialize_bytes<S: serde::Serializer>(
171    bytes: &Option<Vec<u8>>,
172    serializer: S,
173) -> Result<S::Ok, S::Error> {
174    bytes
175        .as_ref()
176        .map(|bytes| STANDARD.encode(bytes))
177        .serialize(serializer)
178}
179
180#[derive(Deserialize)]
181struct SnapshotWire {
182    module_id: String,
183    project_id: Option<String>,
184    workspace_id: Option<String>,
185    layer: ConfigLayer,
186    path: Option<String>,
187    proposal_id: Option<String>,
188    bytes: Option<String>,
189    digest: Option<Digest>,
190}
191
192impl TryFrom<SnapshotWire> for ConfigLayerSnapshot {
193    type Error = String;
194    fn try_from(wire: SnapshotWire) -> Result<Self, Self::Error> {
195        let bytes = wire
196            .bytes
197            .map(|encoded| {
198                let bytes = STANDARD
199                    .decode(&encoded)
200                    .map_err(|_| "bytes: invalid canonical base64")?;
201                if STANDARD.encode(&bytes) != encoded {
202                    return Err("bytes: non-canonical base64");
203                }
204                Ok(bytes)
205            })
206            .transpose()
207            .map_err(str::to_owned)?;
208        match (&bytes, &wire.digest) {
209            (Some(bytes), Some(digest)) if subc_config::raw_digest(bytes) != *digest => {
210                return Err("digest: does not match bytes".into())
211            }
212            (Some(_), None) => return Err("digest: required with bytes".into()),
213            (None, Some(_)) => return Err("bytes: required with digest".into()),
214            _ => {}
215        }
216        Ok(Self {
217            module_id: wire.module_id,
218            project_id: wire.project_id,
219            workspace_id: wire.workspace_id,
220            layer: wire.layer,
221            path: wire.path,
222            proposal_id: wire.proposal_id,
223            bytes,
224            digest: wire.digest,
225        })
226    }
227}
228
229/// One immutable module/project view. Generation zero with `unstamped` status
230/// represents current files before stamping, not an approved generation.
231/// Unknown statuses or snapshot layers must not be activated.
232#[non_exhaustive]
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub struct ConfigView {
235    /// Set only by clients from the config.get reply; never sent by the daemon
236    /// in a view. Delivery state, not part of the approved configuration.
237    #[serde(skip)]
238    pub declaration_pending: Option<ConfigDeclarationPending>,
239    pub generation: u64,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub attempt: Option<u64>,
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub project_id: Option<String>,
244    pub effective: Value,
245    /// JSON pointer to the source layer of each effective field.
246    pub sources: BTreeMap<String, Layer>,
247    pub layers: Vec<ConfigLayerSnapshot>,
248    pub status: ConfigStatus,
249}
250impl ConfigView {
251    pub fn new(
252        generation: u64,
253        effective: Value,
254        sources: BTreeMap<String, Layer>,
255        layers: Vec<ConfigLayerSnapshot>,
256        status: ConfigStatus,
257    ) -> Self {
258        Self {
259            generation,
260            declaration_pending: None,
261            attempt: None,
262            project_id: None,
263            effective,
264            sources,
265            layers,
266            status,
267        }
268    }
269}
270
271/// Pure daemon-to-module review of immutable candidate layers against a supplied
272/// last-approved base, which the plan replaces and which can differ from the
273/// generation the module is running. The module must not read files, environment,
274/// network or secrets, or recompute old values under a new build. `base: null`
275/// means there is no previous approval.
276#[non_exhaustive]
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub struct ConfigReviewRequest {
279    op: ReviewOp,
280    pub base_generation: u64,
281    pub layers: Vec<ConfigLayerSnapshot>,
282    pub base: Option<ConfigView>,
283}
284impl ConfigReviewRequest {
285    pub fn new(
286        base_generation: u64,
287        layers: Vec<ConfigLayerSnapshot>,
288        base: Option<ConfigView>,
289    ) -> Self {
290        Self {
291            op: ReviewOp::Op,
292            base_generation,
293            layers,
294            base,
295        }
296    }
297}
298
299/// A field or project refusal. Cross-field reasons name every implicated JSON
300/// pointer in `paths`. Reasons must not contain secret values.
301#[non_exhaustive]
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303pub struct ConfigReviewRefusal {
304    pub code: String,
305    pub paths: Vec<String>,
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub project_id: Option<String>,
308    pub reasons: Vec<String>,
309}
310impl ConfigReviewRefusal {
311    pub fn new(code: impl Into<String>, paths: Vec<String>, reasons: Vec<String>) -> Self {
312        Self {
313            code: code.into(),
314            paths,
315            project_id: None,
316            reasons,
317        }
318    }
319}
320
321/// Normalized old/new values, sources and apply kinds for every field, including
322/// unchanged values whose source changed. Any refusal prevents approval; the
323/// daemon validates this reply against the schema and supplied immutable base.
324#[non_exhaustive]
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
326pub struct ConfigReviewReply {
327    op: ReviewOp,
328    pub fields: Vec<FieldChange>,
329    pub refusals: Vec<ConfigReviewRefusal>,
330}
331impl ConfigReviewReply {
332    pub fn new(fields: Vec<FieldChange>, refusals: Vec<ConfigReviewRefusal>) -> Self {
333        Self {
334            op: ReviewOp::Op,
335            fields,
336            refusals,
337        }
338    }
339}
340
341/// Declare once after HELLO_ACK and before the first get or applied on this
342/// connection. The schema and layer locations are proposals, not authority:
343/// only the approved declaration is enforced after stamping. Workspace mappings
344/// remain daemon-owned. Module identity comes from the connection, never a body.
345#[non_exhaustive]
346#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
347pub struct ConfigDeclareRequest {
348    op: DeclareOp,
349    pub schema: Value,
350    pub user_file: String,
351    pub project_dirs: Vec<String>,
352}
353impl ConfigDeclareRequest {
354    pub fn new(schema: Value, user_file: impl Into<String>, project_dirs: Vec<String>) -> Self {
355        Self {
356            op: DeclareOp::Op,
357            schema,
358            user_file: user_file.into(),
359            project_dirs,
360        }
361    }
362}
363
364/// Pull the caller's view. Exact-generation selectors are only for the caller's
365/// daemon-assigned delivery attempt, not arbitrary modules or project tuples.
366#[non_exhaustive]
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368pub struct ConfigGetRequest {
369    op: GetOp,
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub project_id: Option<String>,
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub generation: Option<u64>,
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub attempt: Option<u64>,
376}
377impl ConfigGetRequest {
378    pub fn new() -> Self {
379        Self {
380            op: GetOp::Op,
381            project_id: None,
382            generation: None,
383            attempt: None,
384        }
385    }
386}
387impl Default for ConfigGetRequest {
388    fn default() -> Self {
389        Self::new()
390    }
391}
392
393/// Active and optional pending views. Apply `pending` before ACKing it; retain
394/// `active` for recovery. A module with no approved configuration is refused
395/// with [`crate::error_codes::CONFIG_GATED`], never given empty file bytes.
396/// `active: null` is permitted when a first delivery has no prior active view.
397/// A changed declaration can receive only the approved active view, with
398/// `declaration_pending` on this reply and a catch-up attempt on that view.
399#[non_exhaustive]
400#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
401pub struct ConfigGetReply {
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub declaration_pending: Option<ConfigDeclarationPending>,
404    op: GetOp,
405    pub active: Option<ConfigView>,
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub pending: Option<ConfigView>,
408}
409impl ConfigGetReply {
410    pub fn new(active: Option<ConfigView>, pending: Option<ConfigView>) -> Self {
411        Self {
412            declaration_pending: None,
413            op: GetOp::Op,
414            active,
415            pending,
416        }
417    }
418}
419
420/// A newer declaration awaits approval. An absent digest means no plan carries it yet.
421/// Unknown members are ignored for forward compatibility.
422#[non_exhaustive]
423#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
424pub struct ConfigDeclarationPending {
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub plan_digest: Option<subc_config::Digest>,
427}
428
429/// A complete-generation outcome bound to the caller's child, project and
430/// delivery attempt. An ACK includes readiness, never a partial field apply.
431/// Duplicate, stale or wrong-generation outcomes cannot move active pointers.
432#[non_exhaustive]
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
434pub struct ConfigAppliedRequest {
435    op: AppliedOp,
436    pub generation: u64,
437    pub attempt: u64,
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub project_id: Option<String>,
440    pub result: ConfigApplyResult,
441    pub reasons: Vec<String>,
442}
443impl ConfigAppliedRequest {
444    pub fn new(
445        generation: u64,
446        attempt: u64,
447        result: ConfigApplyResult,
448        reasons: Vec<String>,
449    ) -> Self {
450        Self {
451            op: AppliedOp::Op,
452            generation,
453            attempt,
454            project_id: None,
455            result,
456            reasons,
457        }
458    }
459}
460
461/// Daemon hint to the active delivery target only. Resynchronize on reconnect
462/// and ignore stale hints; this is not an activation record.
463#[non_exhaustive]
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465pub struct ConfigChanged {
466    op: ChangedOp,
467    pub generation: u64,
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub project_id: Option<String>,
470    /// JSON pointers of fields whose view changed.
471    pub fields: Vec<String>,
472}
473impl ConfigChanged {
474    pub fn new(generation: u64, fields: Vec<String>) -> Self {
475        Self {
476            op: ChangedOp::Op,
477            generation,
478            project_id: None,
479            fields,
480        }
481    }
482}
483
484macro_rules! empty_reply {
485    ($(#[$meta:meta])* $name:ident, $tag:ident) => {
486        $(#[$meta])*
487        #[non_exhaustive]
488        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
489        pub struct $name { op: $tag }
490        impl $name { pub fn new() -> Self { Self { op: $tag::Op } } }
491        impl Default for $name { fn default() -> Self { Self::new() } }
492    };
493}
494empty_reply! {
495    /// Receipt of a declaration does not approve its schema or locations.
496    ConfigDeclareReply, DeclareOp
497}
498empty_reply! {
499    /// Receipt of an outcome; refusals travel in an ERROR frame instead.
500    ConfigAppliedReply, AppliedOp
501}