Files
crank/crates/crank-import/src/rest/source_safety.rs
T

83 lines
2.9 KiB
Rust

use crate::rest::model::{ExternalDocumentSnapshot, SourceDigest};
use super::model::NormalizationConfig;
use super::{
metadata_findings,
normalize::{ImportParseError, decode, validate_value_limits},
normalize_limits, reference,
};
/// Rejects a source bundle containing credential-like literals before any
/// primary or dependency bytes are persisted. Credential names are collected
/// across all raw documents so split `$ref` targets receive the same checks.
pub fn validate_document_bundle_source_safe(
documents: &[&str],
config: &NormalizationConfig,
) -> Result<(), ImportParseError> {
config
.validate_versions()
.map_err(|_| ImportParseError::UnsupportedDocument)?;
let mut roots = Vec::with_capacity(documents.len());
for document in documents {
if document.len() > config.max_bytes
|| normalize_limits::alias_count(document) > config.max_aliases
{
return Err(ImportParseError::LimitExceeded);
}
let root = decode(document)?;
validate_value_limits(&root, config)?;
roots.push(root);
}
let declared_names = metadata_findings::credential_names(roots.iter());
for mut root in roots {
let mut findings = Vec::new();
let mut locations = Vec::new();
metadata_findings::redact_secret_like_literals_with_names(
&mut root,
"",
&declared_names,
&mut findings,
&mut locations,
);
if !findings.is_empty() {
return Err(ImportParseError::InvalidDocument);
}
}
Ok(())
}
/// Validates the resolved source tree with the same security-aware traversal
/// used by normalization, before a caller persists any bytes in the bundle.
pub fn validate_resolved_bundle_source_safe(
document: &str,
digest: SourceDigest,
snapshots: &[ExternalDocumentSnapshot],
config: &NormalizationConfig,
) -> Result<(), ImportParseError> {
config
.validate_versions()
.map_err(|_| ImportParseError::UnsupportedDocument)?;
if document.len() > config.max_bytes
|| normalize_limits::alias_count(document) > config.max_aliases
{
return Err(ImportParseError::LimitExceeded);
}
let root = decode(document)?;
validate_value_limits(&root, config)?;
for snapshot in snapshots {
if snapshot.document.len() > config.max_external_document_bytes {
return Err(ImportParseError::LimitExceeded);
}
}
let resolution = reference::resolve(root, digest, snapshots, config)?;
let mut root = resolution.root;
validate_value_limits(&root, config)?;
let mut findings = Vec::new();
let mut locations = Vec::new();
metadata_findings::redact_secret_like_literals(&mut root, "", &mut findings, &mut locations);
if !findings.is_empty() {
return Err(ImportParseError::InvalidDocument);
}
Ok(())
}