Coverage for python/lsst/daf/butler/remote_butler/server/_gafaelfawr.py: 0%
48 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-14 18:11 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-14 18:11 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28from __future__ import annotations
30from collections import defaultdict
32import httpx2
33import pydantic
34from fastapi import HTTPException
36from ..authentication.rubin import RubinAuthenticationProvider
39class GafaelfawrClient:
40 """REST client for retrieving authentication information from
41 Gafaelfawr.
43 Parameters
44 ----------
45 base_url : `str`
46 The top-level HTTP path where Gafaelfawr can be found (e.g.
47 ``"https://data-int.lsst.cloud/auth"``).
48 transport : ``httpx2.AsyncBaseTransport``, optional
49 Override the HTTP client's transport. (For unit tests).
50 """
52 def __init__(self, base_url: str, *, transport: httpx2.AsyncBaseTransport | None = None) -> None:
53 if transport is None:
54 transport = httpx2.AsyncHTTPTransport(retries=3)
55 self._client = httpx2.AsyncClient(base_url=base_url, transport=transport, timeout=20.0)
57 async def get_groups(self, user_token: str) -> list[str]:
58 response = await self._client.get(
59 "/api/v1/user-info", headers=RubinAuthenticationProvider(user_token).get_server_headers()
60 )
61 response.raise_for_status()
62 info = _GafaelfawrUserInfo.model_validate_json(response.content)
63 if info.groups is None:
64 return []
65 return [group.name for group in info.groups]
68class _GafaelfawrUserInfo(pydantic.BaseModel):
69 username: str
70 groups: list[_GafaelfawrGroup] | None = None
73class _GafaelfawrGroup(pydantic.BaseModel):
74 name: str
77class GafaelfawrGroupAuthorizer:
78 """Authorizes access to Butler repositories on the basis of Gafaelfawr
79 groups.
81 Parameters
82 ----------
83 client : `GafaelfawrClient`
84 `GafaelfawrClient` instance that will be used to access group
85 information.
86 repository_groups : `dict` [ `str, `list` [ `str` ]]
87 Mapping from repository name to list of Gafaelfawr groups authorized to
88 access that repository. If a user is a member of any one of the groups
89 in the list, access will be granted.
90 """
92 def __init__(self, client: GafaelfawrClient, repository_groups: dict[str, list[str]]) -> None:
93 self._client = client
94 self._repository_groups = repository_groups
95 self._cache: dict[str, set[str]] = defaultdict(set)
97 async def is_user_authorized_for_repository(
98 self, *, repository: str, user_name: str, user_token: str
99 ) -> bool:
100 allowed_groups = self._repository_groups.get(repository)
101 if allowed_groups is None:
102 raise HTTPException(status_code=404, detail=f"Unknown repository '{repository}'")
104 if "*" in allowed_groups:
105 return True
107 if user_name in self._cache[repository]:
108 return True
110 user_groups = await self._client.get_groups(user_token)
111 if any(group in allowed_groups for group in user_groups):
112 self._cache[repository].add(user_name)
113 return True
115 return False
118class MockGafaelfawrGroupAuthorizer:
119 """Mock implementation of ``GafaelfawrGroupAuthorizer`` for unit tests."""
121 def __init__(self) -> None:
122 self._response = True
124 def set_response(self, value: bool) -> None:
125 self._response = value
127 async def is_user_authorized_for_repository(self, **kwargs: str) -> bool:
128 return self._response