Skip to content

Commit

Permalink
nixos/caddy: validate config on build by default
Browse files Browse the repository at this point in the history
  • Loading branch information
6543 committed Feb 10, 2025
1 parent 15fdb27 commit a3b281a
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions nixos/modules/services/web-servers/caddy/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,28 @@ let
configPath = "/etc/${etcConfigFile}";

mkCertOwnershipAssertion = import ../../../security/acme/mk-cert-ownership-assertion.nix lib;

validateCaddyConfig =
adapter: configFile:
builtins.fromJSON (
builtins.readFile (
pkgs.runCommand "caddy-validate"
{
nativeBuildInputs = [ cfg.package ];
}
''
if caddy validate --adapter ${toString adapter} --config ${configFile}; then
echo "true" > $out
else
echo "false" > $out
fi
''
)
);

configValidationResult = validateCaddyConfig (
if cfg.adapter != null then cfg.adapter else "caddyfile"
) cfg.configFile;
in
{
imports = [
Expand Down Expand Up @@ -378,6 +400,16 @@ in
[here](https://caddyserver.com/docs/caddyfile/concepts#environment-variables)
'';
};

enforceConfigValidation = mkOption {
type = types.bool;
default = true;
description = ''
Whether to enforce Caddy configuration validation during build.
If true, invalid configuration will cause the build to fail.
If false, invalid configuration will only show a warning.
'';
};
};

# implementation
Expand All @@ -390,6 +422,10 @@ in
message = "To specify an adapter other than 'caddyfile' please provide your own configuration via `services.caddy.configFile`";
}
]
++ optional cfg.enforceConfigValidation {
assertion = configValidationResult;
message = "Caddy configuration validation failed. Check your configuration.";
}
++ map (
name:
mkCertOwnershipAssertion {
Expand All @@ -399,6 +435,10 @@ in
}
) vhostCertNames;

warnings = lib.optional (
!cfg.enforceConfigValidation && !configValidationResult
) "Caddy configuration validation failed. The service might not start correctly.";

services.caddy.globalConfig = ''
${optionalString (cfg.email != null) "email ${cfg.email}"}
${optionalString (cfg.acmeCA != null) "acme_ca ${cfg.acmeCA}"}
Expand Down

0 comments on commit a3b281a

Please sign in to comment.