Skip to content

feat(api): GitHub webhooks, signed, recorded once, with installations (part of #213) - #466

Merged
samuelmbabhazi merged 16 commits into
mainfrom
feat/213-github-webhooks
Nov 25, 2026
Merged

samuelmbabhazi merged 16 commits into
mainfrom
feat/213-github-webhooks

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

Part of #213 (M3.1), as ADR 0031 decides: GitHub's webhooks for an organization's App. Stacked on #465; retarget to main once #465 is merged.

What changed

  • POST /api/v1/webhooks/github/{organizationId}, the URL the App's manifest names.
    • Raw body. The body is read raw by a dedicated parser, at most 1 MiB (413 beyond), whatever its media type: the signature covers its exact bytes.
    • Signature. X-Hub-Signature-256 is checked in constant time, over those bytes, with the App's decrypted webhook secret, before anything is parsed.
    • One answer for every refusal. A wrong or missing signature, an organization without an App, a secret that no longer decrypts and a ping of another App all answer 401 github_webhook_rejected. Malformed headers or payloads answer 400.
  • AllowSignedBody(), a new route declaration: anonymous, for a route that a server calls rather than a browser. It spares only that route the Origin check of anonymous mutations, because GitHub sends no Origin. The route checks its signature itself. The guard has a test that the plain anonymous mutation still needs its Origin.
  • Deliveries recorded once (github_deliveries). Each X-GitHub-Delivery is recorded in the transaction that applies the delivery, and kept 30 days; older ones are forgotten on the way.
    • The same delivery again answers 204 and does nothing.
    • A delivery that fails is recorded nowhere, so GitHub's redelivery is processed (ADR 0031).
  • Installations (github_installations). installation events created, deleted, suspend and unsuspend keep the account, the repository selection and the suspension, for installations of the organization's own App only.
    • Each change is audited with the system as actor and the GitHub sender's login: github.installation_added, _removed, _suspended and _unsuspended.
  • push deliveries are recorded and deploy nothing yet. Turning a push into a deployment comes next. Per ADR 0031, it will check that the pushed commit is still the head of the branch.
  • New tables under RLS, TENANT_TABLES and runtime grants. SPEC 9 describes the route.

How it was tested

  • Unit tests:
    • headers: a missing or malformed signature, an event name, a delivery GUID;
    • installation events: another App, a bad account or selection, an action that changes nothing;
    • the ping's App;
    • the raw parser's route selection;
    • the guard's AllowSignedBody.
  • Integration test with PostgreSQL, the runtime role and real HMAC signatures. The App is created through feat(api): an organization's GitHub App through the manifest flow (part of #213) #465's flow with a fake GitHub.
    • Before the App exists, a delivery is refused.
    • Refused: another secret, one byte more in the body, an empty or sha1 signature, a ping of another App, and the other organization's URL.
    • A malformed delivery GUID gets 400, and a body over 1 MiB gets 413.
    • An installation is created, delivered again with the same GUID, suspended, unsuspended and deleted: the rows and the four audit events match.
    • An installation of another App is refused and not recorded.
    • A delivery 31 days old is forgotten.
  • The whole integration suite passes locally, except the known PostgreSQL 18 differences (three tests) and the two that need Docker. The route matrix and audit coverage tests include the new route.

Security considerations

  • The only anonymous write added is authenticated by the App's secret over the exact bytes, compared in constant time, before parsing. It is rate limited per IP like the API, and the body is bounded before it is read.
  • AllowSignedBody is explicit and narrow: it removes the Origin check for that route only, and a route that uses it must check a signature itself.
  • A refusal never says why. Deliveries are deduplicated by GitHub's identifier for 30 days. A replayed push will also need its commit to be the branch head before it deploys anything (next PR).
  • The fake keys in tests are put together at run time, so no scanner reads them as keys. Trivy had flagged one on feat(api): an organization's GitHub App through the manifest flow (part of #213) #465.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 23 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between c3cec1f and bf5dd5f.

Files ignored due to path filters: 3

  • apps/api/openapi.json is excluded by !apps/api/openapi.json
  • docs/generated/route-role-matrix.md is excluded by !**/generated/**, !docs/generated/**
  • packages/api-client/src/gen/openapi.ts is excluded by !**/gen/**, !packages/api-client/src/gen/**
Files selected for processing: 22

  • apps/api/prisma/migrations/20261125110000_github_webhooks/migration.sql
  • apps/api/prisma/schema.prisma
  • apps/api/src/audit-coverage.spec.ts
  • apps/api/src/bootstrap.ts
  • apps/api/src/modules/git/application/github-webhooks.ts
  • apps/api/src/modules/git/application/ports.ts
  • apps/api/src/modules/git/domain/github-webhook.spec.ts
  • apps/api/src/modules/git/domain/github-webhook.ts
  • apps/api/src/modules/git/git.module.ts
  • apps/api/src/modules/git/github-webhook-http.integration.spec.ts
  • apps/api/src/modules/git/infrastructure/prisma-github-webhook.store.ts
  • apps/api/src/modules/git/interface/github-webhook.controller.ts
  • apps/api/src/modules/identity/interface/identity.guard.spec.ts
  • apps/api/src/modules/identity/interface/identity.guard.ts
  • apps/api/src/platform/http/allow-anonymous.ts
  • apps/api/src/platform/http/body-limits.spec.ts
  • apps/api/src/platform/http/body-limits.ts
  • apps/api/src/platform/prisma/tenant-database-role.ts
  • deploy/postgres/runtime-role.sql
  • docs/PLAN.md
  • docs/SPEC.md
  • docs/adr/0031-a-github-app-per-organization.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator Author

An independent review of this PR (high effort, while CodeRabbit is rate limited) raised seven points. All seven held up, and the latest commit fixes them:

  • A signed body could be replayed under a new delivery identifier. GitHub signs the body, not X-GitHub-Delivery. The SHA-256 of each body is now recorded too, unique per organization for 30 days, so the same body under any identifier does nothing. Past 30 days, an installation event applies only when GitHub's updated_at for that installation is newer than the last change applied. An old suspension or removal replayed later therefore changes nothing; it must also be no more than five minutes ahead of the clock. The integration test replays a body under a new identifier and sends an older event; both change nothing.
  • A lost created left the installation unrecorded for good. A suspend, unsuspend or selection change for an unknown installation now records it, from the full payload GitHub sends. Tested by a suspension that arrives first.
  • installation_repositories was ignored. It now updates repository_selection and keeps the suspension, audited as github.installation_repositories_changed.
  • Cross-tenant keys. github_deliveries is keyed (organization_id, delivery_id), with (organization_id, body_sha256) unique, and github_installations (organization_id, installation_id). A row hidden by RLS in another organization can no longer block one here.
  • Duplicate OpenAPI headers. The @ApiHeader decorators are gone; the @Headers parameters document them once.
  • Delivery rows without audit events. SPEC 9 now says these rows are replay bookkeeping, like the identity replay records, and that a delivery is audited by what it changes. I did not add an audit event per push or ping, which would be one per delivery with no state change behind it.
  • ADR 0031 now says 204, says that the identifier is not signed and the body hash is recorded, and gives the newer-only rule for installation events.

Unit tests (20) and both GitHub integration files pass. pnpm gen is current.

@samuelmbabhazi
samuelmbabhazi changed the base branch from feat/213-github-app-manifest to main November 25, 2026 11:12
Signed-off-by: samuel mbabhazi <[email protected]>

# Conflicts:
#	apps/api/openapi.json
#	apps/api/prisma/schema.prisma
#	apps/api/src/modules/git/application/ports.ts
#	apps/api/src/modules/git/git.module.ts
#	apps/api/src/platform/prisma/tenant-database-role.ts
#	deploy/postgres/runtime-role.sql
#	docs/PLAN.md
#	docs/SPEC.md
@samuelmbabhazi
samuelmbabhazi merged commit fbcd8cc into main Nov 25, 2026
25 of 27 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/213-github-webhooks branch November 25, 2026 11:50
samuelmbabhazi added a commit that referenced this pull request Nov 25, 2026
…each (part of #213) (#467)

Part of #213 (M3.1), as ADR 0031 decides: the organization's App calls
GitHub as itself, and lists the repositories it can reach. This is what
choosing an application's repository needs, and what a push will use to
check the branch head. Stacked on #466; retarget to `main` once #466 is
merged.

## What changed

- **`GithubApiClient`** (`modules/git/infrastructure`):
- **The App's JWT.** RS256, signed with the App's private key; issued a
minute back for clock drift, nine minutes long.
- **Installation tokens.** Asked with the repositories and permissions a
call needs, as ADR 0031 requires (`POST
/app/installations/{id}/access_tokens`).
- **Repositories.** `GET /installation/repositories`, page by page, up
to a limit.
- **A branch head.** `GET /repos/{owner}/{repo}/branches/{branch}`, with
the branch URL-encoded; an unknown branch is `undefined`.
  - **Revoking a token.** `DELETE /installation/token`, best effort.
- Only `api.github.com`, no redirect, a 10 s timeout and answers bounded
to 2 MiB. Any failure is a 503 that does not repeat GitHub's text.
- **The answers are checked field by field** (`domain/github-api.ts`).
Repository names allow `owner/name` only, branches refuse `..`, `//` and
a leading or trailing `/`, and commits must be 40 hex characters. A page
with one bad entry is refused whole.
- **`GET …/github-app/repositories`** (`organization.read`, API tokens
allowed):
- it lists the repositories of the installations that are not suspended;
- each installation gets a token with `metadata: read` only, revoked
once read;
- at most 500 are listed, sorted by name, with `truncated` beyond that;
- without an App the list is empty, as `GET …/github-app` answers `{app:
null}`.
- **The store** decrypts the App's private key. If it no longer
decrypts, the answer is 409 `github_app_unreadable` ("connect it
again"). The store also lists the active installations.
- **Shared helpers.** The bounded reader is now shared with the manifest
client (`github-http.ts`).

## How it was tested

- Domain:
  - the JWT claims;
  - installation tokens, valid or not;
- repository pages, including a traversal in a name, a branch with `..`
or `//`, and an entry missing a field;
  - branch heads and name validation.
- Client:
- a real RSA key pair generated in the test checks the JWT's header,
claims and RS256 signature;
  - the token request's URL, headers and scoped body;
  - pagination and the limit;
  - an encoded branch, and 404 as an unknown branch;
- a 500, a redirect, an invalid entry, an oversized body or a network
error gives a 503 without GitHub's text;
  - revocation never fails the caller.
- Integration with PostgreSQL, the runtime role and a fake GitHub:
  - the list is empty before the App exists;
- with two installations, one suspended, only the active one is listed,
signed with the stored key, with metadata read only, and its token
revoked;
  - a member can read the list, an outsider gets 404;
  - no token, JWT or key reaches the answer.
- The route matrix in unit and integration tests covers the route.

## Security considerations

- Tokens are as narrow as each call: metadata read to list. Repository
contents read, for builds and head checks, comes later. Every token is
revoked as soon as it has served.
- The private key is decrypted only for the JWT, and is never logged or
returned. The JWT and tokens are `Secret`s.
- GitHub's answers are untrusted input: each entry is checked before it
reaches a caller.

---------

Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi added a commit that referenced this pull request Nov 27, 2026
## What changed

A verified GitHub push deploys its commit (#213, ADR 0031). This pull
request is stacked on #526: its base is that branch until #526 merges.

- **Webhook (`git` module):**
- A `push` to a branch is recorded with a job of the new `github-push`
pg-boss queue, in one transaction, and answered 204 at once.
- A tag, a deleted branch or a malformed field queues nothing
(`pushOf`).
- The job carries identifiers, the branch, the commit and the pusher's
login only.
- **Worker (`deployments` module):** `PushWorker` works the queue,
started by `main.ts`. It checks each payload again (`pushJob`) and hands
it to `PushDeployments`. For each Git application that follows that
branch of that repository through that installation (at most 20):
1. GitHub is asked for the branch head. Only while the pushed commit is
that head does anything happen, so a replayed or overtaken push deploys
nothing.
2. The `shipkeep.yml` there becomes the application's configuration, as
the system (`ApplicationCommands.applyRepositoryConfig`). It is audited
as `application.updated` with the commit. The application's name cannot
change, and domains are claimed as for any configuration.
3. `DeploymentCommands.deployPush` queues a deployment with the trigger
`webhook` and no actor, and its release keeps `commit_sha`.
`release.created` and `deployment.queued` are the system's, with
`commitSha` and `githubPusher`.
- In a protected environment (the default, SPEC 7) or during
maintenance, nothing deploys: `deployment.push_held`.
- When the newest release is already this commit's, nothing deploys
twice.
- **Failures:**
- A configuration that cannot deploy is audited as
`deployment.push_refused` with the error's stable code.
- While a deployment is under way, or GitHub cannot be reached, the push
is tried again a minute later for the applications left, 30 times at
most.
  - A database error fails the job, and pg-boss retries it.
- **Refactor:** `claimDomains` and the application audit take an
`Actor`, so the system can use them.
- **Docs:** SPEC (GitHub App section) and a note in ADR 0031: the
delivery is recorded with the job rather than with the deployment, so
that the webhook answers within GitHub's ten seconds.

## Why

Acceptance of #213: "A verified push webhook enqueues a deploy request
job with the commit and branch; a forged or replayed webhook is
rejected." Forged deliveries were already refused (#466). This adds the
job, the branch head check against replays, and the deployment.

## How it was tested

- **`push-deployments.integration.spec.ts`** (PostgreSQL, the real
webhook route, a fake GitHub):
- a signed push queues exactly one job with the expected payload;
GitHub's redelivery and the same body under another identifier queue
nothing; a tag and a deleted branch queue nothing;
- a protected environment: the configuration follows, `push_held`, no
deployment;
- an unprotected environment: an overtaken push deploys nothing; the
head deploys once with trigger `webhook`, a null actor and the commit;
handled again it does not deploy twice; while that deployment runs, the
next push is answered "try again", then deploys;
- invalid YAML and a renamed application are refused with their codes;
GitHub unavailable means "try again".
- **Mutation check:** without the branch head check, two of these cases
fail.
- **Unit tests:** `pushOf` (tags, deletions, zero commit, upper case,
bad ids, branch tricks) and `pushJob` (every field of the payload,
retries).
- `api` lint, typecheck and unit tests pass: 945 tests. The HTTP
pipeline test fakes the new queue.
- Full integration suite: 455 pass, plus the same environment-only
failures as on #526 (container runtime; PostgreSQL 18's 23001).

## Security considerations

- Replays deploy nothing: the delivery identifier and body are recorded
as before, and only the current branch head deploys.
- A push deploys only Git applications of the organization whose
installation, repository identifier and branch all match.
- Protected environments are never deployed by a push. Audit events
carry codes and identifiers, never configuration or GitHub text.
- No new external service, and no change to the agent or its action
list.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* GitHub push events now trigger deployments when the pushed commit is
the current branch head and the application configuration is valid.
* Configuration updates from pushes are applied automatically. Pushes to
protected environments or during maintenance update configuration
without deploying.
* Busy deployments and temporary GitHub or processing failures are
retried; pushes that cannot be deployed are recorded for review.
* **Documentation**
* Updated GitHub integration guidance to describe push-triggered
deployments, holds, and retries.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: samuel mbabhazi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants