Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(webhooks): fail-closed auth and per-request secret reading (#1408)
Akshat malik087697002133
diff --git a/docs/scale/AUTO_SYNC.md b/docs/scale/AUTO_SYNC.mdindex 6c01ade7b..fbc7aa76d 100644--- a/docs/scale/AUTO_SYNC.md+++ b/docs/scale/AUTO_SYNC.md@@ -94,7 +94,7 @@ server, which triggers an incremental update.### Prerequisites- repowise server running and reachable from the internet (or GitHub's network)-- A webhook secret (recommended for production)+- A webhook secret (**required** — unsigned requests are rejected)### Start the server@@ -132,12 +132,12 @@ Recent Deliveries). You should see a `200` response with:### Security-When `REPOWISE_GITHUB_WEBHOOK_SECRET` is set, every incoming request is-verified using HMAC-SHA256 against the `X-Hub-Signature-256` header. Requests-with invalid or missing signatures are rejected with `401 Unauthorized`.--If the secret is **not** set, signature verification is skipped (convenient for-local development, but not recommended for production).+`REPOWISE_GITHUB_WEBHOOK_SECRET` is **required**. Every incoming request must+carry a valid HMAC-SHA256 signature in the `X-Hub-Signature-256` header.+Requests with an invalid signature are rejected with `401 Unauthorized`.+Requests with **no** signature — including those sent without a secret+configured on your server — are rejected with `403 Forbidden`. There is no+unsigned mode.---@@ -275,5 +275,11 @@ Nothing to do.**Webhook returns 401** -- Check that the secret/token matches between yourgit hosting provider and the environment variable on the server.+**Webhook returns 403** -- The server received a request with no signature at+all. This usually means `REPOWISE_GITHUB_WEBHOOK_SECRET` (or+`REPOWISE_GITLAB_WEBHOOK_TOKEN`) is not set on the server. Set the environment+variable, restart the server, and re-deliver the payload from your provider's+webhook settings page. Unsigned requests are never accepted.+**Update is slow** -- If you're catching up on many commits, the first updatemay take longer. Subsequent single-commit updates are fast (~30-60s).diff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.pyindex 6eb8f8dcb..ed4192dca 100644--- a/packages/server/src/repowise/server/routers/webhooks.py+++ b/packages/server/src/repowise/server/routers/webhooks.py@@ -11,39 +11,78 @@ from fastapi import APIRouter, Depends, HTTPException, Requestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence import crud-from repowise.server.deps import get_db_session+from repowise.server.deps import auth_is_open, get_db_sessionfrom repowise.server.schemas import WebhookResponserouter = APIRouter(prefix="/api/webhooks", tags=["webhooks"])+# Note: no Depends(verify_api_key) here — webhook routes carry their own+# credential (HMAC signature / shared token) issued by the SCM provider.+# Secrets are read per-request (not cached at import) so env changes are+# picked up without a server restart.-_GITHUB_SECRET = os.environ.get("REPOWISE_GITHUB_WEBHOOK_SECRET", "")-_GITLAB_TOKEN = os.environ.get("REPOWISE_GITLAB_WEBHOOK_TOKEN", "")-def _verify_github_signature(body: bytes, signature_header: str) -> None:- """Verify GitHub HMAC-SHA256 webhook signature."""- if not _GITHUB_SECRET:- return # No secret configured — skip verification (dev mode)+def _verify_github_signature(request: Request, body: bytes, signature_header: str) -> None:+ """Verify GitHub HMAC-SHA256 webhook signature.++ Reads REPOWISE_GITHUB_WEBHOOK_SECRET per-call so env changes (e.g.+ from dotenv or test fixtures) are always picked up.++ When the secret is not configured:+ - Local callers (loopback / no network exposure) are accepted — dev+ convenience, matching the posture of ``verify_api_key`` in deps.py.+ - Non-local callers are rejected with 403 (fail-closed).+ """+ secret = os.environ.get("REPOWISE_GITHUB_WEBHOOK_SECRET", "")+ if not secret:+ if not auth_is_open(request):+ raise HTTPException(+ status_code=403,+ detail=(+ "Webhook secret not configured. "+ "Set REPOWISE_GITHUB_WEBHOOK_SECRET or restrict the server "+ "to a loopback interface."+ ),+ )+ return # local caller — dev modeif not signature_header.startswith("sha256="):raise HTTPException(status_code=401, detail="Missing signature prefix")- expected = hmac.new(- _GITHUB_SECRET.encode(),+ expected = "sha256=" + hmac.new(+ secret.encode(),body,hashlib.sha256,).hexdigest()- if not hmac.compare_digest(f"sha256={expected}", signature_header):+ if not hmac.compare_digest(expected, signature_header):raise HTTPException(status_code=401, detail="Invalid signature")-def _verify_gitlab_token(token_header: str) -> None:- """Verify GitLab webhook token."""- if not _GITLAB_TOKEN:- return # No token configured — skip verification (dev mode)+def _verify_gitlab_token(request: Request, token_header: str) -> None:+ """Verify GitLab webhook token.++ Reads REPOWISE_GITLAB_WEBHOOK_TOKEN per-call so env changes are always+ picked up.++ When the token is not configured:+ - Local callers are accepted (dev convenience).+ - Non-local callers are rejected with 403 (fail-closed).+ """+ configured = os.environ.get("REPOWISE_GITLAB_WEBHOOK_TOKEN", "")+ if not configured:+ if not auth_is_open(request):+ raise HTTPException(+ status_code=403,+ detail=(+ "Webhook token not configured. "+ "Set REPOWISE_GITLAB_WEBHOOK_TOKEN or restrict the server "+ "to a loopback interface."+ ),+ )+ return # local caller — dev mode- if not hmac.compare_digest(token_header, _GITLAB_TOKEN):+ if not hmac.compare_digest(token_header, configured):raise HTTPException(status_code=401, detail="Invalid token")@@ -78,7 +117,7 @@ async def github_webhook("""body = await request.body()sig = request.headers.get("X-Hub-Signature-256", "")- _verify_github_signature(body, sig)+ _verify_github_signature(request, body, sig)event_type = request.headers.get("X-GitHub-Event", "unknown")delivery_id = request.headers.get("X-GitHub-Delivery", "")@@ -145,7 +184,7 @@ async def gitlab_webhook(job for push events on the default branch."""token = request.headers.get("X-Gitlab-Token", "")- _verify_gitlab_token(token)+ _verify_gitlab_token(request, token)body = await request.body()payload = json.loads(body)diff --git a/tests/unit/server/test_webhooks.py b/tests/unit/server/test_webhooks.pyindex b94727601..98d00f5e8 100644--- a/tests/unit/server/test_webhooks.py+++ b/tests/unit/server/test_webhooks.py@@ -16,27 +16,97 @@ from repowise.core.persistence.models import GenerationJob, Repository@pytest.mark.asyncio-async def test_github_webhook_no_secret(client: AsyncClient) -> None:- """Without a secret configured, any payload is accepted."""+async def test_github_webhook_no_secret_local_accepted(client: AsyncClient) -> None:+ """Without a secret, local callers (loopback) are accepted — dev convenience."""payload = {"ref": "refs/heads/main","repository": {"clone_url": "https://github.com/example/test-repo.git"},}- resp = await client.post(- "/api/webhooks/github",- content=json.dumps(payload),- headers={- "X-GitHub-Event": "push",- "X-GitHub-Delivery": "test-delivery-1",- "Content-Type": "application/json",- },- )+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop("REPOWISE_GITHUB_WEBHOOK_SECRET", None)+ # auth_is_open() is True in unit tests (no API key, loopback host)+ resp = await client.post(+ "/api/webhooks/github",+ content=json.dumps(payload),+ headers={+ "X-GitHub-Event": "push",+ "X-GitHub-Delivery": "test-delivery-1",+ "Content-Type": "application/json",+ },+ )assert resp.status_code == 200data = resp.json()assert "event_id" in dataassert data["status"] == "accepted"+async def test_github_webhook_no_secret_non_local_rejected(client: AsyncClient) -> None:+ """Without a secret, non-local callers are rejected with 403 (fail-closed)."""+ payload = {+ "ref": "refs/heads/main",+ "repository": {"clone_url": "https://github.com/example/test-repo.git"},+ }+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop("REPOWISE_GITHUB_WEBHOOK_SECRET", None)+ with patch("repowise.server.routers.webhooks.auth_is_open", return_value=False):+ resp = await client.post(+ "/api/webhooks/github",+ content=json.dumps(payload),+ headers={+ "X-GitHub-Event": "push",+ "X-GitHub-Delivery": "test-delivery-1",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 403+ assert "REPOWISE_GITHUB_WEBHOOK_SECRET" in resp.json()["detail"]+++async def test_gitlab_webhook_no_token_local_accepted(client: AsyncClient) -> None:+ """Without a token, local callers are accepted — dev convenience."""+ payload = {+ "ref": "refs/heads/main",+ "project": {"web_url": "https://gitlab.com/example/test-repo"},+ }+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop("REPOWISE_GITLAB_WEBHOOK_TOKEN", None)+ resp = await client.post(+ "/api/webhooks/gitlab",+ content=json.dumps(payload),+ headers={+ "X-Gitlab-Event": "Push Hook",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "event_id" in data+++async def test_gitlab_webhook_no_token_non_local_rejected(client: AsyncClient) -> None:+ """Without a token, non-local callers are rejected with 403 (fail-closed)."""+ payload = {+ "ref": "refs/heads/main",+ "project": {"web_url": "https://gitlab.com/example/test-repo"},+ }+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop("REPOWISE_GITLAB_WEBHOOK_TOKEN", None)+ with patch("repowise.server.routers.webhooks.auth_is_open", return_value=False):+ resp = await client.post(+ "/api/webhooks/gitlab",+ content=json.dumps(payload),+ headers={+ "X-Gitlab-Event": "Push Hook",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 403+ assert "REPOWISE_GITLAB_WEBHOOK_TOKEN" in resp.json()["detail"]++@pytest.mark.parametrize(("endpoint", "headers", "repository_payload"),[@@ -101,40 +171,28 @@ async def test_push_webhook_enqueues_sync_job(@pytest.mark.asyncioasync def test_github_webhook_valid_signature(client: AsyncClient) -> None:- """With a secret configured, a valid signature passes."""+ """With a secret set in the environment, a valid signature passes."""secret = "test-webhook-secret"payload = json.dumps({"ref": "refs/heads/main", "repository": {}})sig = "sha256=" + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()- with patch.dict(os.environ, {"REPOWISE_GITHUB_WEBHOOK_SECRET": ""}):- # Patch the module-level variable- import repowise.server.routers.webhooks as wh_mod-- original_secret = wh_mod._GITHUB_SECRET- wh_mod._GITHUB_SECRET = secret- try:- resp = await client.post(- "/api/webhooks/github",- content=payload,- headers={- "X-GitHub-Event": "push",- "X-Hub-Signature-256": sig,- "Content-Type": "application/json",- },- )- assert resp.status_code == 200- finally:- wh_mod._GITHUB_SECRET = original_secret+ with patch.dict(os.environ, {"REPOWISE_GITHUB_WEBHOOK_SECRET": secret}):+ resp = await client.post(+ "/api/webhooks/github",+ content=payload,+ headers={+ "X-GitHub-Event": "push",+ "X-Hub-Signature-256": sig,+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200@pytest.mark.asyncioasync def test_github_webhook_invalid_signature(client: AsyncClient) -> None:- """With a secret configured, an invalid signature is rejected."""- import repowise.server.routers.webhooks as wh_mod-- original_secret = wh_mod._GITHUB_SECRET- wh_mod._GITHUB_SECRET = "real-secret"- try:+ """With a secret set, an invalid signature is rejected."""+ with patch.dict(os.environ, {"REPOWISE_GITHUB_WEBHOOK_SECRET": "real-secret"}):resp = await client.post("/api/webhooks/github",content=json.dumps({"ref": "refs/heads/main"}),@@ -144,39 +202,34 @@ async def test_github_webhook_invalid_signature(client: AsyncClient) -> None:"Content-Type": "application/json",},)- assert resp.status_code == 401- finally:- wh_mod._GITHUB_SECRET = original_secret+ assert resp.status_code == 401@pytest.mark.asyncio-async def test_gitlab_webhook_no_token(client: AsyncClient) -> None:- """Without a token configured, any payload is accepted."""- payload = {- "ref": "refs/heads/main",- "project": {"web_url": "https://gitlab.com/example/test-repo"},- }- resp = await client.post(- "/api/webhooks/gitlab",- content=json.dumps(payload),- headers={- "X-Gitlab-Event": "Push Hook",- "Content-Type": "application/json",- },- )+async def test_github_webhook_secret_read_per_request(client: AsyncClient) -> None:+ """Secret is read from env per request, not cached at import time."""+ secret = "per-request-secret"+ payload = json.dumps({"ref": "refs/heads/main", "repository": {}})+ sig = "sha256=" + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()++ # Set the env var after module import — must still work+ with patch.dict(os.environ, {"REPOWISE_GITHUB_WEBHOOK_SECRET": secret}):+ resp = await client.post(+ "/api/webhooks/github",+ content=payload,+ headers={+ "X-GitHub-Event": "push",+ "X-Hub-Signature-256": sig,+ "Content-Type": "application/json",+ },+ )assert resp.status_code == 200- data = resp.json()- assert "event_id" in data@pytest.mark.asyncioasync def test_gitlab_webhook_invalid_token(client: AsyncClient) -> None:- """With a token configured, wrong token is rejected."""- import repowise.server.routers.webhooks as wh_mod-- original_token = wh_mod._GITLAB_TOKEN- wh_mod._GITLAB_TOKEN = "correct-token"- try:+ """With a token set, wrong token is rejected."""+ with patch.dict(os.environ, {"REPOWISE_GITLAB_WEBHOOK_TOKEN": "correct-token"}):resp = await client.post("/api/webhooks/gitlab",content=json.dumps({"ref": "refs/heads/main"}),@@ -186,6 +239,22 @@ async def test_gitlab_webhook_invalid_token(client: AsyncClient) -> None:"Content-Type": "application/json",},)- assert resp.status_code == 401- finally:- wh_mod._GITLAB_TOKEN = original_token+ assert resp.status_code == 401+++async def test_gitlab_webhook_token_read_per_request(client: AsyncClient) -> None:+ """Token is read from env per request, not cached at import time."""+ token = "per-request-token"++ with patch.dict(os.environ, {"REPOWISE_GITLAB_WEBHOOK_TOKEN": token}):+ resp = await client.post(+ "/api/webhooks/gitlab",+ content=json.dumps({"ref": "refs/heads/main", "project": {}}),+ headers={+ "X-Gitlab-Event": "Push Hook",+ "X-Gitlab-Token": token,+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200