use std::fmt::{self, Write as _};
use crate::VERSION;
use crate::action_policy::MAX_ACTION_POLICY_BYTES;
use crate::composition::Composition;
use crate::detectors::{
BUILT_IN_PACKS, Pack, built_in_detectors, common_built_in_detectors, declared_common_types,
declared_types,
};
use crate::limits::{DEFAULT_MAX_FINDINGS, DEFAULT_MAX_INPUT_BYTES};
use crate::pii::available_families;
use crate::registry::Profile;
use crate::sha256::{sha256, to_hex};
const SCHEMA_PREFIX: &str = "{\"schema\":\"artifact-manifest/v1\",";
const DETECTOR_IDS_MAX: usize = 256;
const DIAGNOSTICS_MAX: usize = 256;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArtifactKind {
Wasm,
NodeAddon,
PythonWheel,
Cli,
RustRegistry,
}
impl ArtifactKind {
const fn supports_detector_selection(self) -> bool {
matches!(self, Self::Wasm | Self::NodeAddon | Self::RustRegistry)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Wasm => "wasm",
Self::NodeAddon => "node-addon",
Self::PythonWheel => "python-wheel",
Self::Cli => "cli",
Self::RustRegistry => "rust-registry",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArtifactManifestError {
Missing,
SchemaMismatch,
DigestMismatch,
InvalidSourceRevision,
}
impl ArtifactManifestError {
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::Missing => "ARTIFACT_MANIFEST_MISSING",
Self::SchemaMismatch => "ARTIFACT_MANIFEST_SCHEMA_MISMATCH",
Self::DigestMismatch => "ARTIFACT_MANIFEST_DIGEST_MISMATCH",
Self::InvalidSourceRevision => "ARTIFACT_MANIFEST_INVALID_SOURCE_REVISION",
}
}
#[must_use]
pub const fn message(self) -> &'static str {
match self {
Self::Missing => "The artifact manifest is missing.",
Self::SchemaMismatch => "The artifact manifest schema is not supported.",
Self::DigestMismatch => "The artifact manifest does not match this artifact.",
Self::InvalidSourceRevision => "The artifact source revision is invalid.",
}
}
}
impl fmt::Display for ArtifactManifestError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.message())
}
}
impl std::error::Error for ArtifactManifestError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactManifest {
profile: Profile,
kind: ArtifactKind,
pii: bool,
selection: bool,
ids: Vec<&'static str>,
declared: Vec<(&'static str, &'static [&'static str])>,
not_included: Vec<&'static str>,
composition_id: Option<String>,
digest: String,
json: String,
}
struct Entry {
id: &'static str,
pack: &'static str,
types: &'static [&'static str],
}
impl ArtifactManifest {
pub const SCHEMA: &'static str = "artifact-manifest/v1";
pub fn full(
kind: ArtifactKind,
pii: bool,
source_revision: Option<&str>,
) -> Result<Self, ArtifactManifestError> {
let entries = built_in_detectors().iter().map(|row| Entry {
id: row.id,
pack: pack_name(row.id),
types: declared_types(row.id).unwrap_or_default(),
});
Self::assemble(Profile::Full, kind, pii, source_revision, None, entries)
}
pub fn common(
kind: ArtifactKind,
pii: bool,
source_revision: Option<&str>,
) -> Result<Self, ArtifactManifestError> {
let entries = common_built_in_detectors().iter().map(|row| Entry {
id: row.id,
pack: pack_name(row.id),
types: declared_common_types(row.id).unwrap_or_default(),
});
Self::assemble(Profile::Common, kind, pii, source_revision, None, entries)
}
pub fn custom(
kind: ArtifactKind,
composition: &Composition,
source_revision: Option<&str>,
) -> Result<Self, ArtifactManifestError> {
let entries = composition.selected().iter().map(|selected| Entry {
id: selected.id,
pack: pack_name(selected.id),
types: selected.types,
});
Self::assemble(
Profile::Custom,
kind,
composition.pii(),
source_revision,
Some(composition.id()),
entries,
)
}
fn assemble(
profile: Profile,
kind: ArtifactKind,
pii: bool,
source_revision: Option<&str>,
composition_id: Option<&str>,
entries: impl Iterator<Item = Entry>,
) -> Result<Self, ArtifactManifestError> {
if source_revision.is_some_and(|revision| !is_revision(revision)) {
return Err(ArtifactManifestError::InvalidSourceRevision);
}
let entries: Vec<Entry> = entries.collect();
let ids: Vec<&'static str> = entries.iter().map(|entry| entry.id).collect();
let declared = entries
.iter()
.map(|entry| (entry.id, entry.types))
.collect();
let not_included: Vec<&'static str> = BUILT_IN_PACKS
.iter()
.map(|(id, _)| *id)
.filter(|id| !ids.contains(id))
.collect();
let selection = kind.supports_detector_selection();
let members = Members::new(
profile,
kind,
pii,
selection,
source_revision,
composition_id,
&entries,
¬_included,
);
let canonical = members.render(None);
let digest = format!("sha256:{}", to_hex(&sha256(canonical.as_bytes())));
let json = members.render(Some(&digest));
Ok(Self {
profile,
kind,
pii,
selection,
ids,
declared,
not_included,
composition_id: composition_id.map(str::to_owned),
digest,
json,
})
}
#[must_use]
pub const fn profile(&self) -> Profile {
self.profile
}
#[must_use]
pub fn composition_id(&self) -> Option<&str> {
self.composition_id.as_deref()
}
#[must_use]
pub const fn kind(&self) -> ArtifactKind {
self.kind
}
#[must_use]
pub const fn pii_linked(&self) -> bool {
self.pii
}
#[must_use]
pub const fn detector_selection(&self) -> bool {
self.selection
}
pub fn detector_ids(&self) -> impl Iterator<Item = &str> {
self.ids.iter().copied()
}
pub(crate) fn declared_types(
&self,
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> + '_ {
self.declared.iter().copied()
}
pub fn not_included_ids(&self) -> impl Iterator<Item = &str> {
self.not_included.iter().copied()
}
#[must_use]
pub fn digest(&self) -> &str {
&self.digest
}
#[must_use]
pub fn as_json(&self) -> &str {
&self.json
}
pub fn verify_packaged(&self, packaged: Option<&str>) -> Result<(), ArtifactManifestError> {
let Some(document) = packaged else {
return Err(ArtifactManifestError::Missing);
};
if !document.starts_with(SCHEMA_PREFIX) {
return Err(ArtifactManifestError::SchemaMismatch);
}
if document != self.json {
return Err(ArtifactManifestError::DigestMismatch);
}
Ok(())
}
}
fn is_revision(value: &str) -> bool {
value.len() == 40
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
struct Members {
artifact: String,
bounds: String,
capabilities: String,
composition: String,
defaults: &'static str,
detectors: String,
not_included: String,
pii: String,
source_revision: String,
type_vocabulary: &'static str,
version: String,
}
impl Members {
#[allow(clippy::too_many_arguments)] fn new(
profile: Profile,
kind: ArtifactKind,
pii: bool,
selection: bool,
source_revision: Option<&str>,
composition_id: Option<&str>,
entries: &[Entry],
not_included: &[&'static str],
) -> Self {
let profile_name = profile.as_str();
let mut artifact = String::from("{\"kind\":");
push_string(&mut artifact, kind.as_str());
let _ = write!(artifact, ",\"pii\":{pii},\"variant\":");
push_string(&mut artifact, profile_name);
artifact.push('}');
let mut composition = String::from("{\"id\":");
match composition_id {
Some(id) => push_string(&mut composition, id),
None => composition.push_str("null"),
}
composition.push_str(",\"kind\":");
push_string(
&mut composition,
if composition_id.is_some() {
"custom"
} else {
"standard"
},
);
composition.push_str(",\"profile\":");
push_string(&mut composition, profile_name);
composition.push('}');
let mut pii_block = String::new();
let _ = write!(pii_block, "{{\"available\":{pii},\"families\":");
push_array(
&mut pii_block,
if pii {
available_families().iter().copied()
} else {
[].iter().copied()
},
);
pii_block.push('}');
let mut source = String::new();
match source_revision {
Some(revision) => push_string(&mut source, revision),
None => source.push_str("null"),
}
let mut version = String::new();
push_string(&mut version, VERSION);
let mut not_included_json = String::new();
push_array(&mut not_included_json, not_included.iter().copied());
let mut bounds = String::new();
let _ = write!(
bounds,
"{{\"actionPolicyBytes\":{MAX_ACTION_POLICY_BYTES},\
\"detectorIdsMax\":{DETECTOR_IDS_MAX},\
\"diagnosticsMax\":{DIAGNOSTICS_MAX},\
\"limits\":{{\"maxFindings\":{DEFAULT_MAX_FINDINGS},\
\"maxInputBytes\":{DEFAULT_MAX_INPUT_BYTES}}}}}"
);
Self {
artifact,
bounds,
capabilities: format!(
"{{\"actionPolicy\":{{\"revisions\":[1]}},\"detectorSelection\":{selection},\
\"incremental\":true,\"ruleset\":{{\"revisions\":[1]}}}}"
),
composition,
defaults: "{\"actionPolicy\":\"artifact-default\",\"detection\":\"all-included\",\
\"limits\":\"artifact-default\",\"pii\":{\"selectors\":[]},\
\"schema\":\"build-defaults/v1\"}",
detectors: detectors_json(entries),
not_included: not_included_json,
pii: pii_block,
source_revision: source,
type_vocabulary: "{\"builtInTypes\":\"declared\",\"complete\":false,\
\"dynamicSources\":[\"custom-detector\",\"pii\",\"ruleset\"]}",
version,
}
}
fn render(&self, digest: Option<&str>) -> String {
let quoted_digest = digest.map(|value| ["\"", value, "\""].concat());
let schema = "\"artifact-manifest/v1\"";
let rows: [(&str, &str); 14] = [
("artifact", &self.artifact),
("bounds", &self.bounds),
("capabilities", &self.capabilities),
("composition", &self.composition),
("defaults", self.defaults),
("detectors", &self.detectors),
("digest", quoted_digest.as_deref().unwrap_or("")),
("notIncluded", &self.not_included),
("pii", &self.pii),
("product", "\"redact-secret\""),
("schema", schema),
("sourceRevision", &self.source_revision),
("typeVocabulary", self.type_vocabulary),
("version", &self.version),
];
let mut out = String::from("{");
let mut first = true;
if digest.is_some() {
out.push_str("\"schema\":");
out.push_str(schema);
first = false;
}
for (name, value) in rows {
let skipped = value.is_empty() || (digest.is_some() && name == "schema");
if skipped {
continue;
}
if !first {
out.push(',');
}
first = false;
out.push('"');
out.push_str(name);
out.push_str("\":");
out.push_str(value);
}
out.push('}');
out
}
}
fn detectors_json(entries: &[Entry]) -> String {
let mut out = String::from("[");
for (index, entry) in entries.iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str("{\"aliases\":[],\"id\":");
push_string(&mut out, entry.id);
out.push_str(",\"pack\":");
push_string(&mut out, entry.pack);
out.push_str(",\"types\":");
push_array(&mut out, entry.types.iter().copied());
out.push('}');
}
out.push(']');
out
}
fn pack_name(id: &str) -> &'static str {
match BUILT_IN_PACKS.iter().find(|(known, _)| *known == id) {
Some((_, Pack::Common)) => "common",
_ => "provider",
}
}
fn push_string(out: &mut String, value: &str) {
out.push('"');
for character in value.chars() {
match character {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
other if other.is_ascii() && !other.is_ascii_control() => out.push(other),
_ => out.push('?'),
}
}
out.push('"');
}
fn push_array<'a>(out: &mut String, items: impl Iterator<Item = &'a str>) {
out.push('[');
for (index, item) in items.enumerate() {
if index > 0 {
out.push(',');
}
push_string(out, item);
}
out.push(']');
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DetectorRegistry;
const REVISION: &str = "0123456789abcdef0123456789abcdef01234567";
fn full() -> ArtifactManifest {
ArtifactManifest::full(ArtifactKind::RustRegistry, true, None).expect("manifest")
}
fn common() -> ArtifactManifest {
ArtifactManifest::common(ArtifactKind::RustRegistry, true, None).expect("manifest")
}
fn custom() -> ArtifactManifest {
let composition = Composition::new(
"edge-checks",
false,
[
crate::composition::github_token(),
crate::composition::jwt(),
crate::composition::generic_token(),
],
)
.expect("composition");
ArtifactManifest::custom(ArtifactKind::Wasm, &composition, None).expect("manifest")
}
#[test]
fn full_ids_are_the_registered_ids_in_order() {
let registry = DetectorRegistry::with_built_in([]).expect("registry");
let registered: Vec<&str> = registry.ids().collect();
let manifest = full();
let listed: Vec<&str> = manifest.detector_ids().collect();
assert_eq!(listed, registered);
assert_eq!(manifest.not_included_ids().count(), 0);
}
#[test]
fn common_ids_are_the_registered_ids_and_the_rest_are_not_included() {
let registry = DetectorRegistry::with_common_built_in([]).expect("registry");
let registered: Vec<&str> = registry.ids().collect();
let manifest = common();
let listed: Vec<&str> = manifest.detector_ids().collect();
assert_eq!(listed, registered);
let full_manifest = full();
let full_ids: Vec<&str> = full_manifest.detector_ids().collect();
let mut partition: Vec<&str> = manifest
.detector_ids()
.chain(manifest.not_included_ids())
.collect();
partition.sort_unstable();
let mut expected = full_ids;
expected.sort_unstable();
assert_eq!(partition, expected);
assert!(manifest.not_included_ids().all(|id| !listed.contains(&id)));
}
#[test]
fn generation_is_deterministic_and_profile_specific() {
assert_eq!(full(), full());
assert_eq!(common(), common());
assert_ne!(full().digest(), common().digest());
assert_ne!(
full().digest(),
ArtifactManifest::full(ArtifactKind::Wasm, true, None)
.expect("manifest")
.digest()
);
assert_ne!(
full().digest(),
ArtifactManifest::full(ArtifactKind::RustRegistry, false, None)
.expect("manifest")
.digest()
);
}
#[test]
fn document_starts_with_the_schema_and_ends_with_the_digest_member_in_order() {
let manifest = full();
let json = manifest.as_json();
assert!(json.starts_with(SCHEMA_PREFIX));
assert!(json.ends_with('}'));
assert!(json.is_ascii());
assert!(!json.contains(' '));
assert!(json.contains(&format!("\"digest\":\"{}\"", manifest.digest())));
assert_eq!(manifest.digest().len(), "sha256:".len() + 64);
let mut last = 0;
for name in [
"\"artifact\":",
"\"bounds\":",
"\"capabilities\":",
"\"composition\":",
"\"defaults\":",
"\"detectors\":",
"\"digest\":",
"\"notIncluded\":",
"\"pii\":{\"available\"",
"\"product\":",
"\"sourceRevision\":",
"\"typeVocabulary\":",
"\"version\":",
] {
let at = json.find(name).expect("member present");
assert!(at > last, "{name} out of order");
last = at;
}
}
#[test]
fn pii_families_are_listed_only_when_the_runtime_is_linked() {
let on = full();
assert!(
on.as_json()
.contains("\"pii\":{\"available\":true,\"families\":[\"pii:global:email\"")
);
let off = ArtifactManifest::full(ArtifactKind::Wasm, false, None).expect("manifest");
assert!(
off.as_json()
.contains("\"pii\":{\"available\":false,\"families\":[]}")
);
assert!(!off.pii_linked());
}
#[test]
fn source_revision_is_null_or_validated() {
assert!(full().as_json().contains("\"sourceRevision\":null"));
let pinned = ArtifactManifest::full(ArtifactKind::Cli, true, Some(REVISION)).expect("ok");
assert!(
pinned
.as_json()
.contains(&format!("\"sourceRevision\":\"{REVISION}\""))
);
for bad in ["", "abc", &REVISION.to_uppercase(), &format!("{REVISION}0")] {
assert_eq!(
ArtifactManifest::full(ArtifactKind::Cli, true, Some(bad)),
Err(ArtifactManifestError::InvalidSourceRevision)
);
}
}
#[test]
fn dynamic_types_are_not_presented_as_a_closed_vocabulary() {
let json = full().as_json().to_owned();
assert!(
json.contains("\"typeVocabulary\":{\"builtInTypes\":\"declared\",\"complete\":false,")
);
assert!(json.contains("\"dynamicSources\":[\"custom-detector\",\"pii\",\"ruleset\"]"));
}
#[test]
fn a_common_manifest_names_no_provider_type() {
let json = common().as_json().to_owned();
assert!(json.contains("\"id\":\"jwt\""));
assert!(!json.contains("github_token"));
assert!(json.contains("\"notIncluded\":[\"aws-access-key\""));
}
#[test]
fn verification_has_fixed_bounded_diagnostics() {
let manifest = full();
assert_eq!(manifest.verify_packaged(Some(manifest.as_json())), Ok(()));
assert_eq!(
manifest.verify_packaged(None),
Err(ArtifactManifestError::Missing)
);
assert_eq!(
manifest.verify_packaged(Some("")),
Err(ArtifactManifestError::SchemaMismatch)
);
assert_eq!(
manifest.verify_packaged(Some("{\"schema\":\"artifact-manifest/v2\"}")),
Err(ArtifactManifestError::SchemaMismatch)
);
assert_eq!(
manifest.verify_packaged(Some(common().as_json())),
Err(ArtifactManifestError::DigestMismatch)
);
let tampered =
manifest
.as_json()
.replacen("\"incremental\":true", "\"incremental\":false", 1);
assert_eq!(
manifest.verify_packaged(Some(&tampered)),
Err(ArtifactManifestError::DigestMismatch)
);
for error in [
ArtifactManifestError::Missing,
ArtifactManifestError::SchemaMismatch,
ArtifactManifestError::DigestMismatch,
ArtifactManifestError::InvalidSourceRevision,
] {
assert_eq!(error.to_string(), error.message());
assert!(error.code().starts_with("ARTIFACT_MANIFEST_"));
assert!(error.message().len() < 64);
}
}
fn canonical(value: &serde_json::Value) -> String {
serde_json::to_string(value).expect("serializes")
}
#[test]
fn digest_is_the_sha256_of_the_canonical_document_without_digest() {
for manifest in [full(), common(), custom()] {
let mut value: serde_json::Value =
serde_json::from_str(manifest.as_json()).expect("valid JSON");
let object = value.as_object_mut().expect("object");
let digest = object.remove("digest").expect("digest member");
assert_eq!(digest, manifest.digest());
let expected = format!("sha256:{}", to_hex(&sha256(canonical(&value).as_bytes())));
assert_eq!(manifest.digest(), expected);
let mut with_digest = value.clone();
with_digest["digest"] = serde_json::Value::String(expected);
let rendered = canonical(&with_digest);
let moved = rendered.replacen(
"{\"artifact\":",
&format!("{SCHEMA_PREFIX}\"artifact\":"),
1,
);
let without_schema = moved.replacen(
&format!(",\"schema\":\"{}\"", ArtifactManifest::SCHEMA),
"",
1,
);
assert_eq!(without_schema, manifest.as_json());
}
}
#[test]
fn a_custom_manifest_lists_the_composition_and_its_complement() {
let manifest = custom();
assert_eq!(manifest.profile(), Profile::Custom);
let listed: Vec<&str> = manifest.detector_ids().collect();
assert_eq!(listed, ["github-token", "jwt", "generic-token"]);
assert_eq!(
manifest.not_included_ids().count(),
BUILT_IN_PACKS.len() - 3
);
let value: serde_json::Value = serde_json::from_str(manifest.as_json()).expect("JSON");
assert_eq!(value["artifact"]["variant"], "custom");
assert_eq!(value["composition"]["kind"], "custom");
assert_eq!(value["composition"]["profile"], "custom");
let id = manifest.composition_id().expect("custom id");
assert_eq!(value["composition"]["id"], id);
assert!(id.starts_with("custom:") && id.len() == "custom:".len() + 64);
assert_eq!(full().composition_id(), None);
assert_ne!(custom().digest(), full().digest());
let renamed = Composition::new(
"other-name",
false,
[
crate::composition::github_token(),
crate::composition::jwt(),
crate::composition::generic_token(),
],
)
.expect("composition");
assert_ne!(
ArtifactManifest::custom(ArtifactKind::Wasm, &renamed, None)
.expect("manifest")
.digest(),
custom().digest()
);
}
#[test]
fn artifact_kinds_have_their_wire_names() {
for (kind, name) in [
(ArtifactKind::Wasm, "wasm"),
(ArtifactKind::NodeAddon, "node-addon"),
(ArtifactKind::PythonWheel, "python-wheel"),
(ArtifactKind::Cli, "cli"),
(ArtifactKind::RustRegistry, "rust-registry"),
] {
assert_eq!(kind.as_str(), name);
}
}
}