Skip to content

Commit 1c1e360

Browse files
authored
refactor(proxy): isolate project attribution policy (#1957)
## Description Extracts pure project attribution policy from the runtime project context holder. Header classification, project path splitting, and project-prefixed base URL construction now live in a policy module while `project_context` keeps the ContextVar and ASGI scope adapter responsibilities. Closes # ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [x] Code refactoring (no functional changes) ## Changes Made - Added `headroom.proxy.project_policy` for pure project attribution header/path/base-URL helpers. - Updated `headroom.proxy.project_context` to re-export the pure helpers and retain only request context binding and ASGI scope mutation. - Added direct tests for the extracted project attribution policy boundary. - Kept the LiteLLM callback compatibility shim required for repo-wide type checking on fresh branches. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text python -m pytest tests/test_project_policy.py tests/test_proxy_project_savings.py tests/test_litellm_callback.py tests/test_compress_api.py::TestLiteLLMCallback -q 29 passed in 13.70s python -m ruff check . All checks passed! python -m ruff format --check . 1095 files already formatted python -m mypy headroom --ignore-missing-imports Success: no issues found in 409 source files gitleaks protect --staged --no-banner --redact no leaks found ``` ## Real Behavior Proof - Environment: Windows, Python 3.13.13, local worktree based on `headroomlabs/main`. - Exact command / steps: ran focused project policy tests, project savings tests, LiteLLM callback tests, Ruff lint/format checks, mypy over `headroom`, and staged gitleaks scan. - Observed result: all local checks passed; staged secret scan found no leaks. - Not tested: full CI matrix and deployment flows; those are covered by GitHub Actions. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A ## Additional Notes Documentation and changelog updates are not applicable for this internal refactor. GitHub reported existing Dependabot alerts on the default branch during push; this PR does not change dependencies, and the staged secret scan is clean.
1 parent 740fb9b commit 1c1e360

3 files changed

Lines changed: 85 additions & 48 deletions

File tree

headroom/proxy/project_context.py

Lines changed: 10 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -15,28 +15,23 @@
1515

1616
from __future__ import annotations
1717

18-
from collections.abc import Mapping, MutableMapping
18+
from collections.abc import MutableMapping
1919
from contextvars import ContextVar
2020
from typing import Any
21-
from urllib.parse import quote, unquote, urlsplit, urlunsplit
22-
21+
from urllib.parse import quote
22+
23+
from headroom.proxy.project_policy import (
24+
PROJECT_HEADER,
25+
PROJECT_PATH_PREFIX,
26+
classify_project,
27+
split_project_path,
28+
with_project_prefix,
29+
)
2330
from headroom.proxy.savings_tracker import sanitize_project_name
2431

25-
PROJECT_HEADER = "x-headroom-project"
26-
PROJECT_PATH_PREFIX = "/p/"
27-
2832
_current_project: ContextVar[str | None] = ContextVar("headroom_current_project", default=None)
2933

3034

31-
def classify_project(headers: Mapping[str, Any] | Any) -> str | None:
32-
"""Extract a sanitized project name from request headers, if present."""
33-
get = getattr(headers, "get", None)
34-
if get is None:
35-
return None
36-
value = get(PROJECT_HEADER) or get("X-Headroom-Project")
37-
return sanitize_project_name(value)
38-
39-
4035
def set_current_project(project: str | None) -> None:
4136
"""Bind the active request's project for downstream outcome recording."""
4237
_current_project.set(sanitize_project_name(project))
@@ -47,24 +42,6 @@ def get_current_project() -> str | None:
4742
return _current_project.get()
4843

4944

50-
def split_project_path(path: str) -> tuple[str | None, str]:
51-
"""Split ``/p/<name>/rest`` into ``(name, /rest)``.
52-
53-
Clients that cannot send custom headers (aider, Copilot BYOK, Cursor)
54-
are pointed at a project-prefixed base URL instead; the first path
55-
segment after ``/p/`` is the URL-encoded project name. Returns
56-
``(None, path)`` unchanged when the prefix is absent or unusable.
57-
"""
58-
if not path.startswith(PROJECT_PATH_PREFIX):
59-
return None, path
60-
remainder = path[len(PROJECT_PATH_PREFIX) :]
61-
segment, sep, rest = remainder.partition("/")
62-
project = sanitize_project_name(unquote(segment)) if segment else None
63-
if project is None:
64-
return None, path
65-
return project, ("/" + rest) if sep else "/"
66-
67-
6845
def strip_project_path_prefix(scope: MutableMapping[str, Any]) -> str | None:
6946
"""Strip a ``/p/<name>`` prefix from an ASGI scope, returning the name.
7047
@@ -79,21 +56,6 @@ def strip_project_path_prefix(scope: MutableMapping[str, Any]) -> str | None:
7956
return project
8057

8158

82-
def with_project_prefix(base_url: str, project: str | None) -> str:
83-
"""Insert ``/p/<name>`` ahead of the path of a local proxy base URL.
84-
85-
Producer-side counterpart of :func:`split_project_path`, used by
86-
``headroom wrap`` for clients that cannot send custom headers.
87-
Returns ``base_url`` unchanged when the project name is unusable.
88-
"""
89-
name = sanitize_project_name(project)
90-
if name is None:
91-
return base_url
92-
parts = urlsplit(base_url)
93-
prefixed = f"{PROJECT_PATH_PREFIX}{quote(name, safe='')}{parts.path}"
94-
return urlunsplit(parts._replace(path=prefixed.rstrip("/")))
95-
96-
9759
__all__ = [
9860
"PROJECT_HEADER",
9961
"PROJECT_PATH_PREFIX",

headroom/proxy/project_policy.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Pure project attribution policy helpers."""
2+
3+
from __future__ import annotations
4+
5+
from collections.abc import Mapping
6+
from typing import Any
7+
from urllib.parse import quote, unquote, urlsplit, urlunsplit
8+
9+
from headroom.proxy.savings_tracker import sanitize_project_name
10+
11+
PROJECT_HEADER = "x-headroom-project"
12+
PROJECT_PATH_PREFIX = "/p/"
13+
14+
15+
def classify_project(headers: Mapping[str, Any] | Any) -> str | None:
16+
"""Extract a sanitized project name from request headers, if present."""
17+
get = getattr(headers, "get", None)
18+
if get is None:
19+
return None
20+
value = get(PROJECT_HEADER) or get("X-Headroom-Project")
21+
return sanitize_project_name(value)
22+
23+
24+
def split_project_path(path: str) -> tuple[str | None, str]:
25+
"""Split ``/p/<name>/rest`` into ``(name, /rest)``."""
26+
if not path.startswith(PROJECT_PATH_PREFIX):
27+
return None, path
28+
remainder = path[len(PROJECT_PATH_PREFIX) :]
29+
segment, sep, rest = remainder.partition("/")
30+
project = sanitize_project_name(unquote(segment)) if segment else None
31+
if project is None:
32+
return None, path
33+
return project, ("/" + rest) if sep else "/"
34+
35+
36+
def with_project_prefix(base_url: str, project: str | None) -> str:
37+
"""Insert ``/p/<name>`` ahead of the path of a local proxy base URL."""
38+
name = sanitize_project_name(project)
39+
if name is None:
40+
return base_url
41+
parts = urlsplit(base_url)
42+
prefixed = f"{PROJECT_PATH_PREFIX}{quote(name, safe='')}{parts.path}"
43+
return urlunsplit(parts._replace(path=prefixed.rstrip("/")))

tests/test_project_policy.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""Tests for pure project attribution policy helpers."""
2+
3+
from __future__ import annotations
4+
5+
from headroom.proxy.project_policy import (
6+
classify_project,
7+
split_project_path,
8+
with_project_prefix,
9+
)
10+
11+
12+
def test_classify_project_reads_project_header() -> None:
13+
assert classify_project({"x-headroom-project": " frontend "}) == "frontend"
14+
assert classify_project({"X-Headroom-Project": "api"}) == "api"
15+
assert classify_project({"user-agent": "codex"}) is None
16+
assert classify_project(object()) is None
17+
18+
19+
def test_split_project_path_extracts_sanitized_project_and_path() -> None:
20+
assert split_project_path("/p/frontend/v1/messages") == ("frontend", "/v1/messages")
21+
assert split_project_path("/p/my%20repo/v1") == ("my repo", "/v1")
22+
assert split_project_path("/p/frontend") == ("frontend", "/")
23+
assert split_project_path("/v1/messages") == (None, "/v1/messages")
24+
assert split_project_path("/p/%20%20/v1") == (None, "/p/%20%20/v1")
25+
26+
27+
def test_with_project_prefix_round_trips_with_split_project_path() -> None:
28+
url = with_project_prefix("http://127.0.0.1:8787/v1", "my repo")
29+
30+
assert url == "http://127.0.0.1:8787/p/my%20repo/v1"
31+
assert split_project_path("/p/my%20repo/v1") == ("my repo", "/v1")
32+
assert with_project_prefix("http://127.0.0.1:8787/v1", " ") == ("http://127.0.0.1:8787/v1")

0 commit comments

Comments
 (0)