diff --git a/README.md b/README.md index c595d1b..1dbc46a 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,9 @@ Open `http://localhost:8000` in your browser. On first boot, Firebreak redirects ### 4. Sign In and Register Your Token -After setup, sign in with your Forgejo account via OAuth. On first login, Firebreak prompts you to register a `read:repository`-scoped Personal Access Token (PAT) to enable share link viewing. +After setup, sign in with your Forgejo account via OAuth. Register a Personal Access Token (PAT) for the same account with `read:user` and `read:repository` scopes in Settings to enable repository inspection and public grant creation. The code viewer is not implemented yet. + +See [Inspect repository and grant JSON](docs/public-link-inspection.md) for the authenticated API workflow and example responses. ### 5. Alternative Deployments @@ -97,9 +99,10 @@ Firebreak should not assume a VPS-only environment. The requirement is an existi - [x] `firebreak config verify --diagnostic` — comprehensive diagnostics - [x] `firebreak config view` — show current config - [x] Forgejo OAuth authentication -- [ ] Repo ownership verification +- [x] Personal repository ownership verification - [ ] Private link creation (email-verified) -- [ ] Public link creation (time-expired) +- [x] Public grant creation (API; pins a commit and records expiration) +- [ ] Public link viewing with expiration/revocation enforcement - [ ] Web-based code viewer - [x] User dashboard - [ ] SMTP configuration UI diff --git a/agents.md b/agents.md index e5ad20d..9f47056 100644 --- a/agents.md +++ b/agents.md @@ -123,7 +123,19 @@ This file is the single source of truth for codebase obstacles, oddities, and th **Preference:** A valid token alone is insufficient for repository-access verification. ### Forgejo PAT could be sent over remote HTTP -**Area:** cli/src/utils/forgejo-checks.ts, cli/src/commands/config/init.ts +**Area:** cli/src/utils/forgejo-checks.ts, cli/src/commands/config/init.ts, web/app/services/forgejo.py **Obstacle:** CLI setup and verification accepted remote `http://` Forgejo URLs, allowing the PAT to be sent without transport encryption. -**Solution/Workaround:** Centralize Forgejo URL validation, require HTTPS for non-local endpoints, and allow HTTP only for the documented `forgejo` service and loopback hosts. Validate again inside authenticated checks before constructing requests. +**Solution/Workaround:** Centralize Forgejo URL validation, require HTTPS for non-local endpoints, and allow HTTP only for the documented `forgejo` service and loopback hosts. Validate again inside authenticated checks before constructing requests. The web inspection client follows the same transport rule and disables redirects. **Preference:** Reject insecure remote transport instead of adding an acknowledgement flag. + +### Forgejo identity and branch JSON field names +**Area:** web/app/routers/auth.py, web/app/routers/links.py +**Obstacle:** Forgejo's documented user response exposes `login`, not `username`, and a branch response exposes its immutable SHA at `commit.id`. Looking up the wrong fields prevents sign-in or commit pinning. +**Solution/Workaround:** Parse `login` for OAuth (retaining the old `username` fallback), compare PAT and OAuth user IDs, and validate the SHA from `branch.commit.id`. Require `read:user` plus `read:repository` PAT scopes. +**Preference:** Use immutable IDs for personal ownership; collaborator/admin permissions never authorize sharing. + +### JSON inspection and browser error pages +**Area:** web/app/main.py, web/app/middleware.py, web/app/routers/links.py +**Obstacle:** Browser requests normally receive HTML errors or setup redirects; inspection routes need consistent JSON, and default validation errors echo rejected values. +**Solution/Workaround:** Return JSON for `/links/` errors and setup failures, omit validation input values, redact credentials from optional upstream inspection data, and set `Cache-Control: no-store`. Accept only JSON bodies for grant creation. +**Preference:** Keep inspection behind the existing owner session; never persist upstream payloads or return stored token hashes. diff --git a/docs/examples/public-link-inspection.json b/docs/examples/public-link-inspection.json new file mode 100644 index 0000000..92a8303 --- /dev/null +++ b/docs/examples/public-link-inspection.json @@ -0,0 +1,103 @@ +{ + "repositories_response": { + "repositories": [ + { + "owner": "zach", + "name": "example", + "full_name": "zach/example", + "default_branch": "main", + "private": true + } + ], + "page": 1, + "limit": 30, + "next_page": null, + "inspection": { + "forgejo": { + "authenticated_user": { + "id": 17, + "login": "zach", + "email": "zach@example.test", + "is_admin": false + }, + "repositories": [ + { + "id": 91, + "owner": { + "id": 17, + "login": "zach", + "email": "zach@example.test", + "is_admin": false + }, + "name": "example", + "full_name": "zach/example", + "default_branch": "main", + "private": true, + "permissions": {"pull": true, "admin": true}, + "description": "Preserve this unmodeled upstream field" + } + ] + } + } + }, + "create_response": { + "created_grant": { + "id": "603a1abd-f9ae-4052-a070-bea1a6f0454b", + "user_id": "4b57d156-af94-4592-b507-a82a91a7ab5f", + "repo_owner": "zach", + "repo_name": "example", + "commit_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "grant_type": "public", + "created_at": "2026-09-04T22:26:35Z", + "expires_at": "2026-09-11T22:26:35Z", + "revoked_at": null, + "recipient_email": null, + "token_hash": "[redacted]" + }, + "share_url": "https://share.example.test/s/[returned-once]", + "viewer_available": false, + "inspection": { + "request": { + "repo_owner": "zach", + "repo_name": "example", + "branch": "main", + "expires_at": "2026-09-11T22:26:35Z", + "link_type": "public" + }, + "forgejo": { + "authenticated_user": { + "id": 17, + "login": "zach", + "email": "zach@example.test", + "is_admin": false + }, + "repository": { + "id": 91, + "owner": { + "id": 17, + "login": "zach", + "email": "zach@example.test", + "is_admin": false + }, + "name": "example", + "full_name": "zach/example", + "default_branch": "main", + "private": true, + "permissions": {"pull": true, "admin": true}, + "description": "Preserve this unmodeled upstream field" + }, + "branch": { + "name": "main", + "commit": { + "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "message": "Example commit" + } + } + }, + "ownership": { + "allowed": true, + "reason": "repository owner matches authenticated Forgejo user" + } + } + } +} diff --git a/docs/plans/2026-09-04-public-link-inspection-design.md b/docs/plans/2026-09-04-public-link-inspection-design.md index 50b3783..d53a9d2 100644 --- a/docs/plans/2026-09-04-public-link-inspection-design.md +++ b/docs/plans/2026-09-04-public-link-inspection-design.md @@ -68,6 +68,9 @@ personal-ownership rule, and returns: "private": true } ], + "page": 1, + "limit": 30, + "next_page": null, "inspection": { "forgejo": { "authenticated_user": {}, @@ -78,8 +81,10 @@ personal-ownership rule, and returns: ``` `repositories` is the normalized Firebreak contract. `inspection` is included -only when `inspect=true` and contains the unmodified JSON bodies received from -Forgejo after response parsing. Firebreak does not persist the inspection data. +only when `inspect=true` and preserves JSON fields received from Forgejo after +response parsing, except for credential redaction. Discovery accepts `page` and +`limit` and reports `next_page` using Forgejo's pagination header. Firebreak does +not persist the inspection data. ### Create a public grant @@ -182,8 +187,8 @@ returned only to the authenticated Firebreak user that requested inspection. database details Failures identify the stage (`identity`, `repositories`, `repository`, `branch`, -or `grant`) without exposing credentials. An inspection response may include only -the safe upstream JSON successfully received before the failure. +or `grant`) without exposing credentials. Partial upstream inspection payloads +are omitted on failure. ## Testing diff --git a/docs/public-link-inspection.md b/docs/public-link-inspection.md new file mode 100644 index 0000000..892f1e5 --- /dev/null +++ b/docs/public-link-inspection.md @@ -0,0 +1,111 @@ +# Inspect repository and grant JSON + +Firebreak exposes repository discovery and public grant creation as authenticated +JSON endpoints. Sign in through Forgejo, then register a PAT from the same account +with `read:user` and `read:repository` scopes in Settings. + +The owner check compares Forgejo IDs. Collaborator access, administrator access, +and organization ownership do not qualify. All requests require your active +Firebreak session; inspection data is never exposed through the share URL. + +## See what Forgejo returns + +While signed in, open `/links/repositories?inspect=true` on your Firebreak host in +the browser. The response includes: + +- `repositories`: personally owned repositories normalized for Firebreak +- `inspection.forgejo.authenticated_user`: the PAT-authenticated Forgejo user +- `inspection.forgejo.repositories`: the upstream repository JSON for this page, + including accessible repositories excluded by the personal-owner filter +- `page`, `limit`, and `next_page`: pagination; request the next page when present + +For example, `/links/repositories?inspect=true&page=2&limit=30` inspects page 2. +Pagination follows the upstream page boundaries, so a page can contain no eligible +repositories while still having a `next_page`. Omit `inspect=true` to receive only +the normalized results and pagination. + +The inspection payload keeps upstream fields and structure, with credential +fields, credential-bearing URLs, and echoed PAT values redacted. It is returned +only for this request and is not saved in the database. Responses use +`Cache-Control: no-store`. + +## Create and inspect a grant + +Open `/docs` on the same Firebreak host after signing in. Expand `POST /links/`, +click **Try it out**, set `inspect` to `true`, and supply this body with your own +repository and a future expiration: + +```json +{ + "repo_owner": "zach", + "repo_name": "example", + "branch": "main", + "expires_at": "2099-01-01T12:00:00Z", + "link_type": "public" +} +``` + +The same-origin request uses your existing browser session. You do not need to +copy a session cookie or paste your PAT into the request. This operation creates +a real grant each time it succeeds; there is no preview/dry-run mode. + +The JSON request must use `Content-Type: application/json`. The timestamp must +include a timezone, and the branch must exist. Branch names such as +`feature/example` are supported. Private links and recipient-email fields are +rejected in this slice. + +The HTTP 201 response separates: + +- `created_grant`: the saved Firebreak record, including its database-generated + ID and timestamps; `token_hash` is always `[redacted]` +- `share_url`: a freshly generated bearer link, returned once; the database + contains only the SHA-256 hash of its token +- `viewer_available`: `false`, because `/s/{token}` is not implemented yet +- `inspection`: the validated request, upstream user/repository/branch JSON, + and the successful ownership decision + +The commit SHA comes from Forgejo's `branch.commit.id` and stays pinned even when +the branch moves. Grant creation records expiration, but viewer-side expiration +and revocation enforcement will arrive with the viewer. Treat the one-time share +URL as a secret and keep it out of logs or screenshots you publish. + +See [example responses](examples/public-link-inspection.json). These examples +use mocked Forgejo data and a real test database; they are not a capture from +your Forgejo account. IDs/times are illustrative and the one-time share token +has been replaced with `[returned-once]`. + +## Failures + +| Status | Meaning | +| --- | --- | +| 401 | Missing, expired, or revoked Firebreak session | +| 403 | PAT account mismatch, or repository not personally owned | +| 404 | Forgejo repository or branch not found | +| 409 | No registered PAT | +| 415 | Request did not use `application/json` | +| 422 | Invalid names, expiration, pagination, or unsupported request fields | +| 502 | Forgejo rejected the PAT, was unreachable, or returned invalid data | +| 503 | Setup, public URL, Forgejo transport, or PAT decryption needs attention | +| 500 | Grant could not be saved; transaction rolled back | + +Upstream and grant failures include a `detail.stage` and an actionable message. +Failures do not echo raw upstream error bodies, request values, database details, +or partial inspection payloads. + +## Run the tests + +From the repository root: + +```sh +uv --directory web run pytest -q +uv --directory web run mypy app +``` + +Tests default to an isolated in-memory SQLite database with a mocked Forgejo +transport. For PostgreSQL, set `FIREBREAK_TEST_DATABASE_URL` to a disposable local +test database using the `postgresql+asyncpg://` scheme. Each test creates and drops +its own randomly named schema; the account must have schema-creation privileges. +Tests never use `DATABASE_URL` or contact the configured Forgejo instance. + +Upstream reference: [Forgejo API usage](https://forgejo.org/docs/latest/user/api/usage/) +and the instance's `/swagger.v1.json` schema. diff --git a/web/app/auth/pat.py b/web/app/auth/pat.py new file mode 100644 index 0000000..54e0a04 --- /dev/null +++ b/web/app/auth/pat.py @@ -0,0 +1,26 @@ +from fastapi import HTTPException + +from app.auth.crypto import decrypt_token +from app.config import get_fernet +from app.models.user import User + + +def decrypt_pat(user: User) -> str: + if not user.pat_encrypted: + raise HTTPException( + 409, + detail={ + "stage": "identity", + "message": "Register a Forgejo PAT in Settings first.", + }, + ) + try: + return decrypt_token(get_fernet(), user.pat_encrypted) + except ValueError: + raise HTTPException( + 503, + detail={ + "stage": "identity", + "message": "Cannot decrypt the PAT. Check encryption settings and register it again.", + }, + ) from None diff --git a/web/app/main.py b/web/app/main.py index c59f41e..9d8f872 100644 --- a/web/app/main.py +++ b/web/app/main.py @@ -5,12 +5,15 @@ from pathlib import Path from typing import Annotated from fastapi import Depends, FastAPI, Request +from fastapi.exception_handlers import request_validation_exception_handler +from fastapi.exceptions import RequestValidationError from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles +from sqlalchemy import func as sql_func +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.responses import Response -from sqlalchemy import func as sql_func, select -from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app import models as _models # noqa: F401 - register ORM tables on metadata from app.auth.session import get_current_session, get_optional_session @@ -92,7 +95,7 @@ ERROR_TITLES = { async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Response: """Render a styled error page for browser requests, JSON for API clients.""" accept = request.headers.get("accept", "") - if "text/html" in accept: + if "text/html" in accept and not request.url.path.startswith("/links/"): return templates.TemplateResponse( request, "error.html", @@ -106,6 +109,14 @@ async def http_exception_handler(request: Request, exc: StarletteHTTPException) return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) +@app.exception_handler(RequestValidationError) +async def validation_exception_handler(request: Request, exc: RequestValidationError) -> Response: + if request.url.path.startswith("/links/"): + errors = [{"loc": e["loc"], "msg": e["msg"], "type": e["type"]} for e in exc.errors()] + return JSONResponse({"detail": errors}, status_code=422) + return await request_validation_exception_handler(request, exc) + + @app.get("/", response_class=HTMLResponse) async def root( request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)] diff --git a/web/app/middleware.py b/web/app/middleware.py index 29ea3cf..ae1327b 100644 --- a/web/app/middleware.py +++ b/web/app/middleware.py @@ -1,6 +1,6 @@ from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request -from starlette.responses import RedirectResponse, Response +from starlette.responses import JSONResponse, RedirectResponse, Response class SetupRequiredMiddleware(BaseHTTPMiddleware): @@ -12,10 +12,19 @@ class SetupRequiredMiddleware(BaseHTTPMiddleware): return await call_next(request) if request.app.state.app_settings is None: + if path.startswith("/links/"): + return JSONResponse( + {"detail": {"stage": "configuration", "message": "Setup required."}}, + status_code=503, + headers={"Cache-Control": "no-store"}, + ) if request.headers.get("HX-Request"): response = Response(status_code=200) response.headers["HX-Redirect"] = "/setup" return response return RedirectResponse("/setup", status_code=302) - return await call_next(request) + response = await call_next(request) + if path.startswith("/links/"): + response.headers["Cache-Control"] = "no-store" + return response diff --git a/web/app/routers/auth.py b/web/app/routers/auth.py index a05f82c..706567d 100644 --- a/web/app/routers/auth.py +++ b/web/app/routers/auth.py @@ -103,7 +103,7 @@ def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None] def _parse_user_response(data: dict) -> tuple[str, str, str | None]: provider_user_id = str(data.get("id", "")).strip() - provider_username = str(data.get("username", "")).strip() + provider_username = str(data.get("login") or data.get("username", "")).strip() if not provider_user_id or not provider_username: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, diff --git a/web/app/routers/links.py b/web/app/routers/links.py index 48cb8bf..0fd5d2d 100644 --- a/web/app/routers/links.py +++ b/web/app/routers/links.py @@ -1,31 +1,354 @@ -from datetime import datetime -from typing import Literal +from __future__ import annotations -from fastapi import APIRouter -from pydantic import BaseModel, EmailStr +import hashlib +import re +import secrets +import uuid +from datetime import UTC, datetime +from typing import Annotated, Any, Literal +from urllib.parse import quote, urlsplit + +import httpx +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationError, field_validator +from sqlalchemy import select +from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.pat import decrypt_pat +from app.auth.session import get_current_session +from app.config import get_app_settings +from app.deps import get_db +from app.models.app_settings import AppSettings +from app.models.grant import Grant +from app.models.session import Session as BrowserSession +from app.models.user import LinkedIdentity +from app.services import forgejo +from app.services.inspection import redact router = APIRouter(prefix="/links", tags=["links"]) +SessionDep = Annotated[BrowserSession, Depends(get_current_session)] +DatabaseDep = Annotated[AsyncSession, Depends(get_db)] +ClientDep = Annotated[httpx.AsyncClient, Depends(forgejo.get_client)] +SettingsDep = Annotated[AppSettings, Depends(get_app_settings)] +Name = Annotated[str, Field(min_length=1, max_length=255, pattern=r"^[\w.-]+$")] + class CreateLinkRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + repo_owner: Name + repo_name: Name + branch: Annotated[str, Field(min_length=1, max_length=1024)] + expires_at: AwareDatetime + link_type: Literal["public"] = "public" + + @field_validator("repo_owner", "repo_name") + @classmethod + def valid_name(cls, value: str) -> str: + if value in {".", ".."}: + raise ValueError("Invalid repository name or owner") + return value + + @field_validator("branch") + @classmethod + def valid_branch(cls, value: str) -> str: + if ( + value == "@" + or value.startswith(("/", ".")) + or value.endswith(("/", ".")) + or any(part.startswith(".") or part.endswith(".lock") for part in value.split("/")) + or any(s in value for s in ("..", "//", "@{")) + or re.search(r"[\x00-\x20\x7f~^:?*\[\\]", value) + ): + raise ValueError("Invalid branch name") + return value + + @field_validator("expires_at") + @classmethod + def future_expiration(cls, value: datetime) -> datetime: + if value <= datetime.now(UTC): + raise ValueError("Expiration must be in the future") + return value.astimezone(UTC) + + +class ForgejoUser(BaseModel): + model_config = ConfigDict(strict=True) + id: Annotated[int, Field(gt=0)] + login: Name + + +class ForgejoRepository(BaseModel): + model_config = ConfigDict(strict=True) + owner: ForgejoUser + name: Name + full_name: str + default_branch: str + private: bool + + +class Repository(BaseModel): + owner: str + name: str + full_name: str + default_branch: str + private: bool + + +class RepositoryResponse(BaseModel): + repositories: list[Repository] + page: int + limit: int + next_page: int | None + inspection: dict[str, Any] | None = None + + +class CreatedGrant(BaseModel): + id: uuid.UUID + user_id: uuid.UUID repo_owner: str repo_name: str - branch: str + commit_sha: str + grant_type: Literal["public"] + created_at: datetime expires_at: datetime - link_type: Literal["public", "private"] = "public" - recipient_email: EmailStr | None = None + revoked_at: datetime | None + recipient_email: None + token_hash: Literal["[redacted]"] = "[redacted]" class CreateLinkResponse(BaseModel): - repo_owner: str - repo_name: str - branch: str - expires_at: datetime - commit_sha: str + created_grant: CreatedGrant share_url: str + viewer_available: Literal[False] = False + inspection: dict[str, Any] | None = None -@router.post("/", status_code=501) -async def create_link(request: CreateLinkRequest) -> dict: - """Stub — link creation not yet implemented.""" - return {"detail": "Link creation is not yet implemented."} +async def verify_identity( + db: AsyncSession, + sess: BrowserSession, + client: httpx.AsyncClient, + pat: str, +) -> tuple[ForgejoUser, dict[str, Any]]: + raw, _ = await forgejo.get(client, "user", pat, "identity") + try: + user = ForgejoUser.model_validate(raw) + except ValidationError: + raise forgejo.malformed("identity") from None + identity = await db.scalar( + select(LinkedIdentity).where( + LinkedIdentity.user_id == sess.user_id, + LinkedIdentity.provider == "forgejo", + LinkedIdentity.provider_user_id == str(user.id), + ) + ) + if identity is None: + raise HTTPException( + 403, + detail={ + "stage": "identity", + "message": "The PAT must belong to your signed-in Forgejo account.", + }, + ) + return user, raw + + +@router.get("/repositories", response_model_exclude_unset=True) +async def repositories( + response: Response, + sess: SessionDep, + db: DatabaseDep, + client: ClientDep, + inspect: bool = False, + page: Annotated[int, Query(ge=1)] = 1, + limit: Annotated[int, Query(ge=1, le=50)] = 30, +) -> RepositoryResponse: + response.headers["Cache-Control"] = "no-store" + pat = decrypt_pat(sess.user) + user, raw_user = await verify_identity(db, sess, client, pat) + raw, upstream = await forgejo.get( + client, + "user/repos", + pat, + "repositories", + params={"page": page, "limit": limit}, + ) + if not isinstance(raw, list): + raise forgejo.malformed("repositories") + try: + parsed = [ForgejoRepository.model_validate(repo) for repo in raw] + except ValidationError: + raise forgejo.malformed("repositories") from None + result = RepositoryResponse( + repositories=[ + Repository( + owner=repo.owner.login, + name=repo.name, + full_name=repo.full_name, + default_branch=repo.default_branch, + private=repo.private, + ) + for repo in parsed + if repo.owner.id == user.id + ], + page=page, + limit=limit, + next_page=page + 1 if "next" in upstream.links else None, + ) + if inspect: + result.inspection = { + "forgejo": redact( + { + "authenticated_user": raw_user, + "repositories": raw, + }, + pat, + ) + } + return result + + +def public_base_url(settings: AppSettings) -> str: + value = settings.firebreak_public_base_url.strip().rstrip("/") + try: + parsed = urlsplit(value) + valid = ( + parsed.scheme in {"http", "https"} + and parsed.hostname + and not parsed.username + and not parsed.password + and not parsed.query + and not parsed.fragment + ) + _ = parsed.port + except ValueError: + valid = False + if not valid: + raise HTTPException( + 503, + detail={ + "stage": "configuration", + "message": "Configure the Firebreak public base URL in setup.", + }, + ) + return value + + +async def require_json(request: Request) -> None: + if request.headers.get("content-type", "").split(";", 1)[0].lower() != "application/json": + raise HTTPException(415, detail={"stage": "request", "message": "Send application/json."}) + + +@router.post( + "/", status_code=201, response_model_exclude_unset=True, dependencies=[Depends(require_json)] +) +async def create_link( + payload: CreateLinkRequest, + response: Response, + sess: SessionDep, + db: DatabaseDep, + client: ClientDep, + settings: SettingsDep, + inspect: bool = False, +) -> CreateLinkResponse: + response.headers["Cache-Control"] = "no-store" + base_url = public_base_url(settings) + pat = decrypt_pat(sess.user) + user, raw_user = await verify_identity(db, sess, client, pat) + repo_path = f"repos/{quote(payload.repo_owner, safe='')}/{quote(payload.repo_name, safe='')}" + raw_repo, _ = await forgejo.get(client, repo_path, pat, "repository") + try: + repo = ForgejoRepository.model_validate(raw_repo) + except ValidationError: + raise forgejo.malformed("repository") from None + if repo.owner.id != user.id: + raise HTTPException( + 403, + detail={ + "stage": "repository", + "message": "Only personally owned repositories can be shared.", + }, + ) + if (repo.name.casefold(), repo.owner.login.casefold()) != ( + payload.repo_name.casefold(), + payload.repo_owner.casefold(), + ): + raise forgejo.malformed("repository") + raw_branch, _ = await forgejo.get( + client, + f"{repo_path}/branches/{quote(payload.branch, safe='')}", + pat, + "branch", + ) + commit = raw_branch.get("commit") if isinstance(raw_branch, dict) else None + sha = commit.get("id") if isinstance(commit, dict) else None + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", sha): + raise forgejo.malformed("branch") + if raw_branch.get("name") != payload.branch: + raise forgejo.malformed("branch") + if payload.expires_at <= datetime.now(UTC): + raise HTTPException( + 422, detail={"stage": "grant", "message": "Expiration must be in the future."} + ) + token = secrets.token_urlsafe(32) + grant = Grant( + user_id=sess.user_id, + repo_owner=repo.owner.login, + repo_name=repo.name, + commit_sha=sha, + grant_type="public", + expires_at=payload.expires_at, + token_hash=hashlib.sha256(token.encode()).hexdigest(), + recipient_email=None, + revoked_at=None, + ) + try: + db.add(grant) + await db.flush() + await db.refresh(grant) + created = CreatedGrant( + id=grant.id, + user_id=grant.user_id, + repo_owner=grant.repo_owner, + repo_name=grant.repo_name, + commit_sha=grant.commit_sha, + grant_type="public", + created_at=grant.created_at, + expires_at=grant.expires_at, + revoked_at=grant.revoked_at, + recipient_email=None, + token_hash="[redacted]", + ) + await db.commit() + except SQLAlchemyError: + await db.rollback() + raise HTTPException( + 500, + detail={ + "stage": "grant", + "message": "Could not save the grant. Please try again.", + }, + ) from None + result = CreateLinkResponse( + created_grant=created, + share_url=f"{base_url}/s/{token}", + viewer_available=False, + ) + if inspect: + result.inspection = { + "request": payload.model_dump(mode="json"), + "forgejo": redact( + { + "authenticated_user": raw_user, + "repository": raw_repo, + "branch": raw_branch, + }, + pat, + ), + "ownership": { + "allowed": True, + "reason": "repository owner matches authenticated Forgejo user", + }, + } + return result diff --git a/web/app/services/__init__.py b/web/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/web/app/services/forgejo.py b/web/app/services/forgejo.py new file mode 100644 index 0000000..234409c --- /dev/null +++ b/web/app/services/forgejo.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator +from typing import Annotated, Any +from urllib.parse import urlsplit + +import httpx +from fastapi import Depends, HTTPException + +from app.config import get_app_settings +from app.models.app_settings import AppSettings + + +def validate_base_url(value: str) -> str: + """Keep authenticated requests on a configured, encrypted transport.""" + try: + url = urlsplit(value.strip()) + local = url.hostname in {"localhost", "127.0.0.1", "::1", "forgejo"} or ( + url.hostname is not None and url.hostname.endswith(".localhost") + ) + valid = ( + bool(url.hostname) + and (url.scheme == "https" or (url.scheme == "http" and local)) + and not url.username + and not url.password + and not url.query + and not url.fragment + ) + _ = url.port + except ValueError: + valid = False + if not valid: + raise HTTPException( + 503, + detail={ + "stage": "configuration", + "message": "Configure an HTTPS Forgejo URL (HTTP is allowed for local endpoints).", + }, + ) + return value.strip().rstrip("/") + + +async def get_client( + settings: Annotated[AppSettings, Depends(get_app_settings)], +) -> AsyncIterator[httpx.AsyncClient]: + if settings is None: + raise HTTPException(503, detail={"stage": "configuration", "message": "Setup required."}) + base_url = validate_base_url(settings.forgejo_base_url) + async with httpx.AsyncClient( + base_url=base_url + "/api/v1/", + timeout=10.0, + follow_redirects=False, + ) as client: + yield client + + +async def get( + client: httpx.AsyncClient, + path: str, + pat: str, + stage: str, + *, + params: dict[str, int] | None = None, +) -> tuple[Any, httpx.Response]: + """Return the parsed body and pagination headers without reflecting errors.""" + try: + response = await client.get( + path, + params=params, + headers={"Authorization": f"token {pat}", "Accept": "application/json"}, + ) + except httpx.RequestError: + raise HTTPException( + 502, + detail={ + "stage": stage, + "message": "Cannot reach Forgejo. Check the connection settings.", + }, + ) from None + if response.status_code != 200: + status = 404 if response.status_code == 404 and stage in {"repository", "branch"} else 502 + message = ( + "Forgejo could not find the selected repository or branch." + if status == 404 + else ( + "Forgejo rejected the PAT. Check its validity and read:user/read:repository scopes." + if response.status_code in {401, 403} + else "Forgejo returned an unexpected response." + ) + ) + raise HTTPException(status, detail={"stage": stage, "message": message}) + try: + return response.json(), response + except ValueError: + raise malformed(stage) from None + + +def malformed(stage: str) -> HTTPException: + return HTTPException( + 502, detail={"stage": stage, "message": "Forgejo returned invalid JSON data."} + ) diff --git a/web/app/services/inspection.py b/web/app/services/inspection.py new file mode 100644 index 0000000..ad42afd --- /dev/null +++ b/web/app/services/inspection.py @@ -0,0 +1,29 @@ +import re +from typing import Any + + +def redact(value: Any, pat: str) -> Any: + """Preserve JSON shape while removing credential fields and echoed PATs.""" + if isinstance(value, dict): + return { + key: "[redacted]" + if re.search( + r"token|password|secret|authorization|credential|encrypted|^pat$", + key, + re.IGNORECASE, + ) + else redact(item, pat) + for key, item in value.items() + } + if isinstance(value, list): + return [redact(item, pat) for item in value] + if isinstance(value, str): + value = value.replace(pat, "[redacted]") if pat else value + value = re.sub(r"(https?://)[^/\s@]+@", r"\1[redacted]@", value) + return re.sub( + r"([?&](?:access_token|token|password|secret)=)[^&#\s]*", + r"\1[redacted]", + value, + flags=re.IGNORECASE, + ) + return value diff --git a/web/app/templates/settings.html b/web/app/templates/settings.html index 3f98d08..aee79c0 100644 --- a/web/app/templates/settings.html +++ b/web/app/templates/settings.html @@ -13,8 +13,9 @@

Forgejo access token

- A read:repository-scoped - Personal Access Token is required for share link viewing. + A token with read:user and + read:repository scopes is required. + Use a Personal Access Token from the same Forgejo account you signed in with.

{% if pat_registered %}
diff --git a/web/pyproject.toml b/web/pyproject.toml index b13d121..35da70e 100644 --- a/web/pyproject.toml +++ b/web/pyproject.toml @@ -22,8 +22,11 @@ dependencies = [ [dependency-groups] dev = [ + "aiosqlite>=0.21.0", "djlint>=1.36.1", "mypy>=1.19.0", + "pytest>=8.4.0", + "pytest-asyncio>=1.0.0", "ruff>=0.11.0", "uvicorn[standard]>=0.44.0", ] @@ -36,6 +39,11 @@ warn_unused_ignores = true warn_redundant_casts = true strict_optional = true +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] +pythonpath = ["."] + [tool.djlint] indent = 2 profile = "jinja" diff --git a/web/tests/conftest.py b/web/tests/conftest.py new file mode 100644 index 0000000..ee10efd --- /dev/null +++ b/web/tests/conftest.py @@ -0,0 +1,146 @@ +import hashlib +import os +import uuid +from copy import deepcopy +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +import httpx +import pytest +from cryptography.fernet import Fernet +from sqlalchemy import event, text +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.config import get_fernet, get_settings +from app.database import Base +from app.main import app +from app.models.app_settings import AppSettings +from app.models.session import Session +from app.models.user import LinkedIdentity, User +from app.services import forgejo + +PAT = "test-pat-must-never-be-returned" +COOKIE = "test-session-token" +USER_JSON = {"id": 17, "login": "zach", "email": "zach@example.test", "is_admin": False} +REPO_JSON = { + "id": 91, + "owner": USER_JSON, + "name": "example", + "full_name": "zach/example", + "default_branch": "main", + "private": True, + "permissions": {"pull": True, "admin": True}, + "description": "Preserve this unmodeled upstream field", +} +BRANCH_JSON = {"name": "main", "commit": {"id": "a" * 40, "message": "Example commit"}} + + +@pytest.fixture +async def api(monkeypatch): + cipher = Fernet(Fernet.generate_key()) + monkeypatch.setattr("app.auth.pat.get_fernet", lambda: cipher) + database_url = os.environ.get("FIREBREAK_TEST_DATABASE_URL", "sqlite+aiosqlite://") + engine = create_async_engine(database_url) + schema = "test_inspection_" + uuid.uuid4().hex + if engine.dialect.name == "sqlite": + + @event.listens_for(engine.sync_engine, "connect") + def sqlite_functions(connection, _): + connection.create_function("gen_random_uuid", 0, lambda: uuid.uuid4().hex) + connection.execute("PRAGMA foreign_keys=ON") + else: + async with engine.begin() as conn: + await conn.execute(text(f'CREATE SCHEMA "{schema}"')) + engine = engine.execution_options(schema_translate_map={None: schema}) + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + sessionmaker = async_sessionmaker(engine, expire_on_commit=False) + user_id = uuid.uuid4() + async with sessionmaker() as db: + db.add( + User( + id=user_id, display_name="zach", pat_encrypted=cipher.encrypt(PAT.encode()).decode() + ) + ) + await db.flush() + db.add_all( + [ + LinkedIdentity( + user_id=user_id, + provider="forgejo", + provider_user_id="17", + provider_username="old-name", + ), + Session( + user_id=user_id, + token_hash=hashlib.sha256(COOKIE.encode()).hexdigest(), + expires_at=datetime.now(UTC) + timedelta(days=1), + ), + ] + ) + await db.commit() + settings = AppSettings( + forgejo_base_url="https://forgejo.example.test", + firebreak_public_base_url="https://share.example.test", + ) + routes = { + "/api/v1/user": deepcopy(USER_JSON), + "/api/v1/user/repos": [deepcopy(REPO_JSON)], + "/api/v1/repos/zach/example": deepcopy(REPO_JSON), + "/api/v1/repos/zach/example/branches/main": deepcopy(BRANCH_JSON), + } + calls = [] + + def upstream(request): + calls.append(request) + assert request.headers["Authorization"] == f"token {PAT}" + reply = routes[request.url.path] + if isinstance(reply, Exception): + raise reply + if callable(reply): + reply = reply(request) + return reply if isinstance(reply, httpx.Response) else httpx.Response(200, json=reply) + + async def forgejo_client(): + async with httpx.AsyncClient( + base_url=forgejo.validate_base_url(settings.forgejo_base_url) + "/api/v1/", + transport=httpx.MockTransport(upstream), + follow_redirects=False, + ) as client: + yield client + + app.state.db_session = sessionmaker + app.state.app_settings = settings + app.dependency_overrides[forgejo.get_client] = forgejo_client + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="https://firebreak.example.test", + cookies={"firebreak_session": COOKIE}, + ) as client: + yield SimpleNamespace( + client=client, + db=sessionmaker, + routes=routes, + calls=calls, + user_id=user_id, + settings=settings, + cipher=cipher, + ) + app.dependency_overrides.clear() + if engine.dialect.name != "sqlite": + async with engine.begin() as conn: + await conn.execute(text(f'DROP SCHEMA "{schema}" CASCADE')) + await engine.dispose() + get_settings.cache_clear() + get_fernet.cache_clear() + + +@pytest.fixture +def payload(): + return { + "repo_owner": "zach", + "repo_name": "example", + "branch": "main", + "expires_at": (datetime.now(UTC) + timedelta(days=7)).isoformat(), + "link_type": "public", + } diff --git a/web/tests/test_forgejo.py b/web/tests/test_forgejo.py new file mode 100644 index 0000000..d9959b4 --- /dev/null +++ b/web/tests/test_forgejo.py @@ -0,0 +1,92 @@ +import httpx +import pytest +from fastapi import HTTPException + +from app.models.app_settings import AppSettings +from app.services.forgejo import get, get_client, validate_base_url +from app.services.inspection import redact + + +@pytest.mark.parametrize( + "url", + [ + "http://git.example.test", + "ftp://git.example.test", + "https://user:pass@git.example.test", + "https://git.example.test?token=secret", + "https://git.example.test#fragment", + "", + "/api", + "https://git.example.test:bad", + "http://localhost.evil.test", + "http://127.0.0.1.evil.test", + ], +) +def test_rejects_insecure_or_ambiguous_forgejo_urls(url): + with pytest.raises(HTTPException) as error: + validate_base_url(url) + assert error.value.status_code == 503 + assert "pass@" not in str(error.value.detail) + + +@pytest.mark.parametrize( + "url", + [ + "https://git.example.test/forgejo", + "http://forgejo:3000", + "http://localhost:3000", + "http://git.localhost:3000", + "http://127.0.0.1:3000", + "http://[::1]:3000", + ], +) +def test_preserves_documented_local_http_exceptions(url): + assert validate_base_url(url + "/") == url + + +async def test_client_uses_configured_subpath_and_disables_redirects(): + settings = AppSettings(forgejo_base_url="https://git.example.test/forgejo/") + dependency = get_client(settings) + client = await anext(dependency) + try: + assert str(client.base_url) == "https://git.example.test/forgejo/api/v1/" + assert client.follow_redirects is False + assert client.timeout.read == 10 + finally: + await dependency.aclose() + + +async def test_get_preserves_body_and_query_parameters(): + seen = [] + + def upstream(request): + seen.append(request) + return httpx.Response(200, json=[{"unmodeled": "preserved"}]) + + async with httpx.AsyncClient( + base_url="https://git.example.test/forgejo/api/v1/", + transport=httpx.MockTransport(upstream), + ) as client: + body, response = await get( + client, "user/repos", "test-pat", "repositories", params={"page": 2} + ) + assert body == [{"unmodeled": "preserved"}] + assert seen[0].url.path == "/forgejo/api/v1/user/repos" + assert seen[0].headers["Authorization"] == "token test-pat" + assert seen[0].url.params["page"] == "2" + assert response.status_code == 200 + + +def test_redaction_handles_nested_credentials_and_url_query(): + body = { + "items": [{"oauth_secret": "secret", "pat_encrypted": "ciphertext"}], + "url": "https://user:password@git.test/repo?token=secret&ref=main", + "message": "PAT echoed here: known-pat", + "safe": 17, + } + result = redact(body, "known-pat") + assert result["safe"] == 17 + assert result["items"][0] == {"oauth_secret": "[redacted]", "pat_encrypted": "[redacted]"} + assert result["url"] == "https://[redacted]@git.test/repo?token=[redacted]&ref=main" + assert result["message"] == "PAT echoed here: [redacted]" + assert body["items"][0]["oauth_secret"] == "secret" diff --git a/web/tests/test_links.py b/web/tests/test_links.py new file mode 100644 index 0000000..c31498a --- /dev/null +++ b/web/tests/test_links.py @@ -0,0 +1,341 @@ +import hashlib +import json +from copy import deepcopy +from unittest.mock import AsyncMock + +import httpx +import pytest +from conftest import BRANCH_JSON, PAT, REPO_JSON, USER_JSON +from sqlalchemy import select +from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncSession + +from app.main import app +from app.models.grant import Grant +from app.models.session import Session +from app.models.user import LinkedIdentity, User +from app.routers.auth import _parse_user_response + + +async def grants(api): + async with api.db() as db: + return list((await db.scalars(select(Grant))).all()) + + +async def test_create_inspect_persists_exact_snapshot_and_only_hash(api, payload): + response = await api.client.post("/links/?inspect=true", json=payload) + assert response.status_code == 201, response.text + data = response.json() + assert data["viewer_available"] is False + assert response.headers["cache-control"] == "no-store" + raw = data["inspection"]["forgejo"] + assert raw == {"authenticated_user": USER_JSON, "repository": REPO_JSON, "branch": BRANCH_JSON} + (row,) = await grants(api) + created = data["created_grant"] + assert created["id"] == str(row.id) + assert created["user_id"] == str(api.user_id) + assert created["commit_sha"] == row.commit_sha == BRANCH_JSON["commit"]["id"] + assert created["repo_owner"] == row.repo_owner == "zach" + assert created["repo_name"] == row.repo_name == "example" + assert created["created_at"] and created["expires_at"] + assert created["revoked_at"] is None and created["recipient_email"] is None + token = data["share_url"].rsplit("/", 1)[1] + assert len(token) >= 43 + assert row.token_hash == hashlib.sha256(token.encode()).hexdigest() + assert created["token_hash"] == "[redacted]" + assert row.token_hash not in response.text and PAT not in response.text + assert token not in json.dumps(created) and token not in json.dumps(data["inspection"]) + assert not hasattr(row, "branch") + api.routes["/api/v1/repos/zach/example/branches/main"]["commit"]["id"] = "b" * 40 + (row,) = await grants(api) + assert row.commit_sha == "a" * 40 + + +async def test_inspection_omitted_by_default_and_tokens_unique(api, payload): + first = await api.client.post("/links/", json=payload) + second = await api.client.post("/links/", json=payload) + assert first.status_code == second.status_code == 201 + assert "inspection" not in first.json() + assert first.json()["share_url"] != second.json()["share_url"] + response = await api.client.get("/links/repositories") + assert "inspection" not in response.json() + + +async def test_repository_discovery_filters_owners_and_exposes_upstream(api): + collaborator = deepcopy(REPO_JSON) + collaborator["owner"]["id"] = 99 + api.routes["/api/v1/user/repos"] = [REPO_JSON, collaborator] + response = await api.client.get("/links/repositories?inspect=true") + data = response.json() + assert response.status_code == 200 + assert len(data["repositories"]) == 1 + assert data["repositories"][0]["owner"] == "zach" + assert data["inspection"]["forgejo"]["repositories"] == [REPO_JSON, collaborator] + assert data["next_page"] is None + + +async def test_pagination_does_not_follow_arbitrary_links(api): + api.routes["/api/v1/user/repos"] = httpx.Response( + 200, + json=[], + headers={"Link": '; rel="next"'}, + ) + response = await api.client.get("/links/repositories?page=1&limit=2") + assert response.json()["next_page"] == 2 + assert dict(api.calls[-1].url.params) == {"page": "1", "limit": "2"} + assert len(api.calls) == 2 + api.routes["/api/v1/user/repos"] = [REPO_JSON] + response = await api.client.get("/links/repositories?page=2&limit=2") + assert response.json()["page"] == 2 + assert response.json()["repositories"][0]["name"] == "example" + + +@pytest.mark.parametrize("kind", ["collaborator", "organization", "site_admin"]) +async def test_non_owner_rejected_even_with_admin_access(api, payload, kind): + api.routes["/api/v1/repos/zach/example"]["owner"]["id"] = 99 + api.routes["/api/v1/user"]["is_admin"] = kind == "site_admin" + response = await api.client.post("/links/?inspect=true", json=payload) + assert response.status_code == 403 + assert response.json()["detail"]["stage"] == "repository" + assert len(api.calls) == 2 + assert not await grants(api) + + +@pytest.mark.parametrize("path", ["/links/", "/links/repositories"]) +async def test_pat_identity_mismatch(api, payload, path): + api.routes["/api/v1/user"]["id"] = 999 + response = ( + await api.client.post(path, json=payload) + if path == "/links/" + else await api.client.get(path) + ) + assert response.status_code == 403 + assert response.json()["detail"]["stage"] == "identity" + assert len(api.calls) == 1 + assert not await grants(api) + + +async def test_missing_linked_identity_rejected(api, payload): + async with api.db() as db: + identity = await db.scalar(select(LinkedIdentity)) + await db.delete(identity) + await db.commit() + response = await api.client.post("/links/", json=payload) + assert response.status_code == 403 + assert not await grants(api) + + +@pytest.mark.parametrize("pat,status", [(None, 409), ("invalid-ciphertext", 503)]) +async def test_missing_or_corrupt_pat(api, payload, pat, status): + async with api.db() as db: + user = await db.get(User, api.user_id) + user.pat_encrypted = pat + await db.commit() + response = await api.client.post("/links/", json=payload) + assert response.status_code == status + assert not api.calls + assert not await grants(api) + + +async def test_signed_out_browser_receives_json(api, payload): + api.client.cookies.clear() + for response in [ + await api.client.get("/links/repositories", headers={"Accept": "text/html"}), + await api.client.post("/links/", json=payload, headers={"Accept": "text/html"}), + ]: + assert response.status_code == 401 + assert response.headers["content-type"] == "application/json" + assert response.headers["cache-control"] == "no-store" + assert not api.calls + + +@pytest.mark.parametrize( + "changes", + [ + {"link_type": "private"}, + {"recipient_email": "test@example.test"}, + {"expires_at": "2000-01-01T00:00:00Z"}, + {"expires_at": "2099-01-01T00:00:00"}, + {"repo_owner": ".."}, + {"repo_name": "../user"}, + {"branch": "../user"}, + {"branch": "main?token=evil"}, + {"branch": ""}, + {"branch": "main\n"}, + ], +) +async def test_invalid_requests_do_not_create_grants(api, payload, changes): + response = await api.client.post("/links/", json={**payload, **changes}) + assert response.status_code == 422 + assert not api.calls + assert not await grants(api) + + +async def test_form_content_rejected_and_validation_does_not_echo_secrets(api, payload): + response = await api.client.post("/links/", data={**payload, "pat": PAT}) + assert response.status_code == 415 + response = await api.client.post("/links/", json={**payload, "pat": PAT}) + assert response.status_code == 422 + assert PAT not in response.text + + +async def test_slash_branch_encoded_and_timezone_normalized(api, payload): + api.routes["/api/v1/repos/zach/example/branches/feature/hello"] = { + "name": "feature/hello", + "commit": {"id": "c" * 40}, + } + payload["branch"] = "feature/hello" + payload["expires_at"] = "2099-01-01T08:00:00-05:00" + response = await api.client.post("/links/", json=payload) + assert response.status_code == 201, response.text + assert b"feature%2Fhello" in api.calls[-1].url.raw_path + assert response.json()["created_grant"]["expires_at"].startswith("2099-01-01T13:00:00") + + +@pytest.mark.parametrize( + "path,body", + [ + ("/api/v1/user", {}), + ("/api/v1/user", {"id": True, "login": "zach"}), + ("/api/v1/repos/zach/example", {"owner": {"id": 17}}), + ("/api/v1/repos/zach/example/branches/main", {"name": "main", "commit": {"id": "main"}}), + ("/api/v1/repos/zach/example/branches/main", {"name": "wrong", "commit": {"id": "a" * 40}}), + ("/api/v1/repos/zach/example/branches/main", []), + ], +) +async def test_malformed_upstream_fails_closed(api, payload, path, body): + api.routes[path] = body + response = await api.client.post("/links/", json=payload) + assert response.status_code == 502 + assert not await grants(api) + + +@pytest.mark.parametrize( + "status,expected", [(401, 502), (403, 502), (404, 404), (500, 502), (302, 502)] +) +async def test_forgejo_http_errors_do_not_reflect_credentials(api, payload, status, expected): + api.routes["/api/v1/repos/zach/example"] = httpx.Response( + status, + json={"message": PAT}, + headers={"Location": "https://evil.test"}, + ) + response = await api.client.post("/links/?inspect=true", json=payload) + assert response.status_code == expected + assert PAT not in response.text + assert len(api.calls) == 2 + assert not await grants(api) + + +@pytest.mark.parametrize( + "reply", [httpx.ReadTimeout("secret upstream detail"), httpx.Response(200, text="invalid JSON")] +) +async def test_transport_and_json_errors(api, payload, reply): + api.routes["/api/v1/user"] = reply + response = await api.client.post("/links/", json=payload) + assert response.status_code == 502 + assert "secret upstream detail" not in response.text + assert not await grants(api) + + +async def test_redaction_preserves_noncredential_payload_fields(api, payload): + api.routes["/api/v1/repos/zach/example"].update( + { + "token": "raw-token", + "nested": [{"password": "raw-password", "note": PAT}], + "clone_url": "https://user:raw-password@git.example.test/repo", + } + ) + response = await api.client.post("/links/?inspect=true", json=payload) + assert response.status_code == 201 + assert all(secret not in response.text for secret in [PAT, "raw-token", "raw-password"]) + raw = response.json()["inspection"]["forgejo"]["repository"] + assert raw["description"] == REPO_JSON["description"] + assert raw["token"] == raw["nested"][0]["password"] == "[redacted]" + + +@pytest.mark.parametrize("method", ["flush", "commit"]) +async def test_database_failure_rolls_back(api, payload, monkeypatch, method): + original = getattr(AsyncSession, method) + rollback = AsyncMock(wraps=None) + original_rollback = AsyncSession.rollback + + async def fail_grant(session, *args, **kwargs): + if any(isinstance(obj, Grant) for obj in session.new) or session.info.get("grant_flushed"): + raise SQLAlchemyError("private database detail") + return await original(session, *args, **kwargs) + + if method == "commit": + original_flush = AsyncSession.flush + + async def track_grant(session, *args, **kwargs): + if any(isinstance(obj, Grant) for obj in session.new): + session.info["grant_flushed"] = True + return await original_flush(session, *args, **kwargs) + + monkeypatch.setattr(AsyncSession, "flush", track_grant) + + async def record_rollback(session): + await rollback() + await original_rollback(session) + + monkeypatch.setattr(AsyncSession, method, fail_grant) + monkeypatch.setattr(AsyncSession, "rollback", record_rollback) + response = await api.client.post("/links/?inspect=true", json=payload) + assert response.status_code == 500, response.text + assert "private database detail" not in response.text + rollback.assert_awaited_once() + assert not await grants(api) + + +@pytest.mark.parametrize( + "base", ["", "https://user:password@share.test", "https://share.test?query=1"] +) +async def test_invalid_public_url_does_not_persist(api, payload, base): + api.settings.firebreak_public_base_url = base + response = await api.client.post("/links/", json=payload) + assert response.status_code == 503 + assert not await grants(api) + + +def test_oauth_parser_accepts_documented_login_field(): + assert _parse_user_response(USER_JSON) == ("17", "zach", "zach@example.test") + + +@pytest.mark.parametrize("revoked", [False, True]) +async def test_expired_or_revoked_sessions_rejected(api, payload, revoked): + from datetime import UTC, datetime, timedelta + + async with api.db() as db: + session = await db.scalar(select(Session)) + if revoked: + session.revoked_at = datetime.now(UTC) + else: + session.expires_at = datetime.now(UTC) - timedelta(seconds=1) + await db.commit() + response = await api.client.post("/links/", json=payload) + assert response.status_code == 401 + assert not await grants(api) + + +async def test_unconfigured_app_returns_json(api): + app.state.app_settings = None + response = await api.client.get("/links/repositories", headers={"Accept": "text/html"}) + assert response.status_code == 503 + assert response.json()["detail"]["stage"] == "configuration" + + +@pytest.mark.parametrize("body", [{"data": []}, [{"name": "incomplete"}]]) +async def test_malformed_discovery(api, body): + api.routes["/api/v1/user/repos"] = body + response = await api.client.get("/links/repositories?inspect=true") + assert response.status_code == 502 + assert response.json()["detail"]["stage"] == "repositories" + + +async def test_unimplemented_viewer_is_explicit(api, payload): + created = await api.client.post("/links/", json=payload) + assert created.status_code == 201 + assert created.json()["viewer_available"] is False + path = httpx.URL(created.json()["share_url"]).path + response = await api.client.get(path) + assert response.status_code == 404 diff --git a/web/uv.lock b/web/uv.lock index e62d66f..45b44df 100644 --- a/web/uv.lock +++ b/web/uv.lock @@ -6,6 +6,15 @@ resolution-markers = [ "python_full_version < '3.15'", ] +[[package]] +name = "aiosqlite" +version = "0.22.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4e/8a/64761f4005f17809769d23e518d915db74e6310474e733e3593cfc854ef1/aiosqlite-0.22.1.tar.gz", hash = "sha256:043e0bd78d32888c0a9ca90fc788b38796843360c855a7262a532813133a0650", size = 14821, upload-time = "2025-12-23T19:25:43.997Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/b7/e3bf5133d697a08128598c8d0abc5e16377b51465a33756de24fa7dee953/aiosqlite-0.22.1-py3-none-any.whl", hash = "sha256:21c002eb13823fad740196c5a2e9d8e62f6243bd9e7e4a1f87fb5e44ecb4fceb", size = 17405, upload-time = "2025-12-23T19:25:42.139Z" }, +] + [[package]] name = "annotated-doc" version = "0.0.5" @@ -427,8 +436,11 @@ dependencies = [ [package.dev-dependencies] dev = [ + { name = "aiosqlite" }, { name = "djlint" }, { name = "mypy" }, + { name = "pytest" }, + { name = "pytest-asyncio" }, { name = "ruff" }, { name = "uvicorn", extra = ["standard"] }, ] @@ -449,8 +461,11 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ + { name = "aiosqlite", specifier = ">=0.21.0" }, { name = "djlint", specifier = ">=1.36.1" }, { name = "mypy", specifier = ">=1.19.0" }, + { name = "pytest", specifier = ">=8.4.0" }, + { name = "pytest-asyncio", specifier = ">=1.0.0" }, { name = "ruff", specifier = ">=0.11.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.44.0" }, ] @@ -587,6 +602,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, ] +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" @@ -827,6 +851,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + [[package]] name = "pathspec" version = "1.1.1" @@ -836,6 +869,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + [[package]] name = "pycparser" version = "3.0" @@ -935,6 +977,43 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/30/a4/2bffa9f8e804325a09867f0e9d30795c80ea9f8d62560bd1b6ad6220eb2f/pydantic_settings-2.15.0-py3-none-any.whl", hash = "sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42", size = 69413, upload-time = "2026-08-07T09:24:55.839Z" }, ] +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.3"