Skip to main content

stackless_core/def/
validate.rs

1//! Definition validation: everything that fails "at parse time, not at
2//! `up` time" (ARCHITECTURE.md §1 resolution rules).
3//!
4//! Core knows no substrate by name (ground rule: the Substrate trait is
5//! the only provider seam); callers pass the names of registered
6//! substrates so unknown keys can be told apart from substrate blocks.
7
8use std::collections::BTreeMap;
9
10use super::error::DefError;
11use super::interp::{self, Reference};
12use super::model::{Integration, Service, StackDef};
13
14impl StackDef {
15    /// Validate the whole definition against the rules registered substrates share.
16    /// Callers pass the names of registered substrates (core knows none by name).
17    pub fn validate_hosts(&self, known_substrates: &[&str]) -> Result<(), DefError> {
18        validate_definition(self, known_substrates)
19    }
20
21    /// `up --on <s>` fails at validation if any service lacks the config
22    /// that substrate requires (ARCHITECTURE.md §2).
23    pub fn validate_for_substrate(&self, substrate: &str) -> Result<(), DefError> {
24        for (name, service) in &self.services {
25            let target = service.on.as_deref().unwrap_or(substrate);
26            if !service.substrates.contains_key(target)
27                && service.run.is_none()
28                && service.image.is_none()
29            {
30                return Err(DefError::SubstrateConfigMissing {
31                    service: name.clone(),
32                    substrate: target.to_owned(),
33                });
34            }
35        }
36        Ok(())
37    }
38}
39
40fn validate_definition(def: &StackDef, known_substrates: &[&str]) -> Result<(), DefError> {
41    if !crate::types::dns_safe(def.stack.name.as_str()) {
42        return Err(DefError::NameInvalid {
43            kind: "stack",
44            name: def.stack.name.as_str().to_owned(),
45        });
46    }
47    if def.services.is_empty() && def.integrations.is_empty() {
48        return Err(DefError::NoServices);
49    }
50
51    validate_substrate_keys(&def.stack.substrates, "stack", known_substrates)?;
52    validate_integrations(def, known_substrates)?;
53
54    let mut root_origins = Vec::new();
55    for (name, service) in &def.services {
56        if !crate::types::dns_safe(name) {
57            return Err(DefError::NameInvalid {
58                kind: "service",
59                name: name.clone(),
60            });
61        }
62        if service.kind == super::model::WorkloadKind::Service && service.health.is_none() {
63            return Err(DefError::Schema {
64                message: format!("services.{name}.health is required for a service"),
65            });
66        }
67        if service.kind == super::model::WorkloadKind::Job && service.health.is_some() {
68            return Err(DefError::Schema {
69                message: format!(
70                    "jobs.{name} completes with an exit status and cannot declare health"
71                ),
72            });
73        }
74        if let Some(health) = &service.health {
75            health.validate(name)?;
76        }
77        if service.root_origin && service.health.as_ref().is_none_or(|health| health.is_tcp()) {
78            return Err(DefError::Schema {
79                message: format!("services.{name}.root_origin requires an HTTP listener"),
80            });
81        }
82        if service.timeout_secs == 0 || service.timeout_secs > 86400 {
83            return Err(DefError::Schema {
84                message: format!("services.{name}.timeout_secs must be between 1 and 86400"),
85            });
86        }
87        if service.image.as_ref().is_some_and(|image| {
88            image.is_empty()
89                || image
90                    .chars()
91                    .any(|character| character.is_whitespace() || character.is_control())
92        }) {
93            return Err(DefError::Schema {
94                message: format!(
95                    "services.{name}.image must be a nonempty image reference without whitespace"
96                ),
97            });
98        }
99        if !service.source.repo.is_empty() && service.source.path.is_some() {
100            return Err(DefError::Schema {
101                message: format!("services.{name}.source must select repo or path"),
102            });
103        }
104        service.source_root(name, "")?;
105        for provider in service.substrates.keys() {
106            service.source_root(name, provider)?;
107        }
108        if service
109            .on
110            .as_ref()
111            .is_some_and(|on| !known_substrates.contains(&on.as_str()))
112        {
113            return Err(DefError::Schema {
114                message: format!("services.{name}.on names an unknown provider"),
115            });
116        }
117        for (dependency, condition) in &service.depends_on {
118            let Some(target) = def.services.get(dependency) else {
119                return Err(DefError::UndeclaredReference {
120                    location: format!("services.{name}.depends_on"),
121                    kind: "workload",
122                    name: dependency.clone(),
123                });
124            };
125            if dependency == name
126                || (*condition == super::model::DependencyCondition::Completed
127                    && target.kind != super::model::WorkloadKind::Job)
128                || (*condition != super::model::DependencyCondition::Completed
129                    && target.kind == super::model::WorkloadKind::Job)
130            {
131                return Err(DefError::Schema {
132                    message: format!(
133                        "services.{name}.depends_on.{dependency} has an invalid condition for the target workload"
134                    ),
135                });
136            }
137        }
138        if service.root_origin {
139            root_origins.push(name.clone());
140        }
141        validate_substrate_keys(
142            &service.substrates,
143            &format!("services.{name}"),
144            known_substrates,
145        )?;
146        validate_service_references(def, name, service, known_substrates)?;
147    }
148    for (name, endpoint) in &def.endpoints {
149        if !crate::types::dns_safe(name) || !def.services.contains_key(&endpoint.workload) {
150            return Err(DefError::Schema {
151                message: format!("endpoints.{name} must name an existing workload"),
152            });
153        }
154        if def.services[&endpoint.workload].health.is_none() {
155            return Err(DefError::Schema {
156                message: format!("endpoints.{name} requires a workload with a health listener"),
157            });
158        }
159        if let Some(raw) = &endpoint.url {
160            let tcp = def.services[&endpoint.workload]
161                .health
162                .as_ref()
163                .is_some_and(|health| health.is_tcp());
164            let valid = url::Url::parse(raw).is_ok_and(|url| {
165                (if tcp {
166                    url.scheme() == "tcp"
167                        && raw.starts_with("tcp://")
168                        && url.port().is_some_and(|port| port != 0)
169                        && url.path().is_empty()
170                        && url.query().is_none()
171                        && url.fragment().is_none()
172                } else {
173                    matches!(url.scheme(), "http" | "https")
174                        && (raw.starts_with("http://") || raw.starts_with("https://"))
175                }) && url.has_host()
176                    && url.username().is_empty()
177                    && url.password().is_none()
178                    && !raw.chars().any(char::is_whitespace)
179            });
180            if !valid {
181                return Err(DefError::Schema {
182                    message: format!(
183                        "endpoints.{name}.url must match the workload protocol and contain a host without credentials; TCP URLs also require a nonzero port and no path, query, or fragment"
184                    ),
185                });
186            }
187        }
188    }
189    if root_origins.len() > 1 {
190        return Err(DefError::RootOriginConflict {
191            services: root_origins,
192        });
193    }
194
195    if let Some(verify) = &def.stack.verify {
196        if verify.timeout_secs == 0 || verify.timeout_secs > 86400 {
197            return Err(DefError::Schema {
198                message: "stack.verify.timeout_secs must be between 1 and 86400".into(),
199            });
200        }
201        for (key, value) in &verify.env {
202            let location = format!("stack.verify.env.{key}");
203            let refs = interp::references(value, &location)?;
204            validate_references(def, &refs, &location)?;
205        }
206        for (tier, spec) in &verify.tiers {
207            if spec.timeout_secs == 0 || spec.timeout_secs > 86400 {
208                return Err(DefError::Schema {
209                    message: format!(
210                        "stack.verify.tiers.{tier}.timeout_secs must be between 1 and 86400"
211                    ),
212                });
213            }
214            if !crate::types::dns_safe(tier) {
215                return Err(DefError::NameInvalid {
216                    kind: "verify tier",
217                    name: tier.clone(),
218                });
219            }
220            for (key, value) in &spec.env {
221                let location = format!("stack.verify.tiers.{tier}.env.{key}");
222                let refs = interp::references(value, &location)?;
223                validate_references(def, &refs, &location)?;
224            }
225        }
226    }
227
228    Ok(())
229}
230
231fn validate_substrate_keys(
232    substrates: &BTreeMap<String, toml::Value>,
233    location: &str,
234    known_substrates: &[&str],
235) -> Result<(), DefError> {
236    for (key, value) in substrates {
237        if key == "depends_on" {
238            // A dependency must be expressed in wiring; an ordering need
239            // with no wiring expression is a definition bug (§1).
240            return Err(DefError::DependsOnRejected {
241                location: location.to_owned(),
242            });
243        }
244        if !known_substrates.contains(&key.as_str()) {
245            return Err(DefError::UnknownKey {
246                location: location.to_owned(),
247                key: key.clone(),
248                known_substrates: known_substrates.iter().map(|s| (*s).to_owned()).collect(),
249            });
250        }
251        if !value.is_table() {
252            return Err(DefError::SubstrateBlockInvalid {
253                location: format!("{location}.{key}"),
254                found: value.type_str().to_owned(),
255            });
256        }
257    }
258    Ok(())
259}
260
261fn validate_service_references(
262    def: &StackDef,
263    name: &str,
264    service: &Service,
265    known_substrates: &[&str],
266) -> Result<(), DefError> {
267    // Injected same-named secrets must be resolvable before anything
268    // provisions, so they must be in the required list.
269    for key in &service.secrets {
270        if !def.secrets.required.contains(key) {
271            return Err(DefError::SecretNotRequired {
272                location: format!("services.{name}.secrets"),
273                key: key.clone(),
274            });
275        }
276    }
277    for (key, value) in &service.env {
278        let location = format!("services.{name}.env.{key}");
279        let refs = interp::references(value, &location)?;
280        validate_references(def, &refs, &location)?;
281    }
282    // Substrate env overlays participate in wiring (§1: substrate env
283    // blocks overlay the common env), so their references validate too.
284    for substrate in known_substrates {
285        let overlay = service.substrate_env(name, substrate)?;
286        for (key, value) in &overlay {
287            let location = format!("services.{name}.{substrate}.env.{key}");
288            let refs = interp::references(value, &location)?;
289            validate_references(def, &refs, &location)?;
290        }
291    }
292    Ok(())
293}
294
295fn validate_integrations(def: &StackDef, known_substrates: &[&str]) -> Result<(), DefError> {
296    for (name, integration) in &def.integrations {
297        if !crate::types::dns_safe(name) {
298            return Err(DefError::NameInvalid {
299                kind: "integration",
300                name: name.clone(),
301            });
302        }
303        if integration.provider.is_empty() {
304            return Err(DefError::IntegrationInvalid {
305                integration: name.clone(),
306                detail: "provider is required".into(),
307            });
308        }
309        validate_integration_substrate_keys(name, integration, known_substrates)?;
310        validate_integration_string_refs(def, name, integration, known_substrates)?;
311    }
312    Ok(())
313}
314
315fn validate_integration_substrate_keys(
316    name: &str,
317    integration: &Integration,
318    known_substrates: &[&str],
319) -> Result<(), DefError> {
320    let substrates: std::collections::BTreeMap<String, toml::Value> = integration
321        .fields
322        .iter()
323        .filter(|(key, _)| known_substrates.contains(&key.as_str()))
324        .map(|(key, value)| (key.clone(), value.clone()))
325        .collect();
326    validate_substrate_keys(
327        &substrates,
328        &format!("integrations.{name}"),
329        known_substrates,
330    )
331}
332
333fn validate_integration_string_refs(
334    def: &StackDef,
335    name: &str,
336    integration: &Integration,
337    known_substrates: &[&str],
338) -> Result<(), DefError> {
339    for (key, value) in integration.config_fields(known_substrates) {
340        let Some(text) = value.as_str() else {
341            continue;
342        };
343        let location = format!("integrations.{name}.{key}");
344        let refs = interp::references(text, &location)?;
345        validate_references(def, &refs, &location)?;
346    }
347    for substrate in known_substrates {
348        let Some(block) = integration.host_block(substrate) else {
349            continue;
350        };
351        for (key, value) in block {
352            let Some(text) = value.as_str() else {
353                continue;
354            };
355            let location = format!("integrations.{name}.{substrate}.{key}");
356            let refs = interp::references(text, &location)?;
357            validate_references(def, &refs, &location)?;
358        }
359    }
360    Ok(())
361}
362
363fn validate_references(def: &StackDef, refs: &[Reference], location: &str) -> Result<(), DefError> {
364    for reference in refs {
365        match reference {
366            Reference::StackName | Reference::InstanceName => {}
367            Reference::ServiceOrigin(target) => {
368                if !def.services.contains_key(target) {
369                    return Err(DefError::UndeclaredReference {
370                        location: location.to_owned(),
371                        kind: "service",
372                        name: target.clone(),
373                    });
374                }
375                if def.services[target].health.is_none() {
376                    return Err(DefError::Schema {
377                        message: format!("{location}: workload {target:?} has no listener origin"),
378                    });
379                }
380            }
381            Reference::EndpointUrl(target) => {
382                if location.starts_with("integrations.") {
383                    return Err(DefError::Schema {
384                        message: format!(
385                            "{location}: endpoint URL references are supported only in workload and verification environments"
386                        ),
387                    });
388                }
389                if !def.endpoints.contains_key(target) {
390                    return Err(DefError::UndeclaredReference {
391                        location: location.to_owned(),
392                        kind: "endpoint",
393                        name: target.clone(),
394                    });
395                }
396            }
397            Reference::DatastoreUrl(target) => {
398                // Fresh files cannot declare `[datastores.*]`; only
399                // snapshot resume populates `legacy_datastores`.
400                if !def.legacy_datastores.contains(target) {
401                    return Err(DefError::UndeclaredReference {
402                        location: location.to_owned(),
403                        kind: "datastore",
404                        name: target.clone(),
405                    });
406                }
407            }
408            Reference::Secret(key) => {
409                if !def.secrets.required.contains(key) {
410                    return Err(DefError::SecretNotRequired {
411                        location: location.to_owned(),
412                        key: key.clone(),
413                    });
414                }
415            }
416            Reference::IntegrationOutput { integration, .. } => {
417                if !def.integrations.contains_key(integration) {
418                    return Err(DefError::UndeclaredReference {
419                        location: location.to_owned(),
420                        kind: "integration",
421                        name: integration.clone(),
422                    });
423                }
424            }
425        }
426    }
427    Ok(())
428}
429
430#[cfg(test)]
431mod tests {
432    use crate::def::StackDef;
433    use crate::types::dns_safe;
434
435    #[test]
436    fn dns_safety() {
437        assert!(dns_safe("atto"));
438        assert!(dns_safe("a1-b2"));
439        assert!(!dns_safe(""));
440        assert!(!dns_safe("Atto"));
441        assert!(!dns_safe("1atto"));
442        assert!(!dns_safe("atto-"));
443        assert!(!dns_safe("at to"));
444        assert!(!dns_safe(&"a".repeat(64)));
445    }
446
447    #[test]
448    fn verification_deadlines_default_and_reject_invalid_default_or_tier_budgets() {
449        let base = "[stack]\nname='verify-test'\n[jobs.task]\nrun='true'\n";
450        let def = StackDef::parse(&format!(
451            "{base}\n[stack.verify]\nrun='true'\n[stack.verify.tiers.integration]\nrun='true'\n"
452        ))
453        .unwrap();
454        def.validate_hosts(&["local"]).unwrap();
455        let verify = def.stack.verify.unwrap();
456        assert_eq!(verify.resolve(None).unwrap().timeout_secs, 300);
457        assert_eq!(
458            verify.resolve(Some("integration")).unwrap().timeout_secs,
459            300
460        );
461        for table in ["stack.verify", "stack.verify.tiers.integration"] {
462            for budget in [0, 86401] {
463                let def = StackDef::parse(&format!(
464                    "{base}\n[{table}]\nrun='true'\ntimeout_secs={budget}\n"
465                ))
466                .unwrap();
467                assert!(
468                    def.validate_hosts(&["local"])
469                        .unwrap_err()
470                        .to_string()
471                        .contains("timeout_secs")
472                );
473            }
474        }
475    }
476
477    #[test]
478    fn verify_tier_keys_must_be_dns_safe() {
479        let text = r#"
480[stack]
481name = "bad"
482
483[stack.verify.tiers."a);func"]
484run = "true"
485
486[services.web]
487source = { repo = "https://example.invalid/x", ref = "main" }
488health = { path = "/" }
489
490[services.web.local]
491run = "true"
492"#;
493        let def = StackDef::parse(text).expect("parse");
494        let err = def.validate_hosts(&["local"]).expect_err("tier name");
495        assert!(matches!(
496            err,
497            crate::def::DefError::NameInvalid {
498                kind: "verify tier",
499                ..
500            }
501        ));
502    }
503}