diff --git a/horizon/.env.example b/horizon/.env.example index f925961..d69fd04 100644 --- a/horizon/.env.example +++ b/horizon/.env.example @@ -22,6 +22,9 @@ 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. +# Roster source: peopleportal (T3.1 service API, default) or authentik (reads the same +# Authentik groups directly until T3.1 is deployed; needs HORIZON_AUTHENTIK_URL/TOKEN). +HORIZON_ROSTER_SOURCE= HORIZON_PEOPLEPORTAL_BASE_URL=https://peopleportal.example.com HORIZON_PEOPLEPORTAL_SERVICE_TOKEN= diff --git a/horizon/pipeline/authentik_roster.py b/horizon/pipeline/authentik_roster.py new file mode 100644 index 0000000..828ec8d --- /dev/null +++ b/horizon/pipeline/authentik_roster.py @@ -0,0 +1,218 @@ +"""Read the project roster straight from Authentik, using People Portal's T3.1 rules. + +People Portal's Horizon service API (T3.1, ``GET /api/horizon/projects``) is not +deployed yet. Until it is, this resource builds the identical payload itself from +the same Authentik data People Portal reads: + +- a project is a root group with ``peoplePortalCreation`` and ``teamType=PROJECT``; +- its members come from the root group and its Leadership/Engineering subteams; +- each membership's role title is the user's ``attributes.roles[]`` and + is classified with a Python port of People Portal's ``normalizeRole`` and + ``projectSubteamContext`` (``peopleportal/server/src/utils/roles.ts``); +- tenure is the number of distinct project seasons the user appears in. + +The payload then goes through the same ``parse_project_sources`` validation as the +People Portal client, so every downstream asset sees the same rows either way. +Remove this module once T3.1 is live: point ``HORIZON_ROSTER_SOURCE`` back at +``peopleportal`` (the default). +""" +from __future__ import annotations + +import re +from datetime import datetime, timezone + +import httpx + +from .config import PipelineConfigError +from .project_sources import PeoplePortalPayloadError, ProjectSources, parse_project_sources +from .resources import PeoplePortalClient, PeoplePortalError + +ROLE_MAPPING_VERSION = "authentik-direct-2026-11-v1" # T3.1 rules 2026-11-v1, read without People Portal +ROLE_ORDER = ["project_lead", "tech_lead", "engineer", "pm", "designer", "unknown"] + + +def sanitize_group_name(value: str) -> str: + """Port of People Portal's sanitizeGroupName.""" + return re.sub(r"[^A-Za-z0-9\-_]", "", value or "") + + +def subteam_context(project: dict, subteam: dict) -> str: + """Port of People Portal's projectSubteamContext: 'Leadership', 'Engineering' or 'unknown'.""" + name = subteam.get("name") + if name in ("Leadership", "Engineering"): + return name + attributes = project.get("attributes") or {} + project_name, season_type, season_year = project.get("name"), attributes.get("seasonType"), attributes.get("seasonYear") + if not project_name or not season_type or season_year in (None, ""): + return "unknown" + season = f"{season_type}{season_year}" + technical = sanitize_group_name(project_name) + suffix = sanitize_group_name(season) + if not technical.endswith(suffix): + return "unknown" + managed_prefix = sanitize_group_name(technical[: -len(suffix)]) + friendly_prefix = sanitize_group_name(attributes.get("friendlyName") or "") + for context in ("Leadership", "Engineering"): + child_suffix = sanitize_group_name(f"{context}{season}") + if name in (f"{managed_prefix}{child_suffix}", f"{technical}{child_suffix}"): + return context + if friendly_prefix and name == f"{friendly_prefix}{child_suffix}": + return context + return "unknown" + + +def normalize_role(context: str, title: str | None) -> str: + """Port of People Portal's normalizeRole (one membership title -> Horizon role).""" + title = (title or "").strip() + if not title: + return "unknown" + if re.search(r"project\s*lead", title, re.I) and context in ("project", "Leadership"): + return "project_lead" + if context == "Leadership" and re.search(r"tech(nical)?\s*lead", title, re.I): + return "tech_lead" + if re.search(r"product\s*manager|\bpm\b", title, re.I): + return "pm" + if re.search(r"ui|ux|design", title, re.I): + return "designer" + if context == "Engineering" and re.search( + r"engineer|developer|swe|\bml\b|backend|frontend|full.?stack|ios|android|mobile", title, re.I): + return "engineer" + return "unknown" + + +def build_roster(projects: list[dict]) -> list[dict]: + """Port of People Portal's buildHorizonRoster over Authentik group details. + + Each item is a root group detail with ``users`` and ``subteams`` (each subteam + with its own ``users``), as returned by :class:`AuthentikRosterClient`. + """ + def users_of(project): + return [*project.get("users", []), *(u for team in project.get("subteams", []) for u in team.get("users", []))] + + tenure: dict[str, set[str]] = {} + for project in projects: + attributes = project.get("attributes") or {} + season = f"{attributes.get('seasonType')}:{attributes.get('seasonYear')}" + for user in users_of(project): + tenure.setdefault(str(user["pk"]), set()).add(season) + + records = [] + for project in projects: + members: dict[str, dict] = {} + + def add(user: dict, group_pk: str, context: str) -> None: + user_pk = str(user["pk"]) + member = members.setdefault(user_pk, { + "userPk": user_pk, "username": user.get("username") or "", "email": user.get("email") or "", + "name": user.get("name") or "", "roles": [], "roleTitles": {}, + "tenureSemesters": len(tenure.get(user_pk, ())), + }) + title = ((user.get("attributes") or {}).get("roles") or {}).get(str(group_pk)) + if isinstance(title, str): + member["roleTitles"][str(group_pk)] = title + if not (title or "").strip(): + return + role = normalize_role(context, title) + if role not in member["roles"]: + member["roles"].append(role) + + for user in project.get("users", []): + add(user, project["pk"], "project") + for subteam in project.get("subteams", []): + context = subteam_context(project, subteam) + for user in subteam.get("users", []): + add(user, subteam["pk"], context) + ordered = [] + for member in sorted(members.values(), key=lambda m: m["userPk"]): + roles = sorted(member["roles"], key=ROLE_ORDER.index) or ["unknown"] + ordered.append({**member, "roles": roles}) + attributes = project.get("attributes") or {} + records.append({ + "projectPk": str(project["pk"]), "name": project["name"], + "friendlyName": attributes.get("friendlyName") or project["name"], + "teamStartDate": attributes.get("teamStartDate") or None, + "teamEndDate": attributes.get("teamEndDate") or None, + "archived": bool(attributes.get("archivedAt")), "members": ordered, + }) + return records + + +class AuthentikRosterClient(PeoplePortalClient): + """Drop-in ``peopleportal`` resource that reads the roster from Authentik directly.""" + + authentik_url: str | None = None + authentik_token: str | None = None + user_agent: str = "Horizon-Pipeline/1.0" + # Past-season backfill (HORIZON_INCLUDE_ARCHIVED): a finished season's teams + # are archived afterwards but were active during that season. + include_archived: bool = False + + def _client(self) -> httpx.Client: + base = (self.authentik_url or "").strip().rstrip("/") + token = (self.authentik_token or "").strip() + if not base or not token: + raise PipelineConfigError( + "HORIZON_ROSTER_SOURCE=authentik needs HORIZON_AUTHENTIK_URL and HORIZON_AUTHENTIK_API_TOKEN.") + return httpx.Client(base_url=base, timeout=self.timeout_seconds, follow_redirects=False, + headers={"Authorization": f"Bearer {token}", "Accept": "application/json", + "User-Agent": self.user_agent}) + + @staticmethod + def _json(response: httpx.Response): + if response.status_code >= 400: + raise PeoplePortalError(f"Authentik {response.request.url.path} returned {response.status_code}.") + try: + return response.json() + except ValueError as exc: + raise PeoplePortalError(f"Authentik {response.request.url.path} did not return JSON.") from exc + + def _project_groups(self, client: httpx.Client) -> list[dict]: + roots, page = [], 1 + while True: + body = self._json(client.get("/api/v3/core/groups/", params={ + "include_users": "false", "include_children": "true", "page": page, "page_size": 100, + "ordering": "name"})) + for group in body.get("results", []): + attributes = group.get("attributes") or {} + parent = group.get("parent") or (group.get("parents") or [None])[0] + if not parent and attributes.get("peoplePortalCreation") and attributes.get("teamType") == "PROJECT": + roots.append(group) + pagination = body.get("pagination") or {} + if not pagination.get("next"): + return roots + page += 1 + + def _group(self, client: httpx.Client, pk: str) -> dict: + return self._json(client.get(f"/api/v3/core/groups/{pk}/", params={ + "include_users": "true", "include_children": "true"})) + + def _detail(self, client: httpx.Client, root: dict) -> dict: + detail = self._group(client, root["pk"]) + subteams = [] + for child in detail.get("children_obj") or []: + child_detail = self._group(client, child["pk"]) + subteams.append({"pk": str(child["pk"]), "name": child.get("name"), + "attributes": child.get("attributes") or {}, + "users": child_detail.get("users_obj") or []}) + return {"pk": str(detail["pk"]), "name": detail["name"], "attributes": detail.get("attributes") or {}, + "users": detail.get("users_obj") or [], "subteams": subteams} + + def get_projects(self, season_type: str, season_year: int) -> ProjectSources: + try: + with self._client() as client: + details = [self._detail(client, root) for root in self._project_groups(client)] + except httpx.HTTPError as exc: + raise PeoplePortalError(f"Authentik roster request failed: {type(exc).__name__}.") from exc + selected = {d["pk"] for d in details + if (d["attributes"].get("seasonType"), str(d["attributes"].get("seasonYear"))) == + (season_type, str(season_year))} + payload = {"seasonType": season_type, "seasonYear": season_year, + "generatedAt": datetime.now(timezone.utc).isoformat(), + "roleMappingVersion": ROLE_MAPPING_VERSION, + "projects": [{**p, "archived": p["archived"] and not self.include_archived} + for p in build_roster(details) if p["projectPk"] in selected]} + try: + return parse_project_sources(payload, season_type, season_year, datetime.now(timezone.utc)) + except PeoplePortalPayloadError as exc: + raise PeoplePortalError(str(exc)) from exc + diff --git a/horizon/pipeline/config.py b/horizon/pipeline/config.py index 150c844..2884e36 100644 --- a/horizon/pipeline/config.py +++ b/horizon/pipeline/config.py @@ -99,6 +99,18 @@ class PipelineSettings(BaseSettings): description="Model for T4.6 ranking explanations.", ) + include_archived: bool = Field( + default=False, + validation_alias=AliasChoices("HORIZON_INCLUDE_ARCHIVED"), + description=("Past-season backfill only: treat the season's archived projects and archived " + "Gitea repositories as active. Leave unset for the weekly run."), + ) + roster_source: str = Field( + default="peopleportal", + validation_alias=AliasChoices("HORIZON_ROSTER_SOURCE"), + description=("Where project rosters come from: 'peopleportal' (the T3.1 service API) or " + "'authentik' (read the same groups from Authentik until T3.1 is deployed)."), + ) peopleportal_base_url: str | None = Field( default=None, validation_alias=AliasChoices("HORIZON_PEOPLEPORTAL_BASE_URL"), diff --git a/horizon/pipeline/resources.py b/horizon/pipeline/resources.py index a09b0f0..b971709 100644 --- a/horizon/pipeline/resources.py +++ b/horizon/pipeline/resources.py @@ -258,6 +258,10 @@ class GiteaClient(ConfigurableResource): base_url: str | None = None api_token: str | None = None timeout_seconds: float = 30.0 + # Past-season backfill only (HORIZON_INCLUDE_ARCHIVED): a finished team's + # repositories are archived in Gitea afterwards, but were live during the + # season being backfilled. The weekly run leaves this off. + include_archived: bool = False def get_repository(self, org: str, name: str) -> Repository: """Describe one repository. Exactly one API call.""" @@ -557,7 +561,7 @@ def list_org_repositories(self, org: str) -> list[OrgRepository]: org=str(owner.get("login") or org), name=name, default_branch=str(payload.get("default_branch") or ""), - archived=bool(payload.get("archived", False)), + archived=bool(payload.get("archived", False)) and not self.include_archived, empty=bool(payload.get("empty", False)), ) ) @@ -1234,6 +1238,23 @@ def _path_safe(value: str) -> str: return "".join(char if char.isalnum() or char in "._-" else "_" for char in value) +def _roster_resource(resolved: PipelineSettings) -> ConfigurableResource: + """People Portal's T3.1 API by default; Authentik directly when HORIZON_ROSTER_SOURCE=authentik.""" + source = (resolved.roster_source or "peopleportal").strip().lower() + if source == "authentik": + from .authentik_roster import AuthentikRosterClient # local import: it subclasses PeoplePortalClient + + return AuthentikRosterClient(authentik_url=resolved.authentik_url, + authentik_token=resolved.authentik_api_token, + include_archived=resolved.include_archived) + if source != "peopleportal": + raise PipelineConfigError("HORIZON_ROSTER_SOURCE must be 'peopleportal' or 'authentik'.") + return PeoplePortalClient( + base_url=resolved.peopleportal_base_url, + service_token=resolved.peopleportal_service_token, + ) + + def build_resources( settings: PipelineSettings | None = None, ) -> dict[str, ConfigurableResource]: @@ -1249,15 +1270,13 @@ def build_resources( "gitea": GiteaClient( base_url=resolved.gitea_url, api_token=resolved.gitea_api_token, + include_archived=resolved.include_archived, ), "authentik": AuthentikClient( 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, - ), + "peopleportal": _roster_resource(resolved), "workspace": GitWorkspace(), "postgres": PostgresResource(database_url=resolved.database_url), } diff --git a/horizon/pipeline/semesters.yaml b/horizon/pipeline/semesters.yaml index 76f6dd1..1f22e53 100644 --- a/horizon/pipeline/semesters.yaml +++ b/horizon/pipeline/semesters.yaml @@ -8,3 +8,8 @@ FALL: start: 2026-08-31 end: 2026-12-11 placeholder: true +SPRING: + 2026: + start: 2026-01-26 + end: 2026-05-15 + placeholder: true diff --git a/horizon/tests/test_authentik_roster.py b/horizon/tests/test_authentik_roster.py new file mode 100644 index 0000000..b4e5679 --- /dev/null +++ b/horizon/tests/test_authentik_roster.py @@ -0,0 +1,124 @@ +"""T3.1 rules ported for reading the roster from Authentik directly.""" +from datetime import datetime, timezone + +import httpx +import pytest + +from pipeline.authentik_roster import (AuthentikRosterClient, build_roster, normalize_role, + subteam_context) +from pipeline.config import PipelineSettings +from pipeline.resources import PeoplePortalClient, build_resources + +PROJECT = {"pk": "p1", "name": "IonQFALL2026", + "attributes": {"seasonType": "FALL", "seasonYear": 2026, "friendlyName": "IonQ", + "teamType": "PROJECT", "peoplePortalCreation": True}} + + +@pytest.mark.parametrize("context,title,role", [ + ("project", "Project Lead", "project_lead"), + ("Leadership", "Project Lead", "project_lead"), + ("Engineering", "Project Lead", "unknown"), + ("Leadership", "Technical Lead", "tech_lead"), + ("Engineering", "Tech Lead", "unknown"), + ("Engineering", "Software Engineer", "engineer"), + ("Engineering", "Full-stack Developer", "engineer"), + ("Leadership", "Software Engineer", "unknown"), + ("Engineering", "Product Manager", "pm"), + ("Engineering", "UI/UX Designer", "designer"), + ("Engineering", " ", "unknown"), +]) +def test_normalize_role_matches_people_portal(context, title, role): + assert normalize_role(context, title) == role + + +@pytest.mark.parametrize("name,context", [ + ("Leadership", "Leadership"), ("Engineering", "Engineering"), + ("IonQLeadershipFALL2026", "Leadership"), ("IonQEngineeringFALL2026", "Engineering"), + ("IonQFALL2026EngineeringFALL2026", "Engineering"), ("Interns", "unknown"), +]) +def test_subteam_context_matches_people_portal_names(name, context): + assert subteam_context(PROJECT, {"name": name}) == context + + +def _user(pk, username, roles): + return {"pk": pk, "username": username, "email": f"{username}@x.test", "name": username.title(), + "attributes": {"roles": roles}} + + +def test_build_roster_maps_subteam_titles_and_tenure(): + lead = _user(7, "lena", {"lead": "Technical Lead", "p1": "Project Lead"}) + eng = _user(9, "eli", {"eng": "Software Engineer"}) + project = {**PROJECT, "users": [lead], "subteams": [ + {"pk": "lead", "name": "IonQLeadershipFALL2026", "users": [lead]}, + {"pk": "eng", "name": "IonQEngineeringFALL2026", "users": [eng]}]} + older = {"pk": "p0", "name": "IonQSPRING2026", "attributes": {"seasonType": "SPRING", "seasonYear": 2026}, + "users": [], "subteams": [{"pk": "e0", "name": "Engineering", "users": [eng]}]} + rows = {r["projectPk"]: r for r in build_roster([project, older])} + members = {m["userPk"]: m for m in rows["p1"]["members"]} + assert members["7"]["roles"] == ["project_lead", "tech_lead"] + assert members["9"]["roles"] == ["engineer"] + assert members["9"]["tenureSemesters"] == 2 and members["7"]["tenureSemesters"] == 1 + assert rows["p1"]["friendlyName"] == "IonQ" and rows["p1"]["archived"] is False + + +def test_member_without_title_is_unknown_not_dropped(): + project = {**PROJECT, "users": [], "subteams": [ + {"pk": "eng", "name": "IonQEngineeringFALL2026", "users": [_user(3, "ana", {})]}]} + assert build_roster([project])[0]["members"][0]["roles"] == ["unknown"] + + +def test_get_projects_reads_authentik_and_validates_like_people_portal(monkeypatch): + lead = _user(7, "lena", {"lead": "Technical Lead"}) + groups = { + "list": {"results": [ + {"pk": "p1", "name": "IonQFALL2026", "parent": None, "attributes": PROJECT["attributes"]}, + {"pk": "p2", "name": "IonQSPRING2026", "parent": None, + "attributes": {**PROJECT["attributes"], "seasonType": "SPRING"}}, + {"pk": "lead", "name": "IonQLeadershipFALL2026", "parent": "p1", "attributes": {}}, + {"pk": "x", "name": "Admins", "parent": None, "attributes": {}}], + "pagination": {"next": 0}}, + "p1": {"pk": "p1", "name": "IonQFALL2026", "attributes": PROJECT["attributes"], "users_obj": [], + "children_obj": [{"pk": "lead", "name": "IonQLeadershipFALL2026", "attributes": {}}]}, + "p2": {"pk": "p2", "name": "IonQSPRING2026", "attributes": {**PROJECT["attributes"], "seasonType": "SPRING"}, + "users_obj": [], "children_obj": []}, + "lead": {"pk": "lead", "name": "IonQLeadershipFALL2026", "users_obj": [lead], "children_obj": []}, + } + + def handler(request: httpx.Request) -> httpx.Response: + assert request.headers["Authorization"] == "Bearer tok" + path = request.url.path.rstrip("/").split("/")[-1] + return httpx.Response(200, json=groups["list" if path == "groups" else path]) + + transport = httpx.MockTransport(handler) + real_client = httpx.Client + monkeypatch.setattr(httpx, "Client", lambda **kw: real_client(transport=transport, **kw)) + sources = AuthentikRosterClient(authentik_url="https://auth.test", authentik_token="tok").get_projects("FALL", 2026) + assert [p.project_pk for p in sources.projects] == ["p1"] + assert sources.projects[0].gitea_org == "IonQFALL2026" + assert [(m.authentik_user_pk, m.roles) for m in sources.members] == [("7", ("tech_lead",))] + assert sources.role_mapping_version.startswith("authentik-direct") + + +def test_build_resources_selects_the_roster_source(): + default = build_resources(PipelineSettings(_env_file=None))["peopleportal"] + assert type(default) is PeoplePortalClient + chosen = build_resources(PipelineSettings(_env_file=None, HORIZON_ROSTER_SOURCE="authentik", + HORIZON_AUTHENTIK_URL="https://auth.test", HORIZON_AUTHENTIK_API_TOKEN="t"))["peopleportal"] + assert isinstance(chosen, AuthentikRosterClient) and chosen.authentik_url == "https://auth.test" + + +def test_include_archived_reports_a_past_seasons_repositories_as_active(monkeypatch): + payload = [{"name": "old", "owner": {"login": "OrgSPRING2026"}, "default_branch": "main", + "archived": True, "empty": False}] + from pipeline.resources import GiteaClient + weekly = GiteaClient(base_url="https://git.test", api_token="t") + backfill = GiteaClient(base_url="https://git.test", api_token="t", include_archived=True) + def listed(client): + transport = httpx.MockTransport(lambda request: httpx.Response(200, json=payload, headers={"X-Total-Count": "1"})) + real = httpx.Client + monkeypatch.setattr(httpx, "Client", lambda **kw: real(transport=transport, **kw)) + try: + return client.list_org_repositories("OrgSPRING2026")[0].archived + finally: + monkeypatch.setattr(httpx, "Client", real) + assert listed(weekly) is True and listed(backfill) is False