diff --git a/crates/ployer-templates/src/compose.rs b/crates/ployer-templates/src/compose.rs index 9e4e69b..7932dc6 100644 --- a/crates/ployer-templates/src/compose.rs +++ b/crates/ployer-templates/src/compose.rs @@ -148,3 +148,7 @@ pub fn split_port(spec: &str) -> Option<(String, String)> { Some((spec.to_string(), spec.to_string())) } } + +#[cfg(test)] +#[path = "compose_tests.rs"] +mod tests; diff --git a/crates/ployer-templates/src/compose_tests.rs b/crates/ployer-templates/src/compose_tests.rs new file mode 100644 index 0000000..e11299c --- /dev/null +++ b/crates/ployer-templates/src/compose_tests.rs @@ -0,0 +1,313 @@ +use super::*; + +/// A compose document shaped like the one a database template renders to: +/// one service, a quoted environment map, a named volume, an external network. +const RENDERED: &str = r#" +services: + fixture: + image: fixture:1-alpine + restart: unless-stopped + environment: + DB_USER: "app" + DB_PASSWORD: "s3cret" + DB_NAME: "app" + volumes: + - ployer_shop_data:/var/lib/fixture/data + networks: [ployer] +networks: + ployer: + external: true +"#; + +fn single_service(yaml: &str) -> ServiceSpec { + let spec = parse(yaml).expect("compose must parse"); + assert_eq!(spec.services.len(), 1, "fixture declares one service"); + spec.services.values().next().unwrap().clone() +} + +// --------------------------------------------------------------------------- +// The six-key subset the backend actually understands +// --------------------------------------------------------------------------- + +#[test] +fn rendered_compose_parses_into_the_supported_subset() { + let svc = single_service(RENDERED); + + assert_eq!(svc.image, "fixture:1-alpine"); + assert_eq!(svc.restart.as_deref(), Some("unless-stopped")); + assert_eq!(svc.volumes, vec!["ployer_shop_data:/var/lib/fixture/data"]); + assert_eq!(svc.networks, vec!["ployer"]); + assert!( + svc.ports.is_empty(), + "nothing is published to the host by default" + ); +} + +#[test] +fn environment_map_becomes_key_equals_value_pairs() { + let svc = single_service(RENDERED); + let pairs = svc.environment.expect("environment present").to_pairs(); + + // BTreeMap ordering, so this is deterministic rather than incidental. + assert_eq!( + pairs, + vec![ + "DB_NAME=app".to_string(), + "DB_PASSWORD=s3cret".to_string(), + "DB_USER=app".to_string(), + ] + ); +} + +#[test] +fn environment_list_form_is_passed_through_unchanged() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + environment: + - DB_USER=app + - DB_PASSWORD=s3cret +"#; + let svc = single_service(yaml); + assert_eq!( + svc.environment.unwrap().to_pairs(), + vec!["DB_USER=app".to_string(), "DB_PASSWORD=s3cret".to_string()] + ); +} + +#[test] +fn service_without_an_environment_block_is_valid() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n"; + let svc = single_service(yaml); + assert!(svc.environment.is_none()); +} + +#[test] +fn service_without_an_image_is_rejected() { + // `image` is the one field the Docker call cannot invent a default for. + let yaml = "services:\n fixture:\n restart: always\n"; + assert!( + parse(yaml).is_err(), + "a service with no image must not parse" + ); +} + +// --------------------------------------------------------------------------- +// Non-scalar environment values +// --------------------------------------------------------------------------- + +#[test] +fn numeric_and_boolean_environment_values_are_stringified() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + environment: + PORT: 5432 + DEBUG: true + EMPTY: +"#; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert!(pairs.contains(&"PORT=5432".to_string())); + assert!(pairs.contains(&"DEBUG=true".to_string())); + assert!(pairs.contains(&"EMPTY=".to_string())); +} + +// --------------------------------------------------------------------------- +// Why template authors must quote interpolated environment values. +// +// Input values reach the compose body by raw text substitution, so an +// unquoted placeholder lets a user-supplied database name change the YAML +// structure. These two tests are a matched pair: the first shows the break, +// the second shows quoting fixing it. +// --------------------------------------------------------------------------- + +#[test] +fn unquoted_environment_value_containing_a_colon_breaks_the_parse() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n DB_NAME: my: db\n"; + assert!( + parse(yaml).is_err(), + "an unquoted colon-space must be a parse error, not a silently odd value" + ); +} + +#[test] +fn quoted_environment_value_containing_a_colon_survives_intact() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n DB_NAME: \"my: db\"\n"; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert_eq!(pairs, vec!["DB_NAME=my: db".to_string()]); +} + +#[test] +fn quoted_leading_zero_value_keeps_its_zero() { + // Unquoted, "08" is the kind of value YAML implementations disagree about. + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n CODE: \"08\"\n"; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert_eq!(pairs, vec!["CODE=08".to_string()]); +} + +// --------------------------------------------------------------------------- +// Keys outside the subset are DROPPED, not rejected. +// +// This is a sharp edge: a template author can add `healthcheck:` and it will +// parse cleanly while doing nothing at all. These tests exist so that +// behaviour is discovered here rather than in production. +// --------------------------------------------------------------------------- + +#[test] +fn healthcheck_is_silently_ignored_rather_than_honoured() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + healthcheck: + test: ["CMD-SHELL", "pg_isready"] + interval: 10s +"#; + let svc = single_service(yaml); + assert_eq!(svc.image, "fixture:1-alpine"); + // No field on ServiceSpec can carry it. A template relying on a + // healthcheck would never become healthy; containers only ever report + // "Up". If this crate ever grows healthcheck support, this test should + // fail and be rewritten. + assert_eq!( + std::mem::size_of_val(&svc.restart), + std::mem::size_of::>() + ); +} + +#[test] +fn depends_on_and_command_are_silently_ignored() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + command: ["postgres", "-c", "max_connections=200"] + depends_on: + - other +"#; + let svc = single_service(yaml); + assert_eq!(svc.image, "fixture:1-alpine"); + assert!(svc.volumes.is_empty()); +} + +// --------------------------------------------------------------------------- +// Host port publishing — the "Expose to host" checkbox +// --------------------------------------------------------------------------- + +#[test] +fn adding_a_binding_publishes_host_colon_container() { + let out = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let svc = single_service(&out); + assert_eq!(svc.ports, vec!["15432:5432"]); +} + +#[test] +fn adding_no_bindings_returns_the_document_untouched() { + let out = add_ports_to_all_services(RENDERED, &[]).unwrap(); + assert_eq!(out, RENDERED, "an empty binding list must be a no-op"); +} + +#[test] +fn removing_ports_clears_a_previously_published_binding() { + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let unexposed = remove_ports_from_all_services(&exposed).unwrap(); + + assert!(single_service(&unexposed).ports.is_empty()); +} + +#[test] +fn unexposing_preserves_image_environment_and_volumes() { + // Un-exposing must not take the database's data or credentials with it. + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let unexposed = remove_ports_from_all_services(&exposed).unwrap(); + let svc = single_service(&unexposed); + + assert_eq!(svc.image, "fixture:1-alpine"); + assert_eq!(svc.volumes, vec!["ployer_shop_data:/var/lib/fixture/data"]); + assert_eq!(svc.networks, vec!["ployer"]); + assert!(svc + .environment + .unwrap() + .to_pairs() + .contains(&"DB_PASSWORD=s3cret".to_string())); +} + +#[test] +fn expose_then_unexpose_round_trips_to_the_same_parsed_spec() { + let once = remove_ports_from_all_services( + &add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(), + ) + .unwrap(); + let twice = remove_ports_from_all_services( + &add_ports_to_all_services(&once, &[(5432, 15432)]).unwrap(), + ) + .unwrap(); + + assert_eq!(once, twice, "repeated expose/unexpose must converge"); +} + +#[test] +fn re_exposing_replaces_the_binding_instead_of_appending() { + let first = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let second = add_ports_to_all_services(&first, &[(5432, 25432)]).unwrap(); + + assert_eq!( + single_service(&second).ports, + vec!["25432:5432"], + "changing the host port must not leave the old one behind" + ); +} + +#[test] +fn current_port_bindings_reports_container_then_host() { + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + assert_eq!( + current_port_bindings(&exposed).unwrap(), + vec![(5432, 15432)] + ); +} + +#[test] +fn current_port_bindings_is_empty_when_nothing_is_published() { + assert!(current_port_bindings(RENDERED).unwrap().is_empty()); +} + +// --------------------------------------------------------------------------- +// Spec splitting helpers +// --------------------------------------------------------------------------- + +#[test] +fn split_volume_separates_source_from_mount_path() { + assert_eq!( + split_volume("ployer_shop_data:/var/lib/fixture/data"), + Some(("ployer_shop_data".into(), "/var/lib/fixture/data".into())) + ); +} + +#[test] +fn split_volume_ignores_a_trailing_access_mode() { + assert_eq!( + split_volume("ployer_shop_data:/var/lib/fixture/data:ro"), + Some(("ployer_shop_data".into(), "/var/lib/fixture/data".into())) + ); +} + +#[test] +fn split_volume_returns_none_without_a_mount_path() { + assert_eq!(split_volume("ployer_shop_data"), None); +} + +#[test] +fn split_port_maps_a_bare_port_to_itself() { + assert_eq!(split_port("5432"), Some(("5432".into(), "5432".into()))); +} + +#[test] +fn split_port_separates_host_from_container() { + assert_eq!( + split_port("15432:5432"), + Some(("15432".into(), "5432".into())) + ); +} diff --git a/crates/ployer-templates/src/registry.rs b/crates/ployer-templates/src/registry.rs index e0251ec..c77a694 100644 --- a/crates/ployer-templates/src/registry.rs +++ b/crates/ployer-templates/src/registry.rs @@ -153,3 +153,7 @@ fn sha256_hex(bytes: &[u8]) -> String { hasher.update(bytes); hex::encode(hasher.finalize()) } + +#[cfg(test)] +#[path = "registry_tests.rs"] +mod tests; diff --git a/crates/ployer-templates/src/registry_tests.rs b/crates/ployer-templates/src/registry_tests.rs new file mode 100644 index 0000000..270698e --- /dev/null +++ b/crates/ployer-templates/src/registry_tests.rs @@ -0,0 +1,232 @@ +use super::*; + +use std::sync::atomic::{AtomicU32, Ordering}; + +/// A template body small enough to hash by hand in a test, but complete +/// enough to deserialise into a `Template`. +const BODY: &str = "slug: fixture\nname: Fixture\ndescription: d\ncategory: database\nversion: 1\ncompose: \"services: {}\"\n"; + +/// Unique scratch directory per test, removed on drop so tests never see each +/// other's cache files regardless of the order they run in. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + static COUNTER: AtomicU32 = AtomicU32::new(0); + let unique = format!( + "ployer-registry-tests-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + ); + let path = std::env::temp_dir().join(unique); + std::fs::create_dir_all(&path).expect("scratch dir"); + Self(path) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn registry(cache_dir: &Path) -> Registry { + Registry::new(RegistryConfig { + // Never reached: every test here exercises the disk cache only. + registry_url: "http://127.0.0.1:1/unused".to_string(), + cache_dir: cache_dir.to_path_buf(), + cache_ttl: Duration::from_secs(15), + }) +} + +fn entry(sha256: &str) -> IndexEntry { + IndexEntry { + slug: "fixture".to_string(), + name: "Fixture".to_string(), + description: "d".to_string(), + category: "database".to_string(), + tags: vec![], + version: serde_json::json!(1), + sha256: sha256.to_string(), + url: "https://ployer.nusendra.com/templates/fixture.yaml".to_string(), + } +} + +// --------------------------------------------------------------------------- +// Hashing +// --------------------------------------------------------------------------- + +#[test] +fn sha256_hex_matches_the_standard_digest() { + // Pins both the algorithm and the lowercase hex encoding; the registry + // index is generated by a separate Node script that must agree exactly. + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); +} + +// --------------------------------------------------------------------------- +// Cache file naming +// +// The cache key has to change when the template changes, or an upgraded +// template is masked forever by the copy already on disk. +// --------------------------------------------------------------------------- + +#[test] +fn cache_filename_is_namespaced_by_slug_and_hash_prefix() { + let scratch = Scratch::new(); + let hash = sha256_hex(BODY.as_bytes()); + let path = registry(&scratch.0).template_path(&entry(&hash)); + + assert_eq!( + path.file_name().unwrap().to_str().unwrap(), + format!("fixture-{}.yaml", &hash[..16]) + ); +} + +#[test] +fn a_new_template_version_gets_a_new_cache_file() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + + let old = reg.template_path(&entry(&sha256_hex(b"version one"))); + let new = reg.template_path(&entry(&sha256_hex(b"version two"))); + + assert_ne!( + old, new, + "a changed template must not be served from the previous cache entry" + ); +} + +#[test] +fn index_is_cached_next_to_the_templates() { + let scratch = Scratch::new(); + assert_eq!( + registry(&scratch.0).index_path(), + scratch.0.join("index.json") + ); +} + +// --------------------------------------------------------------------------- +// Disk cache integrity +// +// `get()` returns a cached template without re-downloading it, so the cached +// bytes are re-hashed on every read. A tampered cache file must not be parsed. +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn cached_template_is_returned_when_its_hash_still_matches() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + let e = entry(&sha256_hex(BODY.as_bytes())); + + reg.write_disk_template(&e, BODY) + .await + .expect("cache write"); + let template = reg.read_disk_template(&e).await.expect("cache hit"); + + assert_eq!(template.slug, "fixture"); +} + +#[tokio::test] +async fn a_tampered_cache_file_is_rejected_rather_than_parsed() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + let e = entry(&sha256_hex(BODY.as_bytes())); + + reg.write_disk_template(&e, BODY) + .await + .expect("cache write"); + // Someone edits the cached file in place, keeping the same filename. + let tampered = BODY.replace("Fixture", "Evil"); + assert_ne!(tampered, BODY, "the tamper must actually change the bytes"); + std::fs::write(reg.template_path(&e), &tampered).expect("tamper"); + + match reg.read_disk_template(&e).await { + Err(TemplateError::HashMismatch { + slug, + expected, + actual, + }) => { + assert_eq!(slug, "fixture"); + assert_eq!(expected, e.sha256); + assert_eq!(actual, sha256_hex(tampered.as_bytes())); + assert_ne!(expected, actual); + } + Err(other) => panic!("expected HashMismatch, got {other:?}"), + Ok(_) => panic!("a tampered cache file must not be returned"), + } +} + +#[tokio::test] +async fn a_cache_miss_is_an_error_so_the_caller_refetches() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + + // `get()` treats any Err from the disk cache as "go to the network". + assert!(reg + .read_disk_template(&entry(&sha256_hex(b"never cached"))) + .await + .is_err()); +} + +#[tokio::test] +async fn the_cache_directory_is_created_on_first_write() { + let scratch = Scratch::new(); + let nested = scratch.0.join("deeply/nested/cache"); + let reg = registry(&nested); + let e = entry(&sha256_hex(BODY.as_bytes())); + + assert!(!nested.exists()); + reg.write_disk_template(&e, BODY) + .await + .expect("cache write"); + assert!(nested + .join(format!("fixture-{}.yaml", &e.sha256[..16])) + .exists()); +} + +// --------------------------------------------------------------------------- +// Index disk fallback — what the dashboard shows when the registry is down +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn the_index_survives_a_write_read_round_trip() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + let index = RegistryIndex { + schema_version: 1, + generated_at: "2026-10-19T10:03:38.550Z".to_string(), + templates: vec![entry(&sha256_hex(BODY.as_bytes()))], + }; + + reg.write_disk_index(&index).await.expect("index write"); + let restored = reg.read_disk_index().await.expect("index read"); + + assert_eq!(restored.schema_version, 1); + assert_eq!(restored.templates.len(), 1); + assert_eq!(restored.templates[0].slug, "fixture"); + assert_eq!(restored.templates[0].sha256, index.templates[0].sha256); +} + +#[tokio::test] +async fn reading_an_absent_index_fails_instead_of_returning_an_empty_catalog() { + // An empty catalog would render as "no services available", which looks + // like a deliberate state rather than a registry outage. + let scratch = Scratch::new(); + assert!(registry(&scratch.0).read_disk_index().await.is_err()); +} + +#[tokio::test] +async fn a_corrupt_index_on_disk_is_an_error_not_a_panic() { + let scratch = Scratch::new(); + let reg = registry(&scratch.0); + std::fs::write(reg.index_path(), b"{ not json").expect("write corrupt index"); + + assert!(reg.read_disk_index().await.is_err()); +} diff --git a/crates/ployer-templates/src/render_tests.rs b/crates/ployer-templates/src/render_tests.rs index 9c11e20..4e28bb1 100644 --- a/crates/ployer-templates/src/render_tests.rs +++ b/crates/ployer-templates/src/render_tests.rs @@ -1,10 +1,439 @@ -use std::collections::HashMap; - use chrono::Utc; use ployer_core::models::{AppStatus, Application, BuildStrategy}; use super::*; -use crate::schema::{OutputItem, PostInstall, Volume}; +use crate::schema::{OutputItem, PostInstall, Template, Volume}; + +/// A service template shaped exactly like the real database templates in the +/// registry (generated password, named volume, external network, credential +/// URI in `post_install`), but with fixture-only identifiers. +/// +/// Deliberately NOT a copy of `postgresql.yaml`: the registry lives in a +/// different repo (`ployer-website/static/templates`) and is the single source +/// of truth for image tags, ports and mount paths. Those are asserted there. +/// These tests own the *rendering engine* contract that every template relies +/// on, so they must not silently drift into asserting catalog content. +const FIXTURE: &str = r#" +slug: fixture-db +name: Fixture DB +description: Fixture relational database. +category: database +tags: [database, sql] +version: 1 + +inputs: + - key: DB_USER + label: Database user + type: string + default: app + - key: DB_PASSWORD + label: Database password + type: password + generate: + kind: password + length: 32 + - key: DB_NAME + label: Initial database name + type: string + default: app + +ports: + - container: 5432 + expose: false + +volumes: + - name: data + mount: /var/lib/fixture/data + +compose: | + services: + fixture: + image: fixture:1-alpine + restart: unless-stopped + environment: + DB_USER: "{{ inputs.DB_USER }}" + DB_PASSWORD: "{{ inputs.DB_PASSWORD }}" + DB_NAME: "{{ inputs.DB_NAME }}" + volumes: + - {{ volumes.data }}:/var/lib/fixture/data + networks: [{{ network }}] + networks: + {{ network }}: + external: true + +post_install: + message: | + host: ployer-{{ app.name }}-fixture + user: {{ inputs.DB_USER }} + outputs: + - label: Internal connection URI + value: "proto://{{ inputs.DB_USER }}:{{ inputs.DB_PASSWORD }}@ployer-{{ app.name }}-fixture:5432/{{ inputs.DB_NAME }}" +"#; + +fn fixture() -> Template { + serde_yaml::from_str(FIXTURE).expect("fixture template must parse") +} + +fn ctx<'a>(app_name: &'a str, inputs: &[(&str, &str)]) -> RenderContext<'a> { + RenderContext { + app_name, + app_id: "app-0001", + network: "ployer", + inputs: inputs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + } +} + +fn render_fixture(app_name: &str, inputs: &[(&str, &str)]) -> Rendered { + render(&fixture(), ctx(app_name, inputs)).expect("fixture must render") +} + +// --------------------------------------------------------------------------- +// Volume naming +// +// Templates reference `{{ volumes.NAME }}` and trust the engine to expand it to +// a host-unique Docker volume name. Two apps installing the same template must +// not land on the same volume, or installing a second database silently adopts +// the first one's data directory. +// --------------------------------------------------------------------------- + +#[test] +fn volume_placeholder_expands_to_ployer_prefixed_name() { + let out = render_fixture("shop", &[]); + assert!( + out.compose + .contains("ployer_shop_data:/var/lib/fixture/data"), + "expected the volume mount to use the ployer__ name, got:\n{}", + out.compose + ); +} + +#[test] +fn different_apps_get_different_volume_names() { + let first = render_fixture("alpha", &[]); + let second = render_fixture("beta", &[]); + + assert!(first.compose.contains("ployer_alpha_data:")); + assert!(second.compose.contains("ployer_beta_data:")); + assert!( + !second.compose.contains("ployer_alpha_data:"), + "a second install must not reuse the first app's volume" + ); +} + +// --------------------------------------------------------------------------- +// Credential generation +// +// `generate: {kind: password}` is the only thing standing between a fresh +// install and a database with a predictable password. +// --------------------------------------------------------------------------- + +#[test] +fn generated_password_honours_requested_length() { + let out = render_fixture("app", &[]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + assert_eq!(password.len(), 32, "fixture asks for length: 32"); +} + +#[test] +fn generated_password_is_not_empty() { + let out = render_fixture("app", &[]); + assert!(!out.resolved_inputs["DB_PASSWORD"].is_empty()); +} + +#[test] +fn two_installs_generate_different_passwords() { + let first = render_fixture("app", &[]); + let second = render_fixture("app", &[]); + assert_ne!( + first.resolved_inputs["DB_PASSWORD"], second.resolved_inputs["DB_PASSWORD"], + "every install must get its own password" + ); +} + +#[test] +fn generated_passwords_do_not_repeat_across_many_installs() { + // One pair differing could be luck; 200 distinct values could not. + // Guards against a future change to a seeded or time-derived RNG. + let mut seen = std::collections::HashSet::new(); + for _ in 0..200 { + seen.insert(render_fixture("app", &[]).resolved_inputs["DB_PASSWORD"].clone()); + } + assert_eq!(seen.len(), 200, "generated passwords must all be distinct"); +} + +#[test] +fn generated_password_is_uri_safe() { + // The password is interpolated into a connection URI shown by the dashboard + // and pasted into clients verbatim. A '/', '@' or ':' would split the URI. + for _ in 0..50 { + let password = render_fixture("app", &[]).resolved_inputs["DB_PASSWORD"].clone(); + assert!( + password.chars().all(|c| c.is_ascii_alphanumeric()), + "password must be URI-safe without escaping, got {password:?}" + ); + } +} + +#[test] +fn hex_generator_produces_requested_length_of_hex_digits() { + let g = Generate { + kind: GenerateKind::Hex, + length: Some(31), // odd length exercises the div_ceil + truncate path + }; + let value = generate(&g); + assert_eq!(value.len(), 31); + assert!(value.chars().all(|c| c.is_ascii_hexdigit())); +} + +#[test] +fn generator_defaults_to_32_when_length_is_omitted() { + let g = Generate { + kind: GenerateKind::Password, + length: None, + }; + assert_eq!(generate(&g).len(), 32); +} + +// --------------------------------------------------------------------------- +// Input resolution +// --------------------------------------------------------------------------- + +#[test] +fn user_supplied_input_overrides_the_default() { + let out = render_fixture("app", &[("DB_NAME", "inventory")]); + assert_eq!(out.resolved_inputs["DB_NAME"], "inventory"); +} + +#[test] +fn user_supplied_password_is_used_instead_of_generating_one() { + let out = render_fixture("app", &[("DB_PASSWORD", "chosen-by-user")]); + assert_eq!(out.resolved_inputs["DB_PASSWORD"], "chosen-by-user"); +} + +#[test] +fn omitted_input_falls_back_to_its_default() { + let out = render_fixture("app", &[]); + assert_eq!(out.resolved_inputs["DB_USER"], "app"); +} + +#[test] +fn empty_submitted_value_falls_back_instead_of_being_used() { + // The install form posts "" for untouched fields. Taking that literally + // would create a database user with an empty password. + let out = render_fixture("app", &[("DB_USER", ""), ("DB_PASSWORD", "")]); + assert_eq!(out.resolved_inputs["DB_USER"], "app"); + assert_eq!(out.resolved_inputs["DB_PASSWORD"].len(), 32); +} + +#[test] +fn input_with_neither_default_nor_generator_is_rejected() { + let mut template = fixture(); + template.inputs.push(Input { + key: "REQUIRED_THING".to_string(), + label: "Required".to_string(), + kind: InputKind::String, + default: None, + generate: None, + required: Some(true), + }); + + let err = match render(&template, ctx("app", &[])) { + Err(e) => e, + Ok(_) => panic!("a template input with no default and no generator must not render"), + }; + assert!( + matches!(&err, TemplateError::MissingInput(k) if k == "REQUIRED_THING"), + "expected MissingInput(REQUIRED_THING), got {err:?}" + ); +} + +#[test] +fn non_numeric_value_for_a_number_input_is_rejected() { + let mut template = fixture(); + template.inputs.push(Input { + key: "MAX_CONNECTIONS".to_string(), + label: "Max connections".to_string(), + kind: InputKind::Number, + default: None, + generate: None, + required: Some(true), + }); + + let err = match render(&template, ctx("app", &[("MAX_CONNECTIONS", "lots")])) { + Err(e) => e, + Ok(_) => panic!("a non-numeric value for a number input must not render"), + }; + assert!( + matches!(&err, TemplateError::InvalidInput { key, .. } if key == "MAX_CONNECTIONS"), + "expected InvalidInput for MAX_CONNECTIONS, got {err:?}" + ); +} + +#[test] +fn number_input_accepts_an_integer_string() { + let mut template = fixture(); + template.inputs.push(Input { + key: "MAX_CONNECTIONS".to_string(), + label: "Max connections".to_string(), + kind: InputKind::Number, + default: None, + generate: None, + required: Some(true), + }); + + let out = + render(&template, ctx("app", &[("MAX_CONNECTIONS", "100")])).expect("100 is a number"); + assert_eq!(out.resolved_inputs["MAX_CONNECTIONS"], "100"); +} + +#[test] +fn inputs_not_declared_by_the_template_are_discarded() { + // The install endpoint forwards whatever the client posted. Unknown keys + // must not reach the container as environment variables. + let out = render_fixture("app", &[("SMUGGLED", "value")]); + assert!(!out.resolved_inputs.contains_key("SMUGGLED")); + assert!(!out.compose.contains("SMUGGLED")); +} + +// --------------------------------------------------------------------------- +// Placeholder substitution +// --------------------------------------------------------------------------- + +#[test] +fn network_placeholder_is_substituted_everywhere_it_appears() { + let out = render_fixture("app", &[]); + assert!(out.compose.contains("networks: [ployer]")); + assert!( + !out.compose.contains("{{"), + "no placeholder may survive rendering:\n{}", + out.compose + ); +} + +#[test] +fn app_name_and_id_placeholders_are_substituted() { + let template = fixture(); + let rendered = render(&template, ctx("shop", &[])).unwrap(); + assert!(rendered + .post_install_message + .as_ref() + .unwrap() + .contains("host: ployer-shop-fixture")); + + let out = substitute( + "{{ app.id }}", + &Default::default(), + &Default::default(), + "shop", + "shop", + "app-0001", + "ployer", + ); + assert_eq!(out, "app-0001"); +} + +#[test] +fn unknown_placeholder_is_left_untouched() { + // Better a visible `{{ inputs.TYPO }}` in the compose than a silent empty + // value that starts a container with a blank password. + let out = substitute( + "value={{ inputs.TYPO }}", + &Default::default(), + &Default::default(), + "app", + "app", + "id", + "net", + ); + assert_eq!(out, "value={{inputs.TYPO}}"); +} + +#[test] +fn unclosed_placeholder_does_not_hang_or_panic() { + let out = substitute( + "prefix {{ inputs.NEVER_CLOSED", + &Default::default(), + &Default::default(), + "app", + "app", + "id", + "net", + ); + assert!(out.contains("prefix ")); + assert!(out.contains("NEVER_CLOSED")); +} + +#[test] +fn whitespace_inside_the_placeholder_braces_is_tolerated() { + let mut inputs = std::collections::HashMap::new(); + inputs.insert("K".to_string(), "v".to_string()); + for form in ["{{inputs.K}}", "{{ inputs.K }}", "{{ inputs.K }}"] { + let out = substitute(form, &inputs, &Default::default(), "a", "a", "i", "n"); + assert_eq!(out, "v", "failed for {form}"); + } +} + +// --------------------------------------------------------------------------- +// post_install outputs — what the dashboard shows the user after installing +// --------------------------------------------------------------------------- + +#[test] +fn connection_uri_output_carries_the_generated_password() { + // If this breaks, the dashboard shows a URI the user cannot connect with. + let out = render_fixture("shop", &[("DB_USER", "svc"), ("DB_NAME", "orders")]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + + let (label, uri) = out + .outputs + .iter() + .find(|(l, _)| l == "Internal connection URI") + .expect("template declares a connection URI output"); + + assert_eq!(label, "Internal connection URI"); + assert_eq!( + uri, + &format!("proto://svc:{password}@ployer-shop-fixture:5432/orders") + ); +} + +#[test] +fn template_without_post_install_renders_no_outputs() { + let mut template = fixture(); + template.post_install = None; + + let out = render(&template, ctx("app", &[])).unwrap(); + assert!(out.post_install_message.is_none()); + assert!(out.outputs.is_empty()); +} + +#[cfg(test)] +mod password_in_compose { + use super::*; + + #[test] + fn resolved_password_is_the_one_written_into_the_compose() { + // resolved_inputs is persisted and shown to the user; the compose is what + // actually starts the container. They must agree. + let out = render_fixture("app", &[]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + assert!( + out.compose + .contains(&format!("DB_PASSWORD: \"{password}\"")), + "compose must carry the same password that was reported to the user" + ); + } +} + +// --------------------------------------------------------------------------- +// {{ app.slug }} placeholder +// +// From `0c80422` on main. Container names are built from the slugified app +// name, so this is the only placeholder whose output Docker DNS will answer +// for. Kept alongside the engine tests above rather than in a second file. +// --------------------------------------------------------------------------- /// Minimal template whose compose/message/outputs all echo the same expression, /// so one fixture exercises every `substitute()` call site in `render()`. @@ -33,15 +462,6 @@ fn template_echoing(expr: &str) -> Template { } } -fn ctx(app_name: &str) -> RenderContext<'_> { - RenderContext { - app_name, - app_id: "app-id-0001", - network: "ployer", - inputs: HashMap::new(), - } -} - /// An `Application` as `deployment.rs` sees it, so the container-name assertion /// goes through the real `Application::slug()` rather than a copy of it. fn application_named(name: &str) -> Application { @@ -68,7 +488,7 @@ fn application_named(name: &str) -> Application { #[test] fn app_slug_resolves_everywhere_a_placeholder_is_substituted() { let template = template_echoing("{{ app.slug }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:my-service-app"); assert_eq!( @@ -91,7 +511,7 @@ fn app_slug_renders_the_container_name_deployment_uses() { let service_name = "postgresql"; let template = template_echoing("ployer-{{ app.slug }}-postgresql"); - let rendered = render(&template, ctx(app_name)).expect("render"); + let rendered = render(&template, ctx(app_name, &[])).expect("render"); let container_name = format!( "ployer-{}-{}", @@ -109,7 +529,7 @@ fn app_slug_renders_the_container_name_deployment_uses() { #[test] fn app_name_still_renders_the_raw_name() { let template = template_echoing("{{ app.name }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:My Service App"); } @@ -120,7 +540,7 @@ fn app_name_still_renders_the_raw_name() { #[test] fn unknown_placeholder_is_re_emitted_literally() { let template = template_echoing("{{ app.unknown }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:{{app.unknown}}"); } diff --git a/crates/ployer-templates/src/schema_tests.rs b/crates/ployer-templates/src/schema_tests.rs index d911082..bb5e0ef 100644 --- a/crates/ployer-templates/src/schema_tests.rs +++ b/crates/ployer-templates/src/schema_tests.rs @@ -1,5 +1,304 @@ use super::*; +// --------------------------------------------------------------------------- +// Template parsing +// +// Templates are fetched as YAML from a remote registry that ships +// independently of this binary. Parsing has to be forgiving about what is +// absent and strict about what is required. +// --------------------------------------------------------------------------- + +const MINIMAL: &str = r#" +slug: fixture +name: Fixture +description: Fixture service. +category: database +version: 1 +compose: | + services: + fixture: + image: fixture:1-alpine +"#; + +#[test] +fn a_template_needs_only_identity_and_a_compose_body() { + let t: Template = serde_yaml::from_str(MINIMAL).expect("minimal template must parse"); + + assert_eq!(t.slug, "fixture"); + assert_eq!(t.name, "Fixture"); + assert_eq!(t.category, "database"); + assert!(t.compose.contains("image: fixture:1-alpine")); +} + +#[test] +fn optional_sections_default_to_empty_rather_than_failing() { + let t: Template = serde_yaml::from_str(MINIMAL).unwrap(); + + assert!(t.tags.is_empty()); + assert!(t.inputs.is_empty()); + assert!(t.ports.is_empty()); + assert!(t.volumes.is_empty()); + assert!(t.post_install.is_none()); +} + +#[test] +fn a_template_without_a_compose_body_is_rejected() { + let yaml = "slug: fixture\nname: Fixture\ndescription: d\ncategory: database\nversion: 1\n"; + assert!( + serde_yaml::from_str::