wadm_types/validation.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
//! Logic for model ([`Manifest`]) validation
//!
use std::collections::{HashMap, HashSet};
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::OnceLock;
use anyhow::{Context as _, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::{
CapabilityProperties, ComponentProperties, LinkProperty, Manifest, Properties, Trait,
TraitProperty, DEFAULT_LINK_NAME, LATEST_VERSION,
};
/// A namespace -> package -> interface lookup
type KnownInterfaceLookup = HashMap<String, HashMap<String, HashMap<String, ()>>>;
/// Hard-coded list of known namespaces/packages and the interfaces they contain.
///
/// Using an interface that is *not* on this list is not an error --
/// custom interfaces are expected to not be on this list, but when using
/// a known namespace and package, interfaces should generally be well known.
static KNOWN_INTERFACE_LOOKUP: OnceLock<KnownInterfaceLookup> = OnceLock::new();
const SECRET_POLICY_TYPE: &str = "policy.secret.wasmcloud.dev/v1alpha1";
/// Get the static list of known interfaces
fn get_known_interface_lookup() -> &'static KnownInterfaceLookup {
KNOWN_INTERFACE_LOOKUP.get_or_init(|| {
HashMap::from([
(
"wrpc".into(),
HashMap::from([
(
"blobstore".into(),
HashMap::from([("blobstore".into(), ())]),
),
(
"keyvalue".into(),
HashMap::from([("atomics".into(), ()), ("store".into(), ())]),
),
(
"http".into(),
HashMap::from([
("incoming-handler".into(), ()),
("outgoing-handler".into(), ()),
]),
),
]),
),
(
"wasi".into(),
HashMap::from([
(
"blobstore".into(),
HashMap::from([("blobstore".into(), ())]),
),
("config".into(), HashMap::from([("runtime".into(), ())])),
(
"keyvalue".into(),
HashMap::from([
("atomics".into(), ()),
("store".into(), ()),
("batch".into(), ()),
("watch".into(), ()),
]),
),
(
"http".into(),
HashMap::from([
("incoming-handler".into(), ()),
("outgoing-handler".into(), ()),
]),
),
("logging".into(), HashMap::from([("logging".into(), ())])),
]),
),
(
"wasmcloud".into(),
HashMap::from([(
"messaging".into(),
HashMap::from([("consumer".into(), ()), ("handler".into(), ())]),
)]),
),
])
})
}
static MANIFEST_NAME_REGEX_STR: &str = r"^[-\w]+$";
static MANIFEST_NAME_REGEX: OnceLock<Regex> = OnceLock::new();
/// Retrieve regular expression which manifest names must match, compiled to a usable [`Regex`]
fn get_manifest_name_regex() -> &'static Regex {
MANIFEST_NAME_REGEX.get_or_init(|| {
Regex::new(MANIFEST_NAME_REGEX_STR)
.context("failed to parse manifest name regex")
.unwrap()
})
}
/// Check whether a manifest name matches requirements, returning all validation errors
pub fn validate_manifest_name(name: &str) -> impl ValidationOutput {
let mut errors = Vec::new();
if !get_manifest_name_regex().is_match(name) {
errors.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("manifest name [{name}] is not allowed (should match regex [{MANIFEST_NAME_REGEX_STR}])"),
))
}
errors
}
/// Check whether a manifest name matches requirements
pub fn is_valid_manifest_name(name: &str) -> bool {
validate_manifest_name(name).valid()
}
/// Check whether a manifest version is valid, returning all validation errors
pub fn validate_manifest_version(version: &str) -> impl ValidationOutput {
let mut errors = Vec::new();
if version == LATEST_VERSION {
errors.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("{LATEST_VERSION} is not allowed in wadm"),
))
}
errors
}
/// Check whether a manifest version is valid requirements
pub fn is_valid_manifest_version(version: &str) -> bool {
validate_manifest_version(version).valid()
}
/// Check whether a known grouping of namespace, package and interface are valid.
/// A grouping must be both known/expected and invalid to fail this test (ex. a typo).
///
/// NOTE: what is considered a valid interface known to the host depends explicitly on
/// the wasmCloud host and wasmCloud project goals/implementation. This information is
/// subject to change.
fn is_invalid_known_interface(
namespace: &str,
package: &str,
interface: &str,
) -> Vec<ValidationFailure> {
let known_interfaces = get_known_interface_lookup();
let Some(pkg_lookup) = known_interfaces.get(namespace) else {
// This namespace isn't known, so it may be a custom interface
return vec![];
};
let Some(iface_lookup) = pkg_lookup.get(package) else {
// Unknown package inside a known interface we control is probably a bug
return vec![ValidationFailure::new(
ValidationFailureLevel::Warning,
format!("unrecognized interface [{namespace}:{package}/{interface}]"),
)];
};
// Unknown interface inside known namespace and package is probably a bug
if !iface_lookup.contains_key(interface) {
// Unknown package inside a known interface we control is probably a bug, but may be
// a new interface we don't know about yet
return vec![ValidationFailure::new(
ValidationFailureLevel::Warning,
format!("unrecognized interface [{namespace}:{package}/{interface}]"),
)];
}
Vec::new()
}
/// Level of a failure related to validation
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ValidationFailureLevel {
#[default]
Warning,
Error,
}
impl core::fmt::Display for ValidationFailureLevel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"{}",
match self {
Self::Warning => "warning",
Self::Error => "error",
}
)
}
}
/// Failure detailing a validation failure, normally indicating a failure
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ValidationFailure {
pub level: ValidationFailureLevel,
pub msg: String,
}
impl ValidationFailure {
fn new(level: ValidationFailureLevel, msg: String) -> Self {
ValidationFailure { level, msg }
}
}
impl core::fmt::Display for ValidationFailure {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "[{}] {}", self.level, self.msg)
}
}
/// Things that support output validation
pub trait ValidationOutput {
/// Whether the object is valid
fn valid(&self) -> bool;
/// Warnings returned (if any) during validation
fn warnings(&self) -> Vec<&ValidationFailure>;
/// The errors returned by the validation
fn errors(&self) -> Vec<&ValidationFailure>;
}
/// Default implementation for a list of concrete [`ValidationFailure`]s
impl ValidationOutput for [ValidationFailure] {
fn valid(&self) -> bool {
self.errors().is_empty()
}
fn warnings(&self) -> Vec<&ValidationFailure> {
self.iter()
.filter(|m| m.level == ValidationFailureLevel::Warning)
.collect()
}
fn errors(&self) -> Vec<&ValidationFailure> {
self.iter()
.filter(|m| m.level == ValidationFailureLevel::Error)
.collect()
}
}
/// Default implementation for a list of concrete [`ValidationFailure`]s
impl ValidationOutput for Vec<ValidationFailure> {
fn valid(&self) -> bool {
self.as_slice().valid()
}
fn warnings(&self) -> Vec<&ValidationFailure> {
self.iter()
.filter(|m| m.level == ValidationFailureLevel::Warning)
.collect()
}
fn errors(&self) -> Vec<&ValidationFailure> {
self.iter()
.filter(|m| m.level == ValidationFailureLevel::Error)
.collect()
}
}
/// Validate a WADM application manifest, returning a list of validation failures
///
/// At present this can check for:
/// - unsupported interfaces (i.e. typos, etc)
/// - unknown packages under known namespaces
/// - "dangling" links (missing components)
///
/// Since `[ValidationFailure]` implements `ValidationOutput`, you can call `valid()` and other
/// trait methods on it:
///
/// ```rust,ignore
/// let messages = validate_manifest(some_path).await?;
/// let valid = messages.valid();
/// ```
///
/// # Arguments
///
/// * `path` - Path to the Manifest that will be read into memory and validated
#[cfg(not(target_family = "wasm"))]
pub async fn validate_manifest_file(
path: impl AsRef<Path>,
) -> Result<(Manifest, Vec<ValidationFailure>)> {
let content = tokio::fs::read_to_string(path.as_ref())
.await
.with_context(|| format!("failed to read manifest @ [{}]", path.as_ref().display()))?;
validate_manifest_bytes(&content).await.with_context(|| {
format!(
"failed to parse YAML manifest [{}]",
path.as_ref().display()
)
})
}
/// Validate a lsit of bytes that represents a WADM application manifest
///
/// # Arguments
///
/// * `content` - YAML content to the Manifest that will be read into memory and validated
pub async fn validate_manifest_bytes(
content: impl AsRef<[u8]>,
) -> Result<(Manifest, Vec<ValidationFailure>)> {
let raw_yaml_content = content.as_ref();
let manifest =
serde_yaml::from_slice(content.as_ref()).context("failed to parse manifest content")?;
let mut failures = validate_manifest(&manifest).await?;
let mut yaml_issues = validate_raw_yaml(raw_yaml_content)?;
failures.append(&mut yaml_issues);
Ok((manifest, failures))
}
/// Validate a WADM application manifest, returning a list of validation failures
///
/// At present this can check for:
/// - unsupported interfaces (i.e. typos, etc)
/// - unknown packages under known namespaces
/// - "dangling" links (missing components)
/// - secrets mapped to unknown policies
///
/// Since `[ValidationFailure]` implements `ValidationOutput`, you can call `valid()` and other
/// trait methods on it:
///
/// ```rust,ignore
/// let messages = validate_manifest(some_path).await?;
/// let valid = messages.valid();
/// ```
///
/// # Arguments
///
/// * `manifest` - The [`Manifest`] that should be validated
pub async fn validate_manifest(manifest: &Manifest) -> Result<Vec<ValidationFailure>> {
// Check for known failures with the manifest
let mut failures = Vec::new();
failures.extend(
validate_manifest_name(&manifest.metadata.name)
.errors()
.into_iter()
.cloned(),
);
failures.extend(
validate_manifest_version(manifest.version())
.errors()
.into_iter()
.cloned(),
);
failures.extend(core_validation(manifest));
failures.extend(check_misnamed_interfaces(manifest));
failures.extend(check_dangling_links(manifest));
failures.extend(validate_policies(manifest));
failures.extend(ensure_no_custom_traits(manifest));
failures.extend(validate_component_properties(manifest));
failures.extend(check_duplicate_links(manifest));
failures.extend(validate_link_configs(manifest));
Ok(failures)
}
pub fn validate_raw_yaml(content: &[u8]) -> Result<Vec<ValidationFailure>> {
let mut failures = Vec::new();
let raw_content: serde_yaml::Value =
serde_yaml::from_slice(content).context("failed read raw yaml content")?;
failures.extend(validate_components_configs(&raw_content));
Ok(failures)
}
fn core_validation(manifest: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
let mut name_registry: HashSet<String> = HashSet::new();
let mut id_registry: HashSet<String> = HashSet::new();
let mut required_capability_components: HashSet<String> = HashSet::new();
for label in manifest.metadata.labels.iter() {
if !valid_oam_label(label) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Invalid OAM label: {:?}", label),
));
}
}
for annotation in manifest.metadata.annotations.iter() {
if !valid_oam_label(annotation) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Invalid OAM annotation: {:?}", annotation),
));
}
}
for component in manifest.spec.components.iter() {
// Component name validation : each component (components or providers) should have a unique name
if !name_registry.insert(component.name.clone()) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Duplicate component name in manifest: {}", component.name),
));
}
// Provider validation :
// Provider config should be serializable [For all components that have JSON config, validate that it can serialize.
// We need this so it doesn't trigger an error when sending a command down the line]
// Providers should have a unique image ref and link name
if let Properties::Capability {
properties:
CapabilityProperties {
id: Some(component_id),
config: _capability_config,
..
},
} = &component.properties
{
if !id_registry.insert(component_id.to_string()) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"Duplicate component identifier in manifest: {}",
component_id
),
));
}
}
// Component validation : Components should have a unique identifier per manifest
if let Properties::Component {
properties: ComponentProperties { id: Some(id), .. },
} = &component.properties
{
if !id_registry.insert(id.to_string()) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Duplicate component identifier in manifest: {}", id),
));
}
}
// Linkdef validation : A linkdef from a component should have a unique target and reference
if let Some(traits_vec) = &component.traits {
for trait_item in traits_vec.iter() {
if let Trait {
// TODO : add trait type validation after custom types are done. See TraitProperty enum.
properties: TraitProperty::Link(LinkProperty { target, .. }),
..
} = &trait_item
{
// Multiple components{ with type != 'capability'} can declare the same target, so we don't need to check for duplicates on insert
required_capability_components.insert(target.name.to_string());
}
}
}
}
let missing_capability_components = required_capability_components
.difference(&name_registry)
.collect::<Vec<&String>>();
if !missing_capability_components.is_empty() {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"The following capability component(s) are missing from the manifest: {:?}",
missing_capability_components
),
));
};
failures
}
/// Check for misnamed host-supported interfaces in the manifest
fn check_misnamed_interfaces(manifest: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
for link_trait in manifest.links() {
if let TraitProperty::Link(LinkProperty {
namespace,
package,
interfaces,
target: _target,
source: _source,
..
}) = &link_trait.properties
{
for interface in interfaces {
failures.extend(is_invalid_known_interface(namespace, package, interface))
}
}
}
failures
}
/// This validation rule should eventually be removed, but at this time (as of wadm 0.14.0)
/// custom traits are not supported. We technically deserialize the custom trait, but 99%
/// of the time this is just a poorly formatted spread or link scaler which is incredibly
/// frustrating to debug.
fn ensure_no_custom_traits(manifest: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
for component in manifest.components() {
if let Some(traits) = &component.traits {
for trait_item in traits {
match &trait_item.properties {
TraitProperty::Custom(trt) if trait_item.is_link() => failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Link trait deserialized as custom trait, ensure fields are correct: {}", trt),
)),
TraitProperty::Custom(trt) if trait_item.is_scaler() => failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Scaler trait deserialized as custom trait, ensure fields are correct: {}", trt),
)),
_ => (),
}
}
}
}
failures
}
/// Check for "dangling" links, which contain targets that are not specified elsewhere in the
/// WADM manifest.
///
/// A problem of this type only constitutes a warning, because it is possible that the manifest
/// does not *completely* specify targets (they may be deployed/managed external to WADM or in a separte
/// manifest).
fn check_dangling_links(manifest: &Manifest) -> Vec<ValidationFailure> {
let lookup = manifest.component_lookup();
let mut failures = Vec::new();
for link_trait in manifest.links() {
match &link_trait.properties {
TraitProperty::Custom(obj) => {
if obj.get("target").is_none() {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
"custom link is missing 'target' property".into(),
));
continue;
}
// Ensure target property is present
match obj["target"]["name"].as_str() {
// If target is present, ensure it's pointing to a known component
Some(target) if !lookup.contains_key(&String::from(target)) => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Warning,
format!("custom link target [{target}] is not a listed component"),
))
}
// For all keys where the the component is in the lookup we can do nothing
Some(_) => {}
// if target property is not present, note that it is missing
None => failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
"custom link is missing 'target' name property".into(),
)),
}
}
TraitProperty::Link(LinkProperty { name, target, .. }) => {
let link_identifier = name
.as_ref()
.map(|n| format!("(name [{n}])"))
.unwrap_or_else(|| format!("(target [{}])", target.name));
if !lookup.contains_key(&target.name) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Warning,
format!(
"link {link_identifier} target [{}] is not a listed component",
target.name
),
))
}
}
_ => unreachable!("manifest.links() should only return links"),
}
}
failures
}
/// Ensure that a manifest has secrets that are mapped to known policies
/// and that those policies have the expected type and properties.
fn validate_policies(manifest: &Manifest) -> Vec<ValidationFailure> {
let policies = manifest.policy_lookup();
let mut failures = Vec::new();
for c in manifest.components() {
// Ensure policies meant for secrets are valid
for secret in c.secrets() {
match policies.get(&secret.properties.policy) {
Some(policy) if policy.policy_type != SECRET_POLICY_TYPE => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"secret '{}' is mapped to policy '{}' which is not a secret policy. Expected type '{SECRET_POLICY_TYPE}'",
secret.name, secret.properties.policy
),
))
}
Some(policy) => {
if !policy.properties.contains_key("backend") {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"secret '{}' is mapped to policy '{}' which does not include a 'backend' property",
secret.name, secret.properties.policy
),
))
}
}
None => failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"secret '{}' is mapped to unknown policy '{}'",
secret.name, secret.properties.policy
),
)),
}
}
}
failures
}
/// Ensure that all components in a manifest either specify an image reference or a shared
/// component in a different manifest. Note that this does not validate that the image reference
/// is valid or that the shared component is valid, only that one of the two properties is set.
pub fn validate_component_properties(application: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
for component in application.spec.components.iter() {
match &component.properties {
Properties::Component {
properties:
ComponentProperties {
image,
application,
config,
secrets,
..
},
}
| Properties::Capability {
properties:
CapabilityProperties {
image,
application,
config,
secrets,
..
},
} => match (image, application) {
(Some(_), Some(_)) => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
"Component cannot have both 'image' and 'application' properties".into(),
));
}
(None, None) => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
"Component must have either 'image' or 'application' property".into(),
));
}
// This is a problem because of our left-folding config implementation. A shared application
// could specify additional config and actually overwrite the original manifest's config.
(None, Some(shared_properties)) if !config.is_empty() => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"Shared component '{}' cannot specify additional 'config'",
shared_properties.name
),
));
}
(None, Some(shared_properties)) if !secrets.is_empty() => {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"Shared component '{}' cannot specify additional 'secrets'",
shared_properties.name
),
));
}
// Shared application components already have scale properties defined in their original manifest
(None, Some(shared_properties))
if component
.traits
.as_ref()
.is_some_and(|traits| traits.iter().any(|trt| trt.is_scaler())) =>
{
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"Shared component '{}' cannot include a scaler trait",
shared_properties.name
),
));
}
_ => {}
},
}
}
failures
}
/// Validates link configs in a WADM application manifest.
///
/// At present this can check for:
/// - all configs that declare `properties` have unique names
/// (configs without properties refer to existing configs)
///
pub fn validate_link_configs(manifest: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
let mut link_config_names = HashSet::new();
for link_trait in manifest.links() {
if let TraitProperty::Link(LinkProperty { target, source, .. }) = &link_trait.properties {
for config in &target.config {
// we only need to check for uniqueness of configs with properties
if config.properties.is_none() {
continue;
}
// Check if config name is unique
if !link_config_names.insert(config.name.clone()) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Duplicate link config name found: '{}'", config.name),
));
}
}
if let Some(source) = source {
for config in &source.config {
// we only need to check for uniqueness of configs with properties
if config.properties.is_none() {
continue;
}
// Check if config name is unique
if !link_config_names.insert(config.name.clone()) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!("Duplicate link config name found: '{}'", config.name),
));
}
}
}
}
}
failures
}
/// Funtion to validate the component configs
/// from 0.13.0 source_config is deprecated and replaced with source:config:
/// this function validates the raw yaml to check for deprecated source_config and target_config
pub fn validate_components_configs(application: &serde_yaml::Value) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
if let Some(specs) = application.get("spec") {
if let Some(components) = specs.get("components") {
if let Some(components_sequence) = components.as_sequence() {
for component in components_sequence.iter() {
failures.extend(get_deprecated_configs(component));
}
}
}
}
failures
}
fn get_deprecated_configs(component: &serde_yaml::Value) -> Vec<ValidationFailure> {
let mut failures = vec![];
if let Some(traits) = component.get("traits") {
if let Some(traits_sequence) = traits.as_sequence() {
for trait_ in traits_sequence.iter() {
if let Some(trait_type) = trait_.get("type") {
if trait_type.ne("link") {
continue;
}
}
if let Some(trait_properties) = trait_.get("properties") {
if trait_properties.get("source_config").is_some() {
failures.push(ValidationFailure {
level: ValidationFailureLevel::Warning,
msg: "one of the components' link trait contains a source_config key, please use source:config: rather".to_string(),
});
}
if trait_properties.get("target_config").is_some() {
failures.push(ValidationFailure {
level: ValidationFailureLevel::Warning,
msg: "one of the components' link trait contains a target_config key, please use target:config: rather".to_string(),
});
}
}
}
}
}
failures
}
/// This function validates that a key/value pair is a valid OAM label. It's using fairly
/// basic validation rules to ensure that the manifest isn't doing anything horribly wrong. Keeping
/// this function free of regex is intentional to keep this code functional but simple.
///
/// See <https://github.com/oam-dev/spec/blob/master/metadata.md#metadata> for details
pub fn valid_oam_label(label: (&String, &String)) -> bool {
let (key, _) = label;
match key.split_once('/') {
Some((prefix, name)) => is_valid_dns_subdomain(prefix) && is_valid_label_name(name),
None => is_valid_label_name(key),
}
}
pub fn is_valid_dns_subdomain(s: &str) -> bool {
if s.is_empty() || s.len() > 253 {
return false;
}
s.split('.').all(|part| {
// Ensure each part is non-empty, <= 63 characters, starts with an alphabetic character,
// ends with an alphanumeric character, and contains only alphanumeric characters or hyphens
!part.is_empty()
&& part.len() <= 63
&& part.starts_with(|c: char| c.is_ascii_alphabetic())
&& part.ends_with(|c: char| c.is_ascii_alphanumeric())
&& part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
})
}
// Ensure each name is non-empty, <= 63 characters, starts with an alphanumeric character,
// ends with an alphanumeric character, and contains only alphanumeric characters, hyphens,
// underscores, or periods
pub fn is_valid_label_name(name: &str) -> bool {
if name.is_empty() || name.len() > 63 {
return false;
}
name.starts_with(|c: char| c.is_ascii_alphanumeric())
&& name.ends_with(|c: char| c.is_ascii_alphanumeric())
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
}
/// Checks whether a manifest contains "duplicate" links.
///
/// Multiple links from the same source with the same name, namespace, package and interface
/// are considered duplicate links.
fn check_duplicate_links(manifest: &Manifest) -> Vec<ValidationFailure> {
let mut failures = Vec::new();
for component in manifest.components() {
let mut link_ids = HashSet::new();
for link in component.links() {
if let TraitProperty::Link(LinkProperty {
name,
namespace,
package,
interfaces,
..
}) = &link.properties
{
for interface in interfaces {
if !link_ids.insert((
name.clone()
.unwrap_or_else(|| DEFAULT_LINK_NAME.to_string()),
namespace,
package,
interface,
)) {
failures.push(ValidationFailure::new(
ValidationFailureLevel::Error,
format!(
"Duplicate link found inside component '{}': {} ({}:{}/{})",
component.name,
name.clone()
.unwrap_or_else(|| DEFAULT_LINK_NAME.to_string()),
namespace,
package,
interface
),
));
};
}
}
}
}
failures
}
#[cfg(test)]
mod tests {
use super::is_valid_manifest_name;
const VALID_MANIFEST_NAMES: [&str; 4] = [
"mymanifest",
"my-manifest",
"my_manifest",
"mymanifest-v2-v3-final",
];
const INVALID_MANIFEST_NAMES: [&str; 2] = ["my.manifest", "my manifest"];
/// Ensure valid manifest names pass
#[test]
fn manifest_names_valid() {
// Acceptable manifest names
for valid in VALID_MANIFEST_NAMES {
assert!(is_valid_manifest_name(valid));
}
}
/// Ensure invalid manifest names fail
#[test]
fn manifest_names_invalid() {
for invalid in INVALID_MANIFEST_NAMES {
assert!(!is_valid_manifest_name(invalid))
}
}
}