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 @@
- 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.