Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions horizon/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
24 changes: 24 additions & 0 deletions horizon/pipeline/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
31 changes: 30 additions & 1 deletion horizon/pipeline/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
63 changes: 63 additions & 0 deletions horizon/pipeline/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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),
}
20 changes: 20 additions & 0 deletions horizon/tests/project_source_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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'<https://git.example/api/v1/x?page={next_page}>; 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)
51 changes: 51 additions & 0 deletions horizon/tests/test_people_portal_client.py
Original file line number Diff line number Diff line change
@@ -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)
8 changes: 8 additions & 0 deletions horizon/tests/test_pipeline_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ def test_definitions_expose_shared_resources():
assert set(defs.resources) == {
"gitea",
"authentik",
"peopleportal",
"workspace",
"postgres",
}
Expand All @@ -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)
Expand All @@ -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():
Expand Down
Loading