CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Durable worker приостанавливает Task как input_required до dispatch, если закреплённая схема требует отсутствующее поле; authorized schema-validated update атомарно и с аудитом возобновляет тот же Task ровно один раз. Replay/conflict/TTL безопасны, ожидание удерживает admission permit. Additive schema v30: task_input_requests, fingerprint/version, TTL-индекс.
627 lines
26 KiB
Rust
627 lines
26 KiB
Rust
//! Runtime application service of durable Tasks (Story 4.2, FR-22/FR-23).
|
|
//!
|
|
//! The service is the only place that turns an approved background request into the durable domain
|
|
//! request: bounded validated input, canonical input fingerprint, full-scope idempotency digest,
|
|
//! pinned Published Version/deadline/retention and the support identities of the request. It holds an
|
|
//! owned request, never `ResolvedAuth` or raw secrets, and it never dispatches: the durable store
|
|
//! commits Task + dispatch intent + queue slot in one transaction and only then produces an
|
|
//! acknowledgement.
|
|
//!
|
|
//! Reads go through the same owner-scoped access proof, so the durable row is only fetched for the
|
|
//! caller that owns it. There is no in-memory fallback: a store failure is a typed refusal.
|
|
|
|
use std::sync::Arc;
|
|
use std::time::Instant;
|
|
|
|
use crank_core::PlatformApiKeyId;
|
|
use crank_core::{
|
|
CorrelationContext, TASK_DEFAULT_RETENTION_MS, TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES,
|
|
TASK_EXECUTABLE_INPUT_MAX_BYTES, TASK_MAX_RETENTION_MS, TASK_SCOPED_KEY_MAX_BYTES,
|
|
TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError, TaskId,
|
|
TaskInputUpdateOutcome, TaskInputUpdateRequest, TaskLease, TaskOwnerKind, TaskPins, TaskRecord,
|
|
TaskStore, TaskSupportIds, ToolExecutionMode, contains_sensitive_task_keys, current_unix_ms,
|
|
validate_task_envelope,
|
|
};
|
|
use sha2::{Digest, Sha256};
|
|
|
|
/// One owned background request, already authorized by the application layer.
|
|
#[derive(Clone, Debug)]
|
|
pub struct TaskAcceptDraft {
|
|
pub workspace_id: String,
|
|
pub owner_kind: TaskOwnerKind,
|
|
pub owner_id: String,
|
|
/// Server-derived authorization scope identity of the verified principal.
|
|
pub authorization_scope: String,
|
|
/// Typed immutable Platform API key identity of the verified machine credential. It is sealed
|
|
/// into the executable-input binding and revalidated authoritatively by the worker.
|
|
pub platform_api_key_id: Option<PlatformApiKeyId>,
|
|
pub operation_id: String,
|
|
pub operation_version: u32,
|
|
pub policy_mode: ToolExecutionMode,
|
|
/// Caller key, bounded before it becomes a full-scope digest.
|
|
pub scoped_key: String,
|
|
/// Canonical executable input; it is validated, fingerprinted, then persisted redacted.
|
|
pub input: serde_json::Value,
|
|
pub correlation: CorrelationContext,
|
|
/// Absolute execution deadline of the accepted work.
|
|
pub deadline: Instant,
|
|
/// Retention after the execution deadline.
|
|
pub retention_ms: i64,
|
|
pub approval_reference: Option<String>,
|
|
/// Bounded retry snapshot pinned from the exact published operation at acceptance.
|
|
pub retry: crank_core::TaskRetryPolicy,
|
|
}
|
|
|
|
/// Projection of the durable status/result read. `result`/`error` are only present once a terminal
|
|
/// transition committed; a non-terminal Task reports its state and inputs without inventing output.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct TaskOutcome {
|
|
pub task_id: TaskId,
|
|
pub state: crank_core::TaskState,
|
|
pub result: Option<serde_json::Value>,
|
|
pub error: Option<serde_json::Value>,
|
|
}
|
|
|
|
impl TaskOutcome {
|
|
fn from_record(record: TaskRecord) -> Self {
|
|
Self {
|
|
task_id: record.task_id,
|
|
state: record.state,
|
|
result: record.result.map(|envelope| envelope.value().clone()),
|
|
error: record.error.map(|envelope| envelope.value().clone()),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct TaskService {
|
|
store: Arc<dyn TaskStore>,
|
|
crypto: Option<Arc<crate::SecretCrypto>>,
|
|
}
|
|
|
|
impl TaskService {
|
|
pub fn new(store: Arc<dyn TaskStore>) -> Self {
|
|
Self {
|
|
store,
|
|
crypto: None,
|
|
}
|
|
}
|
|
|
|
pub fn with_secret_crypto(store: Arc<dyn TaskStore>, crypto: Arc<crate::SecretCrypto>) -> Self {
|
|
Self {
|
|
store,
|
|
crypto: Some(crypto),
|
|
}
|
|
}
|
|
|
|
/// Readiness of the mandatory durable Task state.
|
|
pub async fn health(&self) -> Result<(), TaskError> {
|
|
self.store.health().await
|
|
}
|
|
|
|
/// Durable acceptance: the returned identity exists only after the store committed it.
|
|
pub async fn accept(&self, draft: TaskAcceptDraft) -> Result<TaskAcceptance, TaskError> {
|
|
validate_task_envelope(&draft.input)?;
|
|
if contains_sensitive_task_keys(&draft.input) {
|
|
return Err(TaskError::invalid(
|
|
"task executable input contains sensitive fields",
|
|
));
|
|
}
|
|
let (scoped_key, input_fingerprint) = (
|
|
scoped_key_digest(&draft)?,
|
|
canonical_input_fingerprint(&draft.input)?,
|
|
);
|
|
let execution_deadline_unix_ms = deadline_unix_ms(draft.deadline);
|
|
let retention_ms = draft.retention_ms.clamp(0, TASK_MAX_RETENTION_MS);
|
|
let task_id = TaskId::generate();
|
|
let crypto = self.crypto.as_ref().ok_or_else(|| {
|
|
TaskError::invalid("secret crypto is required for durable Task acceptance")
|
|
})?;
|
|
let binding = serde_json::json!({
|
|
"task_id": task_id.to_string(),
|
|
"workspace_id": draft.workspace_id,
|
|
"owner_kind": draft.owner_kind.as_str(),
|
|
"owner_id": draft.owner_id,
|
|
"authorization_scope": draft.authorization_scope,
|
|
"platform_api_key_id": draft
|
|
.platform_api_key_id
|
|
.as_ref()
|
|
.map(PlatformApiKeyId::as_str),
|
|
"operation_id": draft.operation_id,
|
|
"operation_version": draft.operation_version,
|
|
"policy_mode": draft.policy_mode,
|
|
"input_fingerprint": input_fingerprint,
|
|
"input": draft.input,
|
|
});
|
|
let ciphertext = crypto
|
|
.encrypt(&binding)
|
|
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
|
if ciphertext.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
|
|
return Err(TaskError::invalid(
|
|
"encrypted task input exceeds its byte budget",
|
|
));
|
|
}
|
|
let (
|
|
executable_input_ciphertext,
|
|
executable_input_key_version,
|
|
executable_input_master_key_epoch,
|
|
) = (
|
|
Some(ciphertext),
|
|
Some(crypto.key_version().to_owned()),
|
|
Some(crypto.master_key_epoch()),
|
|
);
|
|
let request = TaskAcceptRequest {
|
|
task_id,
|
|
workspace_id: draft.workspace_id,
|
|
owner_kind: draft.owner_kind,
|
|
owner_id: draft.owner_id,
|
|
authorization_scope: draft.authorization_scope,
|
|
platform_api_key_id: draft.platform_api_key_id,
|
|
operation_id: draft.operation_id,
|
|
pins: TaskPins {
|
|
operation_version: draft.operation_version,
|
|
policy_mode: draft.policy_mode,
|
|
execution_deadline_unix_ms,
|
|
retain_until_unix_ms: execution_deadline_unix_ms.saturating_add(retention_ms),
|
|
approval_reference: draft.approval_reference,
|
|
retry: draft.retry,
|
|
},
|
|
scoped_key,
|
|
input_fingerprint,
|
|
input: TaskEnvelope::try_redacted(&draft.input)?,
|
|
support: TaskSupportIds::new(
|
|
draft.correlation.request_id().clone(),
|
|
draft.correlation.trace_context(),
|
|
),
|
|
executable_input_ciphertext,
|
|
executable_input_key_version,
|
|
executable_input_master_key_epoch,
|
|
};
|
|
self.store.accept(request).await
|
|
}
|
|
|
|
/// Owner-scoped status read. A foreign or absent Task is one typed not-found.
|
|
pub async fn status(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
) -> Result<TaskRecord, TaskError> {
|
|
self.store.read(access, task_id).await
|
|
}
|
|
|
|
/// Owner-scoped result read, projected from the same authorized row.
|
|
pub async fn result(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
) -> Result<TaskOutcome, TaskError> {
|
|
Ok(TaskOutcome::from_record(
|
|
self.store.read(access, task_id).await?,
|
|
))
|
|
}
|
|
|
|
/// Owner-scoped cancellation of one accepted Task. The store decides under a row lock whether the
|
|
/// Task can still be cancelled or whether an already checkpointed attempt makes the outcome
|
|
/// uncertain; the service only carries the request and a bounded reason.
|
|
pub async fn cancel(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
expected_version: Option<u32>,
|
|
reason: &str,
|
|
) -> Result<crank_core::TaskCancelOutcome, TaskError> {
|
|
let request = crank_core::TaskCancelRequest {
|
|
access: access.clone(),
|
|
task_id,
|
|
expected_version,
|
|
reason: reason.to_owned(),
|
|
};
|
|
request.validate()?;
|
|
self.store.cancel(request).await
|
|
}
|
|
|
|
/// Bounded owner-scoped attempt history of one Task.
|
|
pub async fn attempts(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
) -> Result<Vec<crank_core::TaskAttempt>, TaskError> {
|
|
self.store.attempts(access, task_id).await
|
|
}
|
|
|
|
/// Decrypts and validates the executable input bound to a valid current lease.
|
|
pub async fn executable_input(
|
|
&self,
|
|
lease: &TaskLease,
|
|
) -> Result<serde_json::Value, TaskError> {
|
|
let crypto = self.crypto.as_ref().ok_or_else(|| {
|
|
TaskError::invalid("secret crypto is required for durable Task execution")
|
|
})?;
|
|
let (ciphertext, key_version, epoch) = self
|
|
.store
|
|
.read_executable_input(&lease.owner, lease.record.task_id, lease.fence)
|
|
.await?;
|
|
if ciphertext.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
|
|
return Err(TaskError::invalid(
|
|
"task executable input ciphertext is invalid",
|
|
));
|
|
}
|
|
let binding = crypto
|
|
.decrypt_for_epoch(&key_version, epoch, &ciphertext)
|
|
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
|
let object = binding
|
|
.as_object()
|
|
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
|
|
let check_string = |field: &str, expected: &str| -> Result<(), TaskError> {
|
|
match object.get(field).and_then(|value| value.as_str()) {
|
|
Some(actual) if actual == expected => Ok(()),
|
|
_ => Err(TaskError::invalid("task executable input binding mismatch")),
|
|
}
|
|
};
|
|
check_string("task_id", &lease.record.task_id.to_string())?;
|
|
check_string("workspace_id", &lease.record.workspace_id)?;
|
|
check_string("owner_id", &lease.record.owner_id)?;
|
|
check_string("authorization_scope", &lease.record.authorization_scope)?;
|
|
let expected_key = lease
|
|
.record
|
|
.platform_api_key_id
|
|
.as_ref()
|
|
.map(PlatformApiKeyId::as_str);
|
|
match (object.get("platform_api_key_id"), expected_key) {
|
|
(None | Some(serde_json::Value::Null), None) => {}
|
|
(Some(serde_json::Value::String(actual)), Some(expected)) if actual == expected => {}
|
|
_ => {
|
|
return Err(TaskError::invalid("task executable input binding mismatch"));
|
|
}
|
|
}
|
|
check_string("operation_id", &lease.record.operation_id)?;
|
|
match object.get("owner_kind").and_then(|value| value.as_str()) {
|
|
Some(actual) if actual == lease.record.owner_kind.as_str() => {}
|
|
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
|
|
}
|
|
match object
|
|
.get("operation_version")
|
|
.and_then(|value| value.as_u64())
|
|
{
|
|
Some(actual) if actual == u64::from(lease.record.pins.operation_version) => {}
|
|
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
|
|
}
|
|
let expected_policy = match lease.record.pins.policy_mode {
|
|
ToolExecutionMode::Synchronous => "synchronous",
|
|
ToolExecutionMode::Background => "background",
|
|
ToolExecutionMode::Adaptive => "adaptive",
|
|
};
|
|
match object.get("policy_mode").and_then(|value| value.as_str()) {
|
|
Some(actual) if actual == expected_policy => {}
|
|
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
|
|
}
|
|
check_string("input_fingerprint", &lease.record.input_fingerprint)?;
|
|
let base_input = object
|
|
.get("input")
|
|
.cloned()
|
|
.ok_or_else(|| TaskError::invalid("task executable input binding is missing input"))?;
|
|
if canonical_input_fingerprint(&base_input)? != lease.record.input_fingerprint {
|
|
return Err(TaskError::invalid("task executable input binding mismatch"));
|
|
}
|
|
// A committed continuation replaces only the effective payload. The acceptance fingerprint and
|
|
// the original input stay in the binding, so an original accept replay is still a replay.
|
|
let effective_input = match object.get("continuation") {
|
|
Some(continuation) => {
|
|
let continuation = continuation
|
|
.as_object()
|
|
.ok_or_else(|| TaskError::invalid("task input continuation is invalid"))?;
|
|
let effective = continuation
|
|
.get("effective_input_fingerprint")
|
|
.and_then(|value| value.as_str())
|
|
.ok_or_else(|| TaskError::invalid("task input continuation is invalid"))?;
|
|
if effective != lease.record.effective_input_fingerprint {
|
|
return Err(TaskError::invalid(
|
|
"task input continuation fingerprint mismatch",
|
|
));
|
|
}
|
|
let input = continuation.get("input").cloned().ok_or_else(|| {
|
|
TaskError::invalid("task input continuation is missing input")
|
|
})?;
|
|
if canonical_input_fingerprint(&input)? != effective {
|
|
return Err(TaskError::invalid("task input continuation is invalid"));
|
|
}
|
|
input
|
|
}
|
|
None => {
|
|
if lease.record.effective_input_fingerprint != lease.record.input_fingerprint {
|
|
return Err(TaskError::invalid("task input continuation is missing"));
|
|
}
|
|
base_input
|
|
}
|
|
};
|
|
validate_executable_payload(&effective_input)?;
|
|
Ok(effective_input)
|
|
}
|
|
|
|
/// Default retention pinned by the application layer when it does not choose one explicitly.
|
|
pub fn default_retention_ms() -> i64 {
|
|
TASK_DEFAULT_RETENTION_MS
|
|
}
|
|
|
|
/// Scoped lookup of an already accepted Task by the same full-scope identity, used to keep a
|
|
/// retry of an explicitly pinned version from being accepted as new work.
|
|
pub async fn lookup(&self, draft: &TaskAcceptDraft) -> Result<Option<TaskRecord>, TaskError> {
|
|
let scoped_key = scoped_key_digest(draft)?;
|
|
let access = TaskAccess {
|
|
workspace_id: draft.workspace_id.clone(),
|
|
owner_kind: draft.owner_kind,
|
|
owner_id: draft.owner_id.clone(),
|
|
authorization_scope: draft.authorization_scope.clone(),
|
|
};
|
|
self.store
|
|
.find(&access, &draft.operation_id, &scoped_key)
|
|
.await
|
|
}
|
|
|
|
/// Canonical digest of a validated input, exposed so the application layer can compare a stored
|
|
/// Task against the request it is retrying without duplicating the canonicalization.
|
|
pub fn input_fingerprint(input: &serde_json::Value) -> Result<String, TaskError> {
|
|
canonical_input_fingerprint(input)
|
|
}
|
|
|
|
/// Applies one additional validated input to a suspended Task (Story 4.5).
|
|
///
|
|
/// The stored native schema snapshot is the only validation authority; the canonical digest binds
|
|
/// the effective payload, and the existing encrypted executable-input binding is extended with a
|
|
/// continuation segment instead of a second cipher store. The store transaction owns authority,
|
|
/// receipt, generation, TTL and CAS, so an identical replay returns the committed outcome.
|
|
pub async fn update_input(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
wait_id: &str,
|
|
expected_version: u32,
|
|
update_key: &str,
|
|
input: &serde_json::Value,
|
|
) -> Result<TaskInputUpdateOutcome, TaskError> {
|
|
access.validate()?;
|
|
validate_task_envelope(input)?;
|
|
if contains_sensitive_task_keys(input) {
|
|
return Err(TaskError::invalid(
|
|
"task executable input contains sensitive fields",
|
|
));
|
|
}
|
|
let canonical_fingerprint = canonical_input_fingerprint(input)?;
|
|
let pending = self.store.input_request(access, task_id).await?;
|
|
if pending.wait_id != wait_id {
|
|
return Err(TaskError::StateConflict);
|
|
}
|
|
// The immutable snapshot, never the current publication, is the schema authority.
|
|
let schema: crank_schema::Schema = serde_json::from_value(pending.schema_snapshot.clone())
|
|
.map_err(|_| TaskError::unavailable("stored task input schema is invalid"))?;
|
|
schema
|
|
.validate_shape(input)
|
|
.map_err(|_| TaskError::invalid("task input does not match the pinned input schema"))?;
|
|
let update_key_digest = input_update_key_digest(access, task_id, wait_id, update_key)?;
|
|
let crypto = self.crypto.as_ref().ok_or_else(|| {
|
|
TaskError::invalid("secret crypto is required for durable Task continuation")
|
|
})?;
|
|
let (ciphertext, key_version, epoch) = self
|
|
.store
|
|
.read_executable_input_for_update(access, task_id)
|
|
.await?;
|
|
let binding = crypto
|
|
.decrypt_for_epoch(&key_version, epoch, &ciphertext)
|
|
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
|
let mut object = binding
|
|
.as_object()
|
|
.cloned()
|
|
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
|
|
check_binding_string(&object, "task_id", &task_id.to_string())?;
|
|
check_binding_string(&object, "workspace_id", &access.workspace_id)?;
|
|
check_binding_string(&object, "owner_id", &access.owner_id)?;
|
|
check_binding_string(&object, "authorization_scope", &access.authorization_scope)?;
|
|
let base_input = object
|
|
.get("input")
|
|
.cloned()
|
|
.ok_or_else(|| TaskError::invalid("task executable input binding is missing input"))?;
|
|
let base_fingerprint = object
|
|
.get("input_fingerprint")
|
|
.and_then(|value| value.as_str())
|
|
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
|
|
if canonical_input_fingerprint(&base_input)? != base_fingerprint {
|
|
return Err(TaskError::invalid("task executable input binding mismatch"));
|
|
}
|
|
object.insert(
|
|
"binding_format_version".to_owned(),
|
|
serde_json::json!(2_u32),
|
|
);
|
|
object.insert(
|
|
"continuation".to_owned(),
|
|
serde_json::json!({
|
|
"wait_id": wait_id,
|
|
"schema_revision": pending.schema_revision,
|
|
"effective_input_fingerprint": canonical_fingerprint,
|
|
"input": input,
|
|
}),
|
|
);
|
|
let continuation = crypto
|
|
.encrypt(&serde_json::Value::Object(object))
|
|
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
|
if continuation.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
|
|
return Err(TaskError::invalid(
|
|
"encrypted task input exceeds its byte budget",
|
|
));
|
|
}
|
|
let request = TaskInputUpdateRequest {
|
|
access: access.clone(),
|
|
task_id,
|
|
wait_id: wait_id.to_owned(),
|
|
expected_version,
|
|
update_key_digest,
|
|
effective_input_fingerprint: canonical_fingerprint.clone(),
|
|
canonical_fingerprint,
|
|
executable_input_ciphertext: continuation,
|
|
executable_input_key_version: crypto.key_version().to_owned(),
|
|
executable_input_master_key_epoch: crypto.master_key_epoch(),
|
|
};
|
|
self.store.apply_input(request).await
|
|
}
|
|
}
|
|
|
|
fn deadline_unix_ms(deadline: Instant) -> i64 {
|
|
let remaining = u64::try_from(
|
|
deadline
|
|
.saturating_duration_since(Instant::now())
|
|
.as_millis(),
|
|
)
|
|
.unwrap_or_default();
|
|
current_unix_ms().saturating_add(i64::try_from(remaining.max(1)).unwrap_or(i64::MAX))
|
|
}
|
|
|
|
/// Digest of the caller key over the full Task identity. The scope is never abbreviated to a
|
|
/// connection, protocol revision or raw credential, so two callers cannot collide on one key.
|
|
fn scoped_key_digest(draft: &TaskAcceptDraft) -> Result<String, TaskError> {
|
|
let key = draft.scoped_key.as_str();
|
|
if key.is_empty()
|
|
|| key.len() > TASK_SCOPED_KEY_MAX_BYTES
|
|
|| key.bytes().any(|byte| byte.is_ascii_control())
|
|
{
|
|
return Err(TaskError::invalid("task idempotency key is invalid"));
|
|
}
|
|
let material = format!(
|
|
"{}\n{}\n{}\n{}\n{}\n{}",
|
|
draft.workspace_id,
|
|
draft.owner_kind.as_str(),
|
|
draft.owner_id,
|
|
draft.authorization_scope,
|
|
draft.operation_id,
|
|
key
|
|
);
|
|
Ok(hex_digest(material.as_bytes()))
|
|
}
|
|
|
|
/// Canonical digest of the validated executable input. Object key order never changes the digest,
|
|
/// while any material business or secret value does.
|
|
fn canonical_input_fingerprint(input: &serde_json::Value) -> Result<String, TaskError> {
|
|
let canonical = crate::idempotency::canonical_json(input);
|
|
let encoded = serde_json::to_vec(&canonical)
|
|
.map_err(|_| TaskError::invalid("task input is not canonicalizable"))?;
|
|
Ok(hex_digest(&encoded))
|
|
}
|
|
|
|
fn hex_digest(bytes: &[u8]) -> String {
|
|
Sha256::digest(bytes)
|
|
.iter()
|
|
.map(|byte| format!("{byte:02x}"))
|
|
.collect()
|
|
}
|
|
|
|
fn check_binding_string(
|
|
object: &serde_json::Map<String, serde_json::Value>,
|
|
field: &str,
|
|
expected: &str,
|
|
) -> Result<(), TaskError> {
|
|
match object.get(field).and_then(|value| value.as_str()) {
|
|
Some(actual) if actual == expected => Ok(()),
|
|
_ => Err(TaskError::invalid("task executable input binding mismatch")),
|
|
}
|
|
}
|
|
|
|
fn validate_executable_payload(input: &serde_json::Value) -> Result<(), TaskError> {
|
|
validate_task_envelope(input)?;
|
|
let encoded = serde_json::to_vec(input)
|
|
.map_err(|_| TaskError::invalid("task executable input is not serializable"))?;
|
|
if encoded.len() > TASK_EXECUTABLE_INPUT_MAX_BYTES {
|
|
return Err(TaskError::invalid(
|
|
"task executable input exceeds its byte budget",
|
|
));
|
|
}
|
|
if contains_sensitive_task_keys(input) {
|
|
return Err(TaskError::invalid(
|
|
"task executable input contains sensitive fields",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Digest of the scoped update key. The key itself never leaves the caller, and the scope covers the
|
|
/// exact Task generation so one key cannot be replayed across Tasks or waits.
|
|
fn input_update_key_digest(
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
wait_id: &str,
|
|
key: &str,
|
|
) -> Result<String, TaskError> {
|
|
if key.is_empty()
|
|
|| key.len() > TASK_SCOPED_KEY_MAX_BYTES
|
|
|| key.bytes().any(|byte| byte.is_ascii_control())
|
|
{
|
|
return Err(TaskError::invalid("task input update key is invalid"));
|
|
}
|
|
let material = format!(
|
|
"{}\n{}\n{}\n{}\n{}\n{}\n{}",
|
|
access.workspace_id,
|
|
access.owner_kind.as_str(),
|
|
access.owner_id,
|
|
access.authorization_scope,
|
|
task_id,
|
|
wait_id,
|
|
key
|
|
);
|
|
Ok(hex_digest(material.as_bytes()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
fn draft(key: &str, input: serde_json::Value) -> TaskAcceptDraft {
|
|
TaskAcceptDraft {
|
|
workspace_id: "ws_default".to_owned(),
|
|
owner_kind: TaskOwnerKind::Agent,
|
|
owner_id: "agent_a".to_owned(),
|
|
authorization_scope: "credential:pk_1".to_owned(),
|
|
platform_api_key_id: Some(PlatformApiKeyId::new("pk_1")),
|
|
operation_id: "op_report".to_owned(),
|
|
operation_version: 2,
|
|
policy_mode: ToolExecutionMode::Background,
|
|
scoped_key: key.to_owned(),
|
|
input,
|
|
correlation: CorrelationContext::generate(),
|
|
deadline: Instant::now() + std::time::Duration::from_secs(30),
|
|
retention_ms: TASK_DEFAULT_RETENTION_MS,
|
|
approval_reference: None,
|
|
retry: crank_core::TaskRetryPolicy::single_attempt(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn canonical_fingerprint_ignores_key_order_and_tracks_values() {
|
|
let first = canonical_input_fingerprint(&json!({"a": 1, "b": {"c": 2}})).unwrap();
|
|
let reordered = canonical_input_fingerprint(&json!({"b": {"c": 2}, "a": 1})).unwrap();
|
|
assert_eq!(first, reordered);
|
|
assert_eq!(first.len(), 64);
|
|
|
|
let changed = canonical_input_fingerprint(&json!({"a": 1, "b": {"c": 3}})).unwrap();
|
|
assert_ne!(first, changed);
|
|
}
|
|
|
|
#[test]
|
|
fn scoped_key_digest_covers_the_whole_identity() {
|
|
let base = scoped_key_digest(&draft("key_1", json!({}))).unwrap();
|
|
let mut foreign = draft("key_1", json!({}));
|
|
foreign.owner_id = "agent_b".to_owned();
|
|
assert_ne!(base, scoped_key_digest(&foreign).unwrap());
|
|
|
|
let mut other_scope = draft("key_1", json!({}));
|
|
other_scope.authorization_scope = "credential:pk_2".to_owned();
|
|
assert_ne!(base, scoped_key_digest(&other_scope).unwrap());
|
|
|
|
assert!(scoped_key_digest(&draft("", json!({}))).is_err());
|
|
assert!(
|
|
scoped_key_digest(&draft(
|
|
&"k".repeat(TASK_SCOPED_KEY_MAX_BYTES + 1),
|
|
json!({})
|
|
))
|
|
.is_err()
|
|
);
|
|
}
|
|
}
|