Skip to content

validation

napt.validation

Recipe validation module.

This module provides validation functions for checking recipe syntax and configuration without making network calls or downloading files. This is useful for quick feedback during recipe development and in CI/CD pipelines. napt validate checks the effective configuration (code defaults, org.yaml, vendor defaults, parent, recipe), the same merge every other command loads, so an error in any layer is reported before a pipeline runs into it.

Validation Checks:

  • YAML syntax is valid
  • Required top-level fields present (apiVersion, name, id, discovery)
  • apiVersion is present (a value other than napt/v1 is a warning)
  • id is usable as a folder name (letters, digits, '.', '-', '_', '+', starting with a letter or digit); an id outside the recommended <vendor>-<app> form (lowercase, digits, single hyphens) is a warning
  • parent, when declared, is a string and the file carries the .override.yaml suffix (a mismatch either way is a warning)
  • discovery.strategy exists and is registered
  • Strategy-specific configuration is valid
  • Every section (top level, discovery, psadt, psadt.brand_pack, intune, intune.detection, logging, directories, intunewin, deployment, secrets) is checked against its schema: field types, allowed values, integer bounds, and a warning for each unknown key naming the closest known one
  • A section present but left empty is an error
  • intune.minimum_supported_windows_release matches the Windows10_21H2 or Windows11_23H2 form
  • psadt.app_vars only contains user-settable keys
  • psadt.brand_pack.mappings entries each name a source and a target
  • deployment ring names and groups are present and unique
  • secrets section entries are shaped as NAME: {hosts: [...]}, come from defaults/org.yaml alone, and every ${NAME} a recipe sends is declared and bound to the request host (see napt.secrets)
  • A directory of recipes contains no two files with the same id

ValidationResult dataclass

Result from validating a recipe.

Attributes:

Name Type Description
errors list[str]

List of error messages (empty if valid).

warnings list[str]

List of warning messages.

recipe_path str

String path to the validated recipe file.

parent_path str | None

String path to the parent recipe merged beneath it, or None when the recipe declares no parent.

app_id str | None

The recipe's id, or None when it has no usable one.

config dict[str, Any] | None

The effective configuration that was validated, provenance included, when the recipe is valid; None when it has errors.

Source code in napt/validation.py
@dataclass(frozen=True)
class ValidationResult:
    """Result from validating a recipe.

    Attributes:
        errors: List of error messages (empty if valid).
        warnings: List of warning messages.
        recipe_path: String path to the validated recipe file.
        parent_path: String path to the parent recipe merged beneath it, or
            None when the recipe declares no parent.
        app_id: The recipe's id, or None when it has no usable one.
        config: The effective configuration that was validated, provenance
            included, when the recipe is valid; None when it has errors.
    """

    errors: list[str]
    warnings: list[str]
    recipe_path: str
    parent_path: str | None = None
    app_id: str | None = None
    config: dict[str, Any] | None = None

    @property
    def is_valid(self) -> bool:
        """Whether the recipe passed: no errors were found."""
        return not self.errors

is_valid property

is_valid: bool

Whether the recipe passed: no errors were found.

validate_config

validate_config(
    config: dict[str, Any], recipe_path: str = ""
) -> ValidationResult

Validates a merged configuration dict.

Checks required fields, types, strategy registration, and section-level validation. Used by both validate_recipe (CLI) and load_effective_config (pipeline commands) so that one set of rules applies everywhere. When the dict carries the loader's _provenance entry, the secrets check also reports entries that a layer other than org.yaml tried to declare.

Parameters:

Name Type Description Default
config dict[str, Any]

The merged configuration dictionary to validate.

required
recipe_path str

Optional path string for error context.

''

Returns:

Type Description
ValidationResult

Validation status, errors, warnings, app count, and the app id.

Source code in napt/validation.py
def validate_config(
    config: dict[str, Any],
    recipe_path: str = "",
) -> ValidationResult:
    """Validates a merged configuration dict.

    Checks required fields, types, strategy registration, and section-level
    validation. Used by both ``validate_recipe`` (CLI) and
    ``load_effective_config`` (pipeline commands) so that one set of rules
    applies everywhere. When the dict carries the loader's ``_provenance``
    entry, the secrets check also reports entries that a layer other than
    org.yaml tried to declare.

    Args:
        config: The merged configuration dictionary to validate.
        recipe_path: Optional path string for error context.

    Returns:
        Validation status, errors, warnings, app count, and the app id.

    """
    logger = get_global_logger()

    errors: list[str] = []
    warnings: list[str] = []

    # Types of every top-level field, empty sections, and unknown keys.
    top_level = {k: v for k, v in config.items() if k not in _INTERNAL_KEYS}
    _validate_section(top_level, _TOP_LEVEL_FIELDS, "", errors, warnings)

    for field in ("apiVersion", "name", "id", "discovery"):
        if field not in config:
            errors.append(f"Missing required field: {field}")

    api_version = config.get("apiVersion")
    if isinstance(api_version, str):
        if api_version != "napt/v1":
            warnings.append(
                f"apiVersion '{api_version}' may not be supported (expected: napt/v1)"
            )
        logger.verbose("CONFIG", f"apiVersion: {api_version}")

    app_id = config.get("id")
    if isinstance(app_id, str):
        if not app_id:
            errors.append("Field 'id' cannot be empty")
        elif not is_safe_path_component(app_id):
            # The id names the app's download, build, package, and state
            # folders, so it must be usable as a folder name as-is.
            errors.append(
                "Field 'id' may contain only letters, digits, '.', '-', '_', "
                "and '+', and must start with a letter or digit"
            )
        elif not _RECOMMENDED_ID.fullmatch(app_id):
            warnings.append(
                f"id '{app_id}' works but does not follow the recommended form: "
                f"lowercase letters, digits, and single hyphens, as "
                f"<vendor>-<app> (for example google-chrome or 7zip-x64-msi)"
            )

    _validate_parent_field(config, recipe_path, warnings)

    app_name = config.get("name", "unnamed")
    logger.verbose("CONFIG", f"Validating: {app_name}")

    discovery = config.get("discovery")
    if isinstance(discovery, dict):
        _validate_discovery_section(discovery, config, app_name, errors, warnings)

    _validate_psadt_section(config, errors, warnings)
    _validate_intune_section(config, errors, warnings)
    _validate_table_section(config, "logging", _LOGGING_FIELDS, errors, warnings)
    _validate_table_section(
        config, "directories", _DIRECTORIES_FIELDS, errors, warnings
    )
    _validate_table_section(config, "intunewin", _INTUNEWIN_FIELDS, errors, warnings)
    _validate_deployment_section(config, errors, warnings)
    _validate_secrets_section(config, errors, warnings)

    if errors:
        logger.verbose("CONFIG", f"Recipe has {len(errors)} error(s)")
    else:
        logger.verbose("CONFIG", "Recipe is valid!")

    app_id = config.get("id")
    return ValidationResult(
        errors=errors,
        warnings=warnings,
        recipe_path=recipe_path,
        app_id=app_id if isinstance(app_id, str) and app_id else None,
    )

validate_recipe

validate_recipe(recipe_path: Path) -> ValidationResult

Validates a recipe's effective configuration.

Merges the recipe with its parent, vendor defaults, and org.yaml the way every other command does, then validates the result, so an error in any layer is reported here. A file that cannot be read or merged (a missing file, a YAML syntax error, a missing parent) is an invalid result rather than an exception.

Parameters:

Name Type Description Default
recipe_path Path

Path to the recipe YAML file to validate.

required

Returns:

Type Description
ValidationResult

The errors, warnings, app id, the parent path when the recipe declares one, and the effective configuration when it is valid.

Example

Validate a recipe and check results:

from pathlib import Path

result = validate_recipe(Path("recipes/app.yaml"))
if result.is_valid:
    print("Recipe is valid!")
else:
    for error in result.errors:
        print(f"Error: {error}")

Source code in napt/validation.py
def validate_recipe(recipe_path: Path) -> ValidationResult:
    """Validates a recipe's effective configuration.

    Merges the recipe with its parent, vendor defaults, and org.yaml the
    way every other command does, then validates the result, so an error
    in any layer is reported here. A file that cannot be read or merged (a
    missing file, a YAML syntax error, a missing parent) is an invalid
    result rather than an exception.

    Args:
        recipe_path: Path to the recipe YAML file to validate.

    Returns:
        The errors, warnings, app id, the parent path when the recipe
            declares one, and the effective configuration when it is valid.

    Example:
        Validate a recipe and check results:
            ```python
            from pathlib import Path

            result = validate_recipe(Path("recipes/app.yaml"))
            if result.is_valid:
                print("Recipe is valid!")
            else:
                for error in result.errors:
                    print(f"Error: {error}")
            ```

    """
    logger = get_global_logger()
    recipe_path_str = str(recipe_path)
    logger.verbose("CONFIG", f"Validating recipe: {recipe_path}")

    try:
        merged, parent_path = merge_effective_config(recipe_path)
    except ConfigError as err:
        return ValidationResult(
            errors=[str(err)], warnings=[], recipe_path=recipe_path_str
        )
    logger.verbose("CONFIG", "YAML syntax is valid")
    if parent_path is not None:
        logger.verbose("CONFIG", f"Parent recipe: {parent_path}")

    result = validate_config(merged, recipe_path=recipe_path_str)
    if parent_path is not None:
        result = replace(result, parent_path=str(parent_path))
    if result.errors:
        return result
    # The parent's contents are merged in; the pointer itself is not config.
    merged.pop("parent", None)
    merged["_provenance"].pop("parent", None)
    return replace(result, config=merged)

validate_recipes

validate_recipes(path: Path) -> list[ValidationResult]

Validates a recipe file or every recipe under a directory.

Each file is validated with validate_recipe. For a directory, two files that resolve to the same id are also reported (a parent recipe scanned beside the child that inherits its id is the usual cause), since napt promote refuses such a directory.

Parameters:

Name Type Description Default
path Path

A recipe YAML file, or a directory scanned recursively.

required

Returns:

Type Description
list[ValidationResult]

One result per recipe file, in path order; a single invalid result when the path does not exist or holds no recipes.

Source code in napt/validation.py
def validate_recipes(path: Path) -> list[ValidationResult]:
    """Validates a recipe file or every recipe under a directory.

    Each file is validated with
    [validate_recipe][napt.validation.validate_recipe]. For a directory,
    two files that resolve to the same id are also reported (a parent
    recipe scanned beside the child that inherits its id is the usual
    cause), since ``napt promote`` refuses such a directory.

    Args:
        path: A recipe YAML file, or a directory scanned recursively.

    Returns:
        One result per recipe file, in path order; a single invalid result
            when the path does not exist or holds no recipes.
    """
    try:
        paths = collect_recipe_paths(path)
    except ConfigError as err:
        return [ValidationResult(errors=[str(err)], warnings=[], recipe_path=str(path))]

    results: list[ValidationResult] = []
    sources: dict[str, Path] = {}
    for recipe_path in paths:
        result = validate_recipe(recipe_path)
        if result.is_valid and result.app_id is not None:
            duplicate = register_recipe_id(sources, result.app_id, recipe_path)
            if duplicate is not None:
                result = replace(result, errors=[*result.errors, duplicate])
        results.append(result)
    return results