nixos-config/nix/verify/modules/http.nix

93 lines
2.3 KiB
Nix
Raw Normal View History

2024-09-16 02:06:03 +02:00
{
lib,
config,
pkgs,
...
}:
with lib;
with types;
{
options.verify.http = mkOption {
default = { };
2024-09-16 03:53:03 +02:00
example = {
github = {
url = "https://github.com";
expectedContent = "GitHub";
};
};
2024-09-16 02:06:03 +02:00
description = ''
2024-09-16 03:53:03 +02:00
Run curl commands to verify if response code is as expected and expectedContent is part of the body.
2024-09-16 02:06:03 +02:00
'';
type = attrsOf (submodule {
options = {
url = mkOption {
type = str;
description = ''
URL to analyze.
'';
};
responseCode = mkOption {
type = int;
default = 200;
description = ''
2024-09-16 03:53:03 +02:00
Expected response code
2024-09-16 02:06:03 +02:00
'';
};
expectedContent = mkOption {
type = nullOr str;
description = ''
2024-09-16 03:53:03 +02:00
Expected string in the response
2024-09-16 02:06:03 +02:00
'';
};
};
});
};
config = {
verify.localCommands =
let
curl = lib.getExe pkgs.curl;
grep = lib.getExe pkgs.gnugrep;
scriptWithExpectedContent = url: responseCode: expectedContent: ''
if ${curl} -s -o /dev/null -w "%{http_code}" ${url} | ${grep} -q "${toString responseCode}"; then
if ${curl} -s ${url} | ${grep} -q "${expectedContent}"; then
echo -n ""
else
echo " [Fail] ${url} did return ${toString responseCode}, but did not contain the string '${expectedContent}'."
2024-09-16 02:06:03 +02:00
fi
else
echo " [Fail] ${url} did not return ${toString responseCode}."
2024-09-16 02:06:03 +02:00
fi
'';
scriptWithoutExpectedContent = url: responseCode: ''
if ${curl} -s -o /dev/null -w "%{http_code}" ${url} | ${grep} -q "${toString responseCode}"; then
echo -n ""
else
echo " [Fail] ${url} did not return ${toString responseCode}."
2024-09-16 02:06:03 +02:00
fi
'';
script =
url: responeCode: expectedContent:
if (expectedContent == null) then
scriptWithExpectedContent url responeCode expectedContent
else
scriptWithoutExpectedContent url responeCode;
in
mapAttrs' (
service:
{
url,
responseCode,
expectedContent,
}:
nameValuePair ("http_" + service) (script url responseCode expectedContent)
) config.verify.http;
};
}