231 lines
9.3 KiB
Rust
231 lines
9.3 KiB
Rust
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());
|
|
}
|
|
}
|