1use chrono::{DateTime, Utc};
5use sqlx_core::{from_row::FromRow, query::query, query_as::query_as, query_scalar::query_scalar};
6use sqlx_postgres::{PgRow, Postgres};
7use stateknot_core::{
8 BoxFuture, Digest, SkillActingWindow, SkillActingWindowId, SkillActingWindowOpenRequest,
9 SkillActingWindowRevocation, SkillActingWindowRevocationReason, SkillActivationApproval,
10 SkillActivationSource, SkillActivationStore, SkillActivationStoreError,
11 SkillActivationStoreFailure, TenantId, Timestamp, ToolAuthorizationReceipt,
12};
13
14use super::{
15 PostgresStore, StoreError, decode_digest, from_database_time, has_database_constraint,
16 to_database_time,
17};
18
19const MAX_APPROVAL_BYTES: usize = 65_536;
20const MAX_WINDOW_BYTES: usize = 131_072;
21const MAX_REVOCATION_BYTES: usize = 65_536;
22
23const SELECT_WINDOW: &str = r"
24SELECT tenant_id, window_id, approval_id, run_id, thread_id, subject_digest,
25 opened_at, expires_at, window_digest, window_bytes, window_bytes_digest
26FROM stateknot.skill_acting_windows
27WHERE tenant_id=$1 AND window_id=$2
28";
29
30#[derive(Debug)]
31struct WindowRow {
32 tenant_id: String,
33 window_id: uuid::Uuid,
34 approval_id: uuid::Uuid,
35 run_id: uuid::Uuid,
36 thread_id: uuid::Uuid,
37 subject_digest: Vec<u8>,
38 opened_at: DateTime<Utc>,
39 expires_at: DateTime<Utc>,
40 window_digest: Vec<u8>,
41 window_bytes: Vec<u8>,
42 window_bytes_digest: Vec<u8>,
43}
44
45impl<'row> FromRow<'row, PgRow> for WindowRow {
46 fn from_row(row: &'row PgRow) -> Result<Self, sqlx_core::error::Error> {
47 use sqlx_core::row::Row;
48 Ok(Self {
49 tenant_id: row.try_get("tenant_id")?,
50 window_id: row.try_get("window_id")?,
51 approval_id: row.try_get("approval_id")?,
52 run_id: row.try_get("run_id")?,
53 thread_id: row.try_get("thread_id")?,
54 subject_digest: row.try_get("subject_digest")?,
55 opened_at: row.try_get("opened_at")?,
56 expires_at: row.try_get("expires_at")?,
57 window_digest: row.try_get("window_digest")?,
58 window_bytes: row.try_get("window_bytes")?,
59 window_bytes_digest: row.try_get("window_bytes_digest")?,
60 })
61 }
62}
63
64impl PostgresStore {
65 #[allow(clippy::too_many_lines)]
67 pub async fn open_skill_acting_window(
68 &self,
69 request: SkillActingWindowOpenRequest,
70 ) -> Result<SkillActingWindow, StoreError> {
71 let tenant = request.approval().scope().tenant_id();
72 let mut transaction = self.begin_mutation("Skill acting window open").await?;
73 lock_window(&mut transaction, tenant, request.window_id()).await?;
74
75 if let Some(row) = query_as::<_, WindowRow>(SELECT_WINDOW)
76 .bind(tenant.as_str())
77 .bind(*request.window_id().as_uuid())
78 .fetch_optional(&mut *transaction)
79 .await
80 .map_err(|source| StoreError::database("Skill acting window retry", source))?
81 {
82 let stored = decode_window(&row)?;
83 if stored.approval() != request.approval() {
84 return Err(StoreError::SkillActivationConflict);
85 }
86 if locked_window_inactive(
87 &mut transaction,
88 tenant,
89 request.window_id(),
90 row.expires_at,
91 "Skill acting window retry",
92 )
93 .await?
94 {
95 return Err(StoreError::SkillActingWindowInactive);
96 }
97 transaction.commit().await.map_err(|source| {
98 StoreError::database("Skill acting window retry commit", source)
99 })?;
100 return Ok(stored);
101 }
102
103 if let SkillActivationSource::Nested { parent_window_id } = request.approval().source() {
104 let parent = load_locked_active(
105 &mut transaction,
106 tenant,
107 *parent_window_id,
108 "nested Skill parent",
109 )
110 .await?;
111 if parent.approval().scope() != request.approval().scope() {
112 return Err(StoreError::InvalidSkillActivation);
113 }
114 }
115
116 let now: DateTime<Utc> = query_scalar("SELECT clock_timestamp()")
117 .fetch_one(&mut *transaction)
118 .await
119 .map_err(|source| StoreError::database("Skill acting window database clock", source))?;
120 let opened_at = from_database_time(now)?;
121 let duration_micros = request
122 .approval()
123 .requested_duration()
124 .duration()
125 .as_i64()
126 .checked_mul(1_000)
127 .ok_or(StoreError::InvalidSkillActivation)?;
128 let expires_at = Timestamp::from_unix_micros(
129 opened_at
130 .unix_micros()
131 .checked_add(duration_micros)
132 .ok_or(StoreError::InvalidSkillActivation)?,
133 )
134 .map_err(|_| StoreError::InvalidSkillActivation)?;
135 let window = SkillActingWindow::new(
136 request.window_id(),
137 request.approval().clone(),
138 opened_at,
139 expires_at,
140 )
141 .map_err(|_| StoreError::InvalidSkillActivation)?;
142 let approval_bytes = encode(request.approval(), MAX_APPROVAL_BYTES, "Skill approval")?;
143 let window_bytes = encode(&window, MAX_WINDOW_BYTES, "Skill acting window")?;
144 let (source_kind, parent_window_id) = match request.approval().source() {
145 SkillActivationSource::Direct => ("direct", None),
146 SkillActivationSource::Nested { parent_window_id } => {
147 ("nested", Some(*parent_window_id.as_uuid()))
148 }
149 _ => return Err(StoreError::InvalidSkillActivation),
150 };
151 let approval = request.approval();
152 let scope = approval.scope();
153 let subject = approval.subject();
154 let inserted_approval = query(
155 r"INSERT INTO stateknot.skill_activation_approvals (
156tenant_id,approval_id,run_id,thread_id,protocol,origin,skill_uri,manifest_digest,
157subject_digest,source_kind,parent_window_id,policy_digest,decision_digest,
158requested_duration_ms,approval_digest,recorded_at,approval_bytes
159) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)
160ON CONFLICT (tenant_id,approval_id) DO NOTHING",
161 )
162 .bind(tenant.as_str())
163 .bind(*approval.approval_id().as_uuid())
164 .bind(*scope.run_id().as_uuid())
165 .bind(*scope.thread_id().as_uuid())
166 .bind(subject.protocol())
167 .bind(subject.origin())
168 .bind(subject.uri())
169 .bind(subject.manifest_digest().as_bytes())
170 .bind(subject.subject_digest().as_bytes())
171 .bind(source_kind)
172 .bind(parent_window_id)
173 .bind(approval.policy_digest().as_bytes())
174 .bind(approval.decision_digest().as_bytes())
175 .bind(approval.requested_duration().duration().as_i64())
176 .bind(approval.approval_digest().as_bytes())
177 .bind(now)
178 .bind(&approval_bytes)
179 .execute(&mut *transaction)
180 .await
181 .map_err(|source| StoreError::database("Skill activation approval insert", source))?;
182 if inserted_approval.rows_affected() == 0 {
183 let existing: Vec<u8> = query_scalar(
184 "SELECT approval_bytes FROM stateknot.skill_activation_approvals WHERE tenant_id=$1 AND approval_id=$2",
185 )
186 .bind(tenant.as_str())
187 .bind(*approval.approval_id().as_uuid())
188 .fetch_one(&mut *transaction)
189 .await
190 .map_err(|source| StoreError::database("Skill activation approval conflict", source))?;
191 if existing != approval_bytes
192 || decode::<SkillActivationApproval>(
193 &existing,
194 MAX_APPROVAL_BYTES,
195 "Skill approval",
196 )? != *approval
197 {
198 return Err(StoreError::SkillActivationConflict);
199 }
200 }
201
202 let inserted_window = query(
203 r"INSERT INTO stateknot.skill_acting_windows (
204tenant_id,window_id,approval_id,run_id,thread_id,subject_digest,opened_at,expires_at,
205window_digest,window_bytes
206) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)",
207 )
208 .bind(tenant.as_str())
209 .bind(*window.window_id().as_uuid())
210 .bind(*approval.approval_id().as_uuid())
211 .bind(*scope.run_id().as_uuid())
212 .bind(*scope.thread_id().as_uuid())
213 .bind(subject.subject_digest().as_bytes())
214 .bind(to_database_time(opened_at)?)
215 .bind(to_database_time(expires_at)?)
216 .bind(window.window_digest().as_bytes())
217 .bind(&window_bytes)
218 .execute(&mut *transaction)
219 .await;
220 if let Err(source) = inserted_window {
221 if has_database_constraint(&source, "skill_acting_windows_approval_unique") {
222 return Err(StoreError::SkillActivationConflict);
223 }
224 return Err(StoreError::database("Skill acting window insert", source));
225 }
226 transaction
227 .commit()
228 .await
229 .map_err(|source| StoreError::database("Skill acting window commit", source))?;
230 Ok(window)
231 }
232
233 pub async fn load_active_skill_acting_window(
235 &self,
236 tenant: &TenantId,
237 window_id: SkillActingWindowId,
238 ) -> Result<SkillActingWindow, StoreError> {
239 let mut transaction = self.begin_mutation("Skill acting window load").await?;
240 let window =
241 load_locked_active(&mut transaction, tenant, window_id, "Skill acting window").await?;
242 transaction
243 .commit()
244 .await
245 .map_err(|source| StoreError::database("Skill acting window load commit", source))?;
246 Ok(window)
247 }
248
249 pub async fn assert_skill_acting_window_active(
251 &self,
252 expected: &SkillActingWindow,
253 ) -> Result<(), StoreError> {
254 let actual = self
255 .load_active_skill_acting_window(
256 expected.approval().scope().tenant_id(),
257 expected.window_id(),
258 )
259 .await?;
260 if &actual != expected {
261 return Err(StoreError::SkillActivationConflict);
262 }
263 Ok(())
264 }
265
266 pub async fn revoke_skill_acting_window(
268 &self,
269 expected: &SkillActingWindow,
270 reason: SkillActingWindowRevocationReason,
271 ) -> Result<SkillActingWindowRevocation, StoreError> {
272 let tenant = expected.approval().scope().tenant_id();
273 let mut transaction = self.begin_mutation("Skill acting window revoke").await?;
274 lock_window(&mut transaction, tenant, expected.window_id()).await?;
275 let row = query_as::<_, WindowRow>(SELECT_WINDOW)
276 .bind(tenant.as_str())
277 .bind(*expected.window_id().as_uuid())
278 .fetch_optional(&mut *transaction)
279 .await
280 .map_err(|source| StoreError::database("Skill acting window revoke load", source))?
281 .ok_or(StoreError::SkillActingWindowNotFound)?;
282 if decode_window(&row)? != *expected {
283 return Err(StoreError::SkillActivationConflict);
284 }
285 if let Some(bytes) = query_scalar::<_, Vec<u8>>(
286 "SELECT revocation_bytes FROM stateknot.skill_acting_window_revocations WHERE tenant_id=$1 AND window_id=$2",
287 )
288 .bind(tenant.as_str())
289 .bind(*expected.window_id().as_uuid())
290 .fetch_optional(&mut *transaction)
291 .await
292 .map_err(|source| StoreError::database("Skill acting window revocation retry", source))?
293 {
294 let existing = decode::<SkillActingWindowRevocation>(&bytes, MAX_REVOCATION_BYTES, "Skill revocation")?;
295 if existing.reason() != reason {
296 return Err(StoreError::SkillActivationConflict);
297 }
298 transaction.commit().await.map_err(|source| StoreError::database("Skill acting window revocation retry commit", source))?;
299 return Ok(existing);
300 }
301 let now: DateTime<Utc> = query_scalar("SELECT clock_timestamp()")
302 .fetch_one(&mut *transaction)
303 .await
304 .map_err(|source| StoreError::database("Skill revocation database clock", source))?;
305 let revocation = SkillActingWindowRevocation::new(
306 tenant.clone(),
307 expected.window_id(),
308 reason,
309 from_database_time(now)?,
310 )
311 .map_err(|_| StoreError::InvalidSkillActivation)?;
312 let bytes = encode(&revocation, MAX_REVOCATION_BYTES, "Skill revocation")?;
313 query(
314 "INSERT INTO stateknot.skill_acting_window_revocations (tenant_id,window_id,reason,revoked_at,revocation_digest,revocation_bytes) VALUES ($1,$2,$3,$4,$5,$6)",
315 )
316 .bind(tenant.as_str())
317 .bind(*expected.window_id().as_uuid())
318 .bind(revocation_reason_text(reason))
319 .bind(now)
320 .bind(revocation.revocation_digest().as_bytes())
321 .bind(&bytes)
322 .execute(&mut *transaction)
323 .await
324 .map_err(|source| StoreError::database("Skill acting window revocation insert", source))?;
325 transaction.commit().await.map_err(|source| {
326 StoreError::database("Skill acting window revocation commit", source)
327 })?;
328 Ok(revocation)
329 }
330}
331
332pub(super) async fn validate_receipt_window(
333 transaction: &mut sqlx_core::transaction::Transaction<'_, Postgres>,
334 receipt: &ToolAuthorizationReceipt,
335) -> Result<(), StoreError> {
336 let Some(window_id) = receipt.authorization_window_id() else {
337 return Ok(());
338 };
339 let provenance = receipt.provenance();
340 let window = load_locked_active(
341 transaction,
342 provenance.tenant_id(),
343 window_id,
344 "Tool authorization Skill window",
345 )
346 .await?;
347 let scope = window.approval().scope();
348 if scope.run_id() != provenance.run_id()
349 || scope.thread_id() != provenance.thread_id()
350 || window.approval().subject().subject_digest() != receipt.subject_digest()
351 {
352 return Err(StoreError::InvalidToolAuthorizationReceipt);
353 }
354 Ok(())
355}
356
357async fn load_locked_active(
358 transaction: &mut sqlx_core::transaction::Transaction<'_, Postgres>,
359 tenant: &TenantId,
360 window_id: SkillActingWindowId,
361 operation: &'static str,
362) -> Result<SkillActingWindow, StoreError> {
363 lock_window(transaction, tenant, window_id).await?;
364 let row = query_as::<_, WindowRow>(SELECT_WINDOW)
365 .bind(tenant.as_str())
366 .bind(*window_id.as_uuid())
367 .fetch_optional(&mut **transaction)
368 .await
369 .map_err(|source| StoreError::database(operation, source))?
370 .ok_or(StoreError::SkillActingWindowNotFound)?;
371 let window = decode_window(&row)?;
372 if locked_window_inactive(transaction, tenant, window_id, row.expires_at, operation).await? {
373 return Err(StoreError::SkillActingWindowInactive);
374 }
375 Ok(window)
376}
377
378async fn lock_window(
383 transaction: &mut sqlx_core::transaction::Transaction<'_, Postgres>,
384 tenant: &TenantId,
385 window_id: SkillActingWindowId,
386) -> Result<(), StoreError> {
387 query("SELECT pg_advisory_xact_lock(hashtextextended($1 || '/' || $2::text, 0))")
388 .bind(tenant.as_str())
389 .bind(*window_id.as_uuid())
390 .execute(&mut **transaction)
391 .await
392 .map_err(|source| StoreError::database("Skill acting window serialization", source))?;
393 Ok(())
394}
395
396async fn locked_window_inactive(
397 transaction: &mut sqlx_core::transaction::Transaction<'_, Postgres>,
398 tenant: &TenantId,
399 window_id: SkillActingWindowId,
400 expires_at: DateTime<Utc>,
401 operation: &'static str,
402) -> Result<bool, StoreError> {
403 query_scalar(
404 "SELECT clock_timestamp() >= $3 OR EXISTS (SELECT 1 FROM stateknot.skill_acting_window_revocations WHERE tenant_id=$1 AND window_id=$2)",
405 )
406 .bind(tenant.as_str())
407 .bind(*window_id.as_uuid())
408 .bind(expires_at)
409 .fetch_one(&mut **transaction)
410 .await
411 .map_err(|source| StoreError::database(operation, source))
412}
413
414fn decode_window(row: &WindowRow) -> Result<SkillActingWindow, StoreError> {
415 let window =
416 decode::<SkillActingWindow>(&row.window_bytes, MAX_WINDOW_BYTES, "Skill acting window")?;
417 let scope = window.approval().scope();
418 if row.tenant_id != scope.tenant_id().as_str()
419 || row.window_id != *window.window_id().as_uuid()
420 || row.approval_id != *window.approval().approval_id().as_uuid()
421 || row.run_id != *scope.run_id().as_uuid()
422 || row.thread_id != *scope.thread_id().as_uuid()
423 || decode_digest(&row.subject_digest, "Skill subject")?
424 != window.approval().subject().subject_digest()
425 || from_database_time(row.opened_at)? != window.opened_at()
426 || from_database_time(row.expires_at)? != window.expires_at()
427 || decode_digest(&row.window_digest, "Skill window")? != window.window_digest()
428 || Digest::sha256(&row.window_bytes)
429 != decode_digest(&row.window_bytes_digest, "Skill window bytes")?
430 {
431 return Err(StoreError::corrupt("Skill acting window projection"));
432 }
433 Ok(window)
434}
435
436fn encode<T: serde::Serialize>(
437 value: &T,
438 maximum: usize,
439 component: &'static str,
440) -> Result<Vec<u8>, StoreError> {
441 let bytes =
442 serde_json_canonicalizer::to_vec(value).map_err(|_| StoreError::encoding(component))?;
443 if bytes.is_empty() || bytes.len() > maximum {
444 return Err(StoreError::encoding(component));
445 }
446 Ok(bytes)
447}
448
449fn decode<T: serde::de::DeserializeOwned>(
450 bytes: &[u8],
451 maximum: usize,
452 component: &'static str,
453) -> Result<T, StoreError> {
454 if bytes.is_empty() || bytes.len() > maximum {
455 return Err(StoreError::corrupt(component));
456 }
457 serde_json::from_slice(bytes).map_err(|_| StoreError::corrupt(component))
458}
459
460const fn revocation_reason_text(reason: SkillActingWindowRevocationReason) -> &'static str {
461 match reason {
462 SkillActingWindowRevocationReason::User => "user",
463 SkillActingWindowRevocationReason::Policy => "policy",
464 SkillActingWindowRevocationReason::Compromised => "compromised",
465 SkillActingWindowRevocationReason::Superseded => "superseded",
466 SkillActingWindowRevocationReason::Administrative => "administrative",
467 _ => "invalid",
468 }
469}
470
471impl SkillActivationStore for PostgresStore {
472 fn open(
473 &self,
474 request: SkillActingWindowOpenRequest,
475 ) -> BoxFuture<'_, Result<SkillActingWindow, SkillActivationStoreError>> {
476 Box::pin(async move {
477 self.open_skill_acting_window(request)
478 .await
479 .map_err(store_error)
480 })
481 }
482
483 fn load_active(
484 &self,
485 tenant_id: TenantId,
486 window_id: SkillActingWindowId,
487 ) -> BoxFuture<'_, Result<SkillActingWindow, SkillActivationStoreError>> {
488 Box::pin(async move {
489 self.load_active_skill_acting_window(&tenant_id, window_id)
490 .await
491 .map_err(store_error)
492 })
493 }
494
495 fn assert_active(
496 &self,
497 window: SkillActingWindow,
498 ) -> BoxFuture<'_, Result<(), SkillActivationStoreError>> {
499 Box::pin(async move {
500 self.assert_skill_acting_window_active(&window)
501 .await
502 .map_err(store_error)
503 })
504 }
505
506 fn revoke(
507 &self,
508 window: SkillActingWindow,
509 reason: SkillActingWindowRevocationReason,
510 ) -> BoxFuture<'_, Result<SkillActingWindowRevocation, SkillActivationStoreError>> {
511 Box::pin(async move {
512 self.revoke_skill_acting_window(&window, reason)
513 .await
514 .map_err(store_error)
515 })
516 }
517}
518
519fn store_error(source: StoreError) -> SkillActivationStoreError {
520 let failure = match source {
521 StoreError::SkillActingWindowNotFound => SkillActivationStoreFailure::NotFound,
522 StoreError::SkillActingWindowInactive => SkillActivationStoreFailure::Inactive,
523 StoreError::Database { .. }
524 | StoreError::Migration { .. }
525 | StoreError::UnsupportedServerVersion
526 | StoreError::SchemaNotMigrated
527 | StoreError::IncompatibleSchema
528 | StoreError::IncompleteSchema => SkillActivationStoreFailure::Unavailable,
529 _ => SkillActivationStoreFailure::Rejected,
530 };
531 SkillActivationStoreError::new(failure, source)
532}