Skip to main content

stateknot_runtime/agent_service/
policy.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Default-deny, offline resource policy for trusted static/service-account ACLs.
5//! Retain artifacts privately before activation. No ownership inference, network
6//! PDP, persistent read/deny audit ledger or distributed policy cache is provided.
7//!
8//! ```
9//! use std::{sync::Arc, time::Duration};
10//! use stateknot_core::Digest;
11//! use stateknot_runtime::{JsonSchemaRegistryBuilder, agent_policy::*};
12//!
13//! fn load_policy(
14//!     retained_bytes: &[u8], trusted_digest: Digest,
15//!     schemas: &mut JsonSchemaRegistryBuilder,
16//! ) -> Result<Arc<AgentResourcePolicy>, PolicyError> {
17//!     register_agent_policy_evidence_schema(schemas)?;
18//!     let artifact = PolicyArtifact::from_json(retained_bytes, trusted_digest)?;
19//!     Ok(Arc::new(AgentResourcePolicy::new(artifact, Duration::from_secs(300))?))
20//! }
21//! ```
22
23use super::{
24    AgentServiceAuthorizationError, AgentServiceAuthorizer, AgentServiceRunAuthorization,
25    AgentServiceRunGrant, AgentServiceRunOperation, AgentServiceRunTarget,
26    AgentServiceSubmissionAuthorization, AgentServiceSubmissionGrant,
27};
28use stateknot_core::{
29    AgentAdmissionAuthority, AgentAdmissionBudgetLayer, BoundedJson, BoxFuture, JournalEventKind,
30    JournalPayload,
31};
32use std::{
33    sync::{Arc, RwLock},
34    time::{Duration, SystemTime, UNIX_EPOCH},
35};
36use thiserror::Error;
37use tokio::time::Instant;
38
39mod artifact;
40mod schema;
41use artifact::checksum;
42pub use artifact::{
43    PolicyArtifact, PolicyDocument, RunAccessTarget, RunPermission, RunRule, SubmissionRule,
44};
45pub use schema::{agent_policy_evidence_schema, register_agent_policy_evidence_schema};
46
47/// Sanitized invalid artifact, lease, CAS or unavailable policy state.
48#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
49#[error("Agent resource policy is invalid or unavailable")]
50pub struct PolicyError;
51
52struct Snapshot {
53    artifact: Arc<PolicyArtifact>,
54    expires: Instant,
55    generation: u64,
56}
57
58/// Shared bounded resource policy with explicit expiring CAS refresh.
59/// Replacements affect later authorization checks, not already granted work.
60pub struct AgentResourcePolicy(RwLock<Snapshot>);
61
62impl AgentResourcePolicy {
63    /// Maximum local freshness lease. Renew only from a revalidated trusted source.
64    pub const MAX_LEASE: Duration = Duration::from_secs(3600);
65
66    /// Installs a retained artifact at generation 1 with finite freshness.
67    ///
68    /// # Errors
69    /// Rejects zero/excessive lease, expired artifact or unavailable host clock.
70    pub fn new(artifact: PolicyArtifact, lease: Duration) -> Result<Self, PolicyError> {
71        Ok(Self(RwLock::new(Self::snapshot(artifact, lease, 1)?)))
72    }
73
74    /// Atomically replaces the snapshot after validating a trusted refresh.
75    /// Unrelated rule changes do not alter a selected rule's admission evidence.
76    ///
77    /// # Errors
78    /// Invalid/expired input, stale generation, overflow or poisoned lock leave
79    /// the previous snapshot intact. This is not cross-replica coordination.
80    pub fn replace(
81        &self,
82        expected_generation: u64,
83        artifact: PolicyArtifact,
84        lease: Duration,
85    ) -> Result<u64, PolicyError> {
86        let next = expected_generation.checked_add(1).ok_or(PolicyError)?;
87        let replacement = Self::snapshot(artifact, lease, next)?;
88        let mut current = self.0.write().map_err(|_| PolicyError)?;
89        if current.generation != expected_generation {
90            return Err(PolicyError);
91        }
92        *current = replacement;
93        Ok(next)
94    }
95
96    /// Returns process-local CAS generation; neither a digest nor freshness proof.
97    ///
98    /// # Errors
99    /// Rejects poisoned policy state.
100    pub fn generation(&self) -> Result<u64, PolicyError> {
101        self.0.read().map(|s| s.generation).map_err(|_| PolicyError)
102    }
103
104    /// Checks the current snapshot without granting an operation or doing I/O.
105    /// An empty, fresh deny-all artifact is healthy.
106    ///
107    /// # Errors
108    /// Rejects absolute/monotonic expiration, clock failure or poisoned state.
109    pub fn check_readiness(&self) -> Result<(), PolicyError> {
110        self.current().map(|_| ())
111    }
112
113    fn snapshot(
114        artifact: PolicyArtifact,
115        lease: Duration,
116        generation: u64,
117    ) -> Result<Snapshot, PolicyError> {
118        if lease.is_zero() || lease > Self::MAX_LEASE {
119            return Err(PolicyError);
120        }
121        let remaining = artifact
122            .document
123            .valid_until
124            .unix_micros()
125            .checked_sub(now_micros()?)
126            .filter(|value| *value > 0)
127            .ok_or(PolicyError)?;
128        let absolute = Duration::from_micros(u64::try_from(remaining).map_err(|_| PolicyError)?);
129        Ok(Snapshot {
130            artifact: Arc::new(artifact),
131            expires: Instant::now() + lease.min(absolute),
132            generation,
133        })
134    }
135
136    fn current(&self) -> Result<Arc<PolicyArtifact>, PolicyError> {
137        let current = self.0.read().map_err(|_| PolicyError)?;
138        if Instant::now() >= current.expires
139            || now_micros()? >= current.artifact.document.valid_until.unix_micros()
140        {
141            return Err(PolicyError);
142        }
143        Ok(current.artifact.clone())
144    }
145
146    fn submission(
147        &self,
148        context: &AgentServiceSubmissionAuthorization,
149    ) -> Result<AgentServiceSubmissionGrant, AgentServiceAuthorizationError> {
150        let artifact = self
151            .current()
152            .map_err(|_| AgentServiceAuthorizationError::Unavailable)?;
153        let (index, rule) = artifact
154            .document
155            .submissions
156            .iter()
157            .enumerate()
158            .find(|(_, rule)| {
159                &rule.tenant == context.caller().tenant_id()
160                    && &rule.principal == context.caller().principal()
161                    && &rule.agent == context.agent()
162                    && &rule.input_schema == context.request().input_schema()
163            })
164            .ok_or(AgentServiceAuthorizationError::Denied)?;
165        let policy_digest = artifact.submissions[index];
166        let invalid = |_| AgentServiceAuthorizationError::InvalidEvidence;
167        let request_digest =
168            checksum(b"stateknot.agent-policy-request.v1\0", context.request()).map_err(invalid)?;
169        let (schema, _) = agent_policy_evidence_schema().map_err(invalid)?;
170        let data = BoundedJson::try_from_value(serde_json::json!({
171            "operation": "submission_granted",
172            "policy_digest": policy_digest,
173            "request_digest": request_digest
174        }))
175        .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
176        let kind = JournalEventKind::new(AgentAdmissionAuthority::EVIDENCE_KIND)
177            .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
178        let evidence = JournalPayload::new(schema, kind, data)
179            .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
180        let budget = AgentAdmissionBudgetLayer::new(
181            artifact.document.policy.clone(),
182            evidence.digest(),
183            rule.budget_limits.clone(),
184        )
185        .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
186        let authority = AgentAdmissionAuthority::new(
187            rule.principal.clone(),
188            rule.granted_scopes.clone(),
189            artifact.document.policy.clone(),
190            policy_digest,
191            evidence,
192        )
193        .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
194        Ok(AgentServiceSubmissionGrant::new(authority, vec![budget]))
195    }
196
197    fn run(
198        &self,
199        context: &AgentServiceRunAuthorization,
200    ) -> Result<AgentServiceRunGrant, AgentServiceAuthorizationError> {
201        let artifact = self
202            .current()
203            .map_err(|_| AgentServiceAuthorizationError::Unavailable)?;
204        let operation = match context.operation() {
205            AgentServiceRunOperation::Read => RunPermission::Read,
206            AgentServiceRunOperation::Cancel => RunPermission::Cancel,
207        };
208        let target = match context.target() {
209            AgentServiceRunTarget::Run(id) => RunAccessTarget::Run(*id),
210            AgentServiceRunTarget::Submission(digest) => RunAccessTarget::Submission(*digest),
211        };
212        let index = artifact
213            .document
214            .runs
215            .iter()
216            .position(|rule| {
217                &rule.tenant == context.caller().tenant_id()
218                    && &rule.principal == context.caller().principal()
219                    && rule.operation == operation
220                    && (rule.target == target || rule.target == RunAccessTarget::TenantRuns)
221            })
222            .ok_or(AgentServiceAuthorizationError::Denied)?;
223        let policy_digest = artifact.runs[index];
224        let decision = checksum(
225            b"stateknot.agent-policy-run-decision.v1\0",
226            &(
227                policy_digest,
228                context.caller().tenant_id(),
229                context.caller().principal(),
230                operation,
231                target,
232            ),
233        )
234        .map_err(|_| AgentServiceAuthorizationError::InvalidEvidence)?;
235        Ok(AgentServiceRunGrant::new(
236            context.caller().principal().clone(),
237            artifact.document.policy.clone(),
238            policy_digest,
239            decision,
240        ))
241    }
242}
243
244impl AgentServiceAuthorizer for AgentResourcePolicy {
245    fn authorize_submission(
246        &self,
247        context: AgentServiceSubmissionAuthorization,
248    ) -> BoxFuture<'_, Result<AgentServiceSubmissionGrant, AgentServiceAuthorizationError>> {
249        Box::pin(async move { self.submission(&context) })
250    }
251
252    fn authorize_run(
253        &self,
254        context: AgentServiceRunAuthorization,
255    ) -> BoxFuture<'_, Result<AgentServiceRunGrant, AgentServiceAuthorizationError>> {
256        Box::pin(async move { self.run(&context) })
257    }
258}
259
260fn now_micros() -> Result<i64, PolicyError> {
261    i64::try_from(
262        SystemTime::now()
263            .duration_since(UNIX_EPOCH)
264            .map_err(|_| PolicyError)?
265            .as_micros(),
266    )
267    .map_err(|_| PolicyError)
268}
269
270#[cfg(test)]
271mod tests;