Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(server): add Gitea and Forgejo webhook endpoint (#3797)

Maxwell Burdick7c4837758935
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 0f836b330..3653035d2 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -1141,6 +1141,7 @@ Key routers:
- `/api/graph`: graph export in D3-compatible JSON format
- `/api/webhooks/github`: GitHub webhook handler with HMAC verification
- `/api/webhooks/gitlab`: GitLab webhook handler
+- `/api/webhooks/gitea`: Gitea and Forgejo webhook handler with HMAC verification
- `/api/repos/{id}/git-metadata`: per-file git metadata
- `/api/repos/{id}/hotspots`: high-churn + high-complexity files
- `/api/repos/{id}/ownership`: ownership breakdown (file/module/package granularity)
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index f7bcdf0bd..4fc99ffda 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -70,8 +70,9 @@ change touched.
Two paths enqueue sync jobs on their own, and a sync job can spend:
-- `POST /api/webhooks/github` and `POST /api/webhooks/gitlab` create a sync job
- for pushes to the registered default branch (`routers/webhooks.py`).
+- `POST /api/webhooks/github`, `POST /api/webhooks/gitlab` and
+ `POST /api/webhooks/gitea` create a sync job for pushes to the registered
+ default branch (`routers/webhooks.py`).
- The scheduler's polling fallback runs every 15 minutes in the serving
process, and enqueues a sync job for any repo whose git HEAD has moved past
its stored `last_sync_commit` (`packages/server/src/repowise/server/scheduler.py`).
@@ -183,7 +184,7 @@ a running app with a fabricated remote peer.
### 2.3 Which endpoints enforce it
-Every router under `/api` is protected except the two webhook routes. The two
+Every router under `/api` is protected except the three webhook routes. The two
probe endpoints are unprotected by design:
| Route | Credential |
@@ -191,18 +192,21 @@ probe endpoints are unprotected by design:
| `/health`, `/metrics` | none (`routers/health.py`: "these endpoints are NOT protected by API key auth") |
| `/api/webhooks/github` | GitHub's `X-Hub-Signature-256` HMAC-SHA256 header over the raw body, `sha256=` prefix required |
| `/api/webhooks/gitlab` | GitLab's `X-Gitlab-Token` shared secret |
+| `/api/webhooks/gitea` | Gitea's / Forgejo's `X-Gitea-Signature` or `X-Forgejo-Signature` HMAC-SHA256 header over the raw body, bare hex, no prefix |
| `GET /api/jobs/{job_id}/stream` | bearer, or the per-job `?token=` described in section 4; this one route cannot carry a router-level bearer dependency because an `EventSource` cannot set headers |
| everything else under `/api` | bearer |
-Counting the published document: 188 operations, 184 of which declare the
-`APIKeyHeader` security scheme and 4 of which do not, and those 4 are exactly
-the table's first three rows (the stream route declares the scheme even though
+Counting the published document: 196 operations, 191 of which declare the
+`APIKeyHeader` security scheme and 5 of which do not, and those 5 are exactly
+the table's first four rows (the stream route declares the scheme even though
it also accepts the token, which is a third reason this page exists).
Webhook behaviour when the secret is not configured mirrors the API key:
loopback callers are accepted, a non-loopback caller gets `403`; a bad signature
-is `401 {"detail": "Invalid signature"}`, a missing `sha256=` prefix is `401`,
-and a bad GitLab token is `401 {"detail": "Invalid token"}` (`routers/webhooks.py`).
+is `401 {"detail": "Invalid signature"}`, a missing `sha256=` prefix on the
+GitHub route is `401`, a *present* `sha256=` prefix on the Gitea route is `401`
+(Gitea and Forgejo send bare hex), and a bad GitLab token is
+`401 {"detail": "Invalid token"}` (`routers/webhooks.py`).
Verified by request: remote peer with no key gets the 403 and the exact detail
string.
@@ -268,7 +272,7 @@ detail endpoint returns the object, and two conventions sit on top:
| `{results, accepted, skipped, errors}` with `202` | `POST /api/workspace/sync` | One entry per workspace repo, with its own `job_id` when accepted |
| `RepoResponse` with `201` and `initial_job_id` | `POST /api/repos` with `index: true` | Registration that also enqueued a first index |
| `{ok: true}` (and `{ok: true, deleted_pages: N}` for repo deletion) | mutations with nothing else to report, e.g. conversation delete, repository delete | Acknowledgement only |
-| `{event_id, status: "accepted"}` with `200` | both webhooks | The stored event's id, not a job id |
+| `{event_id, status: "accepted"}` with `200` | all three webhooks | The stored event's id, not a job id |
| `X-Repowise-Redirected-From: <requested id>` response header | `GET /api/pages/{page_id}` and `/api/pages/lookup` | A retired page id resolved to its successor; the header names the id that was asked for (`routers/pages.py`) |
Enum vocabularies are shared deliberately and are the same four values wherever
@@ -537,7 +541,7 @@ one per router area; this table maps an area to the tag to open there.
| Knowledge map | `knowledge-map` | `routers/knowledge_map.py` |
| External systems (third-party packages) | `external-systems` | `routers/external_systems.py` |
| `CLAUDE.md` / `AGENTS.md` generation | `claude-md` | `routers/claude_md.py` |
-| GitHub and GitLab webhooks | `webhooks` | `routers/webhooks.py` |
+| GitHub, GitLab and Gitea/Forgejo webhooks | `webhooks` | `routers/webhooks.py` |
| Liveness, readiness, Prometheus metrics | `health` | `routers/health.py` |
| In-app feedback relay | `feedback` | `routers/feedback.py` |
diff --git a/docs/scale/AUTO_SYNC.md b/docs/scale/AUTO_SYNC.md
index 60c59d5bf..8314c5392 100644
--- a/docs/scale/AUTO_SYNC.md
+++ b/docs/scale/AUTO_SYNC.md
@@ -9,7 +9,8 @@ method that fits your setup; they can be combined.
| [File watcher](#2-file-watcher) | Local development, uncommitted work | No |
| [GitHub webhook](#3-github-webhook) | Teams, a shared repowise server | Yes |
| [GitLab webhook](#4-gitlab-webhook) | Teams, a shared repowise server | Yes |
-| [Polling fallback](#5-polling-fallback) | Safety net for missed webhooks | Yes |
+| [Gitea / Forgejo webhook](#5-gitea--forgejo-webhook) | Self-hosted teams | Yes |
+| [Polling fallback](#6-polling-fallback) | Safety net for missed webhooks | Yes |
Whichever you use, agents are told when the index is behind: the SessionStart
hook reports indexed commit vs `HEAD` ([HOOKS.md](../agent/HOOKS.md)), and MCP
@@ -127,13 +128,49 @@ With `REPOWISE_GITLAB_WEBHOOK_TOKEN` set, the server compares it with the
`401 Unauthorized`. Without the token, only local callers are accepted and every
other caller gets `403 Forbidden`, as with GitHub.
-Both endpoints match the payload's repository to a registered one by a
+---
+
+## 5. Gitea / Forgejo Webhook
+
+One endpoint serves both: Forgejo is a Gitea fork and still sends the
+`X-Gitea-*` headers alongside its own `X-Forgejo-*` ones.
+
+```bash
+export REPOWISE_GITEA_WEBHOOK_SECRET="your-secret-here"
+```
+
+In your repository, open **Settings > Webhooks > Add Webhook > Gitea**
+(**Forgejo** on Forgejo):
+
+1. **Target URL:** `https://your-server.example.com/api/webhooks/gitea`
+2. **HTTP Method:** `POST`
+3. **POST Content Type:** `application/json`
+4. **Secret:** the value of `REPOWISE_GITEA_WEBHOOK_SECRET`
+5. **Trigger On:** **Push Events**
+
+### Security (Gitea / Forgejo)
+
+With `REPOWISE_GITEA_WEBHOOK_SECRET` set, every request must carry a valid
+HMAC-SHA256 digest of the raw body in `X-Gitea-Signature` or
+`X-Forgejo-Signature`. Both forges send it as **bare lowercase hex with no
+`sha256=` prefix**, which is the one way their delivery differs from GitHub's;
+a prefixed value is rejected with `401 Unauthorized`, as is a mismatch.
+
+Without the secret, only local callers are accepted and every other caller gets
+`403 Forbidden`, as with GitHub and GitLab.
+
+Gitea and Forgejo also send GitHub's `X-Hub-Signature-256` for compatibility,
+so an existing hook pointed at `/api/webhooks/github` keeps working — it is
+just recorded as a GitHub event. Use this endpoint to have the delivery
+attributed to the forge that sent it, and to give it its own secret.
+
+All three endpoints match the payload's repository to a registered one by a
canonical key, so clone, ssh and web URLs of the same repository match, case
aside. Other hosts are listed in [GIT_HOSTS.md](../start/GIT_HOSTS.md).
---
-## 5. Polling Fallback
+## 6. Polling Fallback
While `repowise serve` runs, a background job polls every registered repository
every 15 minutes. New commits a webhook missed trigger an incremental update.
@@ -186,6 +223,7 @@ LLM cost. `POST /api/repos/{id}/full-resync` also regenerates every page.
|----------|---------|-------------|
| `REPOWISE_GITHUB_WEBHOOK_SECRET` | Server | HMAC secret for GitHub webhook verification |
| `REPOWISE_GITLAB_WEBHOOK_TOKEN` | Server | Token for GitLab webhook verification |
+| `REPOWISE_GITEA_WEBHOOK_SECRET` | Server | HMAC secret for Gitea / Forgejo webhook verification |
Provider API keys, the database URL and the API token are listed in
[CONFIG.md](../reference/CONFIG.md#environment-variables). Keys saved to
@@ -204,12 +242,14 @@ Provider API keys, the database URL and the API token are listed in
installed.
**Webhook returns 401**: a secret or token is set on the server but the
-request's signature did not match (or the GitHub `sha256=` prefix was missing).
-Check the value matches on both sides.
+request's signature did not match. Check the value matches on both sides, and
+the prefix: GitHub's `X-Hub-Signature-256` needs the `sha256=` prefix, while
+Gitea's and Forgejo's `X-Gitea-Signature` must not have one.
**Webhook returns 403**: no secret or token is set, and the request came from a
-non-local caller. Set `REPOWISE_GITHUB_WEBHOOK_SECRET` or
-`REPOWISE_GITLAB_WEBHOOK_TOKEN`, restart the server, and redeliver the payload.
+non-local caller. Set `REPOWISE_GITHUB_WEBHOOK_SECRET`,
+`REPOWISE_GITLAB_WEBHOOK_TOKEN` or `REPOWISE_GITEA_WEBHOOK_SECRET`, restart the
+server, and redeliver the payload.
**Update is slow**: the first update after many commits does more work.
`repowise update --index-only` skips page regeneration when you only need the
diff --git a/docs/start/GIT_HOSTS.md b/docs/start/GIT_HOSTS.md
index 13601b225..11c94f7c7 100644
--- a/docs/start/GIT_HOSTS.md
+++ b/docs/start/GIT_HOSTS.md
@@ -34,7 +34,8 @@ matching a webhook to a registered repository. This page says what works where.
| Azure DevOps (`dev.azure.com`, `ssh.dev.azure.com`, `*.visualstudio.com`) | Yes, all three URL forms as one repo | Azure Pipelines | Yes | No |
| Bitbucket Cloud | Yes | Bitbucket Pipelines | Yes | No |
| Bitbucket Data Center | With an override | Jenkins or another [listed CI](#ci-systems) | Yes | No |
-| Other git hosts (Gitea, cgit, plain ssh) | As a generic host | Any [listed CI](#ci-systems) | Yes | No |
+| Gitea / Forgejo | As a generic host | Any [listed CI](#ci-systems) | Yes | `/api/webhooks/gitea` |
+| Other git hosts (cgit, plain ssh) | As a generic host | Any [listed CI](#ci-systems) | Yes | No |
Azure DevOps Server needs an override too. Bot accounts and noreply addresses
from every host are recognised on every repository, since history can predate
diff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.py
index 33587784d..e507eb047 100644
--- a/packages/server/src/repowise/server/routers/webhooks.py
+++ b/packages/server/src/repowise/server/routers/webhooks.py
@@ -1,4 +1,4 @@
-"""/api/webhooks — GitHub and GitLab webhook handlers."""
+"""/api/webhooks — GitHub, GitLab and Gitea/Forgejo webhook handlers."""
from __future__ import annotations
@@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.forges import canonical_key
from repowise.core.persistence import crud
-from repowise.core.persistence.models import Repository
+from repowise.core.persistence.models import Repository, WebhookEvent
from repowise.server.auth import LOCAL_PRINCIPAL, Principal, get_authenticator, get_authorizer
from repowise.server.deps import auth_is_open, get_db_session
from repowise.server.schemas import WebhookResponse
@@ -31,6 +31,9 @@ router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
_GITHUB_PRINCIPAL = Principal(id="webhook:github", kind="webhook")
_GITLAB_PRINCIPAL = Principal(id="webhook:gitlab", kind="webhook")
+# One principal for Gitea and Forgejo: they share a secret and an endpoint, so
+# they are one credential here even though the event records which sent it.
+_GITEA_PRINCIPAL = Principal(id="webhook:gitea", kind="webhook")
async def _unsigned_principal(request: Request) -> Principal | None:
@@ -147,6 +150,48 @@ async def _verify_gitlab_token(request: Request, token_header: str) -> Principal
return _GITLAB_PRINCIPAL
+async def _verify_gitea_signature(
+ request: Request, body: bytes, signature_header: str
+) -> Principal:
+ """Verify a Gitea or Forgejo HMAC-SHA256 webhook signature.
+
+ Both sign the raw body with HMAC-SHA256 and send the digest as **bare
+ lowercase hex with no ``sha256=`` prefix** (``X-Gitea-Signature`` /
+ ``X-Forgejo-Signature``), which is the one way their delivery differs from
+ GitHub's. They also send GitHub's prefixed ``X-Hub-Signature-256`` for
+ compatibility, so a Gitea hook pointed at ``/api/webhooks/github`` verifies
+ there too — it is just recorded as a GitHub event. Only the native header
+ is read here; accepting the GitHub form on this route as well would mean two
+ signature grammars per endpoint and no stricter a check.
+
+ Reads REPOWISE_GITEA_WEBHOOK_SECRET per-call so env changes are always
+ picked up.
+
+ When the secret is not configured:
+ - Local callers are accepted (dev convenience).
+ - A caller with a valid bearer credential is accepted as that principal.
+ - Anyone else is rejected with 403 (fail-closed).
+ """
+ secret = os.environ.get("REPOWISE_GITEA_WEBHOOK_SECRET", "")
+ if not secret:
+ principal = await _unsigned_principal(request)
+ if principal is None:
+ raise HTTPException(
+ status_code=403,
+ detail=(
+ "Webhook secret not configured. "
+ "Set REPOWISE_GITEA_WEBHOOK_SECRET or restrict the server "
+ "to a loopback interface."
+ ),
+ )
+ return principal
+
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ if not hmac.compare_digest(expected, signature_header.strip().lower()):
+ raise HTTPException(status_code=401, detail="Invalid signature")
+ return _GITEA_PRINCIPAL
+
+
def _launch_webhook_job(request: Request, job_id: str) -> None:
"""Launch a webhook-triggered job as a background task."""
import asyncio
@@ -166,6 +211,50 @@ def _launch_webhook_job(request: Request, job_id: str) -> None:
task.add_done_callback(_on_done)
+async def _sync_on_push(
+ request: Request,
+ session: AsyncSession,
+ *,
+ event: WebhookEvent,
+ principal: Principal,
+ payload: dict,
+ repo_url: str,
+) -> None:
+ """Enqueue an incremental sync for a push to a registered repo's default branch.
+
+ Every forge route ends here. They differ in how a delivery names its
+ repository and spells its push event, never in what a push means to us, so
+ the branch check, the scope check and the job are shared: a third copy of
+ them is a third place for the scope check to be forgotten.
+
+ A push to any other branch, or to a repo that is not registered, is stored
+ as an event and does nothing else.
+ """
+ ref = payload.get("ref", "")
+ if not ref.startswith("refs/heads/"):
+ return
+ branch = ref[len("refs/heads/") :]
+ repo = await _find_repo_by_scm_url(session, repo_url)
+ if repo is None or branch != repo.default_branch:
+ return
+
+ _require_repo_in_scope(principal, repo)
+ job = await crud.upsert_generation_job(
+ session,
+ repository_id=repo.id,
+ status="pending",
+ config={
+ "mode": "sync",
+ "trigger": "webhook",
+ "before": payload.get("before", ""),
+ "after": payload.get("after", ""),
+ },
+ )
+ await crud.mark_webhook_processed(session, event.id, job_id=job.id)
+ await session.commit()
+ _launch_webhook_job(request, job.id)
+
+
@router.post("/github", response_model=WebhookResponse)
async def github_webhook(
request: Request,
@@ -202,27 +291,14 @@ async def github_webhook(
# For push events: create a sync job
if event_type == "push":
- ref = payload.get("ref", "")
- # Only sync pushes to the default branch
- if ref.startswith("refs/heads/"):
- branch = ref[len("refs/heads/") :]
- repo = await _find_repo_by_scm_url(session, repo_url)
- if repo and branch == repo.default_branch:
- _require_repo_in_scope(principal, repo)
- job = await crud.upsert_generation_job(
- session,
- repository_id=repo.id,
- status="pending",
- config={
- "mode": "sync",
- "trigger": "webhook",
- "before": payload.get("before", ""),
- "after": payload.get("after", ""),
- },
- )
- await crud.mark_webhook_processed(session, event.id, job_id=job.id)
- await session.commit()
- _launch_webhook_job(request, job.id)
+ await _sync_on_push(
+ request,
+ session,
+ event=event,
+ principal=principal,
+ payload=payload,
+ repo_url=repo_url,
+ )
return WebhookResponse(event_id=event.id)
@@ -253,27 +329,76 @@ async def gitlab_webhook(
# For push events: create a sync job
if event_type == "Push Hook":
- ref = payload.get("ref", "")
- if ref.startswith("refs/heads/"):
- branch = ref[len("refs/heads/") :]
- project_url = payload.get("project", {}).get("web_url", "")
-
- repo = await _find_repo_by_scm_url(session, project_url)
- if repo and branch == repo.default_branch:
- _require_repo_in_scope(principal, repo)
- job = await crud.upsert_generation_job(
- session,
- repository_id=repo.id,
- status="pending",
- config={
- "mode": "sync",
- "trigger": "webhook",
- "before": payload.get("before", ""),
- "after": payload.get("after", ""),
- },
- )
- await crud.mark_webhook_processed(session, event.id, job_id=job.id)
- await session.commit()
- _launch_webhook_job(request, job.id)
+ # isinstance, not `.get("project", {})`: an explicit null project would
+ # otherwise raise here, where before it only did so for a branch push.
+ project = payload.get("project")
+ repo_url = project.get("web_url", "") if isinstance(project, dict) else ""
+ await _sync_on_push(
+ request,
+ session,
+ event=event,
+ principal=principal,
+ payload=payload,
+ repo_url=repo_url,
+ )
+
+ return WebhookResponse(event_id=event.id)
+
+
[email protected]("/gitea", response_model=WebhookResponse)
+async def gitea_webhook(
+ request: Request,
+ session: AsyncSession = Depends(get_db_session),
+) -> WebhookResponse:
+ """Receive and process Gitea and Forgejo webhook events.
+
+ One endpoint serves both. Forgejo sends its own ``X-Forgejo-*`` headers
+ *and* the ``X-Gitea-*`` set beside them, so either name is read and a
+ Forgejo instance needs no separate route; the stored ``provider`` still
+ records which of the two sent the delivery.
+
+ Verifies the HMAC-SHA256 signature, stores the event, and enqueues a sync
+ job for push events on the default branch.
+ """
+ body = await request.body()
+ headers = request.headers
+ # Forgejo sends both families; its own header is the more specific, so it
+ # wins where both are present. The digest itself is identical in each.
+ sig = headers.get("X-Forgejo-Signature") or headers.get("X-Gitea-Signature", "")
+ principal = await _verify_gitea_signature(request, body, sig)
+
+ # Forgejo is a Gitea fork and still sends X-Gitea-*, so presence of the
+ # Forgejo header is what distinguishes the two.
+ provider = "forgejo" if "X-Forgejo-Event" in headers else "gitea"
+ event_type = headers.get("X-Forgejo-Event") or headers.get("X-Gitea-Event") or "unknown"
+ delivery_id = headers.get("X-Forgejo-Delivery") or headers.get("X-Gitea-Delivery", "")
+ payload = json.loads(body)
+
+ # Gitea's push payload follows GitHub's shape, clone_url included.
+ repo_url = ""
+ if "repository" in payload:
+ repo_url = payload["repository"].get("clone_url", "")
+ if not repo_url:
+ repo_url = payload["repository"].get("html_url", "")
+
+ event = await crud.store_webhook_event(
+ session,
+ provider=provider,
+ event_type=event_type,
+ payload=payload,
+ delivery_id=delivery_id,
+ )
+
+ # Gitea and Forgejo name the push event "push", as GitHub does — not
+ # GitLab's "Push Hook".
+ if event_type == "push":
+ await _sync_on_push(
+ request,
+ session,
+ event=event,
+ principal=principal,
+ payload=payload,
+ repo_url=repo_url,
+ )
return WebhookResponse(event_id=event.id)
diff --git a/tests/unit/server/test_webhooks.py b/tests/unit/server/test_webhooks.py
index 6f3019a6f..6065990c2 100644
--- a/tests/unit/server/test_webhooks.py
+++ b/tests/unit/server/test_webhooks.py
@@ -12,7 +12,7 @@ import pytest
from httpx import AsyncClient
from sqlalchemy import select
-from repowise.core.persistence.models import GenerationJob, Repository
+from repowise.core.persistence.models import GenerationJob, Repository, WebhookEvent
@pytest.mark.asyncio
@@ -123,6 +123,25 @@ async def test_gitlab_webhook_no_token_non_local_rejected(client: AsyncClient) -
{"X-Gitlab-Event": "Push Hook"},
{"project": {"web_url": "https://example.com/test-repo"}},
),
+ (
+ "/api/webhooks/gitea",
+ {
+ "X-Gitea-Event": "push",
+ "X-Gitea-Delivery": "test-delivery-sync",
+ },
+ {"repository": {"clone_url": "https://example.com/test-repo"}},
+ ),
+ (
+ "/api/webhooks/gitea",
+ # Forgejo sends both header families; the Gitea names are what a
+ # pre-Forgejo integration would have matched on.
+ {
+ "X-Forgejo-Event": "push",
+ "X-Gitea-Event": "push",
+ "X-Forgejo-Delivery": "test-delivery-sync",
+ },
+ {"repository": {"clone_url": "https://example.com/test-repo"}},
+ ),
],
)
@pytest.mark.asyncio
@@ -260,6 +279,156 @@ async def test_gitlab_webhook_token_read_per_request(client: AsyncClient) -> Non
assert resp.status_code == 200
+def _gitea_payload() -> str:
+ return json.dumps(
+ {
+ "ref": "refs/heads/main",
+ "repository": {"clone_url": "https://gitea.example.com/example/test-repo.git"},
+ }
+ )
+
+
+async def test_gitea_webhook_no_secret_local_accepted(client: AsyncClient) -> None:
+ """Without a secret, local callers (loopback) are accepted — dev convenience."""
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("REPOWISE_GITEA_WEBHOOK_SECRET", None)
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=_gitea_payload(),
+ headers={
+ "X-Gitea-Event": "push",
+ "X-Gitea-Delivery": "test-delivery-gitea",
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "accepted"
+
+
+async def test_gitea_webhook_no_secret_non_local_rejected(client: AsyncClient) -> None:
+ """Without a secret, non-local callers are rejected with 403 (fail-closed)."""
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("REPOWISE_GITEA_WEBHOOK_SECRET", None)
+ with patch("repowise.server.routers.webhooks.auth_is_open", return_value=False):
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=_gitea_payload(),
+ headers={
+ "X-Gitea-Event": "push",
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 403
+ assert "REPOWISE_GITEA_WEBHOOK_SECRET" in resp.json()["detail"]
+
+
[email protected]("header", ["X-Gitea-Signature", "X-Forgejo-Signature"])
+async def test_gitea_webhook_valid_signature(client: AsyncClient, header: str) -> None:
+ """A bare lowercase hex HMAC-SHA256 digest passes, under either header name."""
+ secret = "test-webhook-secret"
+ body = _gitea_payload()
+ digest = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
+
+ with patch.dict(os.environ, {"REPOWISE_GITEA_WEBHOOK_SECRET": secret}):
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=body,
+ headers={
+ "X-Gitea-Event": "push",
+ header: digest,
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 200
+
+
+async def test_gitea_webhook_invalid_signature(client: AsyncClient) -> None:
+ """A digest computed with the wrong secret is rejected."""
+ with patch.dict(os.environ, {"REPOWISE_GITEA_WEBHOOK_SECRET": "real-secret"}):
+ body = _gitea_payload()
+ wrong = hmac.new(b"wrong-secret", body.encode(), hashlib.sha256).hexdigest()
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=body,
+ headers={
+ "X-Gitea-Event": "push",
+ "X-Gitea-Signature": wrong,
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 401
+
+
+async def test_gitea_webhook_rejects_github_prefixed_signature(client: AsyncClient) -> None:
+ """The GitHub ``sha256=`` form is not Gitea's: this route takes bare hex only.
+
+ Gitea sends the prefixed digest too, as ``X-Hub-Signature-256``, and the
+ GitHub route reads that one. Accepting the prefix here would make the
+ endpoint take two grammars for the same secret.
+ """
+ secret = "test-webhook-secret"
+ body = _gitea_payload()
+ digest = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
+
+ with patch.dict(os.environ, {"REPOWISE_GITEA_WEBHOOK_SECRET": secret}):
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=body,
+ headers={
+ "X-Gitea-Event": "push",
+ "X-Gitea-Signature": f"sha256={digest}",
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 401
+
+
+async def test_gitea_webhook_missing_signature_rejected(client: AsyncClient) -> None:
+ """With a secret set, a delivery carrying no signature is rejected."""
+ with patch.dict(os.environ, {"REPOWISE_GITEA_WEBHOOK_SECRET": "real-secret"}):
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=_gitea_payload(),
+ headers={"X-Gitea-Event": "push", "Content-Type": "application/json"},
+ )
+ assert resp.status_code == 401
+
+
+ ("headers", "expected_provider"),
+ [
+ ({"X-Gitea-Event": "push"}, "gitea"),
+ ({"X-Gitea-Event": "push", "X-Forgejo-Event": "push"}, "forgejo"),
+ ],
+)
+async def test_gitea_webhook_records_sending_forge(
+ client: AsyncClient,
+ session_factory,
+ headers: dict[str, str],
+ expected_provider: str,
+) -> None:
+ """Forgejo identifies itself, so the event is not recorded as Gitea."""
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("REPOWISE_GITEA_WEBHOOK_SECRET", None)
+ resp = await client.post(
+ "/api/webhooks/gitea",
+ content=_gitea_payload(),
+ headers={**headers, "Content-Type": "application/json"},
+ )
+ assert resp.status_code == 200
+
+ async with session_factory() as session:
+ event = (await session.execute(select(WebhookEvent))).scalar_one()
+ assert event.provider == expected_provider
+
+
@pytest.mark.asyncio
async def test_push_webhook_does_not_match_url_prefix_substring(
client: AsyncClient,