Skip to content

Commit 5b87b7b

Browse files
committed
Possiblity to scope host keys to a list of specific routes.
1 parent c35d3f0 commit 5b87b7b

7 files changed

Lines changed: 561 additions & 5 deletions

File tree

‎samples/config.yml.sample‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ host_keys:
2020
ips: [] # All ip allowed
2121
user: lmn-teacher # cn of a valid ldap user to isolate the permissions
2222
secret: LONG_AND_SECURE_BASE64_ENCODED_STRING
23+
helpdesk: # A key restricted to a few endpoints
24+
ips: [10.0.5.12]
25+
user: helpdesk-account
26+
secret: LONG_AND_SECURE_BASE64_ENCODED_STRING
27+
# Optional. Without it, or with scope: "*", the key reaches the whole API
28+
# with the LDAP role of `user`. A scope only ever narrows: the role is
29+
# still checked behind it.
30+
# Written as "<METHOD> <path>", matched against the path as it appears on
31+
# the wire, without the /v1 prefix. METHOD may be "*".
32+
# "*" matches exactly one path segment
33+
# "**" matches one or more, last position only
34+
# Entries matching no route are logged as warnings when the API starts:
35+
# mind the trailing slash, /users and /users/ are not the same path.
36+
scope:
37+
- "GET /linbo/hosts/pc01/status" # this one host
38+
- "GET /linbo/hosts/*/status" # any host
39+
- "GET /devices/list/*" # any school
40+
- "GET /linbo/**" # everything under /linbo
2341
# Rate limiting of GET /v1/auth/, the only route that mints a JWT. The counter
2442
# is per client address and per route. Callers on the host itself (the webui)
2543
# are never counted and need no entry here.

‎usr/lib/python3/dist-packages/linuxmusterApi/main.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020

2121
from utils.checks import check_tmp_dir
22+
from security.scope import report_unmatched
2223

2324

2425
logger = logging.getLogger(__name__)
@@ -37,6 +38,7 @@ async def lifespan(app: FastAPI):
3738
app.state.host_key_auth_enable = config.get('host_key_auth', False)
3839
app.state.notifications = config.get('notifications', {})
3940
app.state.rate_limit = config.get('rate_limit', {}) or {}
41+
_report_unreachable_host_key_scopes()
4042
_report_invalid_rate_limit_whitelist()
4143
yield
4244

@@ -114,7 +116,7 @@ def home():
114116

115117
return HTML_HOME
116118

117-
_V1_PREFIX = "/v1"
119+
_V1_PREFIX = API_V1_PREFIX
118120
_V1_ROUTERS = [
119121
auth.router,
120122
admins.router_global,
@@ -218,6 +220,33 @@ def _report_invalid_rate_limit_whitelist():
218220
)
219221

220222

223+
def _report_unreachable_host_key_scopes():
224+
"""
225+
Log the host key scope entries that match no route of this API.
226+
227+
A typo fails silently otherwise: the key still authenticates and every
228+
call it makes is refused with no hint as to why. Only reported, never
229+
fatal — the rest of the API is fine, and a scope entry that matches
230+
nothing would not have let anything through in any case.
231+
"""
232+
233+
routes = []
234+
235+
for route, path, _regex in _iter_effective_routes():
236+
if path.startswith(_V1_PREFIX):
237+
path = path[len(_V1_PREFIX):] or '/'
238+
239+
for method in getattr(route, 'methods', None) or []:
240+
routes.append((method, path))
241+
242+
for name, key in (app.state.host_keys or {}).items():
243+
for entry in report_unmatched(key.get('scope'), routes):
244+
logger.warning(
245+
f"Host key '{name}': scope entry {entry!r} matches no route of this API, "
246+
f"it will never allow anything."
247+
)
248+
249+
221250
_METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
222251
_METHOD_COLORS = {
223252
'GET': '\033[32m', # green

‎usr/lib/python3/dist-packages/linuxmusterApi/pytests/test_header.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def test_raises_503_when_ldap_not_provisioned(self, monkeypatch):
6161
)
6262

6363
with pytest.raises(HTTPException) as excinfo:
64-
check_host_header('host-secret', '10.0.0.1', self.KEYS, True)
64+
check_host_header('host-secret', '10.0.0.1', self.KEYS, True, 'GET', '/users/')
6565

6666
assert excinfo.value.status_code == 503
6767
assert excinfo.value.detail == "linuxmuster is not provisioned yet"
@@ -76,7 +76,7 @@ def test_returns_user_when_provisioned(self, monkeypatch):
7676
},
7777
)
7878

79-
result = check_host_header('host-secret', '10.0.0.1', self.KEYS, True)
79+
result = check_host_header('host-secret', '10.0.0.1', self.KEYS, True, 'GET', '/users/')
8080

8181
assert result.user == 'sophomorix'
8282
assert result.role == 'globaladministrator'
Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
"""
2+
Scope of a x-host-key: which endpoints one key may reach.
3+
4+
The scope narrows an existing key, it never grants anything: every test here
5+
checks what is refused, plus that a key without a scope keeps working exactly
6+
as before.
7+
"""
8+
9+
import pytest
10+
from fastapi import HTTPException
11+
12+
from fastapi.testclient import TestClient
13+
14+
from main import app
15+
import security.header as header_module
16+
from security.scope import ScopeError, allows, parse_entry, report_unmatched
17+
18+
19+
@pytest.fixture
20+
def client():
21+
return TestClient(app)
22+
23+
24+
# ── Parsing ──────────────────────────────────────────────────────────
25+
26+
27+
def test_parse_splits_method_from_path():
28+
assert parse_entry("GET /linbo/hosts/pc01/status") == (
29+
"GET", ("linbo", "hosts", "pc01", "status")
30+
)
31+
32+
33+
def test_parse_upper_cases_the_method():
34+
method, _ = parse_entry("get /devices/list/default-school")
35+
assert method == "GET"
36+
37+
38+
def test_parse_keeps_a_trailing_slash_as_a_segment():
39+
# /users and /users/ are different routes in this API.
40+
assert parse_entry("GET /users/") == ("GET", ("users", ""))
41+
assert parse_entry("GET /users") == ("GET", ("users",))
42+
43+
44+
@pytest.mark.parametrize("entry", [
45+
"GET", # no path
46+
"GET devices/list", # path not absolute
47+
"GET /linbo/**/status", # ** anywhere but last
48+
])
49+
def test_parse_rejects_malformed_entries(entry):
50+
with pytest.raises(ScopeError):
51+
parse_entry(entry)
52+
53+
54+
# ── Matching ─────────────────────────────────────────────────────────
55+
56+
57+
def test_no_scope_allows_everything():
58+
assert allows(None, "DELETE", "/users/olduser") is True
59+
assert allows("*", "DELETE", "/users/olduser") is True
60+
61+
62+
def test_exact_entry_allows_only_that_path():
63+
scope = ["GET /linbo/hosts/pc01/status"]
64+
assert allows(scope, "GET", "/linbo/hosts/pc01/status") is True
65+
assert allows(scope, "GET", "/linbo/hosts/pc02/status") is False
66+
67+
68+
def test_method_is_part_of_the_match():
69+
scope = ["GET /linbo/hosts/pc01/status"]
70+
assert allows(scope, "POST", "/linbo/hosts/pc01/status") is False
71+
assert allows(["* /linbo/hosts/pc01/status"], "POST", "/linbo/hosts/pc01/status") is True
72+
73+
74+
def test_single_wildcard_spans_exactly_one_segment():
75+
scope = ["GET /linbo/hosts/*/status"]
76+
assert allows(scope, "GET", "/linbo/hosts/pc01/status") is True
77+
assert allows(scope, "GET", "/linbo/hosts/status") is False
78+
assert allows(scope, "GET", "/linbo/hosts/a/b/status") is False
79+
80+
81+
def test_single_wildcard_does_not_match_an_empty_segment():
82+
# /devices/list/* must not open /devices/list/
83+
assert allows(["GET /devices/list/*"], "GET", "/devices/list/") is False
84+
85+
86+
def test_double_wildcard_spans_the_rest_of_the_path():
87+
scope = ["GET /linbo/**"]
88+
assert allows(scope, "GET", "/linbo/images") is True
89+
assert allows(scope, "GET", "/linbo/hosts/pc01/status") is True
90+
# It stands for at least one segment, not for none.
91+
assert allows(scope, "GET", "/linbo") is False
92+
# And it stays inside its prefix.
93+
assert allows(scope, "GET", "/devices/list/default-school") is False
94+
95+
96+
def test_several_entries_are_alternatives():
97+
scope = ["GET /linbo/hosts/*/status", "POST /linbo/sync/run"]
98+
assert allows(scope, "GET", "/linbo/hosts/pc01/status") is True
99+
assert allows(scope, "POST", "/linbo/sync/run") is True
100+
assert allows(scope, "POST", "/linbo/hosts/pc01/status") is False
101+
102+
103+
def test_an_unparsable_entry_is_dropped_not_fatal():
104+
# The bad entry was already reported at startup; the good one still works.
105+
scope = ["nonsense", "GET /linbo/hosts/pc01/status"]
106+
assert allows(scope, "GET", "/linbo/hosts/pc01/status") is True
107+
assert allows(scope, "GET", "/users/") is False
108+
109+
110+
def test_an_empty_scope_allows_nothing():
111+
assert allows([], "GET", "/linbo/hosts/pc01/status") is False
112+
113+
114+
# ── check_host_header() ──────────────────────────────────────────────
115+
116+
117+
@pytest.fixture
118+
def ldap_user(monkeypatch):
119+
"""Resolve any mapped user without touching LDAP."""
120+
121+
monkeypatch.setattr(
122+
header_module.lr, "getvalues",
123+
lambda *args, **kwargs: {
124+
"sophomorixRole": "schooladministrator",
125+
"sophomorixSchoolname": "default-school",
126+
"distinguishedName": "CN=helpdesk,OU=default-school,DC=linuxmuster,DC=lan",
127+
},
128+
)
129+
130+
131+
def _keys(scope):
132+
return {"helpdesk": {"secret": "s3cret", "user": "helpdesk", "ips": [], "scope": scope}}
133+
134+
135+
def test_a_key_is_refused_outside_its_scope(ldap_user):
136+
with pytest.raises(HTTPException) as refused:
137+
header_module.check_host_header(
138+
"s3cret", "10.0.5.12", _keys(["GET /linbo/hosts/*/status"]), True,
139+
"DELETE", "/users/someone",
140+
)
141+
142+
assert refused.value.status_code == 403
143+
144+
145+
def test_a_key_passes_inside_its_scope(ldap_user):
146+
who = header_module.check_host_header(
147+
"s3cret", "10.0.5.12", _keys(["GET /linbo/hosts/*/status"]), True,
148+
"GET", "/linbo/hosts/pc01/status",
149+
)
150+
151+
assert who.user == "helpdesk"
152+
assert who.role == "schooladministrator"
153+
154+
155+
def test_a_key_without_a_scope_is_unaffected(ldap_user):
156+
keys = {"srv": {"secret": "s3cret", "user": "helpdesk", "ips": []}}
157+
158+
who = header_module.check_host_header(
159+
"s3cret", "10.0.5.12", keys, True, "DELETE", "/users/someone",
160+
)
161+
162+
assert who.user == "helpdesk"
163+
164+
165+
def test_the_ip_check_still_runs_before_the_scope(ldap_user):
166+
keys = {"srv": {"secret": "s3cret", "user": "helpdesk", "ips": ["10.0.5.12"],
167+
"scope": ["GET /linbo/hosts/*/status"]}}
168+
169+
with pytest.raises(HTTPException) as refused:
170+
header_module.check_host_header(
171+
"s3cret", "192.168.0.1", keys, True, "GET", "/linbo/hosts/pc01/status",
172+
)
173+
174+
assert refused.value.status_code == 401
175+
176+
177+
# ── Startup report ───────────────────────────────────────────────────
178+
179+
180+
ROUTES = [
181+
("GET", "/users/"),
182+
("GET", "/linbo/hosts/{hostname}/status"),
183+
("POST", "/linbo/sync/run"),
184+
]
185+
186+
187+
def test_report_accepts_an_entry_matching_a_route_template():
188+
assert report_unmatched(["GET /linbo/hosts/pc01/status"], ROUTES) == []
189+
assert report_unmatched(["GET /linbo/hosts/*/status"], ROUTES) == []
190+
191+
192+
def test_report_flags_a_missing_trailing_slash():
193+
# /users exists only as /users/: the likeliest typo, and a silent one.
194+
assert report_unmatched(["GET /users"], ROUTES) == ["GET /users"]
195+
196+
197+
def test_report_flags_a_wrong_method():
198+
assert report_unmatched(["POST /users/"], ROUTES) == ["POST /users/"]
199+
200+
201+
def test_report_flags_an_unparsable_entry():
202+
assert report_unmatched(["nonsense"], ROUTES) == ["nonsense"]
203+
204+
205+
def test_report_says_nothing_about_an_unrestricted_key():
206+
assert report_unmatched(None, ROUTES) == []
207+
assert report_unmatched("*", ROUTES) == []
208+
209+
210+
# ── Through a real request ───────────────────────────────────────────
211+
212+
213+
@pytest.fixture
214+
def host_key(monkeypatch):
215+
"""
216+
Arm a scoped host key on the running app.
217+
218+
The mapped user is a globaladministrator so that RoleChecker lets every
219+
route through: what is left refusing anything is the scope alone.
220+
"""
221+
222+
monkeypatch.setattr(
223+
header_module.lr, "getvalues",
224+
lambda *args, **kwargs: {
225+
"sophomorixRole": "globaladministrator",
226+
"sophomorixSchoolname": "global",
227+
"distinguishedName": "CN=helpdesk,DC=linuxmuster,DC=lan",
228+
},
229+
)
230+
231+
def arm(scope):
232+
monkeypatch.setattr(app.state, "host_key_auth_enable", True, raising=False)
233+
monkeypatch.setattr(
234+
app.state, "host_keys",
235+
{"helpdesk": {"secret": "s3cret", "user": "helpdesk", "ips": [], "scope": scope}},
236+
raising=False,
237+
)
238+
return {"X-HOST-Key": "s3cret"}
239+
240+
return arm
241+
242+
243+
def test_a_scoped_key_reaches_the_route_it_names(host_key, client):
244+
# The scope is written without /v1, the request carries it: the prefix has
245+
# to be stripped between the two for anything to match at all.
246+
headers = host_key(["GET /schools/"])
247+
248+
assert client.get("/v1/schools/", headers=headers).status_code == 200
249+
250+
251+
def test_a_scoped_key_is_refused_elsewhere(host_key, client):
252+
headers = host_key(["GET /schools/"])
253+
254+
assert client.get("/v1/users/", headers=headers).status_code == 403
255+
256+
257+
def test_a_wildcard_scope_reaches_a_parameterised_route(host_key, client):
258+
headers = host_key(["GET /schools/*"])
259+
260+
# Any school, without the admin having to know FastAPI's {school}.
261+
assert client.get("/v1/schools/default-school", headers=headers).status_code in (200, 404)
262+
assert client.get("/v1/users/", headers=headers).status_code == 403
263+
264+
265+
def test_the_method_is_enforced_over_the_wire(host_key, client):
266+
headers = host_key(["POST /schools/"])
267+
268+
assert client.get("/v1/schools/", headers=headers).status_code == 403
269+
270+
271+
def test_a_key_without_a_scope_still_reaches_everything(host_key, client):
272+
headers = host_key(None)
273+
274+
assert client.get("/v1/schools/", headers=headers).status_code == 200
275+
assert client.get("/v1/users/", headers=headers).status_code == 200

0 commit comments

Comments
 (0)