Repository navigation
Expand file tree
/
Copy pathtest_ui_server.py
More file actions
501 lines (379 loc) · 17.7 KB
/
Copy pathtest_ui_server.py
File metadata and controls
501 lines (379 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import contextlib
import json
import os
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
import assertpy
import pytest
from fastapi.testclient import TestClient
from feast.ui_server import get_app
# Test constants
EXPECTED_SUCCESS_STATUS = 200
EXPECTED_ERROR_STATUS = 503
TEST_PROJECT_NAME = "test_project"
def _create_mock_ui_files(temp_dir):
"""Helper function to create required UI files structure"""
ui_dir = os.path.join(temp_dir, "ui", "build")
os.makedirs(ui_dir, exist_ok=True)
projects_file = os.path.join(ui_dir, "projects-list.json")
with open(projects_file, "w") as f:
json.dump({"projects": []}, f)
index_file = os.path.join(ui_dir, "index.html")
with open(index_file, "w") as f:
f.write("<html><body>Test UI</body></html>")
@contextlib.contextmanager
def _setup_importlib_mocks(temp_dir):
"""Helper function to setup importlib resource mocks."""
mock_path = Path(temp_dir)
mock_context_manager = MagicMock()
mock_context_manager.__enter__.return_value = mock_path
mock_context_manager.__exit__.return_value = None
mock_file_ref = MagicMock()
mock_file_ref.__truediv__.return_value = MagicMock()
with (
patch("feast.ui_server.importlib_resources.files") as mock_files,
patch("feast.ui_server.importlib_resources.as_file") as mock_as_file,
):
mock_files.return_value = mock_file_ref
mock_as_file.return_value = mock_context_manager
yield mock_files, mock_as_file
def _make_project_mock(name, description=""):
"""Create a mock project object with the given name and description."""
proj = MagicMock()
proj.name = name
proj.description = description
return proj
@pytest.fixture
def mock_feature_store():
"""Fixture for creating a mock feature store"""
mock_store = MagicMock()
return mock_store
@pytest.fixture
def ui_app_with_registry(mock_feature_store):
"""Fixture for UI app with valid registry data."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = []
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
yield app
@pytest.fixture
def ui_app_without_registry(mock_feature_store):
"""Fixture for UI app where registry raises on list_projects."""
mock_registry = MagicMock()
mock_registry.list_projects.side_effect = Exception("registry unavailable")
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
yield app
def test_ui_server_health_endpoint(ui_app_with_registry):
"""Health endpoint returns 200 when registry is available."""
client = TestClient(ui_app_with_registry)
response = client.get("/health")
assertpy.assert_that(response.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
def test_ui_server_exposes_version_under_rest_api(ui_app_with_registry):
"""Version endpoint is mounted under the authenticated REST API."""
client = TestClient(ui_app_with_registry)
with patch("feast.api.registry.rest.system.get_version", return_value="1.2.3"):
response = client.get("/api/v1/version")
assertpy.assert_that(response.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
assertpy.assert_that(response.json()).is_equal_to({"version": "1.2.3"})
def test_ui_server_health_endpoint_with_unavailable_registry(ui_app_without_registry):
"""Health endpoint returns 503 when registry is unavailable."""
client = TestClient(ui_app_without_registry)
response = client.get("/health")
assertpy.assert_that(response.status_code).is_equal_to(EXPECTED_ERROR_STATUS)
@pytest.mark.parametrize(
"registry_available,expected_status",
[(True, EXPECTED_SUCCESS_STATUS), (False, EXPECTED_ERROR_STATUS)],
)
def test_health_endpoint_status(
registry_available, expected_status, mock_feature_store
):
"""Health endpoint returns correct status based on registry availability."""
mock_registry = MagicMock()
if registry_available:
mock_registry.list_projects.return_value = []
else:
mock_registry.list_projects.side_effect = Exception("unavailable")
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
client = TestClient(app)
response = client.get("/health")
assertpy.assert_that(response.status_code).is_equal_to(expected_status)
def test_catch_all_route(ui_app_with_registry):
"""Test the catch-all route for React router paths."""
client = TestClient(ui_app_with_registry)
with pytest.raises(Exception):
client.get("/p/some/react/path")
# ---------- projects-list.json tests ----------
def _read_projects_list(app):
"""Fetch the projects-list.json from the dynamic endpoint."""
client = TestClient(app)
resp = client.get("/projects-list.json")
assertpy.assert_that(resp.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
return resp.json()
def test_projects_list_registry_path(mock_feature_store):
"""projects-list.json uses /api/v1 as registryPath."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = []
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
data = _read_projects_list(app)
assertpy.assert_that(data["projects"][0]["registryPath"]).is_equal_to("/api/v1")
def test_projects_list_with_root_path(mock_feature_store):
"""root_path prefix is included in registryPath."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = []
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(
mock_feature_store,
TEST_PROJECT_NAME,
root_path="/feast",
)
data = _read_projects_list(app)
assertpy.assert_that(data["projects"][0]["registryPath"]).is_equal_to(
"/feast/api/v1"
)
def test_projects_list_multiple_projects(mock_feature_store):
"""Multiple projects get an 'All Projects' entry prepended."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = [
_make_project_mock("project_alpha", "Alpha project"),
_make_project_mock("project_beta", "Beta project"),
]
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
data = _read_projects_list(app)
assertpy.assert_that(len(data["projects"])).is_equal_to(3)
assertpy.assert_that(data["projects"][0]["id"]).is_equal_to("all")
assertpy.assert_that(data["projects"][1]["id"]).is_equal_to("project_alpha")
assertpy.assert_that(data["projects"][2]["id"]).is_equal_to("project_beta")
def test_projects_list_fallback_on_empty(mock_feature_store):
"""When list_projects returns empty, fallback project is used."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = []
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
data = _read_projects_list(app)
assertpy.assert_that(len(data["projects"])).is_equal_to(1)
assertpy.assert_that(data["projects"][0]["id"]).is_equal_to(TEST_PROJECT_NAME)
def test_projects_list_fallback_on_exception(mock_feature_store):
"""When list_projects raises, fallback project is used."""
mock_registry = MagicMock()
mock_registry.list_projects.side_effect = Exception("not implemented")
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
data = _read_projects_list(app)
assertpy.assert_that(len(data["projects"])).is_equal_to(1)
assertpy.assert_that(data["projects"][0]["id"]).is_equal_to(TEST_PROJECT_NAME)
def test_projects_list_dynamic_refresh(mock_feature_store):
"""New projects appear without restarting the server."""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = [
_make_project_mock("picked_elk"),
]
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
client = TestClient(app)
data = client.get("/projects-list.json").json()
assertpy.assert_that(len(data["projects"])).is_equal_to(1)
assertpy.assert_that(data["projects"][0]["id"]).is_equal_to("picked_elk")
mock_registry.list_projects.return_value = [
_make_project_mock("picked_elk"),
_make_project_mock("picked_elk2"),
]
data = client.get("/projects-list.json").json()
assertpy.assert_that(len(data["projects"])).is_equal_to(3)
assertpy.assert_that(data["projects"][0]["id"]).is_equal_to("all")
assertpy.assert_that(data["projects"][1]["id"]).is_equal_to("picked_elk")
assertpy.assert_that(data["projects"][2]["id"]).is_equal_to("picked_elk2")
def test_registry_refresh_endpoint(mock_feature_store):
"""POST /api/v1/registry/refresh calls store.refresh_registry()."""
mock_feature_store.refresh_registry = MagicMock()
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
client = TestClient(app)
resp = client.post("/api/v1/registry/refresh")
assertpy.assert_that(resp.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
mock_feature_store.refresh_registry.assert_called_once()
def test_registry_refresh_endpoint_error(mock_feature_store):
"""POST /api/v1/registry/refresh returns 500 when refresh_registry raises."""
mock_feature_store.refresh_registry = MagicMock(
side_effect=Exception("registry unreachable")
)
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(mock_feature_store, TEST_PROJECT_NAME)
client = TestClient(app, raise_server_exceptions=False)
resp = client.post("/api/v1/registry/refresh")
assertpy.assert_that(resp.status_code).is_equal_to(500)
# ---------- CORS tests (CVE-2024-11602) ----------
@contextlib.contextmanager
def _cors_client(mock_feature_store, cors_origins):
"""Yield a TestClient for a UI app built with the given cors_origins.
The static-files directory is only valid while the TemporaryDirectory is
open, so the client must be used inside this context.
"""
mock_registry = MagicMock()
mock_registry.list_projects.return_value = []
mock_feature_store.registry = mock_registry
with tempfile.TemporaryDirectory() as temp_dir:
_create_mock_ui_files(temp_dir)
with _setup_importlib_mocks(temp_dir):
app = get_app(
mock_feature_store,
TEST_PROJECT_NAME,
cors_origins=cors_origins,
)
yield TestClient(app)
def test_cors_disabled_by_default(mock_feature_store):
"""Without cors_origins, no cross-origin request is granted.
Regression test for CVE-2024-11602: the server used to send
``Access-Control-Allow-Origin: *`` with credentials, letting any website a
user visits read authenticated responses from this server. The CVE's
proof of concept is exactly this -- a cross-origin GET carrying an Origin
header.
"""
with _cors_client(mock_feature_store, cors_origins=None) as client:
response = client.get("/health", headers={"Origin": "https://evil.example.com"})
assertpy.assert_that(response.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
assertpy.assert_that(response.headers).does_not_contain_key(
"access-control-allow-origin"
)
def test_cors_allows_only_configured_origins(mock_feature_store):
"""With an explicit allowlist, only trusted origins are echoed back."""
trusted = "https://feast.example.com"
with _cors_client(mock_feature_store, cors_origins=[trusted]) as client:
allowed = client.get("/health", headers={"Origin": trusted})
assertpy.assert_that(
allowed.headers.get("access-control-allow-origin")
).is_equal_to(trusted)
denied = client.get("/health", headers={"Origin": "https://evil.example.com"})
assertpy.assert_that(denied.headers).does_not_contain_key(
"access-control-allow-origin"
)
def test_cors_never_uses_wildcard(mock_feature_store):
"""An untrusted origin is never reflected even when an allowlist is set."""
with _cors_client(
mock_feature_store, cors_origins=["https://feast.example.com"]
) as client:
response = client.get(
"/health", headers={"Origin": "https://attacker.example.com"}
)
assertpy.assert_that(
response.headers.get("access-control-allow-origin")
).is_none()
def test_wildcard_cors_origin_is_allowed_but_warns(mock_feature_store, caplog):
"""An explicit '*' is honored (informed opt-in) but logs a warning.
We intentionally do not reject '*': it is a deliberate, documented operator
choice for local development (mirroring Feast's own `auth_type=no_auth`).
The warning makes the risk visible so it can't be set unknowingly.
"""
import logging
with caplog.at_level(logging.WARNING, logger="feast.ui_server"):
with _cors_client(mock_feature_store, cors_origins=["*"]) as client:
response = client.get(
"/health", headers={"Origin": "https://any.example.com"}
)
assertpy.assert_that(response.status_code).is_equal_to(EXPECTED_SUCCESS_STATUS)
assertpy.assert_that(caplog.text.lower()).contains("allow all origins")
@patch("feast.ui_server.uvicorn")
@patch("feast.ui_server.get_app")
def test_start_server_dual_stack_binds_prebuilt_socket(mock_get_app, mock_uvicorn):
"""host="::" must go through a pre-bound dual-stack socket, not
uvicorn.run(host="::"), which binds IPv6-only and drops IPv4 clients."""
from feast.ui_server import start_server
mock_app = MagicMock()
mock_get_app.return_value = mock_app
mock_sock = MagicMock()
with patch(
"feast.utils._make_dual_stack_socket", return_value=mock_sock
) as mock_make_sock:
start_server(
MagicMock(),
host="::",
port=8888,
project_id=TEST_PROJECT_NAME,
tls_key_path="key.pem",
tls_cert_path="cert.pem",
)
mock_make_sock.assert_called_once_with(8888)
mock_uvicorn.Config.assert_called_once_with(
mock_app, ssl_keyfile="key.pem", ssl_certfile="cert.pem"
)
mock_uvicorn.Server.assert_called_once_with(mock_uvicorn.Config.return_value)
mock_uvicorn.Server.return_value.run.assert_called_once_with(sockets=[mock_sock])
mock_uvicorn.run.assert_not_called()
@patch("feast.utils._make_dual_stack_socket")
@patch("feast.ui_server.uvicorn")
@patch("feast.ui_server.get_app")
def test_start_server_plain_host_uses_uvicorn_run(
mock_get_app, mock_uvicorn, mock_make_sock
):
"""A non dual-stack host keeps today's plain uvicorn.run behavior. Also
mocks _make_dual_stack_socket so a broken host comparison fails fast on
an assertion instead of hanging in a real uvicorn.Server.run()."""
from feast.ui_server import start_server
mock_app = MagicMock()
mock_get_app.return_value = mock_app
start_server(
MagicMock(),
host="0.0.0.0",
port=8888,
project_id=TEST_PROJECT_NAME,
)
mock_uvicorn.run.assert_called_once_with(mock_app, host="0.0.0.0", port=8888)
mock_uvicorn.Server.assert_not_called()
mock_make_sock.assert_not_called()
@patch("feast.utils._make_dual_stack_socket")
@patch("feast.ui_server.uvicorn")
@patch("feast.ui_server.get_app")
def test_start_server_non_wildcard_host_uses_uvicorn_run(
mock_get_app, mock_uvicorn, mock_make_sock
):
"""A host that sorts after "::" (e.g. starting with a letter) must still
take the plain uvicorn.run path -- regression test for a comparison
mutant (host == "::" weakened to >=) that a "0.0.0.0"-only test can't
catch, since "0.0.0.0" < "::" either way."""
from feast.ui_server import start_server
mock_app = MagicMock()
mock_get_app.return_value = mock_app
start_server(
MagicMock(),
host="example.com",
port=8888,
project_id=TEST_PROJECT_NAME,
)
mock_uvicorn.run.assert_called_once_with(mock_app, host="example.com", port=8888)
mock_uvicorn.Server.assert_not_called()
mock_make_sock.assert_not_called()