From b3c9d66e84a5ddb896c4bd68bd7d5617b1122403 Mon Sep 17 00:00:00 2001 From: Yash Ponnaganti Date: Wed, 25 Nov 2026 14:19:06 -0500 Subject: [PATCH] T1.1 (2/8): People Portal client, semester settings and Gitea login resolution - PeoplePortalClient reads GET /api/horizon/projects (T3.1) with the shared service token and validates the payload with parse_project_sources. A missing URL or token is a configuration error. - Settings HORIZON_PEOPLEPORTAL_BASE_URL, HORIZON_PEOPLEPORTAL_SERVICE_TOKEN (HORIZON_SERVICE_TOKEN also accepted), HORIZON_SEASON_TYPE and HORIZON_SEASON_YEAR, with empty values in .env.example. - identity.resolve_gitea_login is the one place a Gitea login resolves to an Authentik pk: the username equals the login, ignoring case. A blank, unknown or ambiguous login stays None and is never guessed. T1.3 adds aliases inside this helper. --- horizon/.env.example | 9 ++++ horizon/pipeline/config.py | 24 +++++++++ horizon/pipeline/identity.py | 31 ++++++++++- horizon/pipeline/resources.py | 63 ++++++++++++++++++++++ horizon/tests/project_source_fixtures.py | 20 +++++++ horizon/tests/test_people_portal_client.py | 51 ++++++++++++++++++ horizon/tests/test_pipeline_definitions.py | 8 +++ 7 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 horizon/tests/test_people_portal_client.py diff --git a/horizon/.env.example b/horizon/.env.example index bd9a9bb0..f925961d 100644 --- a/horizon/.env.example +++ b/horizon/.env.example @@ -19,3 +19,12 @@ HORIZON_DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/DATABASE # summary of their numbers (generated=false) and publishing still runs. ANTHROPIC_API_KEY= HORIZON_ANTHROPIC_MODEL=claude-sonnet-5-5 + +# People Portal Horizon service API (T3.1), used by peopleportal_projects (T1.1). +# The token must equal People Portal's HORIZON_SERVICE_TOKEN. +HORIZON_PEOPLEPORTAL_BASE_URL=https://peopleportal.example.com +HORIZON_PEOPLEPORTAL_SERVICE_TOKEN= + +# Semester the project-source assets ingest (T1.1). +HORIZON_SEASON_TYPE=FALL +HORIZON_SEASON_YEAR=2026 diff --git a/horizon/pipeline/config.py b/horizon/pipeline/config.py index ce0ac2e0..150c844b 100644 --- a/horizon/pipeline/config.py +++ b/horizon/pipeline/config.py @@ -99,6 +99,30 @@ class PipelineSettings(BaseSettings): description="Model for T4.6 ranking explanations.", ) + peopleportal_base_url: str | None = Field( + default=None, + validation_alias=AliasChoices("HORIZON_PEOPLEPORTAL_BASE_URL"), + description="People Portal base URL for the Horizon service API (T3.1).", + ) + peopleportal_service_token: str | None = Field( + default=None, + repr=False, + validation_alias=AliasChoices( + "HORIZON_PEOPLEPORTAL_SERVICE_TOKEN", "HORIZON_SERVICE_TOKEN" + ), + description="Shared secret matching People Portal's HORIZON_SERVICE_TOKEN.", + ) + season_type: str | None = Field( + default=None, + validation_alias=AliasChoices("HORIZON_SEASON_TYPE"), + description="Semester to ingest: FALL or SPRING.", + ) + season_year: int | None = Field( + default=None, + validation_alias=AliasChoices("HORIZON_SEASON_YEAR"), + description="Semester year to ingest, e.g. 2026.", + ) + def require_gitea_url(self) -> str: return _required(self.gitea_url, "HORIZON_GITEA_URL") diff --git a/horizon/pipeline/identity.py b/horizon/pipeline/identity.py index 921be22a..88ed704d 100644 --- a/horizon/pipeline/identity.py +++ b/horizon/pipeline/identity.py @@ -5,7 +5,8 @@ from dataclasses import dataclass from datetime import datetime from collections import Counter -from collections.abc import Sequence +from collections.abc import Iterable, Sequence +from typing import Protocol from .blame_parser import BlameRecord from .resources import AuthentikRoster, PullRequestCommit @@ -87,3 +88,31 @@ def resolve_git_identities( ) ) return clusters + + +class _RosterMember(Protocol): + authentik_user_pk: str + username: str + + +def resolve_gitea_login( + login: str | None, + roster: AuthentikRoster | Iterable[_RosterMember], +) -> str | None: + """Resolve a Gitea login to an Authentik pk: username equals login, case-insensitively. + + The one place Gitea logins are resolved (T1.1). Returns None when the login + is blank, unknown, or matches more than one member: an ambiguous match is + never guessed. T1.3 adds manual aliases inside this helper. + """ + + key = (login or "").strip().casefold() + if not key: + return None + members = roster.users if isinstance(roster, AuthentikRoster) else roster + candidates = { + member.authentik_user_pk + for member in members + if (member.username or "").strip().casefold() == key + } + return next(iter(candidates)) if len(candidates) == 1 else None diff --git a/horizon/pipeline/resources.py b/horizon/pipeline/resources.py index eb0f9702..2406d338 100644 --- a/horizon/pipeline/resources.py +++ b/horizon/pipeline/resources.py @@ -28,6 +28,11 @@ from dagster import ConfigurableResource from .config import PipelineConfigError, PipelineSettings, get_pipeline_settings +from .project_sources import ( + PeoplePortalPayloadError, + ProjectSources, + parse_project_sources, +) from .storage import PostgresResource # The blame invocation, in one place because two things depend on it agreeing: @@ -63,6 +68,10 @@ class AuthentikError(RuntimeError): """Authentik answered, but not with a complete People Portal roster.""" +class PeoplePortalError(RuntimeError): + """People Portal answered, but not with a usable projects payload.""" + + class GitCommandError(RuntimeError): """A git subprocess failed. @@ -788,6 +797,56 @@ def _require_api_token(self) -> str: return token +class PeoplePortalClient(ConfigurableResource): + """People Portal's Horizon service API (T3.1): projects and members per semester.""" + + base_url: str | None = None + service_token: str | None = None + timeout_seconds: float = 30.0 + + def get_projects(self, season_type: str, season_year: int) -> ProjectSources: + """GET /api/horizon/projects and validate every project and member.""" + + base = (self.base_url or "").strip().rstrip("/") + if not base: + raise PipelineConfigError( + "HORIZON_PEOPLEPORTAL_BASE_URL is not set. Export it, or add it to " + "horizon/.env, before materializing peopleportal_projects." + ) + token = (self.service_token or "").strip() + if not token: + raise PipelineConfigError( + "HORIZON_PEOPLEPORTAL_SERVICE_TOKEN is not set. It must match People " + "Portal's HORIZON_SERVICE_TOKEN." + ) + url = f"{base}/api/horizon/projects" + try: + with httpx.Client(timeout=self.timeout_seconds, follow_redirects=False) as client: + response = client.get( + url, + params={"seasonType": season_type, "seasonYear": str(season_year)}, + headers={"Accept": "application/json", "Authorization": f"Bearer {token}"}, + ) + except httpx.HTTPError as exc: + raise PeoplePortalError( + f"People Portal projects request failed: {type(exc).__name__}." + ) from exc + if response.status_code >= 400: + raise PeoplePortalError( + f"GET {url} returned {response.status_code}. Check the URL and service token." + ) + try: + payload = response.json() + except ValueError as exc: + raise PeoplePortalError(f"GET {url} did not return JSON.") from exc + try: + return parse_project_sources( + payload, season_type, season_year, datetime.now(timezone.utc) + ) + except PeoplePortalPayloadError as exc: + raise PeoplePortalError(str(exc)) from exc + + class GitWorkspace(ConfigurableResource): """Owns the lifecycle of the throwaway clone that blame runs against. @@ -933,6 +992,10 @@ def build_resources( base_url=resolved.authentik_url, api_token=resolved.authentik_api_token, ), + "peopleportal": PeoplePortalClient( + base_url=resolved.peopleportal_base_url, + service_token=resolved.peopleportal_service_token, + ), "workspace": GitWorkspace(), "postgres": PostgresResource(database_url=resolved.database_url), } diff --git a/horizon/tests/project_source_fixtures.py b/horizon/tests/project_source_fixtures.py index df9d53a1..f24cdf66 100644 --- a/horizon/tests/project_source_fixtures.py +++ b/horizon/tests/project_source_fixtures.py @@ -2,6 +2,10 @@ from datetime import datetime, timezone +import httpx + +from pipeline import resources as resources_module + NOW = datetime(2026, 11, 14, tzinfo=timezone.utc) @@ -41,3 +45,19 @@ def payload(projects=None, **overrides): } value.update(overrides) return value + + +def page(items, total, page_number, next_page=None): + headers = {"X-Total-Count": str(total), "X-Page": str(page_number)} + if next_page: + headers["Link"] = f'; rel="next"' + return httpx.Response(200, json=items, headers=headers) + + +def use_transport(monkeypatch, handler): + real_client = httpx.Client + + def client(**kwargs): + return real_client(transport=httpx.MockTransport(handler), **kwargs) + + monkeypatch.setattr(resources_module.httpx, "Client", client) diff --git a/horizon/tests/test_people_portal_client.py b/horizon/tests/test_people_portal_client.py new file mode 100644 index 00000000..9f36c5bb --- /dev/null +++ b/horizon/tests/test_people_portal_client.py @@ -0,0 +1,51 @@ +"""T1.1: the People Portal client and Gitea login resolution.""" + +import httpx +import pytest + +from pipeline.config import PipelineConfigError +from pipeline.identity import resolve_gitea_login +from pipeline.project_sources import ProjectMemberRow +from pipeline.resources import AuthentikRoster, AuthentikUser, PeoplePortalClient +from project_source_fixtures import NOW, payload, use_transport + + +# --- login resolution --------------------------------------------------------- + + +def roster_member(pk, username): + return ProjectMemberRow("p1", pk, username, "", "", (), {}, 0, "v1") + + +def test_gitea_login_resolves_case_insensitively_and_never_guesses(): + roster = [roster_member("1", "JDoe"), roster_member("2", "amy"), roster_member("2", "amy")] + assert resolve_gitea_login("jdoe", roster) == "1" + assert resolve_gitea_login(" JDOE ", roster) == "1" + assert resolve_gitea_login("amy", roster) == "2" # same person on two projects + assert resolve_gitea_login("nobody", roster) is None + assert resolve_gitea_login("", roster) is None + assert resolve_gitea_login(None, roster) is None + ambiguous = roster + [roster_member("3", "AMY")] + assert resolve_gitea_login("amy", ambiguous) is None + + +def test_gitea_login_accepts_an_authentik_roster(): + user = AuthentikUser("9", "Zed", "z@x.edu", "Zed", True, NOW) + assert resolve_gitea_login("zed", AuthentikRoster([user], NOW)) == "9" + + +def test_people_portal_client_sends_bearer_token_and_validates(monkeypatch): + seen = {} + + def handler(request): + seen["auth"] = request.headers["authorization"] + seen["params"] = dict(request.url.params) + return httpx.Response(200, json=payload()) + + use_transport(monkeypatch, handler) + client = PeoplePortalClient(base_url="https://pp.example/", service_token="s3cret") + sources = client.get_projects("FALL", 2026) + assert seen == {"auth": "Bearer s3cret", "params": {"seasonType": "FALL", "seasonYear": "2026"}} + assert len(sources.members) == 2 + with pytest.raises(PipelineConfigError, match="SERVICE_TOKEN"): + PeoplePortalClient(base_url="https://pp.example").get_projects("FALL", 2026) diff --git a/horizon/tests/test_pipeline_definitions.py b/horizon/tests/test_pipeline_definitions.py index e28cfc1c..0f41bdbb 100644 --- a/horizon/tests/test_pipeline_definitions.py +++ b/horizon/tests/test_pipeline_definitions.py @@ -256,6 +256,7 @@ def test_definitions_expose_shared_resources(): assert set(defs.resources) == { "gitea", "authentik", + "peopleportal", "workspace", "postgres", } @@ -268,6 +269,10 @@ def test_resources_are_built_from_settings(): HORIZON_AUTHENTIK_URL="https://auth.example.com", HORIZON_AUTHENTIK_API_TOKEN="auth-token-value", HORIZON_DATABASE_URL="postgresql://u@127.0.0.1:5433/db", + HORIZON_PEOPLEPORTAL_BASE_URL="https://pp.example.com", + HORIZON_PEOPLEPORTAL_SERVICE_TOKEN="pp-token", + HORIZON_SEASON_TYPE="FALL", + HORIZON_SEASON_YEAR="2026", ) resources = build_resources(settings) @@ -281,6 +286,9 @@ def test_resources_are_built_from_settings(): assert resources["authentik"].base_url == "https://auth.example.com" assert resources["authentik"].api_token == "auth-token-value" assert resources["postgres"].database_url == "postgresql://u@127.0.0.1:5433/db" + assert resources["peopleportal"].base_url == "https://pp.example.com" + assert resources["peopleportal"].service_token == "pp-token" + assert (settings.season_type, settings.season_year) == ("FALL", 2026) def test_resources_build_even_when_nothing_is_configured():