Custom Caddy with CrowdSec bouncer, AppSec and rate limiting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-27 12:17:00 -07:00
commit f9c44868a4
5 files changed
+266

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
# Builds git.thesatelliteoflove.com/phil/caddy (Caddy + CrowdSec bouncer/AppSec
# + rate limiting) and keeps it current: a daily run fingerprints the upstream
# versions and only builds when something changed. dockcheck on the server
# then rolls the new :2 out (after its DaysOld wait).
#
# The runner has no Docker daemon; images are built by the rootless BuildKit
# container next to it, reached through its socket (same as StarPunk).
name: Build custom Caddy
on:
schedule:
- cron: '30 4 * * *' # daily, before dockcheck at 08:00
push:
branches: [main]
workflow_dispatch:
inputs:
force:
description: Rebuild even if this fingerprint was already built
type: boolean
default: false
env:
REGISTRY: git.thesatelliteoflove.com
IMAGE: git.thesatelliteoflove.com/phil/caddy
BUILDKIT: unix:///run/buildkit/buildkit/buildkitd.sock
ANSIBLE_REPO: https://git.thesatelliteoflove.com/phil/ansible.git
GOTIFY_URL: http://gotify # the runner is on lava
jobs:
build:
runs-on: docker
steps:
- name: Install tools
run: |
apk add --no-cache nodejs git curl jq python3 py3-yaml py3-jinja2 docker-cli docker-cli-buildx
curl -fsSL -o /usr/local/bin/regctl https://github.com/regclient/regclient/releases/latest/download/regctl-linux-amd64
chmod +x /usr/local/bin/regctl
- name: Checkout
uses: actions/checkout@v4
- name: Resolve upstream versions
id: v
run: |
set -euo pipefail
# Follow what Docker Hub has published, so -builder and -alpine exist
CADDY_VERSION=$(regctl image config caddy:2-alpine --platform linux/amd64 \
--format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^CADDY_VERSION=v//p')
test -n "$CADDY_VERSION"
regctl image digest "caddy:${CADDY_VERSION}-builder" >/dev/null
BASE_DIGEST=$(regctl image digest "caddy:${CADDY_VERSION}-alpine")
BOUNCER=$(curl -fsSL https://api.github.com/repos/hslatman/caddy-crowdsec-bouncer/releases/latest | jq -r .tag_name)
RL_SHA=$(curl -fsSL https://api.github.com/repos/mholt/caddy-ratelimit/commits/master | jq -r .sha)
test -n "$BOUNCER" -a "$BOUNCER" != null -a -n "$RL_SHA" -a "$RL_SHA" != null
FP=$(printf '%s\n' "$CADDY_VERSION" "$BASE_DIGEST" "$BOUNCER" "$RL_SHA" "${{ github.sha }}" | sha256sum | cut -c1-12)
{
echo "caddy=$CADDY_VERSION"; echo "bouncer=$BOUNCER"; echo "rl=$RL_SHA"; echo "fp=$FP"
} >> "$GITHUB_OUTPUT"
echo "caddy=$CADDY_VERSION bouncer=$BOUNCER ratelimit=$RL_SHA fp=$FP"
# The automatic Actions token can't use the container registry, so this
# is a personal access token with only write:package (secret REGISTRY_TOKEN).
- name: Log in to the Gitea registry
run: |
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "$REGISTRY" -u "${{ github.repository_owner }}" --password-stdin
echo "${{ secrets.REGISTRY_TOKEN }}" | regctl registry login "$REGISTRY" -u "${{ github.repository_owner }}" --pass-stdin
- name: Already built?
id: skip
run: |
if [ "${{ inputs.force }}" != "true" ] && regctl image digest "$IMAGE:fp-${{ steps.v.outputs.fp }}" >/dev/null 2>&1; then
echo "skip=true" >> "$GITHUB_OUTPUT"
echo "Up to date (fp-${{ steps.v.outputs.fp }})"
fi
# The real Caddyfile (no secrets in it) must validate with the new build,
# so a Caddy or plugin release that breaks it never reaches the server.
- name: Render production Caddyfile
if: steps.skip.outputs.skip != 'true'
run: |
git clone -q --depth 1 "$ANSIBLE_REPO" /tmp/ansible
mkdir -p rendered
python3 test/render_caddyfile.py /tmp/ansible > rendered/Caddyfile
- name: Use the BuildKit socket
if: steps.skip.outputs.skip != 'true'
run: docker buildx create --name ci --driver remote "$BUILDKIT" --use
- name: Test
if: steps.skip.outputs.skip != 'true'
run: |
docker buildx build --target test --progress plain \
--build-arg CADDY_VERSION=${{ steps.v.outputs.caddy }} \
--build-arg CROWDSEC_BOUNCER_VERSION=${{ steps.v.outputs.bouncer }} \
--build-arg RATELIMIT_VERSION=${{ steps.v.outputs.rl }} \
-f Containerfile .
- name: Build and push
if: steps.skip.outputs.skip != 'true'
run: |
v=${{ steps.v.outputs.caddy }}; fp=${{ steps.v.outputs.fp }}
docker buildx build --push --target final \
--build-arg CADDY_VERSION=$v \
--build-arg CROWDSEC_BOUNCER_VERSION=${{ steps.v.outputs.bouncer }} \
--build-arg RATELIMIT_VERSION=${{ steps.v.outputs.rl }} \
--build-arg FINGERPRINT=$fp \
-t "$IMAGE:$v-$fp" -t "$IMAGE:fp-$fp" -t "$IMAGE:$v" \
-t "$IMAGE:${v%.*}" -t "$IMAGE:2" -t "$IMAGE:latest" \
-f Containerfile .
- name: Notify success
if: success() && steps.skip.outputs.skip != 'true'
run: |
curl -fsS "$GOTIFY_URL/message?token=${{ secrets.GOTIFY_TOKEN }}" \
--form-string title="Caddy image built" --form-string priority=3 \
--form-string message="caddy ${{ steps.v.outputs.caddy }}, bouncer ${{ steps.v.outputs.bouncer }}, ratelimit ${{ steps.v.outputs.rl }} -> $IMAGE:2 (dockcheck applies it after 3 days)"
- name: Notify failure
if: failure()
run: |
curl -fsS "$GOTIFY_URL/message?token=${{ secrets.GOTIFY_TOKEN }}" \
--form-string title="Caddy image build FAILED" --form-string priority=8 \
--form-string message="Server keeps its current Caddy image. ${{ github.server_url }}/${{ github.repository }}/actions"
- name: Clean up
if: always()
run: |
docker buildx rm ci || true
docker logout "$REGISTRY" || true
+33
View File
@@ -0,0 +1,33 @@
# syntax=docker/dockerfile:1
# Caddy with the CrowdSec bouncer (+ AppSec) and rate limiting, built with
# xcaddy on the official builder image. Versions come from the workflow.
ARG CADDY_VERSION=2.11.9
FROM caddy:${CADDY_VERSION}-builder AS builder
ARG CROWDSEC_BOUNCER_VERSION=v0.15.1
ARG RATELIMIT_VERSION=master
# The bouncer may need a newer Go than the builder ships; let go fetch it.
ENV GOTOOLCHAIN=auto
RUN xcaddy build \
--with github.com/hslatman/caddy-crowdsec-bouncer/http@${CROWDSEC_BOUNCER_VERSION} \
--with github.com/hslatman/caddy-crowdsec-bouncer/appsec@${CROWDSEC_BOUNCER_VERSION} \
--with github.com/mholt/caddy-ratelimit@${RATELIMIT_VERSION}
FROM caddy:${CADDY_VERSION}-alpine AS final
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
ARG FINGERPRINT=dev
LABEL org.opencontainers.image.source="https://git.thesatelliteoflove.com/phil/caddy-custom" \
org.opencontainers.image.version="${CADDY_VERSION}" \
caddy.custom.fingerprint="${FINGERPRINT}"
# CI gate (BuildKit can't `docker run`): built, never pushed.
FROM final AS test
RUN caddy version && caddy list-modules --versions > /tmp/mods && grep -E 'crowdsec|appsec|rate_limit' /tmp/mods \
&& grep -q '^crowdsec' /tmp/mods \
&& grep -q '^http.handlers.crowdsec' /tmp/mods \
&& grep -q '^http.handlers.appsec' /tmp/mods \
&& grep -q '^http.handlers.rate_limit' /tmp/mods
COPY test/Caddyfile /tmp/fixture/Caddyfile
RUN CROWDSEC_API_KEY=dummy caddy validate --config /tmp/fixture/Caddyfile --adapter caddyfile
# The real production Caddyfile, rendered from phil/ansible by the workflow
COPY rendered/Caddyfile /tmp/prod/Caddyfile
RUN CROWDSEC_API_KEY=dummy caddy validate --config /tmp/prod/Caddyfile --adapter caddyfile
+25
View File
@@ -0,0 +1,25 @@
# caddy-custom
Caddy built with:
- [caddy-crowdsec-bouncer](https://github.com/hslatman/caddy-crowdsec-bouncer) (`http` + `appsec`)
- [caddy-ratelimit](https://github.com/mholt/caddy-ratelimit)
Image: `git.thesatelliteoflove.com/phil/caddy`. Tags: `:2` (what the server runs),
`:<caddy version>`, `:<caddy version>-<fingerprint>` (immutable, pin this to hold a build).
## How it stays current
`.gitea/workflows/build.yml` runs daily at 04:30. It fingerprints the Caddy version,
the `caddy:<ver>-alpine` digest, the bouncer release, the caddy-ratelimit master commit
and this repo's commit. If `:fp-<fingerprint>` already exists it stops; otherwise it
builds, runs the test stage (modules present, fixture and the real production
Caddyfile from `phil/ansible` validate) and pushes. Gotify (app "caddy-build") gets a
message on success and a high-priority one on failure; a failed build pushes nothing.
On the server, dockcheck sees the new `:2` digest and recreates Caddy once the image
is 3 days old (DaysOld). The ansible repo picks the image with `caddy_custom`.
Secrets: `REGISTRY_TOKEN` (PAT, write:package only), `GOTIFY_TOKEN`.
Manual rebuild: Actions → Build custom Caddy → Run workflow (tick *force*).
+41
View File
@@ -0,0 +1,41 @@
# Fixture using every plugin directive in the shapes the real Caddyfile uses.
{
auto_https off
order crowdsec first
order appsec after crowdsec
crowdsec {
api_url http://crowdsec:8080
api_key {$CROWDSEC_API_KEY}
ticker_interval 15s
appsec_url http://crowdsec:7422
appsec_max_body_bytes 1048576
appsec_fail_open
}
}
(protect) {
crowdsec
appsec
}
(ratelimit_login) {
rate_limit {
zone {args[0]} {
match {
method POST
path {args[1:]}
not remote_ip private_ranges 100.64.0.0/10
}
key {client_ip}
events 10
window 1m
}
log_key
}
}
:8080 {
import protect
import ratelimit_login test_login /login /api/token/
respond "ok"
}
+39
View File
@@ -0,0 +1,39 @@
"""Render phil/ansible's Caddyfile.j2 for `caddy validate`.
Usage: render_caddyfile.py <ansible checkout> (prints the Caddyfile)
Only non-secret group_vars are loaded. Values that reference other variables
are resolved by rendering until nothing changes; values that need the vault
stay unresolved, and StrictUndefined makes the Caddyfile fail loudly if it
ever uses one.
"""
import pathlib, sys
import jinja2, yaml
root = pathlib.Path(sys.argv[1])
ctx = {}
for f in ("domains.yml", "infrastructure.yml"):
ctx.update(yaml.safe_load((root / "group_vars/all" / f).read_text()) or {})
ctx["caddy_custom"] = True
env = jinja2.Environment(undefined=jinja2.StrictUndefined, keep_trailing_newline=True)
def resolve(o):
if isinstance(o, dict):
return {k: resolve(v) for k, v in o.items()}
if isinstance(o, list):
return [resolve(v) for v in o]
if isinstance(o, str) and "{{" in o:
try:
return env.from_string(o).render(ctx)
except jinja2.UndefinedError:
return o
return o
for _ in range(10):
new = resolve(ctx)
if new == ctx:
break
ctx = new
tmpl = (root / "roles/docker/templates/Caddyfile.j2").read_text()
sys.stdout.write(env.from_string(tmpl).render(ctx))