Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_identity_audience_signal.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_identity_audience_signal.py · 10.3 KB · 269 lines
1"""An identity upstream that answers without this server's audience leaves a sign.
2
3The refusal itself is old and unchanged (everyone it vouches for arrives as
4anonymous). What was missing was any trace: no ops-log row, no /admin/status
5alert, so a cutover against an upstream that had not been updated looked like
6"everyone is logged out" with nothing pointing at the cause.
7"""
8
9from __future__ import annotations
10
11import json
12
13import pytest
14
15import object_identity_sources
16import object_server
17from tests.test_identity_sources import AUDIENCE, box, stub, tok # noqa: F401
18from tests.test_object_server import auth_headers, request
19
20EVENT = object_server.IDENTITY_AUDIENCE_OPS_EVENT
21
22
23@pytest.fixture(autouse=True)
24def fresh_throttle(monkeypatch):
25 monkeypatch.setattr(object_server, "_IDENTITY_AUDIENCE_LOGGED", {})
26
27
28def _rows():
29 status, _, payload = request(
30 "/admin/ops", query_string=f"kind=auth&event={EVENT}", headers=auth_headers()
31 )
32 assert status == 200, payload
33 return [row for row in payload["events"] if row.get("event") == EVENT]
34
35
36def _alerts():
37 status, _, payload = request("/admin/status", headers=auth_headers())
38 assert status == 200, payload
39 return [a for a in payload["alerts"] if "identity upstream" in a]
40
41
42def _anonymous(token="tok-user-1"):
43 _, _, payload = request("/identity", headers=tok(token))
44 return payload["subject"]["user_id"] is None
45
46
47def test_an_answer_without_the_audience_key_is_a_row_and_an_alert(box, stub):
48 stub.audience = None
49 assert _anonymous() # the refusal is unchanged
50 [row] = _rows()
51 assert row["auth_method"] == "identity_source:http_verify"
52 assert row["label"] == "reason=audience_missing refused=1"
53 assert not row.get("user_id") and not row.get("identifier")
54 [alert] = _alerts()
55 assert 'without the "audience" key' in alert
56 assert "sign-ins through it are refused" in alert
57 assert "DBBASIC_IDENTITY_AUDIENCE" in alert and "X-DBBASIC-Audience" in alert
58 # Nothing of the token, the user, the URL or the audience value.
59 dumped = json.dumps([row, alert])
60 for secret in ("tok-user-1", "alice", stub.url, "127.0.0.1", AUDIENCE):
61 assert secret not in dumped
62
63
64@pytest.mark.parametrize("wrong", ["other-box.example", "", ["box-test.example"], 7])
65def test_an_answer_with_another_audience_is_a_mismatch_row_and_alert(box, stub, wrong):
66 stub.audience = wrong
67 assert _anonymous()
68 [row] = _rows()
69 assert row["label"] == "reason=audience_mismatch refused=1"
70 [alert] = _alerts()
71 assert "that is not this server's name" in alert
72 assert "other-box.example" not in json.dumps([row, alert])
73
74
75def test_the_right_audience_leaves_no_row_and_no_alert(box, stub):
76 assert not _anonymous()
77 # A token the upstream does not know (401) is not an audience problem.
78 assert _anonymous("tok-nobody")
79 assert _rows() == []
80 assert _alerts() == []
81
82
83def test_the_alert_clears_once_the_upstream_names_this_server(box, stub):
84 stub.audience = None
85 assert _anonymous()
86 assert _alerts()
87 stub.audience = AUDIENCE
88 assert not _anonymous("tok-user-2")
89 assert _alerts() == []
90
91
92def test_the_alert_ends_when_the_refusals_are_old(box, stub, monkeypatch):
93 stub.audience = None
94 assert _anonymous()
95 assert _alerts()
96 monkeypatch.setattr(object_server, "IDENTITY_AUDIENCE_ALERT_SECONDS", 0.0)
97 assert _alerts() == []
98
99
100def test_one_row_a_minute_per_reason(box, stub, monkeypatch):
101 stub.audience = None
102 for token in ("tok-user-1", "tok-user-2", "tok-staff"):
103 assert _anonymous(token)
104 assert stub.calls == 3
105 assert [row["label"] for row in _rows()] == ["reason=audience_missing refused=1"]
106
107 # The other reason has its own minute.
108 stub.audience = "other-box.example"
109 assert _anonymous("tok-bool")
110 assert _anonymous("tok-not-numeric")
111 assert sorted(row["label"] for row in _rows()) == [
112 "reason=audience_mismatch refused=1",
113 "reason=audience_missing refused=1",
114 ]
115
116 # A minute later the next refusal is a row again, and the refusals the
117 # limit skipped are counted in a row of their own reason.
118 logged = object_server._IDENTITY_AUDIENCE_LOGGED
119 for key, (at, count) in list(logged.items()):
120 logged[key] = (at - object_server.IDENTITY_AUDIENCE_OPS_SECONDS - 1, count)
121 object_identity_sources.forget()
122 assert _anonymous("tok-user-1")
123 labels = sorted(row["label"] for row in _rows())
124 assert labels == [
125 "reason=audience_mismatch refused=1",
126 "reason=audience_mismatch refused=2",
127 "reason=audience_missing refused=1",
128 "reason=audience_missing refused=2",
129 ]
130
131
132@pytest.mark.parametrize("mode", ["html_type", "not_json", "a_list"])
133def test_a_200_that_is_not_a_json_object_is_a_not_json_row_and_alert(box, stub, monkeypatch, mode):
134 """An upstream that redirects to its login page answers 200 HTML."""
135 if mode == "a_list":
136 # A JSON list where an object belongs.
137 source = object_identity_sources.configured_sources()[0]
138 monkeypatch.setattr(
139 source, "fetch", lambda *args: (200, b'[{"user_id": 1}]', "application/json")
140 )
141 else:
142 stub.mode = mode
143 assert _anonymous() # the refusal is unchanged
144 [row] = _rows()
145 assert row["label"] == "reason=not_json refused=1"
146 assert row["auth_method"] == "identity_source:http_verify"
147 [alert] = _alerts()
148 assert "something that is not a JSON object" in alert
149 assert "sign-ins through it are refused" in alert
150 dumped = json.dumps([row, alert])
151 for secret in ("tok-user-1", "hello", stub.url, "127.0.0.1", AUDIENCE):
152 assert secret not in dumped
153
154
155def test_not_json_has_its_own_minute_and_clears_with_a_good_answer(box, stub):
156 stub.mode = "not_json"
157 assert _anonymous("tok-user-1")
158 assert _anonymous("tok-user-2")
159 stub.mode = "ok"
160 stub.audience = None
161 assert _anonymous("tok-staff")
162 assert sorted(row["label"] for row in _rows()) == [
163 "reason=audience_missing refused=1",
164 "reason=not_json refused=1",
165 ]
166 [alert] = _alerts()
167 assert "not a JSON object" in alert and 'without the "audience" key' in alert
168 stub.audience = AUDIENCE
169 object_identity_sources.forget()
170 assert not _anonymous("tok-user-2")
171 assert _alerts() == []
172
173
174# --- an upstream that refuses this server itself (HTTP 403) -----------------
175#
176# An upstream that checks X-DBBASIC-Verify-Secret and X-DBBASIC-Audience
177# answers 403 to a request that fails either, whatever the token. That is
178# not one user's bad token: it refuses everyone, so it gets the same row and
179# alert. A 401 is one token the upstream does not know and stays silent.
180
181UPSTREAM_SECRET = "made-up-upstream-secret-0123456789"
182WRONG_SECRET = "made-up-wrong-secret-9876543210ab"
183
184
185def _secret_here(monkeypatch, value):
186 if value is None:
187 monkeypatch.delenv(object_identity_sources.IDENTITY_VERIFY_SECRET_ENV, raising=False)
188 else:
189 monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_SECRET_ENV, value)
190 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
191
192
193@pytest.mark.parametrize("here", [WRONG_SECRET, None])
194def test_an_upstream_refusing_this_server_is_a_row_and_an_alert(box, stub, monkeypatch, here):
195 stub.expect_secret = UPSTREAM_SECRET
196 _secret_here(monkeypatch, here)
197 assert _anonymous() # the refusal is unchanged
198 status, _, _ = request("/objects", query_string="format=json", headers=tok("tok-user-1"))
199 assert status == 401 # as before: a token nobody vouched for
200 assert stub.calls == 1 # the refusal is cached as before
201 [row] = _rows()
202 assert row["auth_method"] == "identity_source:http_verify"
203 assert row["label"] == "reason=upstream_forbidden refused=1"
204 assert not row.get("user_id") and not row.get("identifier")
205 [alert] = _alerts()
206 assert "refusing this server's verify requests (HTTP 403)" in alert
207 assert "every sign-in through it is refused" in alert
208 assert "DBBASIC_IDENTITY_VERIFY_SECRET" in alert
209 assert "DBBASIC_IDENTITY_AUDIENCE" in alert
210 assert "audience\" key" not in alert # not an audience-echo problem
211 dumped = json.dumps([row, alert])
212 for secret in (UPSTREAM_SECRET, WRONG_SECRET, "tok-user-1", "alice", stub.url,
213 "127.0.0.1", AUDIENCE):
214 assert secret not in dumped
215
216
217def test_a_401_is_one_bad_token_and_leaves_no_row_and_no_alert(box, stub, monkeypatch):
218 stub.expect_secret = UPSTREAM_SECRET
219 _secret_here(monkeypatch, UPSTREAM_SECRET)
220 assert not _anonymous()
221 for token in ("tok-nobody", "tok-unknown", "tok-nope"):
222 assert _anonymous(token)
223 assert _rows() == []
224 assert _alerts() == []
225
226
227def test_the_forbidden_alert_clears_once_the_upstream_accepts_this_server(box, stub, monkeypatch):
228 stub.expect_secret = UPSTREAM_SECRET
229 _secret_here(monkeypatch, WRONG_SECRET)
230 assert _anonymous()
231 assert _alerts()
232 stub.expect_secret = WRONG_SECRET # the upstream's secret is corrected
233 object_identity_sources.forget()
234 assert not _anonymous("tok-user-2")
235 assert _alerts() == []
236
237
238def test_one_forbidden_row_a_minute(box, stub, monkeypatch):
239 stub.expect_secret = UPSTREAM_SECRET
240 _secret_here(monkeypatch, WRONG_SECRET)
241 for token in ("tok-user-1", "tok-user-2", "tok-staff"):
242 assert _anonymous(token)
243 assert stub.calls == 3
244 assert [row["label"] for row in _rows()] == ["reason=upstream_forbidden refused=1"]
245
246 logged = object_server._IDENTITY_AUDIENCE_LOGGED
247 for key, (at, count) in list(logged.items()):
248 logged[key] = (at - object_server.IDENTITY_AUDIENCE_OPS_SECONDS - 1, count)
249 object_identity_sources.forget()
250 assert _anonymous("tok-user-1")
251 assert sorted(row["label"] for row in _rows()) == [
252 "reason=upstream_forbidden refused=1",
253 "reason=upstream_forbidden refused=3",
254 ]
255
256
257def test_forbidden_and_audience_missing_are_both_named(box, stub):
258 stub.audience = None
259 assert _anonymous("tok-user-1")
260 stub.expect_secret = UPSTREAM_SECRET # this box sends none: 403
261 assert _anonymous("tok-user-2")
262 assert sorted(row["label"] for row in _rows()) == [
263 "reason=audience_missing refused=1",
264 "reason=upstream_forbidden refused=1",
265 ]
266 [alert] = _alerts()
267 assert "(HTTP 403)" in alert and "DBBASIC_IDENTITY_VERIFY_SECRET" in alert
268 assert 'without the "audience" key' in alert
269 assert UPSTREAM_SECRET not in alert