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.

fix(webhooks): match repos by normalized URL, not contains prefix (#1440)

Felix-Ayush6c5c6d2eb947
diff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.py
index ed4192dca..99ad9bede 100644
--- a/packages/server/src/repowise/server/routers/webhooks.py
+++ b/packages/server/src/repowise/server/routers/webhooks.py
@@ -6,11 +6,15 @@ import hashlib
import hmac
import json
import os
+import re
+from urllib.parse import urlparse
from fastapi import APIRouter, Depends, HTTPException, Request
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud
+from repowise.core.persistence.models import Repository
from repowise.server.deps import auth_is_open, get_db_session
from repowise.server.schemas import WebhookResponse
@@ -21,6 +25,46 @@ router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
# picked up without a server restart.
+def _normalize_scm_url(url: str) -> str:
+ """Collapse clone / web URL variants to a comparable host/path key.
+
+ Strips scheme, userinfo, ``.git`` suffix, trailing slashes, and lowercases
+ the **whole** key (host and path). GitHub and GitLab resolve repo paths
+ case-insensitively; the previous ``contains`` match was also case-insensitive
+ under SQLite, so preserving path case would silently stop syncing when a
+ hand-registered URL differed only in casing from the webhook's ``clone_url``.
+ """
+ raw = (url or "").strip()
+ if not raw:
+ return ""
+ # git@host:path → host/path
+ scp = re.match(r"^git@([^:]+):(.+)$", raw)
+ if scp:
+ host, path = scp.group(1), scp.group(2)
+ else:
+ parsed = urlparse(raw if "://" in raw else f"https://{raw}")
+ host = parsed.hostname or ""
+ path = parsed.path or ""
+ path = path.strip("/")
+ if path.endswith(".git"):
+ path = path[: -len(".git")]
+ return f"{host}/{path}".rstrip("/").lower()
+
+
+async def _find_repo_by_scm_url(session: AsyncSession, url: str) -> Repository | None:
+ """Return the registered repo whose URL matches *url*, or None.
+
+ Exact normalized match only — never a truncated ``contains`` prefix.
+ """
+ needle = _normalize_scm_url(url)
+ if not needle:
+ return None
+ result = await session.execute(select(Repository))
+ for repo in result.scalars().all():
+ if _normalize_scm_url(repo.url) == needle:
+ return repo
+ return None
+
def _verify_github_signature(request: Request, body: bytes, signature_header: str) -> None:
"""Verify GitHub HMAC-SHA256 webhook signature.
@@ -145,15 +189,7 @@ async def github_webhook(
# Only sync pushes to the default branch
if ref.startswith("refs/heads/"):
branch = ref[len("refs/heads/") :]
- # Find matching repo by URL
- from sqlalchemy import select
-
- from repowise.core.persistence.models import Repository
-
- result = await session.execute(
- select(Repository).where(Repository.url.contains(repo_url[:50]))
- )
- repo = result.scalar_one_or_none()
+ repo = await _find_repo_by_scm_url(session, repo_url)
if repo and branch == repo.default_branch:
job = await crud.upsert_generation_job(
session,
@@ -204,14 +240,7 @@ async def gitlab_webhook(
branch = ref[len("refs/heads/") :]
project_url = payload.get("project", {}).get("web_url", "")
- from sqlalchemy import select
-
- from repowise.core.persistence.models import Repository
-
- result = await session.execute(
- select(Repository).where(Repository.url.contains(project_url[:50]))
- )
- repo = result.scalar_one_or_none()
+ repo = await _find_repo_by_scm_url(session, project_url)
if repo and branch == repo.default_branch:
job = await crud.upsert_generation_job(
session,
diff --git a/tests/unit/server/test_webhooks.py b/tests/unit/server/test_webhooks.py
index 98d00f5e8..614bd02eb 100644
--- a/tests/unit/server/test_webhooks.py
+++ b/tests/unit/server/test_webhooks.py
@@ -258,3 +258,146 @@ async def test_gitlab_webhook_token_read_per_request(client: AsyncClient) -> Non
},
)
assert resp.status_code == 200
+
+
+async def test_push_webhook_does_not_match_url_prefix_substring(
+ client: AsyncClient,
+ session_factory,
+) -> None:
+ """A short forged clone URL must not hit a longer registered repo URL.
+
+ Regression for #1392: ``Repository.url.contains(repo_url[:50])`` let
+ ``https://github.com/org/re`` match ``https://github.com/org/repowise``.
+ """
+ async with session_factory() as session:
+ session.add(
+ Repository(
+ name="repowise",
+ url="https://github.com/org/repowise.git",
+ local_path="/tmp/repowise",
+ default_branch="main",
+ )
+ )
+ await session.commit()
+
+ payload = {
+ "ref": "refs/heads/main",
+ "before": "before-sha",
+ "after": "after-sha",
+ "repository": {"clone_url": "https://github.com/org/re"},
+ }
+ with patch("repowise.server.routers.webhooks._launch_webhook_job") as launch:
+ response = await client.post(
+ "/api/webhooks/github",
+ content=json.dumps(payload),
+ headers={
+ "X-GitHub-Event": "push",
+ "X-GitHub-Delivery": "prefix-attack",
+ "Content-Type": "application/json",
+ },
+ )
+
+ assert response.status_code == 200
+ launch.assert_not_called()
+ async with session_factory() as session:
+ jobs = (await session.execute(select(GenerationJob))).scalars().all()
+ assert jobs == []
+
+
+async def test_push_webhook_matches_clone_url_without_git_suffix(
+ client: AsyncClient,
+ session_factory,
+) -> None:
+ """Stored ``…/repo`` still matches a GitHub ``…/repo.git`` clone_url."""
+ async with session_factory() as session:
+ session.add(
+ Repository(
+ name="test-repo",
+ url="https://github.com/example/test-repo",
+ local_path="/tmp/test-repo",
+ default_branch="main",
+ )
+ )
+ await session.commit()
+
+ payload = {
+ "ref": "refs/heads/main",
+ "before": "b",
+ "after": "a",
+ "repository": {"clone_url": "https://github.com/example/test-repo.git"},
+ }
+ with patch("repowise.server.routers.webhooks._launch_webhook_job"):
+ response = await client.post(
+ "/api/webhooks/github",
+ content=json.dumps(payload),
+ headers={
+ "X-GitHub-Event": "push",
+ "X-GitHub-Delivery": "suffix-ok",
+ "Content-Type": "application/json",
+ },
+ )
+
+ assert response.status_code == 200
+ async with session_factory() as session:
+ job = (await session.execute(select(GenerationJob))).scalar_one()
+ config = json.loads(job.config_json)
+ assert config["trigger"] == "webhook"
+
+
+async def test_push_webhook_matches_mixed_case_path(
+ client: AsyncClient,
+ session_factory,
+) -> None:
+ """Registered URL and webhook clone_url may differ only in path casing.
+
+ GitHub/GitLab resolve paths case-insensitively; SQLite ``contains`` did
+ too. A case-sensitive normalizer would return 200 without enqueueing.
+ """
+ async with session_factory() as session:
+ session.add(
+ Repository(
+ name="RepoWise",
+ url="https://github.com/org/RepoWise",
+ local_path="/tmp/RepoWise",
+ default_branch="main",
+ )
+ )
+ await session.commit()
+
+ payload = {
+ "ref": "refs/heads/main",
+ "before": "b",
+ "after": "a",
+ "repository": {"clone_url": "https://github.com/org/repowise.git"},
+ }
+ with patch("repowise.server.routers.webhooks._launch_webhook_job"):
+ response = await client.post(
+ "/api/webhooks/github",
+ content=json.dumps(payload),
+ headers={
+ "X-GitHub-Event": "push",
+ "X-GitHub-Delivery": "case-ok",
+ "Content-Type": "application/json",
+ },
+ )
+
+ assert response.status_code == 200
+ async with session_factory() as session:
+ job = (await session.execute(select(GenerationJob))).scalar_one()
+ config = json.loads(job.config_json)
+ assert config["trigger"] == "webhook"
+
+
+def test_normalize_scm_url_variants() -> None:
+ from repowise.server.routers.webhooks import _normalize_scm_url
+
+ assert _normalize_scm_url("https://github.com/Org/Repo.git") == "github.com/org/repo"
+ assert _normalize_scm_url("https://github.com/Org/Repo/") == "github.com/org/repo"
+ assert _normalize_scm_url("[email protected]:Org/Repo.git") == "github.com/org/repo"
+ assert _normalize_scm_url("https://github.com/org/RepoWise") == (
+ _normalize_scm_url("https://github.com/org/repowise.git")
+ )
+ assert _normalize_scm_url("") == ""