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_blocked_enforcement_startup.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_blocked_enforcement_startup.py · 9.2 KB · 197 lines
1"""What a box says at startup when enforcement is requested and something is wrong.
2
3DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true used to be a request that a
4readiness gate could decline: with no admin token, no usable policy or no
5sign-in path, every request ran unenforced (shadow mode) while the operator
6believed customers were fenced. So the server refused to start in that
7state unless DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT=true, which
8started it open.
9
10Requested enforcement is now always effective. The one refusal left is a
11missing admin token, because the token is the way in for every other
12problem. The override now starts the box ENFORCED without a token, and says
13so. Other problems start the box enforced with a WARNING, and /admin/status
14leads with an alert that says enforcement is ON and what the problem does.
15"""
16from __future__ import annotations
17
18import asyncio
19import logging
20
21import pytest
22
23import object_server
24from test_object_server import request
25
26TOKEN = "t" * 32
27
28
29def run_lifespan():
30 sent = []
31 inbox = [{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}]
32
33 async def receive():
34 return inbox.pop(0)
35
36 async def send(message):
37 sent.append(message)
38
39 asyncio.run(object_server._handle_lifespan(receive, send))
40 return sent
41
42
43@pytest.fixture
44def no_token(tmp_path, monkeypatch):
45 """Enforcement requested, no admin token and no policy."""
46 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
47 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
48 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
49 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
50 monkeypatch.delenv(object_server.ALLOW_BLOCKED_ENFORCEMENT_START_ENV, raising=False)
51 monkeypatch.delenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, raising=False)
52 return tmp_path
53
54
55def test_enforcement_without_an_admin_token_refuses_to_start_and_logs_an_error(no_token, caplog, capsys):
56 with caplog.at_level(logging.ERROR):
57 sent = run_lifespan()
58 assert sent[0]["type"] == "lifespan.startup.failed"
59 message = sent[0]["message"]
60 assert message.startswith("Refusing to start:")
61 assert object_server.ADMIN_TOKEN_ENV in message and "Set it and start again" in message
62 assert "UNENFORCED" not in message and "BLOCKED" not in message
63 assert any(r.levelno == logging.ERROR and "Refusing to start" in r.getMessage() for r in caplog.records)
64 assert "ERROR" in capsys.readouterr().err
65
66
67def test_a_failing_diagnostic_does_not_skip_the_missing_token_refusal(no_token, monkeypatch):
68 """The diagnostics are wrapped so they cannot take the box down; the token check
69 sat inside that wrapper, so an unexpected error started an enforced box with no
70 way in over HTTP."""
71 def boom():
72 raise RuntimeError("diagnostic bug")
73
74 monkeypatch.setattr(object_server, "_permission_enforcement_problems", boom)
75 sent = run_lifespan()
76 assert sent[0]["type"] == "lifespan.startup.failed"
77 assert object_server.ADMIN_TOKEN_ENV in sent[0]["message"]
78
79
80def test_override_starts_enforced_without_an_admin_token_and_says_so(no_token, monkeypatch, caplog, capsys):
81 monkeypatch.setenv(object_server.ALLOW_BLOCKED_ENFORCEMENT_START_ENV, "true")
82 with caplog.at_level(logging.ERROR):
83 sent = run_lifespan()
84 assert sent[0]["type"] == "lifespan.startup.complete"
85 err = capsys.readouterr().err
86 assert "starting ENFORCED without DBBASIC_ADMIN_TOKEN" in err
87 assert "no longer runs requests unenforced" in err
88 assert f"{object_server.PERMISSION_ENFORCEMENT_ENV}=false" in err # the way to go unenforced on purpose
89 assert "goes away in a later release" in err
90 assert object_server._permission_enforcement_enabled() is True
91 assert object_server._permission_mode() == "enforced"
92 # enforced: an anonymous caller gets the default (deny-all) policy, not the data
93 status, _, payload = request("/collections/anything/records")
94 assert status in (401, 403, 404), payload
95
96
97def test_enforcement_not_requested_starts_quietly(no_token, monkeypatch, caplog):
98 monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV)
99 with caplog.at_level(logging.ERROR):
100 sent = run_lifespan()
101 assert sent[0]["type"] == "lifespan.startup.complete"
102 assert not caplog.records
103
104
105def test_admin_status_alert_says_enforced_and_names_the_problem(no_token, monkeypatch):
106 # An admin token but no sign-in path: enforced, only the admin token and
107 # public grants get in. That is a problem worth an alert, not an open box.
108 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TOKEN)
109 status, _, payload = request("/admin/status", headers=[("authorization", f"Token {TOKEN}")])
110 assert status == 200
111 perm = payload["capabilities"]["permission_enforcement"]
112 assert perm["blocked"] is False and perm["enabled"] is True and perm["mode"] == "enforced"
113 assert perm["problems"] and perm["blockers"] == perm["problems"] and perm["fix"]
114 alert = payload["alerts"][0]
115 assert alert.startswith("Permission enforcement is ON")
116 assert "No non-admin sign-in path" in alert
117 assert "NOT being enforced" not in alert and "BLOCKED" not in alert
118
119
120def test_problems_name_the_missing_admin_token(no_token):
121 problems = object_server._permission_enforcement_problems()
122 assert any(p.startswith("No admin token") for p in problems)
123
124
125def test_allow_unready_is_a_noop_and_says_so_at_start(no_token, monkeypatch, capsys):
126 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TOKEN)
127 monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true")
128 assert run_lifespan()[0]["type"] == "lifespan.startup.complete"
129 assert "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT is no longer needed" in capsys.readouterr().err
130 status, _, payload = request("/permissions/status", headers=[("authorization", f"Token {TOKEN}")])
131 assert status == 200
132 assert payload["permissions"]["allow_unready_enforcement"] is True # kept one release
133 assert any("no longer does anything" in w for w in payload["warnings"])
134
135
136def test_healthy_server_has_no_alerts_and_starts(tmp_path, monkeypatch):
137 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
138 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
139 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TOKEN)
140 monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV, raising=False)
141 status, _, payload = request("/admin/status", headers=[("authorization", f"Token {TOKEN}")])
142 assert status == 200 and payload["alerts"] == []
143 assert run_lifespan()[0]["type"] == "lifespan.startup.complete"
144
145
146# --- DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT -----------------------------------
147# A hosted, multi-user box must never come up with enforcement off. The flag
148# is opt-in: unset, a box with enforcement off or in audit starts as before.
149
150@pytest.fixture
151def requirable(no_token, monkeypatch):
152 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TOKEN)
153 monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV)
154 monkeypatch.delenv(object_server.PERMISSION_AUDIT_ENV, raising=False)
155 monkeypatch.delenv(object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV, raising=False)
156 return no_token
157
158
159@pytest.mark.parametrize("mode", ["off", "audit"])
160def test_required_enforcement_refuses_to_start_unless_enforced(requirable, monkeypatch, caplog,
161 capsys, mode):
162 if mode == "audit":
163 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
164 monkeypatch.setenv(object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV, "1")
165 with caplog.at_level(logging.ERROR):
166 sent = run_lifespan()
167 assert sent[0]["type"] == "lifespan.startup.failed"
168 message = sent[0]["message"]
169 assert message.startswith("Refusing to start:") and "\n" not in message
170 assert object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV in message
171 assert f"enforcement is {mode}" in message
172 assert f"{object_server.PERMISSION_ENFORCEMENT_ENV}=true" in message
173 assert any("Refusing to start" in r.getMessage() for r in caplog.records)
174 assert "ERROR" in capsys.readouterr().err
175
176
177def test_required_enforcement_refuses_an_enforcement_flag_that_is_not_true(requirable, monkeypatch):
178 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "ture")
179 monkeypatch.setenv(object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV, "true")
180 assert run_lifespan()[0]["type"] == "lifespan.startup.failed"
181
182
183def test_required_enforcement_starts_when_enforced(requirable, monkeypatch):
184 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
185 monkeypatch.setenv(object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV, "true")
186 assert run_lifespan()[0]["type"] == "lifespan.startup.complete"
187
188
189@pytest.mark.parametrize("required", [None, "false", "0"])
190@pytest.mark.parametrize("mode", ["off", "audit"])
191def test_without_the_requirement_off_and_audit_start_as_before(requirable, monkeypatch,
192 required, mode):
193 if mode == "audit":
194 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
195 if required is not None:
196 monkeypatch.setenv(object_server.REQUIRE_PERMISSION_ENFORCEMENT_ENV, required)
197 assert run_lifespan()[0]["type"] == "lifespan.startup.complete"