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

95 lines
2.6 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 ""
#echo " [ OK ] Die Seite hat Statuscode ${toString responseCode} und enthält den String '${expectedContent}'."
else
echo " [Fail] Der Statuscode ist 200, aber die Seite enthält den String '${expectedContent}' nicht."
fi
else
echo " [Fail] Die Seite hat keinen Statuscode ${toString responseCode}."
fi
'';
scriptWithoutExpectedContent = url: responseCode: ''
if ${curl} -s -o /dev/null -w "%{http_code}" ${url} | ${grep} -q "${toString responseCode}"; then
echo -n ""
#echo " [ OK ] Die Seite hat Statuscode ${toString responseCode}."
else
echo " [Fail] Die Seite hat keinen Statuscode ${toString responseCode}."
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;
};
}