Skip to main content

stateknot_core/
child_run.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure child ownership identities, not authority or committed admission proof.
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Deserializer, Serialize, de};
8use thiserror::Error;
9
10use crate::{Digest, NodeActivation, NodeId, NodeIdError, RunId, TenantId};
11
12const KEY_DOMAIN: &[u8] = b"stateknot-child-run-key-v1\0";
13
14/// A stable, case-sensitive child slot declared by an executable definition.
15///
16/// Reuses the bounded [`NodeId`] grammar, but is a distinct Rust type. A slot
17/// is not a child Run ID, physical attempt, arbitrary model string, or path.
18/// Construction validates syntax only; declaration membership is a separate
19/// admission check.
20#[derive(
21    Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
22)]
23#[serde(transparent)]
24pub struct ChildRunSlot(NodeId);
25
26impl ChildRunSlot {
27    /// Maximum encoded slot length in bytes.
28    pub const MAX_LEN: usize = NodeId::MAX_LEN;
29
30    /// Constructs a bounded slot using the same validation on every wire path.
31    pub fn new(value: impl Into<String>) -> Result<Self, NodeIdError> {
32        NodeId::new(value).map(Self)
33    }
34
35    /// Returns the exact declared slot text.
36    #[must_use]
37    pub fn as_str(&self) -> &str {
38        self.0.as_str()
39    }
40}
41
42/// Integrity-bound logical ownership key for one isolated child Run.
43///
44/// The key binds the complete parent activation and slot. It intentionally
45/// excludes physical attempts, fences, clocks, and candidate child Run IDs.
46/// Its digest can index an ownership record but cannot authorize admission:
47/// the store must prove the activation's committed readiness, current worker
48/// authority, declaration membership, and atomic budget reservation.
49///
50/// Deserialization recomputes the digest. A matching checksum detects drift;
51/// it is not a signature and does not authenticate caller-supplied data.
52#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
53#[serde(deny_unknown_fields)]
54pub struct ChildRunKey {
55    parent: NodeActivation,
56    slot: ChildRunSlot,
57    digest: Digest,
58}
59
60impl ChildRunKey {
61    /// Computes a deterministic logical key from validated domain values.
62    pub fn new(parent: NodeActivation, slot: ChildRunSlot) -> Result<Self, ChildRunKeyError> {
63        #[derive(Serialize)]
64        struct Preimage<'a> {
65            tenant_id: &'a TenantId,
66            parent_run_id: RunId,
67            parent_activation_digest: Digest,
68            child_slot: &'a ChildRunSlot,
69        }
70
71        let activation_digest = crate::node_attempt::compute_activation_digest(&parent)
72            .map_err(|_| ChildRunKeyError::CanonicalSerialization)?;
73        let canonical = serde_json_canonicalizer::to_vec(&Preimage {
74            tenant_id: parent.tenant_id(),
75            parent_run_id: parent.run_id(),
76            parent_activation_digest: activation_digest,
77            child_slot: &slot,
78        })
79        .map_err(|_| ChildRunKeyError::CanonicalSerialization)?;
80        let mut preimage = Vec::with_capacity(KEY_DOMAIN.len() + canonical.len());
81        preimage.extend_from_slice(KEY_DOMAIN);
82        preimage.extend_from_slice(&canonical);
83        Ok(Self {
84            parent,
85            slot,
86            digest: Digest::sha256(preimage),
87        })
88    }
89
90    /// Returns the exact parent logical activation, without physical authority.
91    #[must_use]
92    pub const fn parent(&self) -> &NodeActivation {
93        &self.parent
94    }
95
96    /// Returns the declared child slot.
97    #[must_use]
98    pub const fn slot(&self) -> &ChildRunSlot {
99        &self.slot
100    }
101
102    /// Returns the tenant inherited from the parent activation.
103    #[must_use]
104    pub const fn tenant_id(&self) -> &TenantId {
105        self.parent.tenant_id()
106    }
107
108    /// Returns the parent Run ID, never a generated child ID.
109    #[must_use]
110    pub const fn parent_run_id(&self) -> RunId {
111        self.parent.run_id()
112    }
113
114    /// Returns the domain-separated SHA-256 ownership fingerprint.
115    #[must_use]
116    pub const fn digest(&self) -> Digest {
117        self.digest
118    }
119}
120
121impl<'de> Deserialize<'de> for ChildRunKey {
122    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
123    where
124        D: Deserializer<'de>,
125    {
126        #[derive(Deserialize)]
127        #[serde(deny_unknown_fields)]
128        struct Wire {
129            parent: NodeActivation,
130            slot: ChildRunSlot,
131            digest: Digest,
132        }
133
134        let wire = Wire::deserialize(deserializer)?;
135        let key = Self::new(wire.parent, wire.slot).map_err(de::Error::custom)?;
136        if key.digest != wire.digest {
137            return Err(de::Error::custom(ChildRunKeyError::DigestMismatch));
138        }
139        Ok(key)
140    }
141}
142
143/// Failure constructing or restoring a logical child ownership key.
144#[derive(Clone, Debug, Eq, Error, PartialEq)]
145#[non_exhaustive]
146pub enum ChildRunKeyError {
147    /// The closed integrity preimage could not be encoded canonically.
148    #[error("child run key canonical serialization failed")]
149    CanonicalSerialization,
150    /// Stored identity fields no longer match their integrity fingerprint.
151    #[error("child run key digest mismatch")]
152    DigestMismatch,
153}
154
155#[cfg(test)]
156#[path = "child_run_tests.rs"]
157mod tests;