story 2-12-preview-partial-mode: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
d1ba0bd0e4
commit
ab35d67177
56 files changed
+5801
-376
No files matched your search
@@ -1,5 +1,8 @@
|
||||
mod catalog;
|
||||
mod legacy_auth;
|
||||
mod plan_apply;
|
||||
mod semantic;
|
||||
use semantic::plan_digest_from_payload;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
@@ -14,7 +17,8 @@ const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||
const MAX_IMPORT_JOB_DOCUMENTS: usize = 32;
|
||||
const MAX_IMPORT_PLAN_ID_BYTES: usize = 128;
|
||||
const MAX_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const MAX_IMPORT_PLAN_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const DANGLING_OPENAPI_SOURCE_GRACE: time::Duration = time::Duration::minutes(5);
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -119,6 +123,25 @@ impl PostgresRegistry {
|
||||
});
|
||||
}
|
||||
let digest = plan_digest_from_payload(request.payload)?;
|
||||
let v2 = request
|
||||
.payload
|
||||
.get("schema_version")
|
||||
.and_then(Value::as_str)
|
||||
== Some("import-plan-v2");
|
||||
if v2 {
|
||||
semantic::validate_v2_metadata(request.payload)?;
|
||||
plan_apply::validate_v2_creation(&request, &digest)?;
|
||||
if request
|
||||
.payload
|
||||
.get("plan_reference")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(request.id.as_str())
|
||||
|| request.payload.get("job_id").and_then(Value::as_str)
|
||||
!= Some(request.job_id.as_str())
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "identity" });
|
||||
}
|
||||
}
|
||||
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
|
||||
@@ -195,12 +218,31 @@ impl PostgresRegistry {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
if v2 {
|
||||
semantic::validate_v2_sources(request.payload, &preview_payload)?;
|
||||
}
|
||||
|
||||
sqlx::query("select id from workspaces where id = $1 for update")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
if v2
|
||||
&& request
|
||||
.payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(
|
||||
catalog::catalog_revision(&mut *transaction, request.workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: request.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
// Authoritative re-check: any concurrent insert of this (workspace, id)
|
||||
// must also hold the workspace lock, so a winner cannot appear between
|
||||
// the fast-path check and the insert.
|
||||
@@ -878,22 +920,6 @@ fn map_import_plan(row: &PgRow) -> Result<ImportPlan, RegistryError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the canonical plan digest: the lowercase SHA-256 of the payload
|
||||
/// serialized to its deterministic byte form. `serde_json::Value` object keys
|
||||
/// are ordered (BTreeMap-backed map), so `to_vec` is stable across calls and
|
||||
/// platforms — the digest is therefore reproducible for byte-identical
|
||||
/// material without requiring a client-supplied digest.
|
||||
fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(payload)?;
|
||||
if canonical.len() > MAX_IMPORT_PLAN_PAYLOAD_BYTES {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
fn validate_plan_id(id: &ImportPlanId) -> Result<(), RegistryError> {
|
||||
if !(1..=MAX_IMPORT_PLAN_ID_BYTES).contains(&id.as_str().len()) {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "id" });
|
||||
@@ -936,6 +962,7 @@ fn plan_replay_outcome(
|
||||
) -> Result<ImportPlan, RegistryError> {
|
||||
let stored = map_import_plan(&existing)?;
|
||||
let replay = stored.digest == digest
|
||||
&& stored.payload == *request.payload
|
||||
&& stored.job_id == *request.job_id
|
||||
&& stored.created_at == created_at
|
||||
&& stored.expires_at == expires_at;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
use super::*;
|
||||
|
||||
// A bounded metadata read, independent of the size of stored schemas/Drafts.
|
||||
const MAX_IMPORT_CATALOG_ENTRIES: i64 = 10_000;
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn list_import_catalog_names(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Vec<String>, RegistryError> {
|
||||
let names = sqlx::query_scalar::<_, String>(
|
||||
"select name from operations where workspace_id = $1 order by name limit $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
if names.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
/// Deterministic workspace catalog identity for naming and version targets.
|
||||
/// Referenced authentication state is separately bound in plan snapshots.
|
||||
pub async fn import_catalog_revision(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<String, RegistryError> {
|
||||
catalog_revision(&self.pool, workspace_id, false).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn catalog_revision<'c, E>(
|
||||
executor: E,
|
||||
workspace_id: &WorkspaceId,
|
||||
lock: bool,
|
||||
) -> Result<String, RegistryError>
|
||||
where
|
||||
E: Executor<'c, Database = Postgres>,
|
||||
{
|
||||
let query = if lock {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2 for share"
|
||||
} else {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2"
|
||||
};
|
||||
let rows = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(executor)
|
||||
.await?;
|
||||
if rows.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
let metadata = rows
|
||||
.iter()
|
||||
.map(|row| row.try_get::<Value, _>("metadata"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(serde_json::to_vec(&metadata)?)
|
||||
))
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
mod material;
|
||||
mod mutations;
|
||||
mod revalidate;
|
||||
mod verify;
|
||||
|
||||
use material::*;
|
||||
@@ -20,7 +21,7 @@ const PLAN_PAYLOAD_SCHEMA_VERSION: &str = "import-plan-v1";
|
||||
const APPLY_REPORT_SCHEMA_VERSION: &str = "import-plan-apply-report-v1";
|
||||
/// Same upper bound as plan creation keeps the report compatible with every
|
||||
/// plan that was accepted: at most this many candidates / names / targets.
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 512;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
|
||||
@@ -30,10 +31,38 @@ const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
|
||||
/// Bound for the serialized apply report. Must accommodate a full accepted
|
||||
/// plan: report entries carry only key/name/ids (already bounded) while the
|
||||
/// plan payload — which carries far more per candidate — is capped at
|
||||
/// `MAX_IMPORT_PLAN_PAYLOAD_BYTES` (4 MiB) at creation. This keeps every
|
||||
/// `MAX_IMPORT_PLAN_PAYLOAD_BYTES` (16 MiB) at creation. This keeps every
|
||||
/// accepted plan's exact outcomes inside the report without truncation.
|
||||
const MAX_IMPORT_PLAN_REPORT_BYTES: usize = MAX_IMPORT_PLAN_PAYLOAD_BYTES;
|
||||
|
||||
pub(super) fn validate_v2_creation(
|
||||
request: &CreateImportPlanRequest<'_>,
|
||||
digest: &str,
|
||||
) -> Result<(), RegistryError> {
|
||||
let fingerprint =
|
||||
request
|
||||
.payload
|
||||
.get("fingerprint")
|
||||
.ok_or(RegistryError::InvalidImportPlan {
|
||||
field: "fingerprint",
|
||||
})?;
|
||||
let validation = ApplyImportPlanRequest {
|
||||
workspace_id: request.workspace_id,
|
||||
plan_id: request.id,
|
||||
plan_digest: digest,
|
||||
idempotency_key: "creation-validation",
|
||||
verified_fingerprint: fingerprint,
|
||||
applied_at: request.created_at,
|
||||
};
|
||||
read_and_validate_plan_material(
|
||||
request.payload,
|
||||
&validation,
|
||||
digest,
|
||||
request.job_id.as_str(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Failure of one apply transaction: a typed registry conflict, or the
|
||||
/// application-row uniqueness collision that must be reconciled after the
|
||||
/// transaction is rolled back.
|
||||
@@ -254,6 +283,20 @@ async fn apply_import_plan_transaction(
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::catalog::catalog_revision(&mut **tx, request.workspace_id, true)
|
||||
.await
|
||||
.map_err(fail)?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(fail(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Apply the selected candidates in deterministic order.
|
||||
let mut candidates: Vec<&StoredPlanCandidate> = plan.candidates.iter().collect();
|
||||
candidates.sort_by(|a, b| a.key.cmp(&b.key));
|
||||
|
||||
@@ -16,6 +16,16 @@ pub(super) struct StoredPlan {
|
||||
pub(crate) selection: StoredPlanSelection,
|
||||
pub(crate) counts: StoredPlanCounts,
|
||||
pub(crate) candidates: Vec<StoredPlanCandidate>,
|
||||
#[serde(default)]
|
||||
pub(crate) catalog_revision: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) excluded_reasons: Vec<StoredExcludedReason>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredExcludedReason {
|
||||
pub(crate) key: String,
|
||||
pub(crate) reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
@@ -172,18 +182,21 @@ pub(super) fn read_and_validate_plan_material(
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let v2 = payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2");
|
||||
let selected_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 512 };
|
||||
let all_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 1_024 };
|
||||
if payload
|
||||
.pointer("/selection/selected")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
|| payload
|
||||
.pointer("/selection/all")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS * 2)
|
||||
.is_some_and(|items| items.len() > all_limit)
|
||||
|| payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
@@ -219,12 +232,17 @@ pub(super) fn read_and_validate_plan_material(
|
||||
let plan: StoredPlan = serde_json::from_value(payload.clone()).map_err(|_| corrupt())?;
|
||||
|
||||
// The typed material must agree with the request it is being applied for.
|
||||
if plan.schema_version.as_str() != PLAN_PAYLOAD_SCHEMA_VERSION
|
||||
|| plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
if !matches!(
|
||||
plan.schema_version.as_str(),
|
||||
PLAN_PAYLOAD_SCHEMA_VERSION | "import-plan-v2"
|
||||
) || plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
|| plan.job_id != stored_job_id
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
super::super::semantic::validate_v2_metadata(payload).map_err(|_| corrupt())?;
|
||||
}
|
||||
|
||||
// Selection closure.
|
||||
if !matches!(plan.selection.mode.as_str(), "full" | "partial") {
|
||||
@@ -248,6 +266,30 @@ pub(super) fn read_and_validate_plan_material(
|
||||
let selected: BTreeSet<&String> = plan.selection.selected.iter().collect();
|
||||
let excluded: BTreeSet<&String> = plan.selection.excluded.iter().collect();
|
||||
let all: BTreeSet<&String> = plan.selection.all.iter().collect();
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let findings = payload
|
||||
.pointer("/findings/candidates")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(corrupt)?;
|
||||
let keys = findings
|
||||
.iter()
|
||||
.map(|item| {
|
||||
if !item.get("findings").is_some_and(Value::is_array) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
item.get("key").and_then(Value::as_str).ok_or_else(corrupt)
|
||||
})
|
||||
.collect::<Result<BTreeSet<_>, _>>()?;
|
||||
let expected = plan
|
||||
.selection
|
||||
.all
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if keys != expected || keys.len() != findings.len() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
let mut union = selected.clone();
|
||||
union.extend(excluded.iter());
|
||||
if union != all || selected.iter().any(|key| excluded.contains(key)) {
|
||||
@@ -256,6 +298,34 @@ pub(super) fn read_and_validate_plan_material(
|
||||
if plan.selection.mode == "full" && (!excluded.is_empty() || selected != all) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let reasons = plan
|
||||
.excluded_reasons
|
||||
.iter()
|
||||
.map(|item| &item.key)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if reasons != excluded
|
||||
|| reasons.len() != plan.excluded_reasons.len()
|
||||
|| plan.excluded_reasons.iter().any(|item| {
|
||||
item.reason.is_empty() || item.reason.len() > MAX_IMPORT_PLAN_REASON_BYTES
|
||||
})
|
||||
|| !plan
|
||||
.excluded_reasons
|
||||
.windows(2)
|
||||
.all(|items| items[0].key < items[1].key)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.selection.mode == "partial"
|
||||
&& plan
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|candidate| candidate.state != "actionable")
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let candidate_keys: BTreeSet<&String> = plan
|
||||
.candidates
|
||||
.iter()
|
||||
|
||||
@@ -203,7 +203,13 @@ fn excluded_outcomes(plan: &StoredPlan) -> Vec<ImportPlanCandidateReport> {
|
||||
outcome: ImportPlanCandidateOutcome::Excluded,
|
||||
operation_id: None,
|
||||
version: None,
|
||||
reason: Some("not_selected".to_owned()),
|
||||
reason: Some(
|
||||
plan.excluded_reasons
|
||||
.iter()
|
||||
.find(|item| item.key == *key)
|
||||
.map(|item| item.reason.clone())
|
||||
.unwrap_or_else(|| "not_selected".to_owned()),
|
||||
),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Reopens immutable plan evidence without applying it or writing a report.
|
||||
/// The result is current validation evidence, never a promise about a later
|
||||
/// Apply; Apply independently repeats its checks inside its transaction.
|
||||
pub async fn revalidate_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
verified_fingerprint: &Value,
|
||||
) -> Result<(), RegistryError> {
|
||||
let plan = self
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanNotFound {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
})?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id,
|
||||
plan_id,
|
||||
plan_digest: &plan.digest,
|
||||
idempotency_key: "read-only-revalidation",
|
||||
verified_fingerprint,
|
||||
applied_at: &now,
|
||||
};
|
||||
let material = read_and_validate_plan_material(
|
||||
&plan.payload,
|
||||
&request,
|
||||
&plan.digest,
|
||||
plan.job_id.as_str(),
|
||||
)?;
|
||||
let job = self
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: plan.job_id.as_str().to_owned(),
|
||||
})?;
|
||||
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanJobTerminal {
|
||||
job_id: job.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
verify_job_source_consistency(&job.preview_payload, &material, plan_id.as_str())?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let mut envelopes = material
|
||||
.dependencies
|
||||
.iter()
|
||||
.chain(std::iter::once(&material.source))
|
||||
.map(|source| ImportJobSourceEnvelope {
|
||||
source_id: ArtifactSourceId::new(source.source_id.clone()),
|
||||
digest: ArtifactRef::parse(&source.digest).expect("material was validated"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
envelopes.sort_by(|a, b| a.source_id.as_str().cmp(b.source_id.as_str()));
|
||||
for envelope in &envelopes {
|
||||
lock_and_verify_envelope(&mut tx, workspace_id, envelope).await?;
|
||||
}
|
||||
lock_and_verify_auth(&mut tx, workspace_id, &material.candidates).await?;
|
||||
if material.schema_version == "import-plan-v2"
|
||||
&& material.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::super::catalog::catalog_revision(&mut *tx, workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
for candidate in &material.candidates {
|
||||
if let Some(target) = &candidate.target {
|
||||
let row = sqlx::query("select name, status, current_draft_version, latest_published_version from operations where workspace_id = $1 and id = $2 for share")
|
||||
.bind(workspace_id.as_str()).bind(&target.operation_id).fetch_optional(&mut *tx).await?;
|
||||
let matching = match row {
|
||||
Some(row) => {
|
||||
row.try_get::<String, _>("name")? == target.name
|
||||
&& deserialize_enum_text::<OperationStatus>(
|
||||
row.try_get("status")?,
|
||||
"status",
|
||||
)? == target.expected_state.status
|
||||
&& row.try_get::<i32, _>("current_draft_version")? as u32
|
||||
== target.expected_state.current_draft_version
|
||||
&& row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| value as u32)
|
||||
== target.expected_state.latest_published_version
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !matching {
|
||||
return Err(RegistryError::ImportPlanTargetStale {
|
||||
operation_id: target.operation_id.clone(),
|
||||
});
|
||||
}
|
||||
} else if candidate.state == "actionable"
|
||||
&& operation_name_exists(&mut tx, workspace_id, &candidate.name).await?
|
||||
{
|
||||
return Err(RegistryError::ImportPlanNameConflict {
|
||||
name: candidate.name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
tx.rollback().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use super::*;
|
||||
|
||||
/// Derives the canonical plan digest: the lowercase SHA-256 of the payload
|
||||
/// serialized to its deterministic byte form. `serde_json::Value` object keys
|
||||
/// are ordered (BTreeMap-backed map), so `to_vec` is stable across calls and
|
||||
/// platforms — the digest is therefore reproducible for byte-identical
|
||||
/// material without requiring a client-supplied digest.
|
||||
pub(super) fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let limit = if payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2") {
|
||||
MAX_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
} else {
|
||||
MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
};
|
||||
if serde_json::to_vec(payload)?.len() > limit {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(&canonical_material(payload))?;
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_sources(payload: &Value, preview: &Value) -> Result<(), RegistryError> {
|
||||
let dependency_set =
|
||||
|value: &Value| -> Result<std::collections::BTreeSet<(String, String)>, RegistryError> {
|
||||
Ok(dependencies_from_payload(value)?
|
||||
.iter()
|
||||
.map(|source| {
|
||||
(
|
||||
source.source_id.as_str().to_owned(),
|
||||
source.digest.as_str().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
};
|
||||
if source_from_payload(payload)? != source_from_payload(preview)?
|
||||
|| dependency_set(payload)? != dependency_set(preview)?
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "source" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes only server-generated envelope fields from v2 semantic material.
|
||||
/// Paths are explicit: equally named fields in a user schema remain semantic.
|
||||
pub(super) fn canonical_material(payload: &Value) -> Value {
|
||||
let mut material = payload.clone();
|
||||
if payload.get("schema_version").and_then(Value::as_str) != Some("import-plan-v2") {
|
||||
return material;
|
||||
}
|
||||
let object = material.as_object_mut().expect("validated object");
|
||||
object.remove("plan_reference");
|
||||
object.remove("job_id");
|
||||
if let Some(source) = object.get_mut("source").and_then(Value::as_object_mut) {
|
||||
source.remove("source_id");
|
||||
}
|
||||
if let Some(dependencies) = object.get_mut("dependencies").and_then(Value::as_array_mut) {
|
||||
for dependency in dependencies.iter_mut() {
|
||||
if let Some(source) = dependency.as_object_mut() {
|
||||
source.remove("source_id");
|
||||
}
|
||||
}
|
||||
dependencies.sort_by_key(Value::to_string);
|
||||
}
|
||||
if let Some(candidates) = object.get_mut("candidates").and_then(Value::as_array_mut) {
|
||||
for candidate in candidates {
|
||||
let generated = matches!(
|
||||
candidate
|
||||
.pointer("/decision/action")
|
||||
.and_then(Value::as_str),
|
||||
Some("create" | "rename")
|
||||
);
|
||||
if let Some(operation) = candidate
|
||||
.get_mut("operation")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
if generated {
|
||||
operation.remove("id");
|
||||
}
|
||||
operation.remove("created_at");
|
||||
operation.remove("updated_at");
|
||||
operation.remove("published_at");
|
||||
}
|
||||
if let Some(snapshot) = candidate
|
||||
.get_mut("auth_snapshot")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
snapshot.remove("updated_at");
|
||||
if let Some(secrets) = snapshot.get_mut("secrets").and_then(Value::as_array_mut) {
|
||||
for secret in secrets {
|
||||
if let Some(secret) = secret.as_object_mut() {
|
||||
secret.remove("updated_at");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
material
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_metadata(payload: &Value) -> Result<(), RegistryError> {
|
||||
let invalid = || RegistryError::InvalidImportPlan { field: "metadata" };
|
||||
let revision = payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if revision.len() != 64
|
||||
|| !revision
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let matrix = payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if matrix.is_empty() || matrix.len() > 64 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let findings = payload
|
||||
.get("findings")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(invalid)?;
|
||||
if !findings.get("document").is_some_and(Value::is_array)
|
||||
|| !findings.get("candidates").is_some_and(Value::is_array)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::plan_digest_from_payload;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn payload() -> Value {
|
||||
json!({
|
||||
"schema_version": "import-plan-v2", "plan_reference": "plan_a", "job_id": "job_a",
|
||||
"catalog_revision": "a".repeat(64), "support_matrix_version": "1.0.2",
|
||||
"source": {"source_id": "src_a", "digest": format!("sha256:{}", "b".repeat(64))},
|
||||
"dependencies": [{"source_id": "dep_a", "digest": format!("sha256:{}", "c".repeat(64))}],
|
||||
"findings": {"document": [], "candidates": []},
|
||||
"selection": {"mode": "full", "selected": ["GET /a"], "excluded": [], "all": ["GET /a"]},
|
||||
"candidates": [{
|
||||
"key": "GET /a", "decision": {"action": "create"},
|
||||
"operation": {"id": "op_a", "created_at": "time_a", "updated_at": "time_a",
|
||||
"input_schema": {"properties": {"id": {"default": "semantic_id"}, "created_at": {"default": "semantic_time"}}}},
|
||||
"auth_snapshot": {"profile_id": "auth_a", "updated_at": "time_a", "secrets": [
|
||||
{"id": "secret_a", "current_version": 1, "status": "active", "updated_at": "time_a"}
|
||||
]}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_v2_material_ignores_only_identity_envelope_and_runtime_instants() {
|
||||
let first = payload();
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("plan_b");
|
||||
second["job_id"] = json!("job_b");
|
||||
second["source"]["source_id"] = json!("src_b");
|
||||
second["dependencies"][0]["source_id"] = json!("dep_b");
|
||||
second["candidates"][0]["operation"]["id"] = json!("op_b");
|
||||
second["candidates"][0]["operation"]["created_at"] = json!("time_b");
|
||||
second["candidates"][0]["operation"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["secrets"][0]["updated_at"] = json!("time_b");
|
||||
assert_eq!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_semantic_changes_and_schema_fields_named_like_runtime_fields_change_digest() {
|
||||
let first = payload();
|
||||
for pointer in [
|
||||
"/catalog_revision",
|
||||
"/support_matrix_version",
|
||||
"/source/digest",
|
||||
"/candidates/0/decision/action",
|
||||
"/candidates/0/auth_snapshot/secrets/0/current_version",
|
||||
"/candidates/0/operation/input_schema/properties/id/default",
|
||||
"/candidates/0/operation/input_schema/properties/created_at/default",
|
||||
] {
|
||||
let mut changed = first.clone();
|
||||
*changed.pointer_mut(pointer).unwrap() = json!("changed");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&changed).unwrap(),
|
||||
"{pointer}"
|
||||
);
|
||||
}
|
||||
let mut target = first.clone();
|
||||
target["candidates"][0]["decision"]["action"] = json!("new_version");
|
||||
let mut changed_target = target.clone();
|
||||
changed_target["candidates"][0]["operation"]["id"] = json!("different_existing_target");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&target).unwrap(),
|
||||
plan_digest_from_payload(&changed_target).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_payload_digest_still_covers_runtime_and_identity_fields() {
|
||||
let mut first = payload();
|
||||
first["schema_version"] = json!("import-plan-v1");
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("other");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_payload_budget_grows_without_changing_the_legacy_budget() {
|
||||
let mut large =
|
||||
json!({"schema_version": "import-plan-v1", "evidence": "x".repeat(5 * 1024 * 1024)});
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
large["schema_version"] = json!("import-plan-v2");
|
||||
assert!(plan_digest_from_payload(&large).is_ok());
|
||||
large["evidence"] = json!("x".repeat(16 * 1024 * 1024));
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user