diff --git a/headroom/proxy/project_context.py b/headroom/proxy/project_context.py index fe48a7163..e0cd3bf9b 100644 --- a/headroom/proxy/project_context.py +++ b/headroom/proxy/project_context.py @@ -15,28 +15,23 @@ that request, matching pre-feature behavior. from __future__ import annotations -from collections.abc import Mapping, MutableMapping +from collections.abc import MutableMapping from contextvars import ContextVar from typing import Any -from urllib.parse import quote, unquote, urlsplit, urlunsplit +from urllib.parse import quote +from headroom.proxy.project_policy import ( + PROJECT_HEADER, + PROJECT_PATH_PREFIX, + classify_project, + split_project_path, + with_project_prefix, +) from headroom.proxy.savings_tracker import sanitize_project_name -PROJECT_HEADER = "x-headroom-project" -PROJECT_PATH_PREFIX = "/p/" - _current_project: ContextVar[str | None] = ContextVar("headroom_current_project", default=None) -def classify_project(headers: Mapping[str, Any] | Any) -> str | None: - """Extract a sanitized project name from request headers, if present.""" - get = getattr(headers, "get", None) - if get is None: - return None - value = get(PROJECT_HEADER) or get("X-Headroom-Project") - return sanitize_project_name(value) - - def set_current_project(project: str | None) -> None: """Bind the active request's project for downstream outcome recording.""" _current_project.set(sanitize_project_name(project)) @@ -47,24 +42,6 @@ def get_current_project() -> str | None: return _current_project.get() -def split_project_path(path: str) -> tuple[str | None, str]: - """Split ``/p//rest`` into ``(name, /rest)``. - - Clients that cannot send custom headers (aider, Copilot BYOK, Cursor) - are pointed at a project-prefixed base URL instead; the first path - segment after ``/p/`` is the URL-encoded project name. Returns - ``(None, path)`` unchanged when the prefix is absent or unusable. - """ - if not path.startswith(PROJECT_PATH_PREFIX): - return None, path - remainder = path[len(PROJECT_PATH_PREFIX) :] - segment, sep, rest = remainder.partition("/") - project = sanitize_project_name(unquote(segment)) if segment else None - if project is None: - return None, path - return project, ("/" + rest) if sep else "/" - - def strip_project_path_prefix(scope: MutableMapping[str, Any]) -> str | None: """Strip a ``/p/`` prefix from an ASGI scope, returning the name. @@ -79,21 +56,6 @@ def strip_project_path_prefix(scope: MutableMapping[str, Any]) -> str | None: return project -def with_project_prefix(base_url: str, project: str | None) -> str: - """Insert ``/p/`` ahead of the path of a local proxy base URL. - - Producer-side counterpart of :func:`split_project_path`, used by - ``headroom wrap`` for clients that cannot send custom headers. - Returns ``base_url`` unchanged when the project name is unusable. - """ - name = sanitize_project_name(project) - if name is None: - return base_url - parts = urlsplit(base_url) - prefixed = f"{PROJECT_PATH_PREFIX}{quote(name, safe='')}{parts.path}" - return urlunsplit(parts._replace(path=prefixed.rstrip("/"))) - - __all__ = [ "PROJECT_HEADER", "PROJECT_PATH_PREFIX", diff --git a/headroom/proxy/project_policy.py b/headroom/proxy/project_policy.py new file mode 100644 index 000000000..2156f483f --- /dev/null +++ b/headroom/proxy/project_policy.py @@ -0,0 +1,43 @@ +"""Pure project attribution policy helpers.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any +from urllib.parse import quote, unquote, urlsplit, urlunsplit + +from headroom.proxy.savings_tracker import sanitize_project_name + +PROJECT_HEADER = "x-headroom-project" +PROJECT_PATH_PREFIX = "/p/" + + +def classify_project(headers: Mapping[str, Any] | Any) -> str | None: + """Extract a sanitized project name from request headers, if present.""" + get = getattr(headers, "get", None) + if get is None: + return None + value = get(PROJECT_HEADER) or get("X-Headroom-Project") + return sanitize_project_name(value) + + +def split_project_path(path: str) -> tuple[str | None, str]: + """Split ``/p//rest`` into ``(name, /rest)``.""" + if not path.startswith(PROJECT_PATH_PREFIX): + return None, path + remainder = path[len(PROJECT_PATH_PREFIX) :] + segment, sep, rest = remainder.partition("/") + project = sanitize_project_name(unquote(segment)) if segment else None + if project is None: + return None, path + return project, ("/" + rest) if sep else "/" + + +def with_project_prefix(base_url: str, project: str | None) -> str: + """Insert ``/p/`` ahead of the path of a local proxy base URL.""" + name = sanitize_project_name(project) + if name is None: + return base_url + parts = urlsplit(base_url) + prefixed = f"{PROJECT_PATH_PREFIX}{quote(name, safe='')}{parts.path}" + return urlunsplit(parts._replace(path=prefixed.rstrip("/"))) diff --git a/tests/test_project_policy.py b/tests/test_project_policy.py new file mode 100644 index 000000000..2642d83b4 --- /dev/null +++ b/tests/test_project_policy.py @@ -0,0 +1,32 @@ +"""Tests for pure project attribution policy helpers.""" + +from __future__ import annotations + +from headroom.proxy.project_policy import ( + classify_project, + split_project_path, + with_project_prefix, +) + + +def test_classify_project_reads_project_header() -> None: + assert classify_project({"x-headroom-project": " frontend "}) == "frontend" + assert classify_project({"X-Headroom-Project": "api"}) == "api" + assert classify_project({"user-agent": "codex"}) is None + assert classify_project(object()) is None + + +def test_split_project_path_extracts_sanitized_project_and_path() -> None: + assert split_project_path("/p/frontend/v1/messages") == ("frontend", "/v1/messages") + assert split_project_path("/p/my%20repo/v1") == ("my repo", "/v1") + assert split_project_path("/p/frontend") == ("frontend", "/") + assert split_project_path("/v1/messages") == (None, "/v1/messages") + assert split_project_path("/p/%20%20/v1") == (None, "/p/%20%20/v1") + + +def test_with_project_prefix_round_trips_with_split_project_path() -> None: + url = with_project_prefix("http://127.0.0.1:8787/v1", "my repo") + + assert url == "http://127.0.0.1:8787/p/my%20repo/v1" + assert split_project_path("/p/my%20repo/v1") == ("my repo", "/v1") + assert with_project_prefix("http://127.0.0.1:8787/v1", " ") == ("http://127.0.0.1:8787/v1")