Compare commits
1 Commits
feat/recei
...
32a9170428
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32a9170428 |
@@ -12,4 +12,4 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 2024-10-23
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 2024-10-23
|
||||||
- name: Build Docker image (runs make check)
|
- name: Build Docker image (runs make check)
|
||||||
run: script/cibuild
|
run: docker build .
|
||||||
|
|||||||
26
Makefile
26
Makefile
@@ -1,28 +1,22 @@
|
|||||||
.PHONY: bootstrap setup test lint fmt fmt-check check build run dev deps docker clean hooks css
|
.PHONY: test lint fmt fmt-check check build run dev deps docker clean hooks css
|
||||||
|
|
||||||
# Default target
|
# Default target
|
||||||
.DEFAULT_GOAL := check
|
.DEFAULT_GOAL := check
|
||||||
|
|
||||||
bootstrap:
|
|
||||||
@script/bootstrap
|
|
||||||
|
|
||||||
setup:
|
|
||||||
@script/setup
|
|
||||||
|
|
||||||
test:
|
test:
|
||||||
@script/test
|
go test -v -race -timeout 30s ./...
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
@script/lint
|
golangci-lint run --config .golangci.yml ./...
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
@script/fmt
|
gofmt -s -w .
|
||||||
|
@command -v goimports >/dev/null 2>&1 && goimports -w . || true
|
||||||
|
|
||||||
fmt-check:
|
fmt-check:
|
||||||
@script/fmt-check
|
@test -z "$$(gofmt -s -l .)" || { echo "gofmt needed on:"; gofmt -s -l .; exit 1; }
|
||||||
|
|
||||||
check:
|
check: fmt-check lint test build
|
||||||
@script/check
|
|
||||||
|
|
||||||
build:
|
build:
|
||||||
go build -o bin/webhooker ./cmd/webhooker
|
go build -o bin/webhooker ./cmd/webhooker
|
||||||
@@ -38,13 +32,15 @@ deps:
|
|||||||
go mod tidy
|
go mod tidy
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
@script/docker
|
docker build -t webhooker:latest .
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf bin/
|
rm -rf bin/
|
||||||
|
|
||||||
hooks:
|
hooks:
|
||||||
@script/install-precommit
|
@printf '#!/bin/sh\nmake check\n' > .git/hooks/pre-commit
|
||||||
|
@chmod +x .git/hooks/pre-commit
|
||||||
|
@echo "pre-commit hook installed"
|
||||||
|
|
||||||
css:
|
css:
|
||||||
tailwindcss -i static/css/input.css -o static/css/tailwind.css --minify
|
tailwindcss -i static/css/input.css -o static/css/tailwind.css --minify
|
||||||
|
|||||||
149
README.md
149
README.md
@@ -38,16 +38,14 @@ make docker
|
|||||||
### Development Commands
|
### Development Commands
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
make bootstrap # Install all dependencies (idempotent)
|
|
||||||
make setup # Bootstrap + install git pre-commit hook
|
|
||||||
make fmt # Format code (gofmt + goimports)
|
make fmt # Format code (gofmt + goimports)
|
||||||
make lint # Run golangci-lint
|
make lint # Run golangci-lint
|
||||||
make test # Run tests with race detection
|
make test # Run tests with race detection
|
||||||
make check # test + lint + fmt-check (CI gate)
|
make check # fmt-check + lint + test + build (CI gate)
|
||||||
make build # Build binary to bin/webhooker
|
make build # Build binary to bin/webhooker
|
||||||
make dev # go run ./cmd/webhooker
|
make dev # go run ./cmd/webhooker
|
||||||
make docker # Build Docker image
|
make docker # Build Docker image
|
||||||
make hooks # Install git pre-commit hook that runs script/precommit
|
make hooks # Install git pre-commit hook that runs make check
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
@@ -92,7 +90,6 @@ TTY detection, and security headers are always applied.
|
|||||||
| `METRICS_USERNAME` | Basic auth username for `/metrics` | `""` |
|
| `METRICS_USERNAME` | Basic auth username for `/metrics` | `""` |
|
||||||
| `METRICS_PASSWORD` | Basic auth password for `/metrics` | `""` |
|
| `METRICS_PASSWORD` | Basic auth password for `/metrics` | `""` |
|
||||||
| `SENTRY_DSN` | Sentry error reporting DSN | `""` |
|
| `SENTRY_DSN` | Sentry error reporting DSN | `""` |
|
||||||
| `RECEIVER_RATE_LIMIT` | Receiver requests/minute per IP per entrypoint | `120` |
|
|
||||||
|
|
||||||
On first startup, webhooker automatically generates a cryptographically
|
On first startup, webhooker automatically generates a cryptographically
|
||||||
secure session encryption key and stores it in the database. This key
|
secure session encryption key and stores it in the database. This key
|
||||||
@@ -119,31 +116,6 @@ SQLite databases: the main application database (`webhooker.db`) and
|
|||||||
the per-webhook event databases (`events-{uuid}.db`). Mount this as a
|
the per-webhook event databases (`events-{uuid}.db`). Mount this as a
|
||||||
persistent volume to preserve data across container restarts.
|
persistent volume to preserve data across container restarts.
|
||||||
|
|
||||||
## Entrypoints
|
|
||||||
|
|
||||||
This repository adheres to the
|
|
||||||
[Scripts to Rule Them All](https://github.com/github/scripts-to-rule-them-all)
|
|
||||||
standard: normalized scripts in `script/` are the entrypoints for the
|
|
||||||
development workflow, and the Makefile targets are thin shims that call
|
|
||||||
them. We provide:
|
|
||||||
|
|
||||||
- `script/bootstrap` — install all dependencies (idempotent)
|
|
||||||
- `script/setup` — make a fresh clone ready for development
|
|
||||||
(bootstrap, then install-precommit)
|
|
||||||
- `script/projectname` — output the project name ("webhooker")
|
|
||||||
- `script/test` — run the test suite
|
|
||||||
- `script/lint` — run golangci-lint
|
|
||||||
- `script/fmt` — format all code (writes)
|
|
||||||
- `script/fmt-check` — check formatting (read-only)
|
|
||||||
- `script/check` — run test, lint, and fmt-check
|
|
||||||
- `script/docker` — build the Docker image tagged via `script/projectname`
|
|
||||||
- `script/cibuild` — CI entrypoint: `docker build .` (the Dockerfile
|
|
||||||
runs the checks, so a green build implies a green repo)
|
|
||||||
- `script/precommit` — pre-commit checks (`go mod tidy` guard, then
|
|
||||||
`script/check`)
|
|
||||||
- `script/install-precommit` — install the git pre-commit hook that
|
|
||||||
runs `script/precommit`
|
|
||||||
|
|
||||||
## Rationale
|
## Rationale
|
||||||
|
|
||||||
Webhook integrations between services are inherently fragile. The
|
Webhook integrations between services are inherently fragile. The
|
||||||
@@ -677,24 +649,17 @@ just delayed until the target is healthy again.
|
|||||||
|
|
||||||
### Rate Limiting
|
### Rate Limiting
|
||||||
|
|
||||||
Global blanket rate limiting middleware (e.g., a per-IP throttle shared
|
Global rate limiting middleware (e.g., per-IP throttling applied at the
|
||||||
with the web UI) **must not** apply to webhook receiver endpoints.
|
router level) **must not** apply to webhook receiver endpoints. Webhook
|
||||||
Webhook endpoints receive automated traffic from external services at
|
endpoints receive automated traffic from external services at
|
||||||
unpredictable rates, and blanket limits shared with other routes would
|
unpredictable rates, and blanket rate limits would cause legitimate
|
||||||
cause legitimate deliveries to be dropped.
|
deliveries to be dropped.
|
||||||
|
|
||||||
The receiver instead has its own dedicated abuse limit, scoped to the
|
Instead, each webhook has its own individually configurable rate limit,
|
||||||
`/webhook/{uuid}` route only and keyed per client IP per entrypoint: one
|
applied within the webhook handler itself. By default, no rate limit is
|
||||||
misbehaving sender is throttled without affecting other senders of the
|
applied — webhook endpoints accept traffic as fast as it arrives. Rate
|
||||||
same entrypoint or the same sender's other entrypoints. The limit is
|
limits can be configured per-webhook when needed (e.g., to protect
|
||||||
`RECEIVER_RATE_LIMIT` requests per minute (default 120, generous for
|
against a misbehaving sender).
|
||||||
legitimate webhook senders). Requests over the limit receive HTTP 429
|
|
||||||
with a `Retry-After` header. A set-but-invalid `RECEIVER_RATE_LIMIT`
|
|
||||||
value aborts startup rather than silently falling back to the default.
|
|
||||||
|
|
||||||
Finer-grained per-webhook rate limits (configured in the web UI and
|
|
||||||
enforced in the webhook handler) can layer on top of this env-level
|
|
||||||
abuse limit later; they are tracked as future work.
|
|
||||||
|
|
||||||
### API Endpoints
|
### API Endpoints
|
||||||
|
|
||||||
@@ -928,7 +893,95 @@ linted, tested, and compiled.
|
|||||||
|
|
||||||
## TODO
|
## TODO
|
||||||
|
|
||||||
See [TODO.md](TODO.md).
|
### Completed: Code Quality (Phase 1 of MVP)
|
||||||
|
- [x] Rename Processor → Webhook, Webhook → Entrypoint in code
|
||||||
|
([#12](https://git.eeqj.de/sneak/webhooker/issues/12))
|
||||||
|
- [x] Embed templates via `//go:embed`
|
||||||
|
([#7](https://git.eeqj.de/sneak/webhooker/issues/7))
|
||||||
|
- [x] Use `slog.LevelVar` for dynamic log level switching
|
||||||
|
([#8](https://git.eeqj.de/sneak/webhooker/issues/8))
|
||||||
|
- [x] Simplify configuration to prefer environment variables
|
||||||
|
([#10](https://git.eeqj.de/sneak/webhooker/issues/10))
|
||||||
|
- [x] Remove redundant `godotenv/autoload` import
|
||||||
|
([#11](https://git.eeqj.de/sneak/webhooker/issues/11))
|
||||||
|
- [x] Implement authentication middleware for protected routes
|
||||||
|
([#9](https://git.eeqj.de/sneak/webhooker/issues/9))
|
||||||
|
- [x] Replace Bootstrap with Tailwind CSS + Alpine.js
|
||||||
|
([#4](https://git.eeqj.de/sneak/webhooker/issues/4))
|
||||||
|
|
||||||
|
### Completed: Core Webhook Engine (Phase 2 of MVP)
|
||||||
|
- [x] Implement webhook reception and event storage at `/webhook/{uuid}`
|
||||||
|
- [x] Build event processing and target delivery engine
|
||||||
|
- [x] Implement HTTP target type (fire-and-forget with max_retries=0,
|
||||||
|
retries with exponential backoff when max_retries>0)
|
||||||
|
- [x] Implement database target type (store events in per-webhook DB)
|
||||||
|
- [x] Implement log target type (console output)
|
||||||
|
- [x] Implement Slack target type (Slack/Mattermost incoming webhook
|
||||||
|
notifications with pretty-printed payloads)
|
||||||
|
- [x] Webhook management pages (list, create, edit, delete)
|
||||||
|
- [x] Webhook request log viewer with pagination
|
||||||
|
- [x] Entrypoint and target management UI
|
||||||
|
|
||||||
|
### Completed: Per-Webhook Event Databases
|
||||||
|
- [x] Split into main application DB + per-webhook event DBs
|
||||||
|
- [x] Per-webhook database lifecycle management (create on webhook
|
||||||
|
creation, delete on webhook removal)
|
||||||
|
- [x] `WebhookDBManager` component with lazy connection pooling
|
||||||
|
- [x] Event-driven delivery engine (channel notifications + timer-based retries)
|
||||||
|
- [x] Self-contained delivery tasks: in the ≤16KB happy path, the engine
|
||||||
|
delivers without reading from any database — target config, event
|
||||||
|
headers, and body are all carried inline in the channel notification.
|
||||||
|
The engine only touches the DB to record results (success/failure).
|
||||||
|
Large bodies (≥16KB) are fetched from the per-webhook DB on demand.
|
||||||
|
- [x] Database target type marks delivery as immediately successful
|
||||||
|
(events are already in the per-webhook DB)
|
||||||
|
- [x] Parallel fan-out: all targets for an event are delivered via
|
||||||
|
the bounded worker pool (no goroutine-per-target)
|
||||||
|
- [x] Circuit breaker for HTTP targets with retries: tracks consecutive
|
||||||
|
failures per target, opens after 5 failures (30s cooldown),
|
||||||
|
half-open probe to test recovery
|
||||||
|
|
||||||
|
### Completed: Security Hardening
|
||||||
|
- [x] Security headers middleware (HSTS, CSP, X-Frame-Options,
|
||||||
|
X-Content-Type-Options, Referrer-Policy, Permissions-Policy)
|
||||||
|
([#34](https://git.eeqj.de/sneak/webhooker/issues/34))
|
||||||
|
- [x] Session regeneration on login to prevent session fixation
|
||||||
|
([#38](https://git.eeqj.de/sneak/webhooker/issues/38))
|
||||||
|
- [x] Request body size limits on form endpoints
|
||||||
|
([#39](https://git.eeqj.de/sneak/webhooker/issues/39))
|
||||||
|
|
||||||
|
### Remaining: Core Features
|
||||||
|
- [ ] Per-webhook rate limiting in the receiver handler
|
||||||
|
- [ ] Webhook signature verification (GitHub, Stripe formats)
|
||||||
|
- [x] CSRF protection for forms
|
||||||
|
([#35](https://git.eeqj.de/sneak/webhooker/issues/35))
|
||||||
|
- [x] SSRF prevention for HTTP delivery targets
|
||||||
|
([#36](https://git.eeqj.de/sneak/webhooker/issues/36))
|
||||||
|
- [x] Login rate limiting (per-IP brute-force protection)
|
||||||
|
([#37](https://git.eeqj.de/sneak/webhooker/issues/37))
|
||||||
|
- [ ] Session expiration and "remember me"
|
||||||
|
- [ ] Password change/reset flow
|
||||||
|
- [ ] API key authentication for programmatic access
|
||||||
|
- [ ] Manual event redelivery
|
||||||
|
- [ ] Analytics dashboard (success rates, response times)
|
||||||
|
- [ ] Delivery status and retry management UI
|
||||||
|
|
||||||
|
### Remaining: Event Maintenance
|
||||||
|
- [ ] Automatic event retention cleanup based on `retention_days`
|
||||||
|
|
||||||
|
### Remaining: REST API
|
||||||
|
- [ ] RESTful CRUD for webhooks, entrypoints, targets
|
||||||
|
- [ ] Event viewing and filtering endpoints
|
||||||
|
- [ ] Event redelivery endpoint
|
||||||
|
- [ ] OpenAPI specification
|
||||||
|
|
||||||
|
### Future
|
||||||
|
- [ ] Email delivery target type
|
||||||
|
- [ ] SNS, S3, Slack delivery targets
|
||||||
|
- [ ] Data transformations (e.g., webhook-to-Slack message formatting)
|
||||||
|
- [ ] JSONL file delivery with periodic S3 upload
|
||||||
|
- [ ] Webhook event search and filtering
|
||||||
|
- [ ] Multi-user with role-based access
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
250
REPO_POLICIES.md
250
REPO_POLICIES.md
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Repository Policies
|
title: Repository Policies
|
||||||
last_modified: 2026-07-06
|
last_modified: 2026-02-22
|
||||||
---
|
---
|
||||||
|
|
||||||
This document covers repository structure, tooling, and workflow standards. Code
|
This document covers repository structure, tooling, and workflow standards. Code
|
||||||
@@ -34,46 +34,10 @@ style conventions are in separate documents:
|
|||||||
every file before committing. There are zero exceptions to this rule.
|
every file before committing. There are zero exceptions to this rule.
|
||||||
|
|
||||||
- Every repo with software must have a root `Makefile` with these targets:
|
- Every repo with software must have a root `Makefile` with these targets:
|
||||||
`make bootstrap`, `make setup`, `make test`, `make lint`, `make fmt` (writes),
|
`make test`, `make lint`, `make fmt` (writes), `make fmt-check` (read-only),
|
||||||
`make fmt-check` (read-only), `make check` (runs `test`, `lint`, `fmt-check`),
|
`make check` (prereqs: `test`, `lint`, `fmt-check`), `make docker`, and
|
||||||
`make docker`, and `make hooks` (installs pre-commit hook). A model Makefile
|
`make hooks` (installs pre-commit hook). A model Makefile is at
|
||||||
is at `https://git.eeqj.de/sneak/prompts/raw/branch/main/Makefile`.
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/Makefile`.
|
||||||
|
|
||||||
- Repos follow the
|
|
||||||
[Scripts to Rule Them All](https://github.com/github/scripts-to-rule-them-all)
|
|
||||||
pattern: the implementation of each Makefile target lives in an executable
|
|
||||||
script in `script/` (`script/bootstrap`, `script/setup`, `script/test`,
|
|
||||||
`script/lint`, `script/fmt`, `script/fmt-check`, `script/check`,
|
|
||||||
`script/docker`), and the Makefile targets are thin shims that call them. The
|
|
||||||
scripts must be POSIX sh (`#!/bin/sh`, `set -eu`, no bashisms) so they run in
|
|
||||||
minimal containers (e.g. alpine images have no bash); locate the repo root
|
|
||||||
with `$(cd "$(dirname "$0")/.." && pwd -P)` and `cd` there before acting. From
|
|
||||||
the standard's canonical set we use `bootstrap`, `setup` (make the repo ready
|
|
||||||
for development after a fresh clone: runs `bootstrap`, then
|
|
||||||
`install-precommit`, plus any repo-specific initialization), `test`, and
|
|
||||||
`cibuild`. `script/bootstrap` installs all dependencies idempotently and
|
|
||||||
assumes nothing is present: base tools come from nix, apt, brew, or apk
|
|
||||||
(detected in that order; apt runs noninteractive). For node it uses the
|
|
||||||
installed node if present; otherwise it installs a PINNED node version via
|
|
||||||
nvm, first installing nvm itself if missing — from a hash-verified GitHub
|
|
||||||
release archive (never `curl | sh`), with bash installed as an explicit
|
|
||||||
prerequisite since nvm requires bash. yarn is then pinned via
|
|
||||||
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
|
|
||||||
always exact versions. `script/cibuild` runs the CI build: it changes to the
|
|
||||||
repo root and runs `docker build .`; the Gitea workflow calls it. Four further
|
|
||||||
scripts are our own extensions to the standard: `script/check` runs
|
|
||||||
`script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is
|
|
||||||
what the git pre-commit hook runs, and it calls `script/check`;
|
|
||||||
`script/install-precommit` installs the git pre-commit hook (the `make hooks`
|
|
||||||
target shims to it); and `script/projectname` (literally that filename) simply
|
|
||||||
outputs the project's name. Scripts that need the name call
|
|
||||||
`script/projectname` — e.g. `script/docker` assembles its image tag from it —
|
|
||||||
so those scripts stay byte-identical across all repos. Repo-type-specific
|
|
||||||
pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in
|
|
||||||
`script/precommit`, not in the hook itself. Model scripts are at
|
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
|
|
||||||
must document the provided scripts in an **Entrypoints** section (see the
|
|
||||||
README requirements below).
|
|
||||||
|
|
||||||
- Always use Makefile targets (`make fmt`, `make test`, `make lint`, etc.)
|
- Always use Makefile targets (`make fmt`, `make test`, `make lint`, etc.)
|
||||||
instead of invoking the underlying tools directly. The Makefile is the single
|
instead of invoking the underlying tools directly. The Makefile is the single
|
||||||
@@ -93,83 +57,11 @@ style conventions are in separate documents:
|
|||||||
as a build step so the build fails if the branch is not green. For non-server
|
as a build step so the build fails if the branch is not green. For non-server
|
||||||
repos, the Dockerfile should bring up a development environment and run
|
repos, the Dockerfile should bring up a development environment and run
|
||||||
`make check`. For server repos, `make check` should run as an early build
|
`make check`. For server repos, `make check` should run as an early build
|
||||||
stage before the final image is assembled. Dockerfiles install development
|
stage before the final image is assembled.
|
||||||
prerequisites by running `script/bootstrap` rather than duplicating installs
|
|
||||||
inline; COPY `script/` and the dependency manifests (`package.json` +
|
|
||||||
`yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap
|
|
||||||
layer stays cached until dependencies change.
|
|
||||||
|
|
||||||
- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go
|
|
||||||
repos use a multistage build where linting runs in an independent stage based
|
|
||||||
on the `golangci/golangci-lint` image (pinned by hash). This stage runs
|
|
||||||
`make fmt-check` and `make lint` before the full build begins. The build stage
|
|
||||||
then declares an explicit dependency on the lint stage via
|
|
||||||
`COPY --from=lint /src/go.sum /dev/null`, which forces BuildKit to complete
|
|
||||||
linting before proceeding to compilation and tests. This ensures lint failures
|
|
||||||
surface in seconds rather than minutes, without blocking on dependency
|
|
||||||
download or compilation in the build stage.
|
|
||||||
|
|
||||||
The standard pattern for a Go repo Dockerfile is:
|
|
||||||
|
|
||||||
```dockerfile
|
|
||||||
# Lint stage — fast feedback on formatting and lint issues
|
|
||||||
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD
|
|
||||||
FROM golangci/golangci-lint@sha256:... AS lint
|
|
||||||
WORKDIR /src
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download
|
|
||||||
COPY . .
|
|
||||||
RUN make fmt-check
|
|
||||||
RUN make lint
|
|
||||||
|
|
||||||
# Build stage
|
|
||||||
# golang:1.x-alpine, YYYY-MM-DD
|
|
||||||
FROM golang@sha256:... AS builder
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
# Force BuildKit to run the lint stage before proceeding
|
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
|
||||||
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download
|
|
||||||
COPY . .
|
|
||||||
RUN make test
|
|
||||||
|
|
||||||
ARG VERSION=dev
|
|
||||||
RUN CGO_ENABLED=0 go build -trimpath \
|
|
||||||
-ldflags="-s -w -X main.Version=${VERSION}" \
|
|
||||||
-o /app ./cmd/app/
|
|
||||||
|
|
||||||
# Runtime stage
|
|
||||||
FROM alpine@sha256:...
|
|
||||||
COPY --from=builder /app /usr/local/bin/app
|
|
||||||
ENTRYPOINT ["app"]
|
|
||||||
```
|
|
||||||
|
|
||||||
Key points:
|
|
||||||
- The lint stage uses the `golangci/golangci-lint` image directly (it
|
|
||||||
includes both Go and the linter), so there is no need to install the
|
|
||||||
linter separately.
|
|
||||||
- `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates
|
|
||||||
a stage dependency. BuildKit runs stages in parallel by default; without
|
|
||||||
this line, the build stage would not wait for lint to finish and a lint
|
|
||||||
failure might not fail the overall build.
|
|
||||||
- If the project uses `//go:embed` directives that reference build artifacts
|
|
||||||
(e.g. a web frontend compiled in a separate stage), the lint stage must
|
|
||||||
create placeholder files so the embed directives resolve. Example:
|
|
||||||
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
|
|
||||||
The lint stage should not depend on the actual build output — it exists to
|
|
||||||
fail fast.
|
|
||||||
- If the project requires CGO or system libraries for linting (e.g.
|
|
||||||
`vips-dev`), install them in the lint stage with `apk add`.
|
|
||||||
- The build stage runs `make test` after compilation setup. Tests run in the
|
|
||||||
build stage, not the lint stage, because they may require compiled
|
|
||||||
artifacts or heavier dependencies.
|
|
||||||
|
|
||||||
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
||||||
runs `script/cibuild` (which runs `docker build .`) on push. Since the
|
runs `docker build .` on push. Since the Dockerfile already runs `make check`,
|
||||||
Dockerfile already runs `make check`, a successful build implies all checks
|
a successful build implies all checks pass.
|
||||||
pass.
|
|
||||||
|
|
||||||
- Use platform-standard formatters: `black` for Python, `prettier` for
|
- Use platform-standard formatters: `black` for Python, `prettier` for
|
||||||
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
||||||
@@ -177,11 +69,9 @@ style conventions are in separate documents:
|
|||||||
Markdown (hard-wrap at 80 columns). Documentation and writing repos (Markdown,
|
Markdown (hard-wrap at 80 columns). Documentation and writing repos (Markdown,
|
||||||
HTML, CSS) should also have `.prettierrc` and `.prettierignore`.
|
HTML, CSS) should also have `.prettierrc` and `.prettierignore`.
|
||||||
|
|
||||||
- Pre-commit hook: runs `script/precommit`, which calls `script/check`. If local
|
- Pre-commit hook: `make check` if local testing is possible, otherwise
|
||||||
testing is not possible in the repo, `script/precommit` may skip `script/test`
|
`make lint && make fmt-check`. The Makefile should provide a `make hooks`
|
||||||
and run only `script/lint` and `script/fmt-check`. The hook is installed by
|
target to install the pre-commit hook.
|
||||||
`script/install-precommit`; the Makefile must provide a `make hooks` target
|
|
||||||
that shims to it.
|
|
||||||
|
|
||||||
- All repos with software must have tests that run via the platform-standard
|
- All repos with software must have tests that run via the platform-standard
|
||||||
test framework (`go test`, `pytest`, `jest`/`vitest`, etc.). If no meaningful
|
test framework (`go test`, `pytest`, `jest`/`vitest`, etc.). If no meaningful
|
||||||
@@ -192,42 +82,6 @@ style conventions are in separate documents:
|
|||||||
- `make test` must complete in under 20 seconds. Add a 30-second timeout in the
|
- `make test` must complete in under 20 seconds. Add a 30-second timeout in the
|
||||||
Makefile.
|
Makefile.
|
||||||
|
|
||||||
- **`make test` should use the conditional verbose rerun pattern.** Run tests
|
|
||||||
without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to
|
|
||||||
show full output. This keeps CI logs and `docker build` output clean on
|
|
||||||
success (just package/suite summaries) while providing full diagnostic detail
|
|
||||||
on failure (every test case, every assertion). The general shell pattern:
|
|
||||||
|
|
||||||
```makefile
|
|
||||||
test:
|
|
||||||
@<test-command> || \
|
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
|
||||||
<test-command-with-v>; exit 1; }
|
|
||||||
```
|
|
||||||
|
|
||||||
Go example:
|
|
||||||
|
|
||||||
```makefile
|
|
||||||
test:
|
|
||||||
@go test -timeout 30s -race -cover ./... || \
|
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
|
||||||
go test -timeout 30s -race -v ./...; exit 1; }
|
|
||||||
```
|
|
||||||
|
|
||||||
Python example:
|
|
||||||
|
|
||||||
```makefile
|
|
||||||
test:
|
|
||||||
@python -m pytest || \
|
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
|
||||||
python -m pytest -v; exit 1; }
|
|
||||||
```
|
|
||||||
|
|
||||||
The `exit 1` ensures the target always fails after a rerun — the first run
|
|
||||||
already proved the tests are broken, so the build must not pass even if a
|
|
||||||
flaky test happens to succeed on the second attempt. The rerun exists solely
|
|
||||||
for diagnostic output.
|
|
||||||
|
|
||||||
- Docker builds must complete in under 5 minutes.
|
- Docker builds must complete in under 5 minutes.
|
||||||
|
|
||||||
- `make check` must not modify any files in the repo. Tests may use temporary
|
- `make check` must not modify any files in the repo. Tests may use temporary
|
||||||
@@ -244,13 +98,6 @@ style conventions are in separate documents:
|
|||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
||||||
a new repo.
|
a new repo.
|
||||||
|
|
||||||
- **No build artifacts in version control.** Code-derived data (compiled
|
|
||||||
bundles, minified output, generated assets) must never be committed to the
|
|
||||||
repository if it can be avoided. The build process (e.g. Dockerfile, Makefile)
|
|
||||||
should generate these at build time. Notable exception: Go protobuf generated
|
|
||||||
files (`.pb.go`) ARE committed because repos need to work with `go get`, which
|
|
||||||
downloads code but does not execute code generation.
|
|
||||||
|
|
||||||
- Never use `git add -A` or `git add .`. Always stage files explicitly by name.
|
- Never use `git add -A` or `git add .`. Always stage files explicitly by name.
|
||||||
|
|
||||||
- Never force-push to `main`.
|
- Never force-push to `main`.
|
||||||
@@ -274,76 +121,12 @@ style conventions are in separate documents:
|
|||||||
- Dockerized web services listen on port 8080 by default, overridable with
|
- Dockerized web services listen on port 8080 by default, overridable with
|
||||||
`PORT`.
|
`PORT`.
|
||||||
|
|
||||||
- **HTTP/web services must be hardened for production internet exposure before
|
|
||||||
tagging 1.0.** This means full compliance with security best practices
|
|
||||||
including, without limitation, all of the following:
|
|
||||||
- **Security headers** on every response:
|
|
||||||
- `Strict-Transport-Security` (HSTS) with `max-age` of at least one year
|
|
||||||
and `includeSubDomains`.
|
|
||||||
- `Content-Security-Policy` (CSP) with a restrictive default policy
|
|
||||||
(`default-src 'self'` as a baseline, tightened per-resource as
|
|
||||||
needed). Never use `unsafe-inline` or `unsafe-eval` unless
|
|
||||||
unavoidable, and document the reason.
|
|
||||||
- `X-Frame-Options: DENY` (or `SAMEORIGIN` if framing is required).
|
|
||||||
Prefer the `frame-ancestors` CSP directive as the primary control.
|
|
||||||
- `X-Content-Type-Options: nosniff`.
|
|
||||||
- `Referrer-Policy: strict-origin-when-cross-origin` (or stricter).
|
|
||||||
- `Permissions-Policy` restricting access to browser features the
|
|
||||||
application does not use (camera, microphone, geolocation, etc.).
|
|
||||||
- **Request and response limits:**
|
|
||||||
- Maximum request body size enforced on all endpoints (e.g. Go
|
|
||||||
`http.MaxBytesReader`). Choose a sane default per-route; never accept
|
|
||||||
unbounded input.
|
|
||||||
- Maximum response body size where applicable (e.g. paginated APIs).
|
|
||||||
- `ReadTimeout` and `ReadHeaderTimeout` on the `http.Server` to defend
|
|
||||||
against slowloris attacks.
|
|
||||||
- `WriteTimeout` on the `http.Server`.
|
|
||||||
- `IdleTimeout` on the `http.Server`.
|
|
||||||
- Per-handler execution time limits via `context.WithTimeout` or
|
|
||||||
chi/stdlib `middleware.Timeout`.
|
|
||||||
- **Authentication and session security:**
|
|
||||||
- Rate limiting on password-based authentication endpoints. API keys are
|
|
||||||
high-entropy and not susceptible to brute force, so they are exempt.
|
|
||||||
- CSRF tokens on all state-mutating HTML forms. API endpoints
|
|
||||||
authenticated via `Authorization` header (Bearer token, API key) are
|
|
||||||
exempt because the browser does not attach these automatically.
|
|
||||||
- Passwords stored using bcrypt, scrypt, or argon2 — never plain-text,
|
|
||||||
MD5, or SHA.
|
|
||||||
- Session cookies set with `HttpOnly`, `Secure`, and `SameSite=Lax` (or
|
|
||||||
`Strict`) attributes.
|
|
||||||
- **Reverse proxy awareness:**
|
|
||||||
- True client IP detection when behind a reverse proxy
|
|
||||||
(`X-Forwarded-For`, `X-Real-IP`). The application must accept
|
|
||||||
forwarded headers only from a configured set of trusted proxy
|
|
||||||
addresses — never trust `X-Forwarded-For` unconditionally.
|
|
||||||
- **CORS:**
|
|
||||||
- Authenticated endpoints must restrict `Access-Control-Allow-Origin` to
|
|
||||||
an explicit allowlist of known origins. Wildcard (`*`) is acceptable
|
|
||||||
only for public, unauthenticated read-only APIs.
|
|
||||||
- **Error handling:**
|
|
||||||
- Internal errors must never leak stack traces, SQL queries, file paths,
|
|
||||||
or other implementation details to the client. Return generic error
|
|
||||||
messages in production; detailed errors only when `DEBUG` is enabled.
|
|
||||||
- **TLS:**
|
|
||||||
- Services never terminate TLS directly. They are always deployed behind
|
|
||||||
a TLS-terminating reverse proxy. The service itself listens on plain
|
|
||||||
HTTP. However, HSTS headers and `Secure` cookie flags must still be
|
|
||||||
set by the application so that the browser enforces HTTPS end-to-end.
|
|
||||||
|
|
||||||
This list is non-exhaustive. Apply defense-in-depth: if a standard security
|
|
||||||
hardening measure exists for HTTP services and is not listed here, it is
|
|
||||||
still expected. When in doubt, harden.
|
|
||||||
|
|
||||||
- `README.md` is the primary documentation. Required sections:
|
- `README.md` is the primary documentation. Required sections:
|
||||||
- **Description**: First line must include the project name, purpose,
|
- **Description**: First line must include the project name, purpose,
|
||||||
category (web server, SPA, CLI tool, etc.), license, and author. Example:
|
category (web server, SPA, CLI tool, etc.), license, and author. Example:
|
||||||
"µPaaS is an MIT-licensed Go web application by @sneak that receives
|
"µPaaS is an MIT-licensed Go web application by @sneak that receives
|
||||||
git-frontend webhooks and deploys applications via Docker in realtime."
|
git-frontend webhooks and deploys applications via Docker in realtime."
|
||||||
- **Getting Started**: Copy-pasteable install/usage code block.
|
- **Getting Started**: Copy-pasteable install/usage code block.
|
||||||
- **Entrypoints**: Opens by stating that the repo adheres to the
|
|
||||||
[Scripts to Rule Them All](https://github.com/github/scripts-to-rule-them-all)
|
|
||||||
standard (with that link), then documents each provided `script/`
|
|
||||||
entrypoint and its purpose.
|
|
||||||
- **Rationale**: Why does this exist?
|
- **Rationale**: Why does this exist?
|
||||||
- **Design**: How is the program structured?
|
- **Design**: How is the program structured?
|
||||||
- **TODO**: Update meticulously, even between commits. When planning, put
|
- **TODO**: Update meticulously, even between commits. When planning, put
|
||||||
@@ -362,11 +145,11 @@ style conventions are in separate documents:
|
|||||||
|
|
||||||
- Database migrations live in `internal/db/migrations/` and must be embedded in
|
- Database migrations live in `internal/db/migrations/` and must be embedded in
|
||||||
the binary.
|
the binary.
|
||||||
- `000_migration.sql` — contains ONLY the creation of the migrations
|
- `000_migration.sql` — contains ONLY the creation of the migrations tracking
|
||||||
tracking table itself. Nothing else.
|
table itself. Nothing else.
|
||||||
- `001_schema.sql` — the full application schema.
|
- `001_schema.sql` — the full application schema.
|
||||||
- **Pre-1.0.0:** never add additional migration files (002, 003, etc.).
|
- **Pre-1.0.0:** never add additional migration files (002, 003, etc.). There
|
||||||
There is no installed base to migrate. Edit `001_schema.sql` directly.
|
is no installed base to migrate. Edit `001_schema.sql` directly.
|
||||||
- **Post-1.0.0:** add new numbered migration files for each schema change.
|
- **Post-1.0.0:** add new numbered migration files for each schema change.
|
||||||
Never edit existing migrations after release.
|
Never edit existing migrations after release.
|
||||||
|
|
||||||
@@ -398,9 +181,6 @@ style conventions are in separate documents:
|
|||||||
- `README.md`, `.git`, `.gitignore`, `.editorconfig`
|
- `README.md`, `.git`, `.gitignore`, `.editorconfig`
|
||||||
- `LICENSE`, `REPO_POLICIES.md` (copy from the `prompts` repo)
|
- `LICENSE`, `REPO_POLICIES.md` (copy from the `prompts` repo)
|
||||||
- `Makefile`
|
- `Makefile`
|
||||||
- `script/` entrypoints (`bootstrap`, `setup`, `projectname`, `test`,
|
|
||||||
`lint`, `fmt`, `fmt-check`, `check`, `docker`, `cibuild`, `precommit`,
|
|
||||||
`install-precommit`)
|
|
||||||
- `Dockerfile`, `.dockerignore`
|
- `Dockerfile`, `.dockerignore`
|
||||||
- `.gitea/workflows/check.yml`
|
- `.gitea/workflows/check.yml`
|
||||||
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
||||||
|
|||||||
78
TODO.md
78
TODO.md
@@ -1,78 +0,0 @@
|
|||||||
# Workflow
|
|
||||||
|
|
||||||
* branch (from `main`)
|
|
||||||
* do the work in Next Step
|
|
||||||
* move Next Step to the top of Completed Steps
|
|
||||||
* move the top item of Future Steps into Next Step
|
|
||||||
* commit (`TODO.md` changes in the same commit as the work)
|
|
||||||
* merge to `main` if the branch is not protected, otherwise open a PR
|
|
||||||
* push
|
|
||||||
|
|
||||||
# Status
|
|
||||||
|
|
||||||
pre-1.0. No git tags exist. main (81413c5) is a working webhook proxy
|
|
||||||
with auth, CSRF/SSRF protections, login rate limiting, Slack target,
|
|
||||||
policy compliance (#6), pinned lint tooling (#55), a per-webhook event
|
|
||||||
retention reaper (#63), and delivery targets behind a Target interface
|
|
||||||
(#77). Work is tracked as Gitea issues (the authoritative TODO); this
|
|
||||||
file is a summary. Note: TODO.md was deliberately deleted from this
|
|
||||||
repo in f9a9569 (2026-03-01, #6); its content was folded into the
|
|
||||||
README TODO section, which this draft reconstructs as of 2026-07-06.
|
|
||||||
|
|
||||||
# Next Step
|
|
||||||
|
|
||||||
Manual event redelivery from the web UI (replay is a core promised
|
|
||||||
capability in the README rationale).
|
|
||||||
|
|
||||||
# Completed Steps
|
|
||||||
|
|
||||||
- 2026-08-07 Rate-limit the public webhook receiver per client IP per
|
|
||||||
entrypoint, env-configurable with fail-loud parsing (#64)
|
|
||||||
- 2026-08-07 Per-webhook event retention reaper (#63); NoCache
|
|
||||||
middleware for authenticated pages (#61); Target interface refactor
|
|
||||||
(#77)
|
|
||||||
- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints,
|
|
||||||
Makefile shims, README Entrypoints section
|
|
||||||
- 2026-03-25 pin golangci-lint Docker image for linting (#55)
|
|
||||||
- 2026-03-18 CSRF middleware detects TLS per-request, fixing login over
|
|
||||||
plain HTTP and behind reverse proxies (#54)
|
|
||||||
- 2026-03-17 root path redirects based on auth state (#52)
|
|
||||||
- 2026-03-17 CSRF protection, SSRF prevention for HTTP delivery targets
|
|
||||||
with DNS rebinding defense, and per-IP login rate limiting (#42)
|
|
||||||
- 2026-03-17 Slack target type for incoming webhook notifications (#47)
|
|
||||||
- 2026-03-17 Dockerfile absolute paths and static linking (#49);
|
|
||||||
absolute dev DATA_DIR default and clarified env docs (#46)
|
|
||||||
- 2026-03-05 security headers middleware, session regeneration on
|
|
||||||
login, request body size limits (#41)
|
|
||||||
- 2026-03-04 tests for delivery, middleware, and session packages
|
|
||||||
(#32); removed globals.Buildarch (#31)
|
|
||||||
- 2026-03-04 1.0 MVP merge: Webhook/Entrypoint/Target rename, core
|
|
||||||
delivery engine with bounded worker pool and circuit breaker,
|
|
||||||
parallel fan-out, per-webhook event databases, management UI (#16)
|
|
||||||
- 2026-03-01 repo brought to REPO_POLICIES standards; TODO.md folded
|
|
||||||
into README (#6)
|
|
||||||
|
|
||||||
# Future Steps
|
|
||||||
|
|
||||||
- Delivery status and retry management UI
|
|
||||||
- Per-webhook rate limiting in the receiver handler (per-webhook config
|
|
||||||
plus handler enforcement, layered on the env-level receiver limit
|
|
||||||
from #64; global limits must not apply to receiver endpoints)
|
|
||||||
- Webhook signature verification for GitHub and Stripe HMAC formats
|
|
||||||
- API key authentication for programmatic access (APIKey model exists;
|
|
||||||
Bearer token middleware does not)
|
|
||||||
- REST API v1
|
|
||||||
- CRUD for webhooks, entrypoints, targets
|
|
||||||
- event viewing and filtering endpoints
|
|
||||||
- event redelivery endpoint
|
|
||||||
- OpenAPI specification
|
|
||||||
- Analytics dashboard: success rates, response times, volume
|
|
||||||
- Session expiration tuning and a remember-me option
|
|
||||||
- Password change and reset flow
|
|
||||||
- Later, nice to have
|
|
||||||
- email delivery target type
|
|
||||||
- SNS and S3 delivery targets
|
|
||||||
- data transformations (e.g. webhook to Slack message formatting)
|
|
||||||
- JSONL file delivery with periodic S3 upload
|
|
||||||
- webhook event search and filtering
|
|
||||||
- multi-user with role-based access control
|
|
||||||
@@ -34,7 +34,6 @@ func main() {
|
|||||||
config.New,
|
config.New,
|
||||||
database.New,
|
database.New,
|
||||||
database.NewWebhookDBManager,
|
database.NewWebhookDBManager,
|
||||||
database.NewRetentionReaper,
|
|
||||||
healthcheck.New,
|
healthcheck.New,
|
||||||
session.New,
|
session.New,
|
||||||
handlers.New,
|
handlers.New,
|
||||||
@@ -45,13 +44,6 @@ func main() {
|
|||||||
func(e *delivery.Engine) delivery.Notifier { return e },
|
func(e *delivery.Engine) delivery.Notifier { return e },
|
||||||
server.New,
|
server.New,
|
||||||
),
|
),
|
||||||
fx.Invoke(
|
fx.Invoke(func(*server.Server, *delivery.Engine) {}),
|
||||||
func(
|
|
||||||
*server.Server,
|
|
||||||
*delivery.Engine,
|
|
||||||
*database.RetentionReaper,
|
|
||||||
) {
|
|
||||||
},
|
|
||||||
),
|
|
||||||
).Run()
|
).Run()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"sneak.berlin/go/webhooker/internal/globals"
|
"sneak.berlin/go/webhooker/internal/globals"
|
||||||
@@ -27,27 +26,12 @@ const (
|
|||||||
|
|
||||||
// defaultPort is the default HTTP listen port.
|
// defaultPort is the default HTTP listen port.
|
||||||
defaultPort = 8080
|
defaultPort = 8080
|
||||||
|
|
||||||
// defaultRetentionSweepInterval is how often the retention
|
|
||||||
// reaper deletes events older than each webhook's RetentionDays.
|
|
||||||
defaultRetentionSweepInterval = time.Hour
|
|
||||||
|
|
||||||
// defaultReceiverRateLimit is the default number of requests
|
|
||||||
// per minute each client IP may send to a single webhook
|
|
||||||
// receiver entrypoint. Generous for legitimate webhook
|
|
||||||
// senders while bounding abuse of the one unauthenticated,
|
|
||||||
// internet-exposed endpoint.
|
|
||||||
defaultReceiverRateLimit = 120
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrInvalidEnvironment is returned when WEBHOOKER_ENVIRONMENT
|
// ErrInvalidEnvironment is returned when WEBHOOKER_ENVIRONMENT
|
||||||
// contains an unrecognised value.
|
// contains an unrecognised value.
|
||||||
var ErrInvalidEnvironment = errors.New("invalid environment")
|
var ErrInvalidEnvironment = errors.New("invalid environment")
|
||||||
|
|
||||||
// ErrNonPositiveValue is returned when an environment variable that
|
|
||||||
// requires a positive integer is set to zero or a negative number.
|
|
||||||
var ErrNonPositiveValue = errors.New("value must be positive")
|
|
||||||
|
|
||||||
//nolint:revive // ConfigParams is a standard fx naming convention.
|
//nolint:revive // ConfigParams is a standard fx naming convention.
|
||||||
type ConfigParams struct {
|
type ConfigParams struct {
|
||||||
fx.In
|
fx.In
|
||||||
@@ -67,14 +51,6 @@ type Config struct {
|
|||||||
MetricsUsername string
|
MetricsUsername string
|
||||||
Port int
|
Port int
|
||||||
SentryDSN string
|
SentryDSN string
|
||||||
|
|
||||||
// RetentionSweepInterval is how often the retention reaper runs.
|
|
||||||
RetentionSweepInterval time.Duration
|
|
||||||
|
|
||||||
// ReceiverRateLimit is the number of requests per minute each
|
|
||||||
// client IP may send to a single webhook receiver entrypoint.
|
|
||||||
ReceiverRateLimit int
|
|
||||||
|
|
||||||
params *ConfigParams
|
params *ConfigParams
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
}
|
}
|
||||||
@@ -119,62 +95,6 @@ func envInt(key string, defaultValue int) int {
|
|||||||
return defaultValue
|
return defaultValue
|
||||||
}
|
}
|
||||||
|
|
||||||
// envPositiveInt returns the value of the named environment variable
|
|
||||||
// parsed as a positive integer. Returns defaultValue if not set. If
|
|
||||||
// the variable is set but cannot be parsed, or parses to less than
|
|
||||||
// one, it returns a wrapped error naming the key and the bad value,
|
|
||||||
// so startup fails loudly rather than silently falling back to the
|
|
||||||
// default.
|
|
||||||
func envPositiveInt(
|
|
||||||
key string,
|
|
||||||
defaultValue int,
|
|
||||||
) (int, error) {
|
|
||||||
v := os.Getenv(key)
|
|
||||||
if v == "" {
|
|
||||||
return defaultValue, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
i, err := strconv.Atoi(v)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"invalid integer for %s: %q: %w", key, v, err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if i < 1 {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"%w: %s must be at least 1, got %q",
|
|
||||||
ErrNonPositiveValue, key, v,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return i, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// envDuration returns the value of the named environment variable
|
|
||||||
// parsed as a Go duration (e.g. "1h", "30m"). Returns defaultValue if
|
|
||||||
// not set. If the variable is set but cannot be parsed, it returns a
|
|
||||||
// wrapped error naming the key and the bad value, so startup fails
|
|
||||||
// loudly rather than silently falling back to the default.
|
|
||||||
func envDuration(
|
|
||||||
key string,
|
|
||||||
defaultValue time.Duration,
|
|
||||||
) (time.Duration, error) {
|
|
||||||
v := os.Getenv(key)
|
|
||||||
if v == "" {
|
|
||||||
return defaultValue, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
d, err := time.ParseDuration(v)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"invalid duration for %s: %q: %w", key, v, err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return d, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a Config by reading environment variables.
|
// New creates a Config by reading environment variables.
|
||||||
//
|
//
|
||||||
//nolint:revive // lc parameter is required by fx even if unused.
|
//nolint:revive // lc parameter is required by fx even if unused.
|
||||||
@@ -198,28 +118,6 @@ func New(lc fx.Lifecycle, params ConfigParams) (*Config, error) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the retention sweep interval; a set-but-unparseable value
|
|
||||||
// is a hard error so fx aborts startup rather than silently using
|
|
||||||
// the default.
|
|
||||||
retentionSweepInterval, err := envDuration(
|
|
||||||
"RETENTION_SWEEP_INTERVAL",
|
|
||||||
defaultRetentionSweepInterval,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse the receiver rate limit; a set-but-unparseable or
|
|
||||||
// non-positive value is a hard error so fx aborts startup
|
|
||||||
// rather than silently using the default.
|
|
||||||
receiverRateLimit, err := envPositiveInt(
|
|
||||||
"RECEIVER_RATE_LIMIT",
|
|
||||||
defaultReceiverRateLimit,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load configuration values from environment variables
|
// Load configuration values from environment variables
|
||||||
s := &Config{
|
s := &Config{
|
||||||
DataDir: envString("DATA_DIR"),
|
DataDir: envString("DATA_DIR"),
|
||||||
@@ -230,8 +128,6 @@ func New(lc fx.Lifecycle, params ConfigParams) (*Config, error) {
|
|||||||
MetricsPassword: envString("METRICS_PASSWORD"),
|
MetricsPassword: envString("METRICS_PASSWORD"),
|
||||||
Port: envInt("PORT", defaultPort),
|
Port: envInt("PORT", defaultPort),
|
||||||
SentryDSN: envString("SENTRY_DSN"),
|
SentryDSN: envString("SENTRY_DSN"),
|
||||||
RetentionSweepInterval: retentionSweepInterval,
|
|
||||||
ReceiverRateLimit: receiverRateLimit,
|
|
||||||
log: log,
|
log: log,
|
||||||
params: ¶ms,
|
params: ¶ms,
|
||||||
}
|
}
|
||||||
@@ -255,8 +151,6 @@ func New(lc fx.Lifecycle, params ConfigParams) (*Config, error) {
|
|||||||
"debug", s.Debug,
|
"debug", s.Debug,
|
||||||
"maintenanceMode", s.MaintenanceMode,
|
"maintenanceMode", s.MaintenanceMode,
|
||||||
"dataDir", s.DataDir,
|
"dataDir", s.DataDir,
|
||||||
"retentionSweepInterval", s.RetentionSweepInterval.String(),
|
|
||||||
"receiverRateLimit", s.ReceiverRateLimit,
|
|
||||||
"hasSentryDSN", s.SentryDSN != "",
|
"hasSentryDSN", s.SentryDSN != "",
|
||||||
"hasMetricsAuth",
|
"hasMetricsAuth",
|
||||||
s.MetricsUsername != "" && s.MetricsPassword != "",
|
s.MetricsUsername != "" && s.MetricsPassword != "",
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package config_test
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
@@ -121,100 +120,6 @@ func testEnvironmentConfigSuccess(
|
|||||||
assert.Equal(t, isProd, cfg.IsProd())
|
assert.Equal(t, isProd, cfg.IsProd())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRetentionSweepInterval(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
set bool
|
|
||||||
value string
|
|
||||||
expectError bool
|
|
||||||
expected time.Duration
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "unset uses default",
|
|
||||||
set: false,
|
|
||||||
expected: time.Hour,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "valid value is parsed",
|
|
||||||
set: true,
|
|
||||||
value: "15m",
|
|
||||||
expected: 15 * time.Minute,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unparseable value fails startup",
|
|
||||||
set: true,
|
|
||||||
value: "not-a-duration",
|
|
||||||
expectError: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
// Cannot use t.Parallel() here because t.Setenv
|
|
||||||
// is incompatible with parallel subtests.
|
|
||||||
t.Setenv("WEBHOOKER_ENVIRONMENT", "dev")
|
|
||||||
|
|
||||||
if tt.set {
|
|
||||||
t.Setenv("RETENTION_SWEEP_INTERVAL", tt.value)
|
|
||||||
} else {
|
|
||||||
require.NoError(t, os.Unsetenv(
|
|
||||||
"RETENTION_SWEEP_INTERVAL",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
if tt.expectError {
|
|
||||||
testRetentionSweepIntervalError(t)
|
|
||||||
} else {
|
|
||||||
testRetentionSweepIntervalSuccess(t, tt.expected)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testRetentionSweepIntervalError(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var cfg *config.Config
|
|
||||||
|
|
||||||
app := fx.New(
|
|
||||||
fx.NopLogger,
|
|
||||||
fx.Provide(
|
|
||||||
globals.New,
|
|
||||||
logger.New,
|
|
||||||
config.New,
|
|
||||||
),
|
|
||||||
fx.Populate(&cfg),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Error(t, app.Err())
|
|
||||||
}
|
|
||||||
|
|
||||||
func testRetentionSweepIntervalSuccess(
|
|
||||||
t *testing.T,
|
|
||||||
expected time.Duration,
|
|
||||||
) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var cfg *config.Config
|
|
||||||
|
|
||||||
app := fxtest.New(
|
|
||||||
t,
|
|
||||||
fx.Provide(
|
|
||||||
globals.New,
|
|
||||||
logger.New,
|
|
||||||
config.New,
|
|
||||||
),
|
|
||||||
fx.Populate(&cfg),
|
|
||||||
)
|
|
||||||
require.NoError(t, app.Err())
|
|
||||||
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
defer app.RequireStop()
|
|
||||||
|
|
||||||
assert.Equal(t, expected, cfg.RetentionSweepInterval)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDefaultDataDir(t *testing.T) {
|
func TestDefaultDataDir(t *testing.T) {
|
||||||
for _, env := range []string{"", "dev", "prod"} {
|
for _, env := range []string{"", "dev", "prod"} {
|
||||||
name := env
|
name := env
|
||||||
@@ -258,109 +163,3 @@ func TestDefaultDataDir(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReceiverRateLimit(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
set bool
|
|
||||||
value string
|
|
||||||
expectError bool
|
|
||||||
expected int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "unset uses default",
|
|
||||||
set: false,
|
|
||||||
expected: 120,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "valid value is parsed",
|
|
||||||
set: true,
|
|
||||||
value: "30",
|
|
||||||
expected: 30,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "unparseable value fails startup",
|
|
||||||
set: true,
|
|
||||||
value: "not-a-number",
|
|
||||||
expectError: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "zero fails startup",
|
|
||||||
set: true,
|
|
||||||
value: "0",
|
|
||||||
expectError: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "negative fails startup",
|
|
||||||
set: true,
|
|
||||||
value: "-5",
|
|
||||||
expectError: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
// Cannot use t.Parallel() here because t.Setenv
|
|
||||||
// is incompatible with parallel subtests.
|
|
||||||
t.Setenv("WEBHOOKER_ENVIRONMENT", "dev")
|
|
||||||
|
|
||||||
if tt.set {
|
|
||||||
t.Setenv("RECEIVER_RATE_LIMIT", tt.value)
|
|
||||||
} else {
|
|
||||||
require.NoError(t, os.Unsetenv(
|
|
||||||
"RECEIVER_RATE_LIMIT",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
if tt.expectError {
|
|
||||||
testReceiverRateLimitError(t)
|
|
||||||
} else {
|
|
||||||
testReceiverRateLimitSuccess(t, tt.expected)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testReceiverRateLimitError(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var cfg *config.Config
|
|
||||||
|
|
||||||
app := fx.New(
|
|
||||||
fx.NopLogger,
|
|
||||||
fx.Provide(
|
|
||||||
globals.New,
|
|
||||||
logger.New,
|
|
||||||
config.New,
|
|
||||||
),
|
|
||||||
fx.Populate(&cfg),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Error(t, app.Err())
|
|
||||||
}
|
|
||||||
|
|
||||||
func testReceiverRateLimitSuccess(
|
|
||||||
t *testing.T,
|
|
||||||
expected int,
|
|
||||||
) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var cfg *config.Config
|
|
||||||
|
|
||||||
app := fxtest.New(
|
|
||||||
t,
|
|
||||||
fx.Provide(
|
|
||||||
globals.New,
|
|
||||||
logger.New,
|
|
||||||
config.New,
|
|
||||||
),
|
|
||||||
fx.Populate(&cfg),
|
|
||||||
)
|
|
||||||
require.NoError(t, app.Err())
|
|
||||||
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
defer app.RequireStop()
|
|
||||||
|
|
||||||
assert.Equal(t, expected, cfg.ReceiverRateLimit)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewTestRetentionReaper builds a RetentionReaper backed by the given
|
|
||||||
// main database and per-webhook database manager, without the fx
|
|
||||||
// lifecycle. Intended for tests.
|
|
||||||
func NewTestRetentionReaper(
|
|
||||||
db *Database,
|
|
||||||
mgr *WebhookDBManager,
|
|
||||||
) *RetentionReaper {
|
|
||||||
return &RetentionReaper{
|
|
||||||
db: db,
|
|
||||||
dbManager: mgr,
|
|
||||||
log: slog.New(slog.NewTextHandler(
|
|
||||||
os.Stderr,
|
|
||||||
&slog.HandlerOptions{Level: slog.LevelDebug},
|
|
||||||
)),
|
|
||||||
interval: time.Hour,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExportSweep runs a single retention sweep synchronously for tests.
|
|
||||||
func (r *RetentionReaper) ExportSweep(ctx context.Context) {
|
|
||||||
r.sweep(ctx)
|
|
||||||
}
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"go.uber.org/fx"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/config"
|
|
||||||
"sneak.berlin/go/webhooker/internal/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
// hoursPerDay converts a RetentionDays count into hours for cutoff
|
|
||||||
// computation.
|
|
||||||
const hoursPerDay = 24
|
|
||||||
|
|
||||||
// RetentionReaperParams holds the fx dependencies for the
|
|
||||||
// RetentionReaper.
|
|
||||||
type RetentionReaperParams struct {
|
|
||||||
fx.In
|
|
||||||
|
|
||||||
Config *config.Config
|
|
||||||
Database *Database
|
|
||||||
DBManager *WebhookDBManager
|
|
||||||
Logger *logger.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// RetentionReaper periodically deletes expired events (and their
|
|
||||||
// dependent deliveries and delivery results) from each per-webhook
|
|
||||||
// database, enforcing every webhook's RetentionDays. Rows are removed
|
|
||||||
// permanently so that per-webhook SQLite files do not grow without
|
|
||||||
// bound.
|
|
||||||
type RetentionReaper struct {
|
|
||||||
db *Database
|
|
||||||
dbManager *WebhookDBManager
|
|
||||||
log *slog.Logger
|
|
||||||
interval time.Duration
|
|
||||||
cancel context.CancelFunc
|
|
||||||
wg sync.WaitGroup
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRetentionReaper creates the retention reaper and registers its
|
|
||||||
// fx lifecycle hooks. The background sweep loop starts on OnStart and
|
|
||||||
// stops cleanly on OnStop via context cancellation.
|
|
||||||
func NewRetentionReaper(
|
|
||||||
lc fx.Lifecycle,
|
|
||||||
params RetentionReaperParams,
|
|
||||||
) *RetentionReaper {
|
|
||||||
r := &RetentionReaper{
|
|
||||||
db: params.Database,
|
|
||||||
dbManager: params.DBManager,
|
|
||||||
log: params.Logger.Get(),
|
|
||||||
interval: params.Config.RetentionSweepInterval,
|
|
||||||
}
|
|
||||||
|
|
||||||
lc.Append(fx.Hook{
|
|
||||||
OnStart: func(ctx context.Context) error {
|
|
||||||
r.start(ctx)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
OnStop: func(_ context.Context) error {
|
|
||||||
r.stop()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *RetentionReaper) start(ctx context.Context) {
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
r.cancel = cancel
|
|
||||||
|
|
||||||
r.wg.Add(1)
|
|
||||||
|
|
||||||
go r.run(ctx)
|
|
||||||
|
|
||||||
r.log.Info(
|
|
||||||
"retention reaper started",
|
|
||||||
"interval", r.interval.String(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *RetentionReaper) stop() {
|
|
||||||
r.log.Info("retention reaper stopping")
|
|
||||||
|
|
||||||
if r.cancel != nil {
|
|
||||||
r.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
r.wg.Wait()
|
|
||||||
r.log.Info("retention reaper stopped")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *RetentionReaper) run(ctx context.Context) {
|
|
||||||
defer r.wg.Done()
|
|
||||||
|
|
||||||
ticker := time.NewTicker(r.interval)
|
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-ticker.C:
|
|
||||||
r.sweep(ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// sweep lists every webhook from the main database and reaps expired
|
|
||||||
// rows from each per-webhook database whose RetentionDays is positive.
|
|
||||||
func (r *RetentionReaper) sweep(ctx context.Context) {
|
|
||||||
var webhooks []Webhook
|
|
||||||
|
|
||||||
err := r.db.DB().
|
|
||||||
Model(&Webhook{}).
|
|
||||||
Find(&webhooks).Error
|
|
||||||
if err != nil {
|
|
||||||
r.log.Error(
|
|
||||||
"retention sweep: failed to list webhooks",
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := range webhooks {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
wh := webhooks[i]
|
|
||||||
|
|
||||||
// RetentionDays of zero or less means retain forever.
|
|
||||||
if wh.RetentionDays <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing to reap if the per-webhook database has never
|
|
||||||
// been created.
|
|
||||||
if !r.dbManager.DBExists(wh.ID) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
r.reapWebhook(wh.ID, wh.RetentionDays)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// reapWebhook removes every expired event (and its dependents) from a
|
|
||||||
// single webhook's database.
|
|
||||||
func (r *RetentionReaper) reapWebhook(
|
|
||||||
webhookID string,
|
|
||||||
retentionDays int,
|
|
||||||
) {
|
|
||||||
db, err := r.dbManager.GetDB(webhookID)
|
|
||||||
if err != nil {
|
|
||||||
r.log.Error(
|
|
||||||
"retention sweep: failed to open webhook database",
|
|
||||||
"webhook_id", webhookID,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cutoff := time.Now().Add(
|
|
||||||
-time.Duration(retentionDays*hoursPerDay) * time.Hour,
|
|
||||||
)
|
|
||||||
|
|
||||||
deleted, err := reapExpired(db, cutoff)
|
|
||||||
if err != nil {
|
|
||||||
r.log.Error(
|
|
||||||
"retention sweep: failed to reap expired events",
|
|
||||||
"webhook_id", webhookID,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if deleted > 0 {
|
|
||||||
r.log.Info(
|
|
||||||
"retention sweep: reaped expired events",
|
|
||||||
"webhook_id", webhookID,
|
|
||||||
"retention_days", retentionDays,
|
|
||||||
"events_deleted", deleted,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// reapExpired hard-deletes, in foreign-key-safe order, the delivery
|
|
||||||
// results, deliveries, and events associated with events older than
|
|
||||||
// cutoff. Deletes are unscoped so rows are physically removed rather
|
|
||||||
// than soft-deleted, reclaiming disk. It returns the number of events
|
|
||||||
// deleted.
|
|
||||||
func reapExpired(db *gorm.DB, cutoff time.Time) (int64, error) {
|
|
||||||
// Fresh subqueries are built per statement to avoid reusing a
|
|
||||||
// mutated builder across executions.
|
|
||||||
expiredEventIDs := func() *gorm.DB {
|
|
||||||
return db.Model(&Event{}).
|
|
||||||
Select("id").
|
|
||||||
Where("created_at < ?", cutoff)
|
|
||||||
}
|
|
||||||
expiredDeliveryIDs := func() *gorm.DB {
|
|
||||||
return db.Model(&Delivery{}).
|
|
||||||
Select("id").
|
|
||||||
Where("event_id IN (?)", expiredEventIDs())
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Delivery results whose delivery belongs to an expired event.
|
|
||||||
res := db.Unscoped().
|
|
||||||
Where("delivery_id IN (?)", expiredDeliveryIDs()).
|
|
||||||
Delete(&DeliveryResult{})
|
|
||||||
if res.Error != nil {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"deleting expired delivery results: %w",
|
|
||||||
res.Error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Deliveries belonging to an expired event.
|
|
||||||
del := db.Unscoped().
|
|
||||||
Where("event_id IN (?)", expiredEventIDs()).
|
|
||||||
Delete(&Delivery{})
|
|
||||||
if del.Error != nil {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"deleting expired deliveries: %w",
|
|
||||||
del.Error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. The expired events themselves.
|
|
||||||
ev := db.Unscoped().
|
|
||||||
Where("created_at < ?", cutoff).
|
|
||||||
Delete(&Event{})
|
|
||||||
if ev.Error != nil {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"deleting expired events: %w",
|
|
||||||
ev.Error,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ev.RowsAffected, nil
|
|
||||||
}
|
|
||||||
@@ -1,277 +0,0 @@
|
|||||||
package database_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"go.uber.org/fx/fxtest"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
"sneak.berlin/go/webhooker/internal/config"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
"sneak.berlin/go/webhooker/internal/globals"
|
|
||||||
"sneak.berlin/go/webhooker/internal/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
// retentionTestEnv bundles the pieces a retention test drives.
|
|
||||||
type retentionTestEnv struct {
|
|
||||||
reaper *database.RetentionReaper
|
|
||||||
mainDB *database.Database
|
|
||||||
mgr *database.WebhookDBManager
|
|
||||||
}
|
|
||||||
|
|
||||||
func setupRetentionTest(t *testing.T) *retentionTestEnv {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
lc := fxtest.NewLifecycle(t)
|
|
||||||
|
|
||||||
g := &globals.Globals{
|
|
||||||
Appname: "webhooker-test",
|
|
||||||
Version: "test",
|
|
||||||
}
|
|
||||||
|
|
||||||
l, err := logger.New(lc, logger.LoggerParams{Globals: g})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
cfg := &config.Config{
|
|
||||||
DataDir: t.TempDir(),
|
|
||||||
Environment: "dev",
|
|
||||||
}
|
|
||||||
|
|
||||||
mainDB, err := database.New(lc, database.DatabaseParams{
|
|
||||||
Config: cfg,
|
|
||||||
Logger: l,
|
|
||||||
})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
mgr, err := database.NewWebhookDBManager(
|
|
||||||
lc,
|
|
||||||
database.WebhookDBManagerParams{Config: cfg, Logger: l},
|
|
||||||
)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
require.NoError(t, lc.Start(ctx))
|
|
||||||
t.Cleanup(func() { require.NoError(t, lc.Stop(ctx)) })
|
|
||||||
|
|
||||||
return &retentionTestEnv{
|
|
||||||
reaper: database.NewTestRetentionReaper(mainDB, mgr),
|
|
||||||
mainDB: mainDB,
|
|
||||||
mgr: mgr,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// createWebhook inserts a webhook row into the main database with the
|
|
||||||
// given retention policy and returns its ID.
|
|
||||||
func createWebhook(
|
|
||||||
t *testing.T,
|
|
||||||
db *gorm.DB,
|
|
||||||
retentionDays int,
|
|
||||||
) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
wh := &database.Webhook{
|
|
||||||
UserID: uuid.New().String(),
|
|
||||||
Name: "test-webhook",
|
|
||||||
RetentionDays: retentionDays,
|
|
||||||
}
|
|
||||||
require.NoError(
|
|
||||||
t,
|
|
||||||
db.Omit(clause.Associations).Create(wh).Error,
|
|
||||||
)
|
|
||||||
|
|
||||||
// The RetentionDays column carries a GORM default of 30, so a
|
|
||||||
// zero (or negative) value passed to Create is replaced by that
|
|
||||||
// default. Force the requested value explicitly so the
|
|
||||||
// retain-forever (<= 0) path can be exercised.
|
|
||||||
require.NoError(
|
|
||||||
t,
|
|
||||||
db.Model(wh).
|
|
||||||
Update("retention_days", retentionDays).Error,
|
|
||||||
)
|
|
||||||
|
|
||||||
return wh.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
// eventChain is the set of row IDs seeded for a single event.
|
|
||||||
type eventChain struct {
|
|
||||||
eventID string
|
|
||||||
deliveryID string
|
|
||||||
resultID string
|
|
||||||
}
|
|
||||||
|
|
||||||
// seedEventChain creates an event with one delivery and one delivery
|
|
||||||
// result, all stamped with createdAt, and returns their IDs.
|
|
||||||
func seedEventChain(
|
|
||||||
t *testing.T,
|
|
||||||
db *gorm.DB,
|
|
||||||
webhookID string,
|
|
||||||
createdAt time.Time,
|
|
||||||
) eventChain {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
event := &database.Event{
|
|
||||||
WebhookID: webhookID,
|
|
||||||
EntrypointID: uuid.New().String(),
|
|
||||||
Method: "POST",
|
|
||||||
Body: `{"seed": true}`,
|
|
||||||
ContentType: "application/json",
|
|
||||||
}
|
|
||||||
event.CreatedAt = createdAt
|
|
||||||
require.NoError(t, db.Create(event).Error)
|
|
||||||
|
|
||||||
delivery := &database.Delivery{
|
|
||||||
EventID: event.ID,
|
|
||||||
TargetID: uuid.New().String(),
|
|
||||||
Status: database.DeliveryStatusDelivered,
|
|
||||||
}
|
|
||||||
delivery.CreatedAt = createdAt
|
|
||||||
require.NoError(t, db.Create(delivery).Error)
|
|
||||||
|
|
||||||
result := &database.DeliveryResult{
|
|
||||||
DeliveryID: delivery.ID,
|
|
||||||
AttemptNum: 1,
|
|
||||||
Success: true,
|
|
||||||
StatusCode: 200,
|
|
||||||
Duration: 10,
|
|
||||||
}
|
|
||||||
result.CreatedAt = createdAt
|
|
||||||
require.NoError(t, db.Create(result).Error)
|
|
||||||
|
|
||||||
return eventChain{
|
|
||||||
eventID: event.ID,
|
|
||||||
deliveryID: delivery.ID,
|
|
||||||
resultID: result.ID,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// countByID returns how many rows of model match the given id,
|
|
||||||
// counting even hard-deletable rows via Unscoped.
|
|
||||||
func countByID(
|
|
||||||
t *testing.T,
|
|
||||||
db *gorm.DB,
|
|
||||||
model any,
|
|
||||||
id string,
|
|
||||||
) int64 {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var n int64
|
|
||||||
|
|
||||||
require.NoError(
|
|
||||||
t,
|
|
||||||
db.Unscoped().Model(model).
|
|
||||||
Where("id = ?", id).Count(&n).Error,
|
|
||||||
)
|
|
||||||
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertChainGone(
|
|
||||||
t *testing.T,
|
|
||||||
db *gorm.DB,
|
|
||||||
chain eventChain,
|
|
||||||
) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
assert.Zero(
|
|
||||||
t,
|
|
||||||
countByID(t, db, &database.Event{}, chain.eventID),
|
|
||||||
"expired event should be removed",
|
|
||||||
)
|
|
||||||
assert.Zero(
|
|
||||||
t,
|
|
||||||
countByID(t, db, &database.Delivery{}, chain.deliveryID),
|
|
||||||
"expired delivery should be removed",
|
|
||||||
)
|
|
||||||
assert.Zero(
|
|
||||||
t,
|
|
||||||
countByID(
|
|
||||||
t, db, &database.DeliveryResult{}, chain.resultID,
|
|
||||||
),
|
|
||||||
"expired delivery result should be removed",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertChainPresent(
|
|
||||||
t *testing.T,
|
|
||||||
db *gorm.DB,
|
|
||||||
chain eventChain,
|
|
||||||
) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
assert.Equal(
|
|
||||||
t,
|
|
||||||
int64(1),
|
|
||||||
countByID(t, db, &database.Event{}, chain.eventID),
|
|
||||||
"recent event should be retained",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t,
|
|
||||||
int64(1),
|
|
||||||
countByID(t, db, &database.Delivery{}, chain.deliveryID),
|
|
||||||
"recent delivery should be retained",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t,
|
|
||||||
int64(1),
|
|
||||||
countByID(
|
|
||||||
t, db, &database.DeliveryResult{}, chain.resultID,
|
|
||||||
),
|
|
||||||
"recent delivery result should be retained",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRetentionReaper_ReapsExpiredKeepsRecent(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := setupRetentionTest(t)
|
|
||||||
|
|
||||||
const retentionDays = 30
|
|
||||||
|
|
||||||
webhookID := createWebhook(
|
|
||||||
t, env.mainDB.DB(), retentionDays,
|
|
||||||
)
|
|
||||||
|
|
||||||
db, err := env.mgr.GetDB(webhookID)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
old := seedEventChain(
|
|
||||||
t, db, webhookID,
|
|
||||||
now.Add(-40*24*time.Hour),
|
|
||||||
)
|
|
||||||
recent := seedEventChain(
|
|
||||||
t, db, webhookID,
|
|
||||||
now.Add(-1*24*time.Hour),
|
|
||||||
)
|
|
||||||
|
|
||||||
env.reaper.ExportSweep(context.Background())
|
|
||||||
|
|
||||||
assertChainGone(t, db, old)
|
|
||||||
assertChainPresent(t, db, recent)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRetentionReaper_RetainsForeverWhenNonPositive(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := setupRetentionTest(t)
|
|
||||||
|
|
||||||
// RetentionDays of zero means retain forever.
|
|
||||||
webhookID := createWebhook(t, env.mainDB.DB(), 0)
|
|
||||||
|
|
||||||
db, err := env.mgr.GetDB(webhookID)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
ancient := seedEventChain(
|
|
||||||
t, db, webhookID,
|
|
||||||
time.Now().Add(-365*24*time.Hour),
|
|
||||||
)
|
|
||||||
|
|
||||||
env.reaper.ExportSweep(context.Background())
|
|
||||||
|
|
||||||
assertChainPresent(t, db, ancient)
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package delivery_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"sneak.berlin/go/webhooker/internal/delivery"
|
|
||||||
)
|
|
||||||
|
|
||||||
// newSSRFTestEngine builds an Engine whose shared client
|
|
||||||
// carries the SSRF-safe transport, mirroring production.
|
|
||||||
func newSSRFTestEngine() *delivery.Engine {
|
|
||||||
log := slog.New(slog.DiscardHandler)
|
|
||||||
|
|
||||||
client := &http.Client{
|
|
||||||
Timeout: 30 * time.Second,
|
|
||||||
Transport: delivery.NewSSRFSafeTransport(),
|
|
||||||
}
|
|
||||||
|
|
||||||
return delivery.NewTestEngine(log, client, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientForConfig_TimeoutKeepsSSRFGuard asserts that a
|
|
||||||
// client returned by clientForConfig for a config with a
|
|
||||||
// per-target timeout still refuses connections to
|
|
||||||
// private/reserved addresses (the timeout must not drop the
|
|
||||||
// SSRF-safe transport).
|
|
||||||
func TestClientForConfig_TimeoutKeepsSSRFGuard(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
engine := newSSRFTestEngine()
|
|
||||||
|
|
||||||
blocked := []string{
|
|
||||||
"http://127.0.0.1/hook",
|
|
||||||
"http://169.254.169.254/latest/meta-data/",
|
|
||||||
"http://[fe80::1]/hook",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, target := range blocked {
|
|
||||||
t.Run(target, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
cfg := &delivery.HTTPTargetConfig{
|
|
||||||
URL: target,
|
|
||||||
Timeout: 5,
|
|
||||||
}
|
|
||||||
|
|
||||||
client := engine.ExportClientForConfig(cfg)
|
|
||||||
|
|
||||||
require.NotSame(t, engine.ExportClient(), client,
|
|
||||||
"a per-target timeout must yield a "+
|
|
||||||
"distinct client",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Equal(t,
|
|
||||||
5*time.Second, client.Timeout,
|
|
||||||
"the per-target timeout must be applied",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Same(t,
|
|
||||||
engine.ExportClient().Transport,
|
|
||||||
client.Transport,
|
|
||||||
"the SSRF-safe transport must be reused, "+
|
|
||||||
"not dropped",
|
|
||||||
)
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(
|
|
||||||
context.Background(),
|
|
||||||
http.MethodPost, target, nil,
|
|
||||||
)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
resp, doErr := client.Do(req)
|
|
||||||
if resp != nil {
|
|
||||||
_ = resp.Body.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
require.Error(t, doErr,
|
|
||||||
"request to %s must be blocked", target,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Contains(t, doErr.Error(), "blocked",
|
|
||||||
"error must come from the SSRF guard",
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientForConfig_NoTimeoutUnchanged asserts that with
|
|
||||||
// no per-target timeout the shared SSRF-safe client is
|
|
||||||
// returned unchanged.
|
|
||||||
func TestClientForConfig_NoTimeoutUnchanged(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
engine := newSSRFTestEngine()
|
|
||||||
|
|
||||||
cfg := &delivery.HTTPTargetConfig{
|
|
||||||
URL: "https://example.com/hook",
|
|
||||||
}
|
|
||||||
|
|
||||||
client := engine.ExportClientForConfig(cfg)
|
|
||||||
|
|
||||||
assert.Same(t, engine.ExportClient(), client,
|
|
||||||
"without a per-target timeout the shared client "+
|
|
||||||
"must be returned unchanged",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,6 @@
|
|||||||
package delivery_test
|
package delivery_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@@ -1653,179 +1652,6 @@ func TestProcessDelivery_RoutesToSlack(t *testing.T) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newLogCaptureEngine builds a test engine whose logger
|
|
||||||
// writes to the returned buffer, for inspecting log output.
|
|
||||||
func newLogCaptureEngine(
|
|
||||||
t *testing.T,
|
|
||||||
) (*delivery.Engine, *bytes.Buffer) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var buf bytes.Buffer
|
|
||||||
|
|
||||||
log := slog.New(slog.NewTextHandler(
|
|
||||||
&buf,
|
|
||||||
&slog.HandlerOptions{Level: slog.LevelDebug},
|
|
||||||
))
|
|
||||||
|
|
||||||
e := delivery.NewTestEngine(
|
|
||||||
log, &http.Client{Timeout: 5 * time.Second}, 1,
|
|
||||||
)
|
|
||||||
|
|
||||||
return e, &buf
|
|
||||||
}
|
|
||||||
|
|
||||||
// assertLogLineComplete asserts the captured log output
|
|
||||||
// carries the full inbound webhook content and ids.
|
|
||||||
func assertLogLineComplete(
|
|
||||||
t *testing.T, out string, event database.Event,
|
|
||||||
) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
assert.Contains(t, out, "log-body-marker",
|
|
||||||
"log line must contain the full request body",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Contains(t, out, "Content-Type",
|
|
||||||
"log line must contain the full request headers",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Contains(t, out, event.EntrypointID,
|
|
||||||
"log line must contain the entrypoint id",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Contains(t, out, event.WebhookID,
|
|
||||||
"log line must contain the webhook id",
|
|
||||||
)
|
|
||||||
|
|
||||||
assert.Contains(t, out, "application/json",
|
|
||||||
"log line must contain the content type",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeliverLog_LogsFullContent(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
db := testWebhookDB(t)
|
|
||||||
e, buf := newLogCaptureEngine(t)
|
|
||||||
|
|
||||||
event := seedEvent(
|
|
||||||
t, db, `{"log-body-marker":"abc123"}`,
|
|
||||||
)
|
|
||||||
|
|
||||||
dlv := seedDelivery(
|
|
||||||
t, db, event.ID, uuid.New().String(),
|
|
||||||
database.DeliveryStatusPending,
|
|
||||||
)
|
|
||||||
|
|
||||||
d := &database.Delivery{
|
|
||||||
EventID: event.ID,
|
|
||||||
TargetID: dlv.TargetID,
|
|
||||||
Status: database.DeliveryStatusPending,
|
|
||||||
Event: event,
|
|
||||||
Target: database.Target{
|
|
||||||
Name: "test-log-full",
|
|
||||||
Type: database.TargetTypeLog,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
d.ID = dlv.ID
|
|
||||||
|
|
||||||
e.ExportDeliverLog(db, d)
|
|
||||||
|
|
||||||
assertLogLineComplete(t, buf.String(), event)
|
|
||||||
|
|
||||||
assertDeliveryStatus(t, db, dlv.ID,
|
|
||||||
database.DeliveryStatusDelivered,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// buildSlackRetryDelivery builds a Slack delivery whose
|
|
||||||
// target is configured with retries enabled.
|
|
||||||
func buildSlackRetryDelivery(
|
|
||||||
dlv database.Delivery,
|
|
||||||
event database.Event,
|
|
||||||
targetID, cfg string,
|
|
||||||
) *database.Delivery {
|
|
||||||
d := &database.Delivery{
|
|
||||||
EventID: event.ID,
|
|
||||||
TargetID: targetID,
|
|
||||||
Status: database.DeliveryStatusPending,
|
|
||||||
Event: event,
|
|
||||||
Target: database.Target{
|
|
||||||
Name: "test-slack-retry",
|
|
||||||
Type: database.TargetTypeSlack,
|
|
||||||
Config: cfg,
|
|
||||||
MaxRetries: 5,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
d.ID = dlv.ID
|
|
||||||
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeliverSlack_WithRetries_SchedulesRetry(
|
|
||||||
t *testing.T,
|
|
||||||
) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
db := testWebhookDB(t)
|
|
||||||
ts := newStatusServer(t, http.StatusServiceUnavailable)
|
|
||||||
e := testEngine(t, 1)
|
|
||||||
targetID := uuid.New().String()
|
|
||||||
|
|
||||||
slackCfg, err := json.Marshal(
|
|
||||||
delivery.SlackTargetConfig{WebhookURL: ts.URL},
|
|
||||||
)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
event := seedEvent(t, db, `{"slack":"retry"}`)
|
|
||||||
|
|
||||||
dlv := seedDelivery(
|
|
||||||
t, db, event.ID, targetID,
|
|
||||||
database.DeliveryStatusPending,
|
|
||||||
)
|
|
||||||
|
|
||||||
d := buildSlackRetryDelivery(
|
|
||||||
dlv, event, targetID, string(slackCfg),
|
|
||||||
)
|
|
||||||
|
|
||||||
task := &delivery.Task{
|
|
||||||
DeliveryID: dlv.ID,
|
|
||||||
TargetID: targetID,
|
|
||||||
TargetType: database.TargetTypeSlack,
|
|
||||||
MaxRetries: 5,
|
|
||||||
AttemptNum: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
e.ExportProcessDelivery(context.TODO(), db, d, task)
|
|
||||||
|
|
||||||
assertDeliveryStatus(t, db, dlv.ID,
|
|
||||||
database.DeliveryStatusRetrying,
|
|
||||||
)
|
|
||||||
|
|
||||||
assertDeliveryResult(
|
|
||||||
t, db, dlv.ID, false,
|
|
||||||
http.StatusServiceUnavailable,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// newStatusServer starts a test server that always responds
|
|
||||||
// with the given status code.
|
|
||||||
func newStatusServer(
|
|
||||||
t *testing.T, code int,
|
|
||||||
) *httptest.Server {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
ts := httptest.NewServer(http.HandlerFunc(
|
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
w.WriteHeader(code)
|
|
||||||
},
|
|
||||||
))
|
|
||||||
|
|
||||||
t.Cleanup(ts.Close)
|
|
||||||
|
|
||||||
return ts
|
|
||||||
}
|
|
||||||
|
|
||||||
// readAll is a small helper to avoid importing io in
|
// readAll is a small helper to avoid importing io in
|
||||||
// a test handler inline.
|
// a test handler inline.
|
||||||
func readAll(r interface {
|
func readAll(r interface {
|
||||||
|
|||||||
@@ -39,50 +39,37 @@ func ExportTruncate(s string, maxLen int) string {
|
|||||||
return truncate(s, maxLen)
|
return truncate(s, maxLen)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDeliverHTTP delivers via the http target for testing.
|
// ExportDeliverHTTP exposes deliverHTTP for testing.
|
||||||
func (e *Engine) ExportDeliverHTTP(
|
func (e *Engine) ExportDeliverHTTP(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
webhookDB *gorm.DB,
|
webhookDB *gorm.DB,
|
||||||
d *database.Delivery,
|
d *database.Delivery,
|
||||||
task *Task,
|
task *Task,
|
||||||
) {
|
) {
|
||||||
e.httpTarget.Deliver(ctx, webhookDB, d, task, e)
|
e.deliverHTTP(ctx, webhookDB, d, task)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDeliverDatabase delivers via the database target.
|
// ExportDeliverDatabase exposes deliverDatabase.
|
||||||
func (e *Engine) ExportDeliverDatabase(
|
func (e *Engine) ExportDeliverDatabase(
|
||||||
webhookDB *gorm.DB, d *database.Delivery,
|
webhookDB *gorm.DB, d *database.Delivery,
|
||||||
) {
|
) {
|
||||||
e.targets[database.TargetTypeDatabase].Deliver(
|
e.deliverDatabase(webhookDB, d)
|
||||||
context.Background(), webhookDB, d, &Task{}, e,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDeliverLog delivers via the log target for testing.
|
// ExportDeliverLog exposes deliverLog for testing.
|
||||||
func (e *Engine) ExportDeliverLog(
|
func (e *Engine) ExportDeliverLog(
|
||||||
webhookDB *gorm.DB, d *database.Delivery,
|
webhookDB *gorm.DB, d *database.Delivery,
|
||||||
) {
|
) {
|
||||||
e.targets[database.TargetTypeLog].Deliver(
|
e.deliverLog(webhookDB, d)
|
||||||
context.Background(), webhookDB, d, &Task{}, e,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDeliverSlack delivers via the slack target for
|
// ExportDeliverSlack exposes deliverSlack for testing.
|
||||||
// testing.
|
|
||||||
func (e *Engine) ExportDeliverSlack(
|
func (e *Engine) ExportDeliverSlack(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
webhookDB *gorm.DB,
|
webhookDB *gorm.DB,
|
||||||
d *database.Delivery,
|
d *database.Delivery,
|
||||||
) {
|
) {
|
||||||
task := &Task{
|
e.deliverSlack(ctx, webhookDB, d)
|
||||||
DeliveryID: d.ID,
|
|
||||||
TargetID: d.TargetID,
|
|
||||||
AttemptNum: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
e.targets[database.TargetTypeSlack].Deliver(
|
|
||||||
ctx, webhookDB, d, task, e,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportProcessNewTask exposes processNewTask.
|
// ExportProcessNewTask exposes processNewTask.
|
||||||
@@ -109,56 +96,41 @@ func (e *Engine) ExportProcessDelivery(
|
|||||||
e.processDelivery(ctx, webhookDB, d, task)
|
e.processDelivery(ctx, webhookDB, d, task)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportGetCircuitBreaker exposes the http target's
|
// ExportGetCircuitBreaker exposes getCircuitBreaker.
|
||||||
// getCircuitBreaker.
|
|
||||||
func (e *Engine) ExportGetCircuitBreaker(
|
func (e *Engine) ExportGetCircuitBreaker(
|
||||||
targetID string,
|
targetID string,
|
||||||
) *CircuitBreaker {
|
) *CircuitBreaker {
|
||||||
return e.httpTarget.getCircuitBreaker(targetID)
|
return e.getCircuitBreaker(targetID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportParseHTTPConfig exposes parseHTTPConfig.
|
// ExportParseHTTPConfig exposes parseHTTPConfig.
|
||||||
func (e *Engine) ExportParseHTTPConfig(
|
func (e *Engine) ExportParseHTTPConfig(
|
||||||
configJSON string,
|
configJSON string,
|
||||||
) (*HTTPTargetConfig, error) {
|
) (*HTTPTargetConfig, error) {
|
||||||
return parseHTTPConfig(configJSON)
|
return e.parseHTTPConfig(configJSON)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportParseSlackConfig exposes parseSlackConfig.
|
// ExportParseSlackConfig exposes parseSlackConfig.
|
||||||
func (e *Engine) ExportParseSlackConfig(
|
func (e *Engine) ExportParseSlackConfig(
|
||||||
configJSON string,
|
configJSON string,
|
||||||
) (*SlackTargetConfig, error) {
|
) (*SlackTargetConfig, error) {
|
||||||
return parseSlackConfig(configJSON)
|
return e.parseSlackConfig(configJSON)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportDoHTTPRequest exposes the http target's
|
// ExportDoHTTPRequest exposes doHTTPRequest.
|
||||||
// doHTTPRequest.
|
|
||||||
func (e *Engine) ExportDoHTTPRequest(
|
func (e *Engine) ExportDoHTTPRequest(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
cfg *HTTPTargetConfig,
|
cfg *HTTPTargetConfig,
|
||||||
event *database.Event,
|
event *database.Event,
|
||||||
) (int, string, int64, error) {
|
) (int, string, int64, error) {
|
||||||
return e.httpTarget.doHTTPRequest(ctx, cfg, event)
|
return e.doHTTPRequest(ctx, cfg, event)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportClientForConfig exposes the http target's
|
// ExportScheduleRetry exposes scheduleRetry.
|
||||||
// clientForConfig.
|
|
||||||
func (e *Engine) ExportClientForConfig(
|
|
||||||
cfg *HTTPTargetConfig,
|
|
||||||
) *http.Client {
|
|
||||||
return e.httpTarget.clientForConfig(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExportClient returns the http target's shared HTTP client.
|
|
||||||
func (e *Engine) ExportClient() *http.Client {
|
|
||||||
return e.httpTarget.client
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExportScheduleRetry exposes ScheduleRetry.
|
|
||||||
func (e *Engine) ExportScheduleRetry(
|
func (e *Engine) ExportScheduleRetry(
|
||||||
task Task, delay time.Duration,
|
task Task, delay time.Duration,
|
||||||
) {
|
) {
|
||||||
e.ScheduleRetry(task, delay)
|
e.scheduleRetry(task, delay)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportRecoverPendingDeliveries exposes
|
// ExportRecoverPendingDeliveries exposes
|
||||||
@@ -215,15 +187,13 @@ func NewTestEngine(
|
|||||||
client *http.Client,
|
client *http.Client,
|
||||||
workers int,
|
workers int,
|
||||||
) *Engine {
|
) *Engine {
|
||||||
e := &Engine{
|
return &Engine{
|
||||||
log: log,
|
log: log,
|
||||||
|
client: client,
|
||||||
deliveryCh: make(chan Task, deliveryChannelSize),
|
deliveryCh: make(chan Task, deliveryChannelSize),
|
||||||
retryCh: make(chan Task, retryChannelSize),
|
retryCh: make(chan Task, retryChannelSize),
|
||||||
workers: workers,
|
workers: workers,
|
||||||
}
|
}
|
||||||
e.initTargets(client)
|
|
||||||
|
|
||||||
return e
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTestEngineSmallRetry creates an Engine with a tiny
|
// NewTestEngineSmallRetry creates an Engine with a tiny
|
||||||
@@ -231,13 +201,10 @@ func NewTestEngine(
|
|||||||
func NewTestEngineSmallRetry(
|
func NewTestEngineSmallRetry(
|
||||||
log *slog.Logger,
|
log *slog.Logger,
|
||||||
) *Engine {
|
) *Engine {
|
||||||
e := &Engine{
|
return &Engine{
|
||||||
log: log,
|
log: log,
|
||||||
retryCh: make(chan Task, 1),
|
retryCh: make(chan Task, 1),
|
||||||
}
|
}
|
||||||
e.initTargets(nil)
|
|
||||||
|
|
||||||
return e
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTestEngineWithDB creates an Engine with a real
|
// NewTestEngineWithDB creates an Engine with a real
|
||||||
@@ -249,17 +216,15 @@ func NewTestEngineWithDB(
|
|||||||
client *http.Client,
|
client *http.Client,
|
||||||
workers int,
|
workers int,
|
||||||
) *Engine {
|
) *Engine {
|
||||||
e := &Engine{
|
return &Engine{
|
||||||
database: db,
|
database: db,
|
||||||
dbManager: dbMgr,
|
dbManager: dbMgr,
|
||||||
log: log,
|
log: log,
|
||||||
|
client: client,
|
||||||
deliveryCh: make(chan Task, deliveryChannelSize),
|
deliveryCh: make(chan Task, deliveryChannelSize),
|
||||||
retryCh: make(chan Task, retryChannelSize),
|
retryCh: make(chan Task, retryChannelSize),
|
||||||
workers: workers,
|
workers: workers,
|
||||||
}
|
}
|
||||||
e.initTargets(client)
|
|
||||||
|
|
||||||
return e
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTestCircuitBreaker creates a CircuitBreaker with
|
// NewTestCircuitBreaker creates a CircuitBreaker with
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
package delivery
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Scheduler re-enqueues a task for a future delivery attempt.
|
|
||||||
// The engine provides one to each target so a target can own
|
|
||||||
// its retries durably: it records the attempt, marks the
|
|
||||||
// delivery retrying, and asks the Scheduler to deliver the
|
|
||||||
// next attempt after delay — exactly what the engine does for
|
|
||||||
// its own restart recovery.
|
|
||||||
type Scheduler interface {
|
|
||||||
ScheduleRetry(task Task, delay time.Duration)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Target delivers an event to one target type. Each type is
|
|
||||||
// an implementation. A Target owns its whole delivery: it
|
|
||||||
// makes the attempt, records the DeliveryResult and updates
|
|
||||||
// the DeliveryStatus, and — for targets that retry — decides
|
|
||||||
// whether to retry, computes its own backoff, gates with its
|
|
||||||
// own circuit breaker, and reschedules via the injected
|
|
||||||
// Scheduler. Fire-and-forget targets simply record a single
|
|
||||||
// attempt.
|
|
||||||
type Target interface {
|
|
||||||
Deliver(
|
|
||||||
ctx context.Context,
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// rescheduler is implemented by targets that own durable
|
|
||||||
// retries. The engine's restart recovery and periodic sweep
|
|
||||||
// use it to let the target recompute the schedule for an
|
|
||||||
// orphaned retrying delivery, keeping the retry schedule
|
|
||||||
// target-owned. Fire-and-forget targets do not implement it
|
|
||||||
// and their (never-occurring) retrying deliveries are
|
|
||||||
// skipped.
|
|
||||||
type rescheduler interface {
|
|
||||||
// remainingBackoff returns how long to wait before the
|
|
||||||
// next attempt of a recovered retrying delivery.
|
|
||||||
remainingBackoff(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
deliveryID string,
|
|
||||||
attemptNum int,
|
|
||||||
) time.Duration
|
|
||||||
|
|
||||||
// backoffElapsed reports whether the backoff window for
|
|
||||||
// the last attempt has already passed, so the periodic
|
|
||||||
// sweep can re-enqueue the delivery now.
|
|
||||||
backoffElapsed(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
deliveryID string,
|
|
||||||
attemptNum int,
|
|
||||||
) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// attemptResult is the outcome of a single delivery attempt,
|
|
||||||
// as reported by a target's per-attempt function to the
|
|
||||||
// shared retry core.
|
|
||||||
type attemptResult struct {
|
|
||||||
statusCode int
|
|
||||||
respBody string
|
|
||||||
duration int64
|
|
||||||
success bool
|
|
||||||
errMsg string
|
|
||||||
}
|
|
||||||
|
|
||||||
// initTargets builds the target registry, wiring each target
|
|
||||||
// to the engine's persistence helpers and giving the HTTP and
|
|
||||||
// Slack targets the shared SSRF-safe client. It is called by
|
|
||||||
// both New and the test constructors so the registry is
|
|
||||||
// always populated.
|
|
||||||
func (e *Engine) initTargets(client *http.Client) {
|
|
||||||
httpT := &httpTarget{
|
|
||||||
httpCore: &httpCore{eng: e},
|
|
||||||
client: client,
|
|
||||||
}
|
|
||||||
|
|
||||||
slackT := &slackTarget{
|
|
||||||
httpCore: &httpCore{eng: e},
|
|
||||||
client: client,
|
|
||||||
}
|
|
||||||
|
|
||||||
e.httpTarget = httpT
|
|
||||||
|
|
||||||
e.targets = map[database.TargetType]Target{
|
|
||||||
database.TargetTypeHTTP: httpT,
|
|
||||||
database.TargetTypeSlack: slackT,
|
|
||||||
database.TargetTypeDatabase: &databaseTarget{eng: e},
|
|
||||||
database.TargetTypeLog: &logTarget{eng: e},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package delivery
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// databaseTarget is a fire-and-forget target: the event is
|
|
||||||
// already persisted in the per-webhook database by the time
|
|
||||||
// delivery runs, so the target records a single successful
|
|
||||||
// attempt. (Durable archiving to a separate store is tracked
|
|
||||||
// as its own work.)
|
|
||||||
type databaseTarget struct {
|
|
||||||
eng *Engine
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deliver implements Target.
|
|
||||||
func (t *databaseTarget) Deliver(
|
|
||||||
_ context.Context,
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
_ *Task,
|
|
||||||
_ Scheduler,
|
|
||||||
) {
|
|
||||||
t.eng.recordResult(
|
|
||||||
webhookDB, d, 1, true, 0, "", "", 0,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusDelivered,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,499 +0,0 @@
|
|||||||
package delivery
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Sentinel errors returned by the config parsers.
|
|
||||||
var (
|
|
||||||
errEmptyTargetConfig = errors.New(
|
|
||||||
"empty target config",
|
|
||||||
)
|
|
||||||
errMissingTargetURL = errors.New(
|
|
||||||
"target URL is required",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTPTargetConfig holds configuration for http target
|
|
||||||
// types.
|
|
||||||
type HTTPTargetConfig struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
Headers map[string]string `json:"headers,omitempty"`
|
|
||||||
Timeout int `json:"timeout,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// httpCore holds the retry, backoff, and circuit-breaker
|
|
||||||
// machinery shared by the HTTP and Slack targets. Each of
|
|
||||||
// those targets owns its own httpCore instance (and thus its
|
|
||||||
// own circuit breakers); the per-attempt request differs
|
|
||||||
// between them and is supplied as a closure.
|
|
||||||
type httpCore struct {
|
|
||||||
eng *Engine
|
|
||||||
|
|
||||||
// circuitBreakers stores a *CircuitBreaker per target ID.
|
|
||||||
circuitBreakers sync.Map
|
|
||||||
}
|
|
||||||
|
|
||||||
// deliver runs one delivery attempt through the retry core.
|
|
||||||
// A maxRetries of 0 is fire-and-forget: a single attempt is
|
|
||||||
// recorded and no circuit breaker is consulted. A positive
|
|
||||||
// maxRetries gates the attempt on the circuit breaker and
|
|
||||||
// schedules a backed-off retry on failure.
|
|
||||||
func (c *httpCore) deliver(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
maxRetries int,
|
|
||||||
attempt func() attemptResult,
|
|
||||||
) {
|
|
||||||
if maxRetries == 0 {
|
|
||||||
c.fireAndForget(webhookDB, d, attempt())
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.withRetry(
|
|
||||||
webhookDB, d, task, sched, maxRetries, attempt,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *httpCore) fireAndForget(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
res attemptResult,
|
|
||||||
) {
|
|
||||||
c.eng.recordResult(
|
|
||||||
webhookDB, d, 1, res.success,
|
|
||||||
res.statusCode, res.respBody, res.errMsg,
|
|
||||||
res.duration,
|
|
||||||
)
|
|
||||||
|
|
||||||
if res.success {
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d,
|
|
||||||
database.DeliveryStatusDelivered,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusFailed,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *httpCore) withRetry(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
maxRetries int,
|
|
||||||
attempt func() attemptResult,
|
|
||||||
) {
|
|
||||||
cb := c.getCircuitBreaker(task.TargetID)
|
|
||||||
if c.circuitBreakerBlock(webhookDB, d, task, sched, cb) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
attemptNum := task.AttemptNum
|
|
||||||
|
|
||||||
res := attempt()
|
|
||||||
|
|
||||||
c.eng.recordResult(
|
|
||||||
webhookDB, d, attemptNum, res.success,
|
|
||||||
res.statusCode, res.respBody, res.errMsg,
|
|
||||||
res.duration,
|
|
||||||
)
|
|
||||||
|
|
||||||
if res.success {
|
|
||||||
cb.RecordSuccess()
|
|
||||||
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d,
|
|
||||||
database.DeliveryStatusDelivered,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cb.RecordFailure()
|
|
||||||
|
|
||||||
c.handleRetry(
|
|
||||||
webhookDB, d, task, sched, maxRetries, attemptNum,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *httpCore) circuitBreakerBlock(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
cb *CircuitBreaker,
|
|
||||||
) bool {
|
|
||||||
if cb.Allow() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
remaining := cb.CooldownRemaining()
|
|
||||||
|
|
||||||
c.eng.log.Info(
|
|
||||||
"circuit breaker open, skipping delivery",
|
|
||||||
"target_id", task.TargetID,
|
|
||||||
"target_name", task.TargetName,
|
|
||||||
"delivery_id", d.ID,
|
|
||||||
"cooldown_remaining", remaining,
|
|
||||||
)
|
|
||||||
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d,
|
|
||||||
database.DeliveryStatusRetrying,
|
|
||||||
)
|
|
||||||
|
|
||||||
retryTask := *task
|
|
||||||
sched.ScheduleRetry(retryTask, remaining)
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *httpCore) handleRetry(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
maxRetries int,
|
|
||||||
attemptNum int,
|
|
||||||
) {
|
|
||||||
if attemptNum >= maxRetries {
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d,
|
|
||||||
database.DeliveryStatusFailed,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusRetrying,
|
|
||||||
)
|
|
||||||
|
|
||||||
backoff := calcBackoff(attemptNum)
|
|
||||||
|
|
||||||
retryTask := *task
|
|
||||||
retryTask.AttemptNum = attemptNum + 1
|
|
||||||
sched.ScheduleRetry(retryTask, backoff)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *httpCore) getCircuitBreaker(
|
|
||||||
targetID string,
|
|
||||||
) *CircuitBreaker {
|
|
||||||
if val, ok := c.circuitBreakers.Load(targetID); ok {
|
|
||||||
cb, _ := val.(*CircuitBreaker)
|
|
||||||
|
|
||||||
return cb
|
|
||||||
}
|
|
||||||
|
|
||||||
fresh := NewCircuitBreaker()
|
|
||||||
|
|
||||||
actual, _ := c.circuitBreakers.LoadOrStore(
|
|
||||||
targetID, fresh,
|
|
||||||
)
|
|
||||||
|
|
||||||
cb, _ := actual.(*CircuitBreaker)
|
|
||||||
|
|
||||||
return cb
|
|
||||||
}
|
|
||||||
|
|
||||||
// remainingBackoff returns how long remains of the backoff
|
|
||||||
// window for the last attempt of a recovered retrying
|
|
||||||
// delivery. It implements rescheduler.
|
|
||||||
func (c *httpCore) remainingBackoff(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
deliveryID string,
|
|
||||||
attemptNum int,
|
|
||||||
) time.Duration {
|
|
||||||
var lastResult database.DeliveryResult
|
|
||||||
|
|
||||||
err := webhookDB.
|
|
||||||
Where("delivery_id = ?", deliveryID).
|
|
||||||
Order("created_at DESC").
|
|
||||||
First(&lastResult).Error
|
|
||||||
if err != nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
backoff := calcBackoff(attemptNum)
|
|
||||||
elapsed := time.Since(lastResult.CreatedAt)
|
|
||||||
remaining := backoff - elapsed
|
|
||||||
|
|
||||||
return max(remaining, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// backoffElapsed reports whether the backoff window for the
|
|
||||||
// last attempt of a retrying delivery has passed. It
|
|
||||||
// implements rescheduler.
|
|
||||||
func (c *httpCore) backoffElapsed(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
deliveryID string,
|
|
||||||
attemptNum int,
|
|
||||||
) bool {
|
|
||||||
var lastResult database.DeliveryResult
|
|
||||||
|
|
||||||
err := webhookDB.
|
|
||||||
Where("delivery_id = ?", deliveryID).
|
|
||||||
Order("created_at DESC").
|
|
||||||
First(&lastResult).Error
|
|
||||||
if err != nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
backoff := calcBackoff(attemptNum)
|
|
||||||
|
|
||||||
return time.Since(lastResult.CreatedAt) >= backoff
|
|
||||||
}
|
|
||||||
|
|
||||||
func calcBackoff(attemptNum int) time.Duration {
|
|
||||||
shift := max(attemptNum-1, 0)
|
|
||||||
shift = min(shift, maxBackoffShift)
|
|
||||||
|
|
||||||
return time.Duration(1<<uint(shift)) * time.Second
|
|
||||||
}
|
|
||||||
|
|
||||||
// httpTarget delivers events to http targets. It forwards the
|
|
||||||
// event body and (filtered) request headers to the configured
|
|
||||||
// URL and owns retry, backoff, and circuit breaking through
|
|
||||||
// the shared httpCore.
|
|
||||||
type httpTarget struct {
|
|
||||||
*httpCore
|
|
||||||
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deliver implements Target.
|
|
||||||
func (t *httpTarget) Deliver(
|
|
||||||
ctx context.Context,
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
) {
|
|
||||||
cfg, err := parseHTTPConfig(d.Target.Config)
|
|
||||||
if err != nil {
|
|
||||||
t.eng.log.Error(
|
|
||||||
"invalid HTTP target config",
|
|
||||||
"target_id", d.TargetID,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.recordResult(
|
|
||||||
webhookDB, d, task.AttemptNum,
|
|
||||||
false, 0, "", err.Error(), 0,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusFailed,
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
attempt := func() attemptResult {
|
|
||||||
return t.attempt(ctx, cfg, &d.Event)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.deliver(
|
|
||||||
webhookDB, d, task, sched,
|
|
||||||
d.Target.MaxRetries, attempt,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// attempt performs a single HTTP delivery attempt and derives
|
|
||||||
// the success flag and error message the same way the engine
|
|
||||||
// did: a non-2xx response is a failure but carries no error
|
|
||||||
// string; only a transport-level error does.
|
|
||||||
func (t *httpTarget) attempt(
|
|
||||||
ctx context.Context,
|
|
||||||
cfg *HTTPTargetConfig,
|
|
||||||
event *database.Event,
|
|
||||||
) attemptResult {
|
|
||||||
statusCode, respBody, duration, reqErr :=
|
|
||||||
t.doHTTPRequest(ctx, cfg, event)
|
|
||||||
|
|
||||||
success := reqErr == nil &&
|
|
||||||
statusCode >= httpSuccessMin &&
|
|
||||||
statusCode < httpSuccessMax
|
|
||||||
|
|
||||||
errMsg := ""
|
|
||||||
if reqErr != nil {
|
|
||||||
errMsg = reqErr.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
return attemptResult{
|
|
||||||
statusCode: statusCode,
|
|
||||||
respBody: respBody,
|
|
||||||
duration: duration,
|
|
||||||
success: success,
|
|
||||||
errMsg: errMsg,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *httpTarget) doHTTPRequest(
|
|
||||||
ctx context.Context,
|
|
||||||
cfg *HTTPTargetConfig,
|
|
||||||
event *database.Event,
|
|
||||||
) (int, string, int64, error) {
|
|
||||||
start := time.Now()
|
|
||||||
|
|
||||||
req, reqErr := http.NewRequestWithContext(
|
|
||||||
ctx,
|
|
||||||
http.MethodPost,
|
|
||||||
cfg.URL,
|
|
||||||
bytes.NewReader([]byte(event.Body)),
|
|
||||||
)
|
|
||||||
if reqErr != nil {
|
|
||||||
return 0, "", 0, fmt.Errorf(
|
|
||||||
"creating request: %w", reqErr,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
applyRequestHeaders(req, event, cfg)
|
|
||||||
|
|
||||||
client := t.clientForConfig(cfg)
|
|
||||||
|
|
||||||
resp, doErr := executeHTTPRequest(client, req)
|
|
||||||
|
|
||||||
dur := time.Since(start).Milliseconds()
|
|
||||||
if doErr != nil {
|
|
||||||
return 0, "", dur, fmt.Errorf(
|
|
||||||
"sending request: %w", doErr,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() { _ = resp.Body.Close() }()
|
|
||||||
|
|
||||||
body, readErr := io.ReadAll(
|
|
||||||
io.LimitReader(resp.Body, maxBodyLog),
|
|
||||||
)
|
|
||||||
if readErr != nil {
|
|
||||||
return resp.StatusCode, "", dur,
|
|
||||||
fmt.Errorf(
|
|
||||||
"reading response body: %w", readErr,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return resp.StatusCode, string(body), dur, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *httpTarget) clientForConfig(
|
|
||||||
cfg *HTTPTargetConfig,
|
|
||||||
) *http.Client {
|
|
||||||
if cfg.Timeout > 0 {
|
|
||||||
// Reuse the shared client's SSRF-safe transport so
|
|
||||||
// a per-target timeout does not drop the
|
|
||||||
// request-time private-IP guard. Only the timeout
|
|
||||||
// is overridden.
|
|
||||||
return &http.Client{
|
|
||||||
Timeout: time.Duration(
|
|
||||||
cfg.Timeout,
|
|
||||||
) * time.Second,
|
|
||||||
Transport: t.client.Transport,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return t.client
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseHTTPConfig(
|
|
||||||
configJSON string,
|
|
||||||
) (*HTTPTargetConfig, error) {
|
|
||||||
if configJSON == "" {
|
|
||||||
return nil, errEmptyTargetConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
var cfg HTTPTargetConfig
|
|
||||||
|
|
||||||
err := json.Unmarshal(
|
|
||||||
[]byte(configJSON), &cfg,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"parsing config JSON: %w", err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.URL == "" {
|
|
||||||
return nil, errMissingTargetURL
|
|
||||||
}
|
|
||||||
|
|
||||||
return &cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// isForwardableHeader returns true if the header should
|
|
||||||
// be forwarded to targets.
|
|
||||||
func isForwardableHeader(name string) bool {
|
|
||||||
switch http.CanonicalHeaderKey(name) {
|
|
||||||
case "Host", "Connection", "Keep-Alive",
|
|
||||||
"Transfer-Encoding", "Te", "Trailer",
|
|
||||||
"Upgrade", "Proxy-Authorization",
|
|
||||||
"Proxy-Connection", "Content-Length":
|
|
||||||
return false
|
|
||||||
default:
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyRequestHeaders(
|
|
||||||
req *http.Request,
|
|
||||||
event *database.Event,
|
|
||||||
cfg *HTTPTargetConfig,
|
|
||||||
) {
|
|
||||||
if event.ContentType != "" {
|
|
||||||
req.Header.Set(
|
|
||||||
"Content-Type", event.ContentType,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var originalHeaders map[string][]string
|
|
||||||
|
|
||||||
if event.Headers != "" {
|
|
||||||
jsonErr := json.Unmarshal(
|
|
||||||
[]byte(event.Headers),
|
|
||||||
&originalHeaders,
|
|
||||||
)
|
|
||||||
if jsonErr == nil {
|
|
||||||
for k, vals := range originalHeaders {
|
|
||||||
if isForwardableHeader(k) {
|
|
||||||
for _, v := range vals {
|
|
||||||
req.Header.Add(k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range cfg.Headers {
|
|
||||||
req.Header.Set(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("User-Agent", "webhooker/1.0")
|
|
||||||
}
|
|
||||||
|
|
||||||
// executeHTTPRequest sends an HTTP request using the provided
|
|
||||||
// client. URLs are validated by the config parsers and the
|
|
||||||
// SSRF-safe transport before reaching here.
|
|
||||||
func executeHTTPRequest(
|
|
||||||
client *http.Client, req *http.Request,
|
|
||||||
) (*http.Response, error) {
|
|
||||||
return client.Do(req) //#nosec G704 -- URL validated by parseHTTPConfig/parseSlackConfig and SSRF-safe transport
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
package delivery
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// logTarget is a fire-and-forget target that logs the entire
|
|
||||||
// inbound webhook — the full request body and headers, plus
|
|
||||||
// the method, content type, and the webhook and entrypoint
|
|
||||||
// ids — then records a single successful attempt.
|
|
||||||
type logTarget struct {
|
|
||||||
eng *Engine
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deliver implements Target.
|
|
||||||
func (t *logTarget) Deliver(
|
|
||||||
_ context.Context,
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
_ *Task,
|
|
||||||
_ Scheduler,
|
|
||||||
) {
|
|
||||||
t.eng.log.Info(
|
|
||||||
"webhook event delivered to log target",
|
|
||||||
"delivery_id", d.ID,
|
|
||||||
"event_id", d.EventID,
|
|
||||||
"target_id", d.TargetID,
|
|
||||||
"target_name", d.Target.Name,
|
|
||||||
"webhook_id", d.Event.WebhookID,
|
|
||||||
"entrypoint_id", d.Event.EntrypointID,
|
|
||||||
"method", d.Event.Method,
|
|
||||||
"content_type", d.Event.ContentType,
|
|
||||||
"headers", d.Event.Headers,
|
|
||||||
"body", d.Event.Body,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.recordResult(
|
|
||||||
webhookDB, d, 1, true, 0, "", "", 0,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusDelivered,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,299 +0,0 @@
|
|||||||
package delivery
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"sneak.berlin/go/webhooker/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// errMissingWebhookURL is returned when a Slack target config
|
|
||||||
// omits its webhook URL.
|
|
||||||
var errMissingWebhookURL = errors.New(
|
|
||||||
"webhook_url is required",
|
|
||||||
)
|
|
||||||
|
|
||||||
// SlackTargetConfig holds configuration for slack target
|
|
||||||
// types.
|
|
||||||
type SlackTargetConfig struct {
|
|
||||||
WebhookURL string `json:"webhookUrl"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// slackTarget delivers events to Slack incoming webhooks. It
|
|
||||||
// formats the event into a Slack message and posts it as
|
|
||||||
// JSON. It shares the retry core with the HTTP target: a
|
|
||||||
// MaxRetries of 0 stays single-attempt fire-and-forget
|
|
||||||
// (preserving existing Slack targets), while a positive
|
|
||||||
// MaxRetries adds backoff and circuit breaking.
|
|
||||||
type slackTarget struct {
|
|
||||||
*httpCore
|
|
||||||
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deliver implements Target.
|
|
||||||
func (t *slackTarget) Deliver(
|
|
||||||
ctx context.Context,
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
task *Task,
|
|
||||||
sched Scheduler,
|
|
||||||
) {
|
|
||||||
cfg, err := parseSlackConfig(d.Target.Config)
|
|
||||||
if err != nil {
|
|
||||||
t.eng.log.Error(
|
|
||||||
"invalid Slack target config",
|
|
||||||
"target_id", d.TargetID,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.failConfig(webhookDB, d, err)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := FormatSlackMessage(&d.Event)
|
|
||||||
|
|
||||||
payload, err := json.Marshal(
|
|
||||||
map[string]string{"text": msg},
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.eng.log.Error(
|
|
||||||
"failed to marshal Slack payload",
|
|
||||||
"target_id", d.TargetID,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.failConfig(webhookDB, d, err)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
attempt := func() attemptResult {
|
|
||||||
return t.attempt(ctx, cfg, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.deliver(
|
|
||||||
webhookDB, d, task, sched,
|
|
||||||
d.Target.MaxRetries, attempt,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// failConfig records a first-attempt failure for a delivery
|
|
||||||
// that could not be prepared (bad config or unmarshalable
|
|
||||||
// payload) and marks it failed.
|
|
||||||
func (t *slackTarget) failConfig(
|
|
||||||
webhookDB *gorm.DB,
|
|
||||||
d *database.Delivery,
|
|
||||||
err error,
|
|
||||||
) {
|
|
||||||
t.eng.recordResult(
|
|
||||||
webhookDB, d, 1,
|
|
||||||
false, 0, "", err.Error(), 0,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.eng.updateDeliveryStatus(
|
|
||||||
webhookDB, d, database.DeliveryStatusFailed,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// attempt performs a single Slack POST and derives its
|
|
||||||
// outcome, preserving the engine's original semantics: a
|
|
||||||
// non-2xx response records an "HTTP <code>" error string and
|
|
||||||
// a transport error records a "sending request" error.
|
|
||||||
func (t *slackTarget) attempt(
|
|
||||||
ctx context.Context,
|
|
||||||
cfg *SlackTargetConfig,
|
|
||||||
payload []byte,
|
|
||||||
) attemptResult {
|
|
||||||
start := time.Now()
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(
|
|
||||||
ctx,
|
|
||||||
http.MethodPost,
|
|
||||||
cfg.WebhookURL,
|
|
||||||
bytes.NewReader(payload),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return attemptResult{
|
|
||||||
success: false,
|
|
||||||
errMsg: err.Error(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
req.Header.Set("User-Agent", "webhooker/1.0")
|
|
||||||
|
|
||||||
resp, doErr := executeHTTPRequest(t.client, req)
|
|
||||||
durationMs := time.Since(start).Milliseconds()
|
|
||||||
|
|
||||||
if doErr != nil {
|
|
||||||
return attemptResult{
|
|
||||||
success: false,
|
|
||||||
duration: durationMs,
|
|
||||||
errMsg: fmt.Errorf(
|
|
||||||
"sending request: %w", doErr,
|
|
||||||
).Error(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() { _ = resp.Body.Close() }()
|
|
||||||
|
|
||||||
return t.readSlackResponse(resp, durationMs)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *slackTarget) readSlackResponse(
|
|
||||||
resp *http.Response,
|
|
||||||
durationMs int64,
|
|
||||||
) attemptResult {
|
|
||||||
body, readErr := io.ReadAll(
|
|
||||||
io.LimitReader(resp.Body, maxBodyLog),
|
|
||||||
)
|
|
||||||
if readErr != nil {
|
|
||||||
t.eng.log.Error(
|
|
||||||
"failed to read Slack response body",
|
|
||||||
"error", readErr,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
success := resp.StatusCode >= httpSuccessMin &&
|
|
||||||
resp.StatusCode < httpSuccessMax
|
|
||||||
|
|
||||||
errMsg := ""
|
|
||||||
if !success {
|
|
||||||
errMsg = fmt.Sprintf("HTTP %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return attemptResult{
|
|
||||||
statusCode: resp.StatusCode,
|
|
||||||
respBody: string(body),
|
|
||||||
duration: durationMs,
|
|
||||||
success: success,
|
|
||||||
errMsg: errMsg,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseSlackConfig(
|
|
||||||
configJSON string,
|
|
||||||
) (*SlackTargetConfig, error) {
|
|
||||||
if configJSON == "" {
|
|
||||||
return nil, errEmptyTargetConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
var cfg SlackTargetConfig
|
|
||||||
|
|
||||||
err := json.Unmarshal(
|
|
||||||
[]byte(configJSON), &cfg,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"parsing config JSON: %w", err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.WebhookURL == "" {
|
|
||||||
return nil, errMissingWebhookURL
|
|
||||||
}
|
|
||||||
|
|
||||||
return &cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// FormatSlackMessage builds a Slack-compatible message
|
|
||||||
// string from a webhook event.
|
|
||||||
func FormatSlackMessage(
|
|
||||||
event *database.Event,
|
|
||||||
) string {
|
|
||||||
var b strings.Builder
|
|
||||||
|
|
||||||
b.WriteString("*Webhook Event Received*\n")
|
|
||||||
|
|
||||||
fmt.Fprintf(
|
|
||||||
&b, "*Method:* `%s`\n", event.Method,
|
|
||||||
)
|
|
||||||
|
|
||||||
fmt.Fprintf(
|
|
||||||
&b,
|
|
||||||
"*Content-Type:* `%s`\n",
|
|
||||||
event.ContentType,
|
|
||||||
)
|
|
||||||
|
|
||||||
fmt.Fprintf(
|
|
||||||
&b,
|
|
||||||
"*Timestamp:* `%s`\n",
|
|
||||||
event.CreatedAt.UTC().Format(time.RFC3339),
|
|
||||||
)
|
|
||||||
|
|
||||||
fmt.Fprintf(
|
|
||||||
&b,
|
|
||||||
"*Body Size:* %d bytes\n",
|
|
||||||
len(event.Body),
|
|
||||||
)
|
|
||||||
|
|
||||||
if event.Body == "" {
|
|
||||||
b.WriteString("\n_(empty body)_\n")
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
if formatted := formatJSONBody(event.Body); formatted != "" {
|
|
||||||
b.WriteString(formatted)
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
formatRawBody(&b, event.Body)
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatJSONBody(body string) string {
|
|
||||||
var parsed json.RawMessage
|
|
||||||
if json.Unmarshal([]byte(body), &parsed) != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var pretty bytes.Buffer
|
|
||||||
if json.Indent(&pretty, parsed, "", " ") != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
|
|
||||||
b.WriteString("\n```\n")
|
|
||||||
|
|
||||||
prettyStr := pretty.String()
|
|
||||||
|
|
||||||
const maxPayloadDisplay = 3500
|
|
||||||
if len(prettyStr) > maxPayloadDisplay {
|
|
||||||
b.WriteString(prettyStr[:maxPayloadDisplay])
|
|
||||||
b.WriteString("\n... (truncated)")
|
|
||||||
} else {
|
|
||||||
b.WriteString(prettyStr)
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString("\n```\n")
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatRawBody(b *strings.Builder, body string) {
|
|
||||||
b.WriteString("\n```\n")
|
|
||||||
|
|
||||||
const maxRawDisplay = 3500
|
|
||||||
if len(body) > maxRawDisplay {
|
|
||||||
b.WriteString(body[:maxRawDisplay])
|
|
||||||
b.WriteString("\n... (truncated)")
|
|
||||||
} else {
|
|
||||||
b.WriteString(body)
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString("\n```\n")
|
|
||||||
}
|
|
||||||
@@ -12,13 +12,3 @@ func (s *Handlers) RenderTemplateForTest(
|
|||||||
) {
|
) {
|
||||||
s.renderTemplate(w, r, pageTemplate, data)
|
s.renderTemplate(w, r, pageTemplate, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BuildSlackTargetConfigForTest exposes buildSlackTargetConfig
|
|
||||||
// for use in the handlers_test package.
|
|
||||||
func (s *Handlers) BuildSlackTargetConfigForTest(
|
|
||||||
w http.ResponseWriter,
|
|
||||||
r *http.Request,
|
|
||||||
targetURL string,
|
|
||||||
) (string, error) {
|
|
||||||
return s.buildSlackTargetConfig(w, r, targetURL)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -116,52 +116,6 @@ func TestHandleIndex_Authenticated(t *testing.T) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBuildSlackTargetConfig_AcceptsPublicURL(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var h *handlers.Handlers
|
|
||||||
|
|
||||||
app := newTestApp(t, &h)
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
t.Cleanup(app.RequireStop)
|
|
||||||
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(), http.MethodPost, "/", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
cfg, err := h.BuildSlackTargetConfigForTest(
|
|
||||||
w, req, "http://93.184.216.34/services/T00/B00/xxx",
|
|
||||||
)
|
|
||||||
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, http.StatusOK, w.Code)
|
|
||||||
assert.Contains(t, cfg, "webhookUrl")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBuildSlackTargetConfig_RejectsReservedURL(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var h *handlers.Handlers
|
|
||||||
|
|
||||||
app := newTestApp(t, &h)
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
t.Cleanup(app.RequireStop)
|
|
||||||
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(), http.MethodPost, "/", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
cfg, err := h.BuildSlackTargetConfigForTest(
|
|
||||||
w, req, "http://169.254.169.254/latest/meta-data/",
|
|
||||||
)
|
|
||||||
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.Empty(t, cfg)
|
|
||||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRenderTemplate(t *testing.T) {
|
func TestRenderTemplate(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -17,13 +17,11 @@ func (h *Handlers) HandleProfile() http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get session. RequireAuth middleware guarantees an
|
// Get session
|
||||||
// authenticated session before this handler runs, so we
|
|
||||||
// only need to guard against an unexpected retrieval error.
|
|
||||||
sess, err := h.session.Get(r)
|
sess, err := h.session.Get(r)
|
||||||
if err != nil {
|
if err != nil || !h.session.IsAuthenticated(sess) {
|
||||||
h.log.Error("failed to get session", "error", err)
|
// Redirect to login if not authenticated
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Redirect(w, r, "/pages/login", http.StatusSeeOther)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,159 +0,0 @@
|
|||||||
package handlers_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"sneak.berlin/go/webhooker/internal/config"
|
|
||||||
"sneak.berlin/go/webhooker/internal/handlers"
|
|
||||||
"sneak.berlin/go/webhooker/internal/logger"
|
|
||||||
"sneak.berlin/go/webhooker/internal/middleware"
|
|
||||||
"sneak.berlin/go/webhooker/internal/session"
|
|
||||||
)
|
|
||||||
|
|
||||||
// authenticatedCookies creates an authenticated session for the given
|
|
||||||
// user and returns the resulting cookies for use on a later request.
|
|
||||||
func authenticatedCookies(
|
|
||||||
t *testing.T,
|
|
||||||
sess *session.Session,
|
|
||||||
userID, username string,
|
|
||||||
) []*http.Cookie {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
setupReq := httptest.NewRequestWithContext(
|
|
||||||
context.Background(), http.MethodGet, "/setup", nil,
|
|
||||||
)
|
|
||||||
setupW := httptest.NewRecorder()
|
|
||||||
|
|
||||||
s, err := sess.Get(setupReq)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
sess.SetUser(s, userID, username)
|
|
||||||
require.NoError(t, sess.Save(setupReq, setupW, s))
|
|
||||||
|
|
||||||
cookies := setupW.Result().Cookies()
|
|
||||||
require.NotEmpty(t, cookies, "session cookie should be set")
|
|
||||||
|
|
||||||
return cookies
|
|
||||||
}
|
|
||||||
|
|
||||||
// profileRequest builds a GET request for the given profile username,
|
|
||||||
// attaching the supplied cookies and the chi URL parameter that the
|
|
||||||
// handler reads via chi.URLParam.
|
|
||||||
func profileRequest(
|
|
||||||
username string,
|
|
||||||
cookies []*http.Cookie,
|
|
||||||
) *http.Request {
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(), http.MethodGet, "/user/"+username, nil,
|
|
||||||
)
|
|
||||||
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
rctx := chi.NewRouteContext()
|
|
||||||
rctx.URLParams.Add("username", username)
|
|
||||||
|
|
||||||
return req.WithContext(
|
|
||||||
context.WithValue(req.Context(), chi.RouteCtxKey, rctx),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleProfile_OwnProfile_OK(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var h *handlers.Handlers
|
|
||||||
|
|
||||||
var sess *session.Session
|
|
||||||
|
|
||||||
app := newTestApp(t, &h, &sess)
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
t.Cleanup(app.RequireStop)
|
|
||||||
|
|
||||||
cookies := authenticatedCookies(t, sess, "test-user-id", "testuser")
|
|
||||||
|
|
||||||
req := profileRequest("testuser", cookies)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
h.HandleProfile().ServeHTTP(w, req)
|
|
||||||
|
|
||||||
assert.Equal(t, http.StatusOK, w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleProfile_OtherProfile_Forbidden(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var h *handlers.Handlers
|
|
||||||
|
|
||||||
var sess *session.Session
|
|
||||||
|
|
||||||
app := newTestApp(t, &h, &sess)
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
t.Cleanup(app.RequireStop)
|
|
||||||
|
|
||||||
cookies := authenticatedCookies(t, sess, "test-user-id", "testuser")
|
|
||||||
|
|
||||||
req := profileRequest("otheruser", cookies)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
h.HandleProfile().ServeHTTP(w, req)
|
|
||||||
|
|
||||||
assert.Equal(t, http.StatusForbidden, w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestUserRoute_Unauthenticated_RedirectedByMiddleware exercises the
|
|
||||||
// /user/{username} route group's middleware chain (CSRF then
|
|
||||||
// RequireAuth, matching setupUserRoutes) and proves that an
|
|
||||||
// unauthenticated request is redirected to /pages/login at the
|
|
||||||
// middleware layer, never reaching the endpoint handler.
|
|
||||||
func TestUserRoute_Unauthenticated_RedirectedByMiddleware(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var log *logger.Logger
|
|
||||||
|
|
||||||
var cfg *config.Config
|
|
||||||
|
|
||||||
var sess *session.Session
|
|
||||||
|
|
||||||
app := newTestApp(t, &log, &cfg, &sess)
|
|
||||||
app.RequireStart()
|
|
||||||
|
|
||||||
t.Cleanup(app.RequireStop)
|
|
||||||
|
|
||||||
mw := middleware.NewForTest(log.Get(), cfg, sess)
|
|
||||||
|
|
||||||
var handlerReached bool
|
|
||||||
|
|
||||||
router := chi.NewRouter()
|
|
||||||
router.Route("/user/{username}", func(r chi.Router) {
|
|
||||||
r.Use(mw.CSRF())
|
|
||||||
r.Use(mw.RequireAuth())
|
|
||||||
r.Get("/", func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
handlerReached = true
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(), http.MethodGet, "/user/testuser", nil,
|
|
||||||
)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
router.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
assert.False(
|
|
||||||
t, handlerReached,
|
|
||||||
"handler must not be reached for unauthenticated request",
|
|
||||||
)
|
|
||||||
assert.Equal(t, http.StatusSeeOther, w.Code)
|
|
||||||
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
|
|
||||||
}
|
|
||||||
@@ -902,7 +902,7 @@ func (h *Handlers) buildTargetConfig(
|
|||||||
case database.TargetTypeHTTP:
|
case database.TargetTypeHTTP:
|
||||||
return h.buildHTTPTargetConfig(w, r, targetURL)
|
return h.buildHTTPTargetConfig(w, r, targetURL)
|
||||||
case database.TargetTypeSlack:
|
case database.TargetTypeSlack:
|
||||||
return h.buildSlackTargetConfig(w, r, targetURL)
|
return h.buildSlackTargetConfig(w, targetURL)
|
||||||
case database.TargetTypeDatabase, database.TargetTypeLog:
|
case database.TargetTypeDatabase, database.TargetTypeLog:
|
||||||
return "", nil
|
return "", nil
|
||||||
default:
|
default:
|
||||||
@@ -967,7 +967,6 @@ func (h *Handlers) buildHTTPTargetConfig(
|
|||||||
// buildSlackTargetConfig builds config JSON for a Slack target.
|
// buildSlackTargetConfig builds config JSON for a Slack target.
|
||||||
func (h *Handlers) buildSlackTargetConfig(
|
func (h *Handlers) buildSlackTargetConfig(
|
||||||
w http.ResponseWriter,
|
w http.ResponseWriter,
|
||||||
r *http.Request,
|
|
||||||
targetURL string,
|
targetURL string,
|
||||||
) (string, error) {
|
) (string, error) {
|
||||||
if targetURL == "" {
|
if targetURL == "" {
|
||||||
@@ -980,24 +979,6 @@ func (h *Handlers) buildSlackTargetConfig(
|
|||||||
return "", errMissingURL
|
return "", errMissingURL
|
||||||
}
|
}
|
||||||
|
|
||||||
err := delivery.ValidateTargetURL(
|
|
||||||
r.Context(), targetURL,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
h.log.Warn(
|
|
||||||
"target URL blocked by SSRF protection",
|
|
||||||
"url", targetURL,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
http.Error(
|
|
||||||
w,
|
|
||||||
"Invalid target URL: "+err.Error(),
|
|
||||||
http.StatusBadRequest,
|
|
||||||
)
|
|
||||||
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := map[string]any{"webhookUrl": targetURL}
|
cfg := map[string]any{"webhookUrl": targetURL}
|
||||||
|
|
||||||
configBytes, err := json.Marshal(cfg)
|
configBytes, err := json.Marshal(cfg)
|
||||||
|
|||||||
@@ -329,7 +329,6 @@ func (h *Handlers) buildDeliveryTasks(
|
|||||||
DeliveryID: dlv.ID,
|
DeliveryID: dlv.ID,
|
||||||
EventID: event.ID,
|
EventID: event.ID,
|
||||||
WebhookID: entrypoint.WebhookID,
|
WebhookID: entrypoint.WebhookID,
|
||||||
EntrypointID: entrypoint.ID,
|
|
||||||
TargetID: targets[i].ID,
|
TargetID: targets[i].ID,
|
||||||
TargetName: targets[i].Name,
|
TargetName: targets[i].Name,
|
||||||
TargetType: targets[i].Type,
|
TargetType: targets[i].Type,
|
||||||
|
|||||||
@@ -265,26 +265,6 @@ func (s *Middleware) SecurityHeaders() func(http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NoCache returns middleware that instructs browsers and
|
|
||||||
// intermediary proxies not to cache the response. It sets
|
|
||||||
// Cache-Control: no-store and Pragma: no-cache (the latter for
|
|
||||||
// older HTTP/1.0 intermediaries). Apply it to authenticated pages
|
|
||||||
// so webhook configuration and captured event data are not stored
|
|
||||||
// by caches.
|
|
||||||
func (s *Middleware) NoCache() func(http.Handler) http.Handler {
|
|
||||||
return func(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(
|
|
||||||
w http.ResponseWriter,
|
|
||||||
r *http.Request,
|
|
||||||
) {
|
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
|
||||||
w.Header().Set("Pragma", "no-cache")
|
|
||||||
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MaxBodySize returns middleware that limits the request body size
|
// MaxBodySize returns middleware that limits the request body size
|
||||||
// for POST requests. If the body exceeds the given limit in
|
// for POST requests. If the body exceeds the given limit in
|
||||||
// bytes, the server returns 413 Request Entity Too Large. This
|
// bytes, the server returns 413 Request Entity Too Large. This
|
||||||
|
|||||||
@@ -387,45 +387,6 @@ func TestRequireAuth_UnauthenticatedSession_RedirectsToLogin(
|
|||||||
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
|
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- NoCache Middleware Tests ---
|
|
||||||
|
|
||||||
func TestNoCache_SetsHeaders(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
m, _ := testMiddleware(t, config.EnvironmentDev)
|
|
||||||
|
|
||||||
var called bool
|
|
||||||
|
|
||||||
handler := m.NoCache()(http.HandlerFunc(
|
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
called = true
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
},
|
|
||||||
))
|
|
||||||
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(),
|
|
||||||
http.MethodGet, "/sources", nil,
|
|
||||||
)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
|
|
||||||
handler.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
assert.True(
|
|
||||||
t, called,
|
|
||||||
"NoCache middleware should call the next handler",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t, "no-store",
|
|
||||||
w.Header().Get("Cache-Control"),
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t, "no-cache",
|
|
||||||
w.Header().Get("Pragma"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Helper Tests ---
|
// --- Helper Tests ---
|
||||||
|
|
||||||
func TestIpFromHostPort(t *testing.T) {
|
func TestIpFromHostPort(t *testing.T) {
|
||||||
|
|||||||
@@ -14,11 +14,6 @@ const (
|
|||||||
|
|
||||||
// loginRateInterval is the time window for the rate limit.
|
// loginRateInterval is the time window for the rate limit.
|
||||||
loginRateInterval = 1 * time.Minute
|
loginRateInterval = 1 * time.Minute
|
||||||
|
|
||||||
// receiverRateInterval is the time window for the webhook
|
|
||||||
// receiver rate limit. The configured limit is expressed in
|
|
||||||
// requests per minute.
|
|
||||||
receiverRateInterval = 1 * time.Minute
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// LoginRateLimit returns middleware that enforces per-IP rate
|
// LoginRateLimit returns middleware that enforces per-IP rate
|
||||||
@@ -67,37 +62,3 @@ func (m *Middleware) LoginRateLimit() func(http.Handler) http.Handler {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReceiverRateLimit returns middleware that rate-limits the
|
|
||||||
// public webhook receiver endpoint per client IP per request
|
|
||||||
// path (the path contains the entrypoint UUID, so each sender
|
|
||||||
// is limited per entrypoint without affecting other senders or
|
|
||||||
// other entrypoints). The limit is Config.ReceiverRateLimit
|
|
||||||
// requests per minute. Requests over the limit receive a 429;
|
|
||||||
// httprate adds the Retry-After header (RFC 6585). IP
|
|
||||||
// extraction honours X-Forwarded-For, X-Real-IP, and
|
|
||||||
// True-Client-IP headers for reverse-proxy setups.
|
|
||||||
func (m *Middleware) ReceiverRateLimit() func(http.Handler) http.Handler {
|
|
||||||
return httprate.Limit(
|
|
||||||
m.params.Config.ReceiverRateLimit,
|
|
||||||
receiverRateInterval,
|
|
||||||
httprate.WithKeyFuncs(
|
|
||||||
httprate.KeyByRealIP,
|
|
||||||
httprate.KeyByEndpoint,
|
|
||||||
),
|
|
||||||
httprate.WithLimitHandler(http.HandlerFunc(
|
|
||||||
func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
m.log.Warn(
|
|
||||||
"webhook receiver rate limit exceeded",
|
|
||||||
"path", r.URL.Path,
|
|
||||||
)
|
|
||||||
http.Error(
|
|
||||||
w,
|
|
||||||
"Too many requests. "+
|
|
||||||
"Please slow down.",
|
|
||||||
http.StatusTooManyRequests,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,10 +2,8 @@ package middleware_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -147,94 +145,3 @@ func TestLoginRateLimit_IndependentPerIP(t *testing.T) {
|
|||||||
"different IP should not be affected",
|
"different IP should not be affected",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// receiverLimitedHandler builds a ReceiverRateLimit-wrapped
|
|
||||||
// handler with the given per-minute limit.
|
|
||||||
func receiverLimitedHandler(
|
|
||||||
t *testing.T, limit int,
|
|
||||||
) http.Handler {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
log := slog.New(slog.NewTextHandler(
|
|
||||||
os.Stderr,
|
|
||||||
&slog.HandlerOptions{Level: slog.LevelDebug},
|
|
||||||
))
|
|
||||||
|
|
||||||
m := middleware.NewForTest(
|
|
||||||
log,
|
|
||||||
&config.Config{ReceiverRateLimit: limit},
|
|
||||||
nil,
|
|
||||||
)
|
|
||||||
|
|
||||||
return m.ReceiverRateLimit()(http.HandlerFunc(
|
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
// receiverPost sends one POST to the handler from the given IP
|
|
||||||
// and path and returns the recorder.
|
|
||||||
func receiverPost(
|
|
||||||
handler http.Handler, ip, path string,
|
|
||||||
) *httptest.ResponseRecorder {
|
|
||||||
req := httptest.NewRequestWithContext(
|
|
||||||
context.Background(),
|
|
||||||
http.MethodPost, path, nil,
|
|
||||||
)
|
|
||||||
req.RemoteAddr = ip
|
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
handler.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
return w
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReceiverRateLimit_LimitsPerIPAndPath(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const limit = 3
|
|
||||||
|
|
||||||
handler := receiverLimitedHandler(t, limit)
|
|
||||||
|
|
||||||
// The first limit requests from one IP to one entrypoint
|
|
||||||
// pass.
|
|
||||||
for i := range limit {
|
|
||||||
w := receiverPost(
|
|
||||||
handler, "9.9.9.9:1234", "/webhook/uuid-a",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t, http.StatusOK, w.Code,
|
|
||||||
"request %d should pass", i,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The next request over the limit is rejected with a 429
|
|
||||||
// carrying a Retry-After header.
|
|
||||||
w := receiverPost(
|
|
||||||
handler, "9.9.9.9:1234", "/webhook/uuid-a",
|
|
||||||
)
|
|
||||||
assert.Equal(t, http.StatusTooManyRequests, w.Code)
|
|
||||||
assert.NotEmpty(
|
|
||||||
t, w.Header().Get("Retry-After"),
|
|
||||||
"429 must carry a Retry-After header",
|
|
||||||
)
|
|
||||||
|
|
||||||
// The same IP is not limited on a different entrypoint.
|
|
||||||
w = receiverPost(
|
|
||||||
handler, "9.9.9.9:1234", "/webhook/uuid-b",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t, http.StatusOK, w.Code,
|
|
||||||
"a different entrypoint must not be affected",
|
|
||||||
)
|
|
||||||
|
|
||||||
// A different IP is not limited on the same entrypoint.
|
|
||||||
w = receiverPost(
|
|
||||||
handler, "8.8.8.8:1234", "/webhook/uuid-a",
|
|
||||||
)
|
|
||||||
assert.Equal(
|
|
||||||
t, http.StatusOK, w.Code,
|
|
||||||
"a different client IP must not be affected",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -13,11 +13,8 @@ const (
|
|||||||
httpReadTimeout = 10 * time.Second
|
httpReadTimeout = 10 * time.Second
|
||||||
|
|
||||||
// httpWriteTimeout is the maximum duration before timing out
|
// httpWriteTimeout is the maximum duration before timing out
|
||||||
// writes of the response. It must stay above the router's
|
// writes of the response.
|
||||||
// requestTimeout (60s, in routes.go) so the middleware timeout
|
httpWriteTimeout = 10 * time.Second
|
||||||
// fires first and returns a clean 503, rather than the transport
|
|
||||||
// cutting the connection at the socket write deadline.
|
|
||||||
httpWriteTimeout = 65 * time.Second
|
|
||||||
|
|
||||||
// httpMaxHeaderBytes is the maximum number of bytes the
|
// httpMaxHeaderBytes is the maximum number of bytes the
|
||||||
// server will read parsing the request headers.
|
// server will read parsing the request headers.
|
||||||
|
|||||||
@@ -91,7 +91,6 @@ func (s *Server) setupRoutes() {
|
|||||||
func (s *Server) setupPageRoutes() {
|
func (s *Server) setupPageRoutes() {
|
||||||
s.router.Route("/pages", func(r chi.Router) {
|
s.router.Route("/pages", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.NoCache())
|
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
||||||
|
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
@@ -107,8 +106,6 @@ func (s *Server) setupPageRoutes() {
|
|||||||
func (s *Server) setupUserRoutes() {
|
func (s *Server) setupUserRoutes() {
|
||||||
s.router.Route("/user/{username}", func(r chi.Router) {
|
s.router.Route("/user/{username}", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.NoCache())
|
|
||||||
r.Use(s.mw.RequireAuth())
|
|
||||||
r.Get("/", s.h.HandleProfile())
|
r.Get("/", s.h.HandleProfile())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -116,7 +113,6 @@ func (s *Server) setupUserRoutes() {
|
|||||||
func (s *Server) setupSourceRoutes() {
|
func (s *Server) setupSourceRoutes() {
|
||||||
s.router.Route("/sources", func(r chi.Router) {
|
s.router.Route("/sources", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.NoCache())
|
|
||||||
r.Use(s.mw.RequireAuth())
|
r.Use(s.mw.RequireAuth())
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
||||||
r.Get("/", s.h.HandleSourceList())
|
r.Get("/", s.h.HandleSourceList())
|
||||||
@@ -126,7 +122,6 @@ func (s *Server) setupSourceRoutes() {
|
|||||||
|
|
||||||
s.router.Route("/source/{sourceID}", func(r chi.Router) {
|
s.router.Route("/source/{sourceID}", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.NoCache())
|
|
||||||
r.Use(s.mw.RequireAuth())
|
r.Use(s.mw.RequireAuth())
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
||||||
r.Get("/", s.h.HandleSourceDetail())
|
r.Get("/", s.h.HandleSourceDetail())
|
||||||
@@ -159,7 +154,7 @@ func (s *Server) setupSourceRoutes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) setupWebhookRoutes() {
|
func (s *Server) setupWebhookRoutes() {
|
||||||
s.router.With(s.mw.ReceiverRateLimit()).HandleFunc(
|
s.router.HandleFunc(
|
||||||
"/webhook/{uuid}",
|
"/webhook/{uuid}",
|
||||||
s.h.HandleWebhook(),
|
s.h.HandleWebhook(),
|
||||||
)
|
)
|
||||||
|
|||||||
121
script/bootstrap
121
script/bootstrap
@@ -1,121 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/bootstrap: install all dependencies needed to build and develop
|
|
||||||
# this repo. Idempotent: every install is guarded by a check so already
|
|
||||||
# installed tools are skipped. Base tooling comes from nix, apt, brew,
|
|
||||||
# or apk (detected in that order); assumes NOTHING is present (not git,
|
|
||||||
# make, or go). golangci-lint is packaged in nix, brew, and apk; on apt
|
|
||||||
# it is installed from a hash-verified GitHub release archive (never
|
|
||||||
# curl | sh).
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
# Pinned versions, 2026-07-07. Never "latest"; exact versions only.
|
|
||||||
GOLANGCI_LINT_VERSION="2.11.3"
|
|
||||||
# sha256 of golangci-lint-2.11.3-linux-<arch>.tar.gz release archives
|
|
||||||
GOLANGCI_LINT_SHA256_AMD64="87bb8cddbcc825d5778b64e8a91b46c0526b247f4e2f2904dea74ec7450475d1"
|
|
||||||
GOLANGCI_LINT_SHA256_ARM64="ee3d95f301359e7d578e6d99c8ad5aeadbabc5a13009a30b2b0df11c8058afe9"
|
|
||||||
|
|
||||||
PKGMGR=""
|
|
||||||
SUDO=""
|
|
||||||
|
|
||||||
detect_pkgmgr() {
|
|
||||||
[ -n "$PKGMGR" ] && return 0
|
|
||||||
if command -v nix-env >/dev/null 2>&1; then
|
|
||||||
PKGMGR="nix"
|
|
||||||
elif command -v apt-get >/dev/null 2>&1; then
|
|
||||||
PKGMGR="apt"
|
|
||||||
elif command -v brew >/dev/null 2>&1; then
|
|
||||||
PKGMGR="brew"
|
|
||||||
elif command -v apk >/dev/null 2>&1; then
|
|
||||||
PKGMGR="apk"
|
|
||||||
else
|
|
||||||
echo "bootstrap: no supported package manager (nix, apt, brew, apk)" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
if [ "$PKGMGR" = "apt" ]; then
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
if [ "$(id -u)" != "0" ]; then
|
|
||||||
SUDO="sudo"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# pkg_install <nix-attr> <apt-pkg> <brew-formula> <apk-pkg>
|
|
||||||
pkg_install() {
|
|
||||||
detect_pkgmgr
|
|
||||||
case "$PKGMGR" in
|
|
||||||
nix) nix-env -iA "nixpkgs.$1" ;;
|
|
||||||
apt) $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y "$2" ;;
|
|
||||||
brew) brew install "$3" ;;
|
|
||||||
apk) apk add --no-cache "$4" ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
missing() {
|
|
||||||
! command -v "$1" >/dev/null 2>&1
|
|
||||||
}
|
|
||||||
|
|
||||||
# verify_sha256 <file> <expected-hash>
|
|
||||||
verify_sha256() {
|
|
||||||
if command -v sha256sum >/dev/null 2>&1; then
|
|
||||||
actual="$(sha256sum "$1" | cut -d' ' -f1)"
|
|
||||||
else
|
|
||||||
actual="$(shasum -a 256 "$1" | cut -d' ' -f1)"
|
|
||||||
fi
|
|
||||||
if [ "$actual" != "$2" ]; then
|
|
||||||
echo "bootstrap: sha256 mismatch for $1" >&2
|
|
||||||
echo " expected: $2" >&2
|
|
||||||
echo " actual: $actual" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# apt has no golangci-lint package: install a pinned release archive
|
|
||||||
# from GitHub, verified by hardcoded sha256 (never curl | sh).
|
|
||||||
install_golangci_lint_release() {
|
|
||||||
case "$(uname -m)" in
|
|
||||||
x86_64) goarch="amd64"; sha="$GOLANGCI_LINT_SHA256_AMD64" ;;
|
|
||||||
aarch64|arm64) goarch="arm64"; sha="$GOLANGCI_LINT_SHA256_ARM64" ;;
|
|
||||||
*)
|
|
||||||
echo "bootstrap: unsupported architecture $(uname -m)" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
if missing curl; then pkg_install curl curl curl curl; fi
|
|
||||||
name="golangci-lint-${GOLANGCI_LINT_VERSION}-linux-${goarch}"
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fsSL -o "$tmp/$name.tar.gz" \
|
|
||||||
"https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT_VERSION}/${name}.tar.gz"
|
|
||||||
verify_sha256 "$tmp/$name.tar.gz" "$sha"
|
|
||||||
tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
|
|
||||||
$SUDO install -m 0755 "$tmp/$name/golangci-lint" /usr/local/bin/golangci-lint
|
|
||||||
rm -rf "$tmp"
|
|
||||||
}
|
|
||||||
|
|
||||||
ensure_golangci_lint() {
|
|
||||||
if ! missing golangci-lint; then return 0; fi
|
|
||||||
detect_pkgmgr
|
|
||||||
case "$PKGMGR" in
|
|
||||||
apt) install_golangci_lint_release ;;
|
|
||||||
*) pkg_install golangci-lint golangci-lint golangci-lint golangci-lint ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
|
|
||||||
# Base tooling
|
|
||||||
if missing git; then pkg_install git git git git; fi
|
|
||||||
if missing make; then pkg_install gnumake make make make; fi
|
|
||||||
|
|
||||||
# Go toolchain and linter
|
|
||||||
if missing go; then pkg_install go golang go go; fi
|
|
||||||
ensure_golangci_lint
|
|
||||||
|
|
||||||
go mod download
|
|
||||||
|
|
||||||
echo "bootstrap complete"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
15
script/check
15
script/check
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/check: run all checks (test, lint, fmt-check). Our own
|
|
||||||
# extension to scripts-to-rule-them-all. Must not modify any files.
|
|
||||||
# Generic: usually needs no adaptation.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
"$SCRIPT_DIR/test"
|
|
||||||
"$SCRIPT_DIR/lint"
|
|
||||||
"$SCRIPT_DIR/fmt-check"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/cibuild: run the CI build. The Dockerfile runs the checks
|
|
||||||
# (make fmt-check, lint, test), so a successful build implies a green
|
|
||||||
# repo. Generic: needs no adaptation. The Gitea workflow runs this on
|
|
||||||
# push.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
docker build .
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/docker: build the Docker image tagged with the project name.
|
|
||||||
# Identical in all repos; the tag comes from script/projectname.
|
|
||||||
# Generic: needs no adaptation.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
|
||||||
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
docker build -t "$("$SCRIPT_DIR/projectname")" .
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
15
script/fmt
15
script/fmt
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/fmt: format all files (writes).
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
gofmt -s -w .
|
|
||||||
if command -v goimports >/dev/null 2>&1; then
|
|
||||||
goimports -w .
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/fmt-check: check formatting (read-only). Same scope as
|
|
||||||
# script/fmt, but fails instead of writing.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
if [ -n "$(gofmt -s -l .)" ]; then
|
|
||||||
echo "gofmt needed on:"
|
|
||||||
gofmt -s -l .
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/install-precommit: install the git pre-commit hook that runs
|
|
||||||
# script/precommit. Our own extension to scripts-to-rule-them-all.
|
|
||||||
# Generic: needs no adaptation.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
printf '#!/bin/sh\nset -e\nscript/precommit\n' > .git/hooks/pre-commit
|
|
||||||
chmod +x .git/hooks/pre-commit
|
|
||||||
echo "pre-commit hook installed: runs script/precommit"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
12
script/lint
12
script/lint
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/lint: run the linter.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
golangci-lint run --config .golangci.yml ./...
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/precommit: run by the git pre-commit hook; fails the commit if
|
|
||||||
# checks fail. Our own extension to scripts-to-rule-them-all. Go repo
|
|
||||||
# extras: go mod tidy must not change go.mod/go.sum.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
|
||||||
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
go mod tidy
|
|
||||||
git diff --exit-code -- go.mod go.sum || {
|
|
||||||
echo "precommit: go mod tidy changed go.mod/go.sum;" \
|
|
||||||
"stage the changes and retry" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
"$SCRIPT_DIR/check"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/projectname: output the name of this project. Our own
|
|
||||||
# extension to scripts-to-rule-them-all. Other scripts that need the
|
|
||||||
# name (e.g. script/docker) call this, so they can stay identical
|
|
||||||
# across all repos.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
main() {
|
|
||||||
echo "webhooker"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
14
script/setup
14
script/setup
@@ -1,14 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/setup: set up the repo for development after a fresh clone:
|
|
||||||
# installs dependencies (script/bootstrap) and the git pre-commit hook.
|
|
||||||
# Add any repo-specific initialization (db init, .env template) here.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
"$SCRIPT_DIR/bootstrap"
|
|
||||||
"$SCRIPT_DIR/install-precommit"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
12
script/test
12
script/test
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/test: run the test suite.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
go test -v -race -timeout 30s ./...
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
Reference in New Issue
Block a user