Files
homelab/services/dev/gitea-hermes-webhook-relay.nix
T
darmanandClaude Opus 5 1fc4395068 hermes: add read-only Gitea PR comment filter, break the reply loop
The gitea-events subscription woke the agent on every delivery. That is an
unbounded loop as soon as she is given a prompt that tells her to answer on
the PR: her answer is itself a pull_request_comment, which wakes her again.

Adds a Hermes route script that drops the deliveries that must never reach an
LLM call: luna's own comments (the loop guard), "deleted" actions (the body
is still in the payload, so acting on one means acting on a request that was
explicitly withdrawn), non-pull-request comments, empty bodies, and edits
that did not actually change the body — a label or attachment change fires
"edited" too. Everything else passes through unchanged.

Mounted READ-ONLY from the nix store rather than written into hermesHome.
Hermes resolves route scripts under ~/.hermes/scripts, which here is inside
/opt/data — HERMES_WRITE_SAFE_ROOT — so a filter written there would be a
loop guard sitting in the writable root of the agent it constrains. Deleting
it fails closed (Hermes treats a missing script as "ignore"), but rewriting
it to always-allow would silently restore the loop. Read-only from the store
makes that impossible and keeps the guard in git.

The script also normalises changes.body.from to always exist. Gitea omits
`changes` entirely on created events, and Hermes replaces the prompt payload
with whatever JSON the script emits, so guaranteeing the key here means a
prompt referencing {changes.body.from} renders empty instead of leaving an
unfilled placeholder.

Note the stdout contract (gateway/platforms/webhook.py): only exactly
"[SILENT]", empty output, or a nonzero exit drop a delivery. Any OTHER text
on stdout lets it through and is attached as script_output — so a stray
debug print would silently defeat the filter. All diagnostics go to stderr,
and gitea-pr-comment-filter-test.py asserts that discipline along with each
drop rule (25 cases). Run it after any edit: the fail-closed behaviour means
a syntax error produces silence, not an error.

--events is still unset; event selection remains runtime-tunable policy.
The filter covers only what must not be.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S94o42aQ8VkBmEWvDem5xa
2026-08-23 06:32:31 +02:00

125 lines
5.2 KiB
Nix

{ config, pkgs, ... }:
# Gitea -> Hermes webhook relay.
#
# Why this exists at all, since Gitea could POST straight at Hermes's own
# webhook port (8644, already tailnet-reachable — tailscale0 is a
# trustedInterface): AUTH would work directly. Gitea's addDefaultHeaders()
# signs every webhook type with `X-Hub-Signature-256: sha256=<hmac>`, the
# exact GitHub scheme, and Hermes accepts that header on any route with no
# per-route provider gating. What does NOT work directly is EVENT SELECTION.
# Hermes reads the event name from `X-GitHub-Event`/`X-GitLab-Event`, then
# the payload's `event_type`/`type` keys, then gives up and calls it
# "unknown". Gitea sends `X-Gitea-Event` and no such payload key, so a direct
# hook authenticates fine and then arrives as "unknown" forever — which makes
# `hermes webhook subscribe --events ...` unable to select anything, i.e. the
# "Hermes owns event policy" split this module is built around cannot exist
# without something copying that one header.
#
# So that is all this does: verify the signature, copy X-Gitea-Event into
# X-GitHub-Event, forward body and signature untouched. No re-signing, no
# payload rewriting, no event/repo/action filtering.
#
# It binds 0.0.0.0 but gets no allowedTCPPorts entry, so it is reachable over
# tailscale0 only — same posture as the Hermes dashboard on 9119.
let
relayScript = pkgs.writeText "gitea-hermes-webhook-relay.py" (
builtins.readFile ./gitea-hermes-webhook-relay.py
);
in
{
systemd.services.gitea-hermes-webhook-relay = {
description = "Relay Gitea webhooks to Hermes with a Hermes-readable event header";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [
"network-online.target"
"podman-hermes-agent.service"
"tailscaled-autoconnect.service"
];
environment = {
LISTEN_HOST = "0.0.0.0";
LISTEN_PORT = "8645";
HERMES_WEBHOOK_URL = "http://127.0.0.1:8644/webhooks/gitea-events";
MAX_BODY_BYTES = "1048576";
};
serviceConfig = {
ExecStart = "${pkgs.python3}/bin/python ${relayScript}";
LoadCredential = [
"webhook_secret:${config.sops.secrets.gitea_hermes_webhook_secret.path}"
];
DynamicUser = true;
Restart = "on-failure";
RestartSec = 5;
PrivateDevices = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
NoNewPrivileges = true;
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
RestrictRealtime = true;
UMask = "0077";
};
};
# The relay forwards into a generic Hermes webhook subscription. Keep the
# subscription declaratively present without putting event policy or prompt
# text in this transport unit. Hermes owns interpretation and response policy.
#
# `--events` is deliberately omitted: an empty events list means "accept
# everything", and the selection is Hermes-side policy that darman can
# retune with `hermes webhook subscribe` at runtime without a redeploy.
# That only works because the relay supplies X-GitHub-Event — see the
# header comment above.
#
# --script does the selection that MUST NOT be retunable at runtime.
# hosts/mars/gitea-pr-comment-filter.py drops luna's own comments before
# any LLM call, which is what stops the reply loop: the prompt tells her to
# answer on the PR, and her answer is itself a pull_request_comment. It is
# bind-mounted read-only from the nix store (see hosts/mars/hermes-agent.nix)
# so the agent cannot edit its own guard out. Hermes resolves the name
# relative to ~/.hermes/scripts, hence the bare filename here.
#
# The secret is read from the CONTAINER's environment ($GITEA_HERMES_
# WEBHOOK_SECRET, injected via sops.templates."hermes-agent.env"), which is
# why hosts/mars/secrets.nix restarts podman-hermes-agent BEFORE this unit
# on rotation — re-subscribing against a container still holding the old
# value would silently pin the stale secret.
systemd.services.hermes-agent-webhook-route = {
description = "Configure Hermes Gitea event webhook route";
wantedBy = [ "multi-user.target" ];
after = [ "podman-hermes-agent.service" ];
requires = [ "podman-hermes-agent.service" ];
path = [ pkgs.podman ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
set -euo pipefail
# The container unit is ordered before us, but its gateway may still be
# warming up while the image initializes its persistent state directory.
for _ in $(seq 1 60); do
if podman exec hermes-agent hermes webhook list >/dev/null 2>&1; then
break
fi
sleep 1
done
podman exec hermes-agent hermes webhook remove gitea-pr-comments >/dev/null 2>&1 || true
podman exec hermes-agent hermes webhook remove gitea-events >/dev/null 2>&1 || true
podman exec hermes-agent sh -c '
hermes webhook subscribe gitea-events \
--secret "$GITEA_HERMES_WEBHOOK_SECRET" \
--description "Forward authenticated Gitea events to L.U.N.A." \
--script gitea-pr-comment-filter.py \
--deliver telegram --deliver-chat-id "15151223"
'
'';
};
}