Skip to main content

stateknot_runtime/agent_service/policy/
artifact.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use super::PolicyError;
5use serde::{Deserialize, Serialize};
6use stateknot_core::{
7    BoundedJson, BudgetLimits, CapabilityIdentity, Digest, PrincipalIdentity, RunId,
8    SchemaReference, ScopeSet, TenantId, Timestamp,
9};
10
11/// One exact admission selector and the restrictions it grants.
12#[derive(Clone, Deserialize, Serialize)]
13#[serde(deny_unknown_fields)]
14pub struct SubmissionRule {
15    /// Trusted tenant, never taken from request JSON.
16    pub tenant: TenantId,
17    /// Exact authenticated issuer/subject.
18    pub principal: PrincipalIdentity,
19    /// Exact owner-qualified Agent revision.
20    pub agent: CapabilityIdentity,
21    /// Exact input schema including its content digest.
22    pub input_schema: SchemaReference,
23    /// Explicit execution scopes; normal admission checks still apply.
24    pub granted_scopes: ScopeSet,
25    /// Nonempty restrictive layer, intersected with descriptor/request limits.
26    pub budget_limits: BudgetLimits,
27}
28
29/// Explicit operation granted by a run rule.
30#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
31#[serde(rename_all = "snake_case")]
32pub enum RunPermission {
33    /// Read snapshots, key lookups and activity.
34    Read,
35    /// Request cooperative durable cancellation.
36    Cancel,
37}
38
39/// Exact target or explicitly privileged tenant-operator scope.
40#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
41#[serde(
42    tag = "kind",
43    content = "value",
44    rename_all = "snake_case",
45    deny_unknown_fields
46)]
47pub enum RunAccessTarget {
48    /// One exact run; does not also grant key lookup.
49    Run(RunId),
50    /// One tenant-bound submission digest; does not also grant run-ID lookup.
51    Submission(Digest),
52    /// All run IDs and submission digests in this rule's tenant. Use sparingly.
53    TenantRuns,
54}
55
56/// One explicit run permission. Overlapping selectors are rejected at startup.
57#[derive(Clone, Deserialize, Serialize)]
58#[serde(deny_unknown_fields)]
59pub struct RunRule {
60    /// Trusted tenant boundary.
61    pub tenant: TenantId,
62    /// Exact authenticated issuer/subject.
63    pub principal: PrincipalIdentity,
64    /// Read or cancel, never inferred from submission permission.
65    pub operation: RunPermission,
66    /// Exact resource or explicit tenant-wide operator scope.
67    pub target: RunAccessTarget,
68}
69
70/// Host-controlled versioned policy configuration, not an authentication token.
71#[derive(Clone, Deserialize, Serialize)]
72#[serde(deny_unknown_fields)]
73pub struct PolicyDocument {
74    /// Must be 1; unsupported versions fail closed.
75    pub format_version: u16,
76    /// Identity of this versioned policy implementation/configuration family.
77    pub policy: CapabilityIdentity,
78    /// Absolute expiration retained across process restarts.
79    pub valid_until: Timestamp,
80    /// Explicit admission rules; empty denies all submissions.
81    pub submissions: Vec<SubmissionRule>,
82    /// Explicit run rules; empty denies all reads/cancellations.
83    pub runs: Vec<RunRule>,
84}
85
86/// Validated canonical policy artifact. Retain bytes privately before installation.
87/// Its digest is not proof of origin; authenticate the configuration source.
88#[derive(Clone)]
89pub struct PolicyArtifact {
90    pub(super) document: PolicyDocument,
91    canonical: Vec<u8>,
92    digest: Digest,
93    pub(super) submissions: Vec<Digest>,
94    pub(super) runs: Vec<Digest>,
95}
96
97impl PolicyArtifact {
98    /// Maximum total rules; bounded JSON may impose a lower effective ceiling.
99    pub const MAX_RULES: usize = 1024;
100
101    /// Validates trusted configuration and computes normalized canonical bytes.
102    /// No clock check is performed until installation into a live policy.
103    ///
104    /// # Errors
105    /// Rejects unknown versions, oversized configuration, empty budgets and
106    /// duplicate/overlapping selectors. Rule ordering never resolves ambiguity.
107    pub fn new(document: PolicyDocument) -> Result<Self, PolicyError> {
108        if document.format_version != 1
109            || document
110                .submissions
111                .len()
112                .saturating_add(document.runs.len())
113                > Self::MAX_RULES
114        {
115            return Err(PolicyError);
116        }
117        // Validate structure before canonicalizing or retaining any rule copies.
118        let value = serde_json::to_value(&document).map_err(|_| PolicyError)?;
119        BoundedJson::try_from_value(value).map_err(|_| PolicyError)?;
120        for (i, rule) in document.submissions.iter().enumerate() {
121            if rule.budget_limits.is_empty()
122                || document.submissions[..i].iter().any(|old| {
123                    old.tenant == rule.tenant
124                        && old.principal == rule.principal
125                        && old.agent == rule.agent
126                        && old.input_schema == rule.input_schema
127                })
128            {
129                return Err(PolicyError);
130            }
131        }
132        for (i, rule) in document.runs.iter().enumerate() {
133            if document.runs[..i].iter().any(|old| {
134                old.tenant == rule.tenant
135                    && old.principal == rule.principal
136                    && old.operation == rule.operation
137                    && (old.target == rule.target
138                        || old.target == RunAccessTarget::TenantRuns
139                        || rule.target == RunAccessTarget::TenantRuns)
140            }) {
141                return Err(PolicyError);
142            }
143            if rule.operation == RunPermission::Cancel
144                && matches!(rule.target, RunAccessTarget::Submission(_))
145            {
146                // The service has no cancellation-by-key endpoint.
147                return Err(PolicyError);
148            }
149        }
150        let canonical = serde_json_canonicalizer::to_vec(&document).map_err(|_| PolicyError)?;
151        let digest = Digest::sha256(&canonical);
152        let submissions = document
153            .submissions
154            .iter()
155            .map(|rule| {
156                checksum(
157                    b"stateknot.agent-policy-submission-rule.v1\0",
158                    &(&document.policy, rule),
159                )
160            })
161            .collect::<Result<_, _>>()?;
162        let runs = document
163            .runs
164            .iter()
165            .map(|rule| {
166                checksum(
167                    b"stateknot.agent-policy-run-rule.v1\0",
168                    &(&document.policy, rule),
169                )
170            })
171            .collect::<Result<_, _>>()?;
172        Ok(Self {
173            document,
174            canonical,
175            digest,
176            submissions,
177            runs,
178        })
179    }
180
181    /// Loads bounded duplicate-free JSON and verifies its normalized digest.
182    /// The expected digest must come from an independently trusted manifest.
183    ///
184    /// # Errors
185    /// Rejects malformed/unknown/oversized configuration or checksum mismatch.
186    pub fn from_json(bytes: &[u8], expected: Digest) -> Result<Self, PolicyError> {
187        let bounded = BoundedJson::from_slice(bytes).map_err(|_| PolicyError)?;
188        let document = serde_json::from_value(bounded.into_value()).map_err(|_| PolicyError)?;
189        let artifact = Self::new(document)?;
190        if artifact.digest != expected {
191            return Err(PolicyError);
192        }
193        Ok(artifact)
194    }
195
196    /// Returns the complete normalized artifact checksum, not a selected-rule digest.
197    #[must_use]
198    pub const fn digest(&self) -> Digest {
199        self.digest
200    }
201
202    /// Returns private canonical configuration bytes for immutable retention.
203    #[must_use]
204    pub fn canonical_bytes(&self) -> &[u8] {
205        &self.canonical
206    }
207}
208
209pub(super) fn checksum(domain: &[u8], value: &impl Serialize) -> Result<Digest, PolicyError> {
210    let mut bytes = domain.to_vec();
211    bytes.extend(serde_json_canonicalizer::to_vec(value).map_err(|_| PolicyError)?);
212    Ok(Digest::sha256(bytes))
213}