From e17717b5c977348c619e0c48988c3f68ecc096aa Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Wed, 19 Aug 2026 19:36:51 +0530 Subject: [PATCH 1/6] test: Add failing regression test for remote online store provisioning Applying a new feature view through a client whose online store is `type: remote` leaves it unwritable: the feature view reaches the registry, but no table is provisioned server-side, so the write that `feast materialize` performs returns HTTP 500 with `no such table`. The existing test_remote_online_store_read_write does apply a feature view through a remote client and write to it, but it applies `driver_hourly_stats` -- a name the server already provisioned during its own `feast apply` at setup. The table exists before the client touches it, which masks the bug. This test applies a feature view the server has never seen. The assertion is on the user-visible contract (a feature view applied through a remote online store must be writable) rather than on any particular mechanism, so it holds regardless of how the fix is implemented. Refs #6693 Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- .../test_remote_online_store_provisioning.py | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py diff --git a/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py new file mode 100644 index 00000000000..7ead4a8b33d --- /dev/null +++ b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py @@ -0,0 +1,217 @@ +""" +Regression test for feast-dev/feast#6693. + + 'feast apply' does not create online store tables in remote mode. + +Contract under test (holds regardless of how the fix is implemented): + + Applying a NEW feature view through a client whose online store is + `type: remote` must leave that feature view writable. Today it does not: + the feature view lands in the registry, but no table is ever provisioned + server-side, so the write that `feast materialize` performs returns 500. + +Note on the existing coverage: `test_remote_online_store_read_write` in +sdk/python/tests/integration/online_store/test_remote_online_store.py already +applies a feature view through a remote client and writes to it, and passes. +It passes because it applies `driver_hourly_stats` -- a name the server had +already provisioned during its own `feast apply` at setup. The table exists +before the client ever touches it, which masks the bug. This test applies a +feature view the server has never seen. +""" + +import os +import socket +import subprocess +import tempfile +import time +from datetime import timedelta +from textwrap import dedent + +import pandas as pd +import pytest + +from feast import Entity, FeatureStore, FeatureView, FileSource +from feast.driver_test_data import create_driver_hourly_stats_df +from feast.field import Field +from feast.types import Float32, Int64 +from feast.utils import _utc_now + +FEAST_BIN = "feast" +PROJECT = "remote_provisioning" + +# A feature view name the server has never applied. This is the whole point. +NEW_FV_NAME = "never_applied_server_side" + + +def _free_port() -> int: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def _port_open(host: str, port: int) -> bool: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(1.0) + return s.connect_ex((host, port)) == 0 + + +@pytest.fixture(scope="module") +def remote_server(): + """`feast init` + `feast apply` + `feast serve`, backed by SQLite.""" + tmp = tempfile.mkdtemp(prefix="feast_6693_server_") + + subprocess.run( + [FEAST_BIN, "init", PROJECT], cwd=tmp, capture_output=True, check=True + ) + repo_path = os.path.join(tmp, PROJECT, "feature_repo") + subprocess.run( + [FEAST_BIN, "-c", repo_path, "apply"], cwd=tmp, capture_output=True, check=True + ) + + registry_path = os.path.join(repo_path, "data", "registry.db") + assert os.path.exists(registry_path), "server registry was not created" + + port = _free_port() + # Log to files, NOT subprocess.PIPE: `feast serve` is chatty, and an + # undrained pipe fills its 64K OS buffer and deadlocks the server. + log_path = os.path.join(tmp, "server.log") + log_file = open(log_path, "w") + proc = subprocess.Popen( + [ + FEAST_BIN, + "-c", + repo_path, + "serve", + "--host", + "127.0.0.1", + "--port", + str(port), + ], + stdout=log_file, + stderr=subprocess.STDOUT, + text=True, + ) + + def _server_log() -> str: + log_file.flush() + with open(log_path) as f: + return f.read() + + deadline = time.time() + 90 + while time.time() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"feast serve exited early:\n{_server_log()}") + if _port_open("127.0.0.1", port): + break + time.sleep(1) + else: + proc.kill() + raise RuntimeError(f"feast serve did not come up in 90s:\n{_server_log()}") + + yield { + "url": f"http://127.0.0.1:{port}", + "registry_path": registry_path, + "server_log": _server_log, + } + + proc.kill() + proc.wait(timeout=30) + log_file.close() + + +@pytest.fixture(scope="module") +def client_store(remote_server) -> FeatureStore: + """A client whose online store is the remote feature server.""" + tmp = tempfile.mkdtemp(prefix="feast_6693_client_") + with open(os.path.join(tmp, "feature_store.yaml"), "w") as f: + f.write( + dedent( + f""" + project: {PROJECT} + registry: {remote_server["registry_path"]} + provider: local + entity_key_serialization_version: 3 + auth: + type: no_auth + online_store: + type: remote + path: {remote_server["url"]} + """ + ).strip() + ) + return FeatureStore(repo_path=tmp) + + +def _new_feature_view(data_path: str) -> tuple: + driver = Entity(name="driver_id", description="Driver id") + source = FileSource( + path=data_path, + timestamp_field="event_timestamp", + created_timestamp_column="created", + ) + fv = FeatureView( + name=NEW_FV_NAME, + entities=[driver], + ttl=timedelta(days=1), + schema=[ + Field(name="conv_rate", dtype=Float32), + Field(name="avg_daily_trips", dtype=Int64), + ], + source=source, + ) + return driver, source, fv + + +@pytest.mark.integration +def test_apply_through_remote_online_store_provisions_the_table( + client_store, remote_server +): + """A feature view applied through a remote online store must be writable. + + Fails before the fix with HTTP 500 / `no such table`, because + RemoteOnlineStore.update() is a no-op and nothing provisions server-side. + """ + # A real parquet file, so nothing fails for want of a source on disk. + data_dir = os.path.join(client_store.repo_path, "data") + os.makedirs(data_dir, exist_ok=True) + data_path = os.path.join(data_dir, "driver_stats.parquet") + end = _utc_now().replace(microsecond=0, second=0, minute=0) + create_driver_hourly_stats_df([1001], end - timedelta(days=1), end).to_parquet( + path=data_path, allow_truncated_timestamps=True + ) + + driver, source, fv = _new_feature_view(data_path) + client_store.apply([driver, fv]) + + # The registry accepted it -- the feature view genuinely exists. + assert NEW_FV_NAME in [v.name for v in client_store.list_feature_views()] + + now = pd.Timestamp(_utc_now()).round("ms") + df = pd.DataFrame( + { + "driver_id": [1001], + "conv_rate": [0.75], + "avg_daily_trips": [42], + "event_timestamp": [now], + "created": [now], + } + ) + + # This is what `feast materialize` does through the feature server. + try: + client_store.write_to_online_store(feature_view_name=NEW_FV_NAME, df=df) + except Exception: + print("\n------------------- server log (tail) -------------------") + print(remote_server["server_log"]()[-4000:]) + print("---------------------------------------------------------") + raise + + features = client_store.get_online_features( + features=[f"{NEW_FV_NAME}:conv_rate", f"{NEW_FV_NAME}:avg_daily_trips"], + entity_rows=[{"driver_id": 1001}], + ).to_dict() + + assert features["avg_daily_trips"] == [42] + assert round(features["conv_rate"][0], 2) == 0.75 From bd367e48d8f412d6ea65f2c04cd20d6e58ddfa2e Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Wed, 19 Aug 2026 19:47:19 +0530 Subject: [PATCH 2/6] fix: Provision online store infra for remote feast apply `feast apply` against `online_store: type: remote` registered feature views but never created their tables, so `feast materialize` failed with HTTP 500 and `no such table`. `RemoteOnlineStore.update()` and `.teardown()` were both `pass`, and the feature server never calls `update_infra()` on its own -- it only refreshes the registry. Since table DDL lives exclusively in the concrete online store's `update()`, this affected any online store behind `type: remote`, not just SQLite. RemoteOnlineStore.update()/teardown() now call two new feature server endpoints, /update-infra and /teardown-infra, which run update_infra() and teardown_infra() against the server's real online store. The objects travel in the request body as base64-encoded protos rather than being looked up server-side by name, because FeatureStore.apply() calls update_infra() *before* registry.commit() -- at that point the server cannot see them yet, and with a file registry they are not even on disk. Authorization reuses the existing CREATE and DELETE actions, so no new permission surface is introduced. Fixes #6693 Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- .../feature-servers/python-feature-server.md | 2 + sdk/python/feast/feature_server.py | 77 ++++++++++ .../feast/infra/online_stores/remote.py | 134 ++++++++++++++++- .../online_store/test_remote_online_store.py | 139 +++++++++++++++++- 4 files changed, 349 insertions(+), 3 deletions(-) diff --git a/docs/reference/feature-servers/python-feature-server.md b/docs/reference/feature-servers/python-feature-server.md index b1b873cc7d2..23d0d97e0e7 100644 --- a/docs/reference/feature-servers/python-feature-server.md +++ b/docs/reference/feature-servers/python-feature-server.md @@ -643,6 +643,8 @@ The [PyTorch NLP template](https://github.com/feast-dev/feast/tree/main/sdk/pyth | /write-to-online-store | FeatureView | Write Online | Write features to the online store | | /materialize | FeatureView | Write Online | Materialize features within a specified time range | | /materialize-incremental | FeatureView | Write Online | Incrementally materialize features up to a specified timestamp | +| /update-infra | FeatureView | Create, Delete | Provision online store infrastructure for a remote `feast apply` | +| /teardown-infra | FeatureView | Delete | Drop online store infrastructure for a remote `feast teardown` | ## How to configure Authentication and Authorization ? diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index e42e28d6db9..e7c7eda9bbc 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -83,6 +83,29 @@ class WriteToFeatureStoreRequest(BaseModel): transform_on_write: bool = True +class UpdateInfraRequest(BaseModel): + """Objects to provision, sent by RemoteOnlineStore.update(). + + Each entry is `{"type": , "proto": }`. They are + carried in the body rather than looked up in the registry because + `FeatureStore.apply()` runs `update_infra()` before `registry.commit()`, + so the server cannot see them yet. + """ + + tables_to_delete: List[Dict[str, str]] = [] + tables_to_keep: List[Dict[str, str]] = [] + entities_to_delete: List[Dict[str, str]] = [] + entities_to_keep: List[Dict[str, str]] = [] + partial: bool = False + + +class TeardownInfraRequest(BaseModel): + """Objects to tear down, sent by RemoteOnlineStore.teardown().""" + + tables: List[Dict[str, str]] = [] + entities: List[Dict[str, str]] = [] + + class PushFeaturesRequest(BaseModel): push_source_name: str df: dict @@ -932,6 +955,60 @@ async def write_to_online_store(request: WriteToFeatureStoreRequest) -> None: transform_on_write=request.transform_on_write, ) + @app.post("/update-infra", dependencies=[Depends(inject_user_details)]) + async def update_infra(request: UpdateInfraRequest) -> None: + """Provision online store infrastructure on behalf of a remote client. + + `feast apply` against `online_store: type: remote` cannot create tables + itself -- the concrete online store lives here. Without this the feature + view is registered but its table never exists (#6693). + """ + # Imported here, not at module scope: feast.infra.online_stores.remote + # imports from `feast`, which is still initializing when this module loads. + from feast.infra.online_stores.remote import decode_infra_object + + tables_to_keep = [decode_infra_object(o) for o in request.tables_to_keep] + tables_to_delete = [decode_infra_object(o) for o in request.tables_to_delete] + entities_to_keep = [decode_infra_object(o) for o in request.entities_to_keep] + entities_to_delete = [ + decode_infra_object(o) for o in request.entities_to_delete + ] + + for table in tables_to_keep: + assert_permissions(resource=table, actions=[AuthzedAction.CREATE]) + for table in tables_to_delete: + assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) + + await run_in_threadpool( + store._get_provider().update_infra, + project=store.project, + tables_to_delete=tables_to_delete, + tables_to_keep=tables_to_keep, + entities_to_delete=entities_to_delete, + entities_to_keep=entities_to_keep, + partial=request.partial, + ) + + @app.post("/teardown-infra", dependencies=[Depends(inject_user_details)]) + async def teardown_infra(request: TeardownInfraRequest) -> None: + """Drop online store infrastructure on behalf of a remote client.""" + # Imported here, not at module scope: feast.infra.online_stores.remote + # imports from `feast`, which is still initializing when this module loads. + from feast.infra.online_stores.remote import decode_infra_object + + tables = [decode_infra_object(o) for o in request.tables] + entities = [decode_infra_object(o) for o in request.entities] + + for table in tables: + assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) + + await run_in_threadpool( + store._get_provider().teardown_infra, + project=store.project, + tables=tables, + entities=entities, + ) + @app.get("/health") async def health(): try: diff --git a/sdk/python/feast/infra/online_stores/remote.py b/sdk/python/feast/infra/online_stores/remote.py index 8aa5df1563e..add4278a28a 100644 --- a/sdk/python/feast/infra/online_stores/remote.py +++ b/sdk/python/feast/infra/online_stores/remote.py @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import base64 import json import logging import uuid as uuid_module @@ -60,6 +61,67 @@ logger = logging.getLogger(__name__) +def _infra_object_types() -> Dict[str, Tuple[Any, Any]]: + """Map type name -> (feast class, proto class) for objects sent to /update-infra. + + Imported lazily: these modules import from `feast` at module scope, and + pulling them in at the top of this file would create an import cycle. + """ + from feast.labeling.label_view import LabelView + from feast.on_demand_feature_view import OnDemandFeatureView + from feast.protos.feast.core.Entity_pb2 import Entity as EntityProto + from feast.protos.feast.core.FeatureView_pb2 import FeatureView as FeatureViewProto + from feast.protos.feast.core.LabelView_pb2 import LabelView as LabelViewProto + from feast.protos.feast.core.OnDemandFeatureView_pb2 import ( + OnDemandFeatureView as OnDemandFeatureViewProto, + ) + from feast.protos.feast.core.StreamFeatureView_pb2 import ( + StreamFeatureView as StreamFeatureViewProto, + ) + from feast.stream_feature_view import StreamFeatureView + + return { + "FeatureView": (FeatureView, FeatureViewProto), + "StreamFeatureView": (StreamFeatureView, StreamFeatureViewProto), + "OnDemandFeatureView": (OnDemandFeatureView, OnDemandFeatureViewProto), + "LabelView": (LabelView, LabelViewProto), + "Entity": (Entity, EntityProto), + } + + +def encode_infra_object(obj: Any) -> Dict[str, str]: + """Serialize a feature view or entity for transport to the feature server. + + The registry is not a usable channel here: `FeatureStore.apply()` calls + `update_infra()` *before* `registry.commit()`, so the server cannot yet see + these objects. They travel in the request body instead. + """ + type_name = type(obj).__name__ + if type_name not in _infra_object_types(): + raise ValueError( + f"Cannot send {type_name} to the remote online store; " + f"expected one of {sorted(_infra_object_types())}" + ) + return { + "type": type_name, + "proto": base64.b64encode(obj.to_proto().SerializeToString()).decode("ascii"), + } + + +def decode_infra_object(payload: Mapping[str, str]) -> Any: + """Inverse of :func:`encode_infra_object`, used by the feature server.""" + type_name = payload["type"] + types = _infra_object_types() + if type_name not in types: + raise ValueError( + f"Unknown object type {type_name!r}; expected one of {sorted(types)}" + ) + feast_class, proto_class = types[type_name] + return feast_class.from_proto( + proto_class.FromString(base64.b64decode(payload["proto"])) + ) + + def _json_safe(val: Any) -> Any: """Convert uuid.UUID objects and sets to JSON-serializable form.""" if isinstance(val, uuid_module.UUID): @@ -742,7 +804,33 @@ def update( entities_to_keep: Sequence[Entity], partial: bool, ): - pass + """Provision online store infrastructure through the feature server. + + Table creation happens inside the concrete online store's `update()`. + In remote mode that store lives server-side, so `feast apply` has to ask + the feature server to run it -- otherwise the feature view is registered + but its table never exists, and materialization fails with a missing + table (#6693). + """ + assert isinstance(config.online_store, RemoteOnlineStoreConfig) + config.online_store.__class__ = RemoteOnlineStoreConfig + + req_body = { + "tables_to_delete": [encode_infra_object(t) for t in tables_to_delete], + "tables_to_keep": [encode_infra_object(t) for t in tables_to_keep], + "entities_to_delete": [encode_infra_object(e) for e in entities_to_delete], + "entities_to_keep": [encode_infra_object(e) for e in entities_to_keep], + "partial": partial, + } + + response = post_remote_update_infra(config=config, req_body=req_body) + if response.status_code != 200: + error_msg = ( + "Unable to update online store infrastructure using feature server API. " + f"Error_code={response.status_code}, error_message={response.text}" + ) + logger.error(error_msg) + raise RuntimeError(error_msg) def teardown( self, @@ -750,7 +838,27 @@ def teardown( tables: Sequence[FeatureView], entities: Sequence[Entity], ): - pass + """Drop online store infrastructure through the feature server. + + The mirror of :meth:`update`: without this, `feast teardown` in remote + mode leaves every table behind. + """ + assert isinstance(config.online_store, RemoteOnlineStoreConfig) + config.online_store.__class__ = RemoteOnlineStoreConfig + + req_body = { + "tables": [encode_infra_object(t) for t in tables], + "entities": [encode_infra_object(e) for e in entities], + } + + response = post_remote_teardown_infra(config=config, req_body=req_body) + if response.status_code != 200: + error_msg = ( + "Unable to teardown online store infrastructure using feature server API. " + f"Error_code={response.status_code}, error_message={response.text}" + ) + logger.error(error_msg) + raise RuntimeError(error_msg) async def close(self) -> None: """ @@ -812,3 +920,25 @@ def post_remote_online_write( return session.post(url, json=req_body, verify=config.online_store.cert) else: return session.post(url, json=req_body) + + +@rest_error_handling_decorator +def post_remote_update_infra( + session: requests.Session, config: RepoConfig, req_body: dict +) -> requests.Response: + url = f"{config.online_store.path}/update-infra" + if config.online_store.cert: + return session.post(url, json=req_body, verify=config.online_store.cert) + else: + return session.post(url, json=req_body) + + +@rest_error_handling_decorator +def post_remote_teardown_infra( + session: requests.Session, config: RepoConfig, req_body: dict +) -> requests.Response: + url = f"{config.online_store.path}/teardown-infra" + if config.online_store.cert: + return session.post(url, json=req_body, verify=config.online_store.cert) + else: + return session.post(url, json=req_body) diff --git a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py index 3babb384f6f..23c13549c48 100644 --- a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py @@ -8,7 +8,12 @@ from feast import Entity, FeatureView, Field, FileSource, RepoConfig from feast.feature_service import FeatureService from feast.infra.online_stores.online_store import OnlineStore -from feast.infra.online_stores.remote import RemoteOnlineStore, RemoteOnlineStoreConfig +from feast.infra.online_stores.remote import ( + RemoteOnlineStore, + RemoteOnlineStoreConfig, + decode_infra_object, + encode_infra_object, +) from feast.online_response import OnlineResponse from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto @@ -779,3 +784,135 @@ def test_unix_timestamp_value_serialized_as_int( # Event timestamps should be ISO strings as before assert df["event_timestamp"] == ["2023-11-15T00:00:00"] + + +class TestRemoteOnlineStoreUpdateInfra: + """Tests for RemoteOnlineStore.update / teardown. + + Both were no-ops, so `feast apply` and `feast teardown` in remote mode never + provisioned or dropped anything server-side (#6693). + """ + + @pytest.fixture + def remote_store(self): + return RemoteOnlineStore() + + @pytest.fixture + def config(self): + return RepoConfig( + project="test_project", + online_store=RemoteOnlineStoreConfig( + type="remote", path="http://localhost:6566" + ), + registry="dummy_registry", + ) + + @pytest.fixture + def entity(self): + return Entity(name="user_id", value_type=ValueType.INT64) + + @pytest.fixture + def feature_view(self, entity): + return FeatureView( + name="test_feature_view", + entities=[entity], + ttl=timedelta(days=1), + schema=[ + Field(name="user_id", dtype=Int64), + Field(name="feature1", dtype=String), + ], + source=FileSource(path="test.parquet", timestamp_field="event_timestamp"), + ) + + def test_infra_object_round_trip(self, feature_view, entity): + """Objects must survive the base64 proto hop to the feature server.""" + for original in (feature_view, entity): + decoded = decode_infra_object(encode_infra_object(original)) + assert type(decoded) is type(original) + assert decoded.name == original.name + + def test_encode_rejects_unsupported_type(self): + with pytest.raises(ValueError, match="Cannot send"): + encode_infra_object(object()) + + def test_decode_rejects_unknown_type(self): + with pytest.raises(ValueError, match="Unknown object type"): + decode_infra_object({"type": "NotAFeastObject", "proto": ""}) + + @patch("feast.infra.online_stores.remote.post_remote_update_infra") + def test_update_posts_tables_to_the_feature_server( + self, mock_post, remote_store, config, feature_view, entity + ): + """update() must send the objects, not silently do nothing.""" + mock_response = Mock() + mock_response.status_code = 200 + mock_post.return_value = mock_response + + remote_store.update( + config=config, + tables_to_delete=[], + tables_to_keep=[feature_view], + entities_to_delete=[], + entities_to_keep=[entity], + partial=False, + ) + + mock_post.assert_called_once() + req_body = mock_post.call_args[1]["req_body"] + + assert [t["type"] for t in req_body["tables_to_keep"]] == ["FeatureView"] + assert [e["type"] for e in req_body["entities_to_keep"]] == ["Entity"] + assert req_body["tables_to_delete"] == [] + assert req_body["partial"] is False + + # The payload must be decodable back into the same feature view. + assert ( + decode_infra_object(req_body["tables_to_keep"][0]).name == feature_view.name + ) + + @patch("feast.infra.online_stores.remote.post_remote_update_infra") + def test_update_raises_on_error_response( + self, mock_post, remote_store, config, feature_view + ): + """A failed provisioning call must not pass silently -- that is the bug.""" + mock_response = Mock() + mock_response.status_code = 500 + mock_response.text = "boom" + mock_post.return_value = mock_response + + with pytest.raises(RuntimeError, match="Unable to update online store"): + remote_store.update( + config=config, + tables_to_delete=[], + tables_to_keep=[feature_view], + entities_to_delete=[], + entities_to_keep=[], + partial=False, + ) + + @patch("feast.infra.online_stores.remote.post_remote_teardown_infra") + def test_teardown_posts_tables_to_the_feature_server( + self, mock_post, remote_store, config, feature_view, entity + ): + mock_response = Mock() + mock_response.status_code = 200 + mock_post.return_value = mock_response + + remote_store.teardown(config=config, tables=[feature_view], entities=[entity]) + + mock_post.assert_called_once() + req_body = mock_post.call_args[1]["req_body"] + assert [t["type"] for t in req_body["tables"]] == ["FeatureView"] + assert [e["type"] for e in req_body["entities"]] == ["Entity"] + + @patch("feast.infra.online_stores.remote.post_remote_teardown_infra") + def test_teardown_raises_on_error_response( + self, mock_post, remote_store, config, feature_view + ): + mock_response = Mock() + mock_response.status_code = 503 + mock_response.text = "unavailable" + mock_post.return_value = mock_response + + with pytest.raises(RuntimeError, match="Unable to teardown online store"): + remote_store.teardown(config=config, tables=[feature_view], entities=[]) From 70459ce8b7ef39cd05ab7ecea956dd7b1a6a9014 Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Sat, 22 Aug 2026 22:16:47 +0530 Subject: [PATCH 3/6] fix: Authorize entities on infra endpoints and cover teardown end to end Review follow-ups on the remote online store provisioning endpoints. /update-infra and /teardown-infra asserted permissions on the feature views in the request body but not on the entities, so a caller could provision or drop entity infrastructure without an authorization check. Both endpoints now apply the same CREATE and DELETE actions to entities that they already apply to tables. _infra_object_types() re-ran its five lazy imports on every call, and encode_infra_object() invoked it twice per object across four lists. It is now cached and read once per call. The integration test proved that apply() provisions a table but never exercised the teardown path, and both of its fixtures leaked their temp directories. It now asserts against the server's own SQLite file on both sides of the lifecycle -- the table exists after apply and is gone after teardown, which covers /update-infra and /teardown-infra end to end -- and removes its temp directories on the way out. Co-Authored-By: Claude Opus 5 Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- sdk/python/feast/feature_server.py | 6 ++ .../feast/infra/online_stores/remote.py | 9 ++- .../test_remote_online_store_provisioning.py | 58 +++++++++++++++++-- 3 files changed, 66 insertions(+), 7 deletions(-) diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index e7c7eda9bbc..d0ce1cb1e60 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -978,6 +978,10 @@ async def update_infra(request: UpdateInfraRequest) -> None: assert_permissions(resource=table, actions=[AuthzedAction.CREATE]) for table in tables_to_delete: assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) + for entity in entities_to_keep: + assert_permissions(resource=entity, actions=[AuthzedAction.CREATE]) + for entity in entities_to_delete: + assert_permissions(resource=entity, actions=[AuthzedAction.DELETE]) await run_in_threadpool( store._get_provider().update_infra, @@ -1001,6 +1005,8 @@ async def teardown_infra(request: TeardownInfraRequest) -> None: for table in tables: assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) + for entity in entities: + assert_permissions(resource=entity, actions=[AuthzedAction.DELETE]) await run_in_threadpool( store._get_provider().teardown_infra, diff --git a/sdk/python/feast/infra/online_stores/remote.py b/sdk/python/feast/infra/online_stores/remote.py index add4278a28a..4f6c0cc6fd9 100644 --- a/sdk/python/feast/infra/online_stores/remote.py +++ b/sdk/python/feast/infra/online_stores/remote.py @@ -17,6 +17,7 @@ import uuid as uuid_module from collections import defaultdict from datetime import datetime +from functools import lru_cache from typing import ( Any, Callable, @@ -61,11 +62,14 @@ logger = logging.getLogger(__name__) +@lru_cache(maxsize=1) def _infra_object_types() -> Dict[str, Tuple[Any, Any]]: """Map type name -> (feast class, proto class) for objects sent to /update-infra. Imported lazily: these modules import from `feast` at module scope, and pulling them in at the top of this file would create an import cycle. + Cached because `update()` calls this once per object in four lists, and + re-running the imports each time is pure overhead. """ from feast.labeling.label_view import LabelView from feast.on_demand_feature_view import OnDemandFeatureView @@ -96,11 +100,12 @@ def encode_infra_object(obj: Any) -> Dict[str, str]: `update_infra()` *before* `registry.commit()`, so the server cannot yet see these objects. They travel in the request body instead. """ + types = _infra_object_types() type_name = type(obj).__name__ - if type_name not in _infra_object_types(): + if type_name not in types: raise ValueError( f"Cannot send {type_name} to the remote online store; " - f"expected one of {sorted(_infra_object_types())}" + f"expected one of {sorted(types)}" ) return { "type": type_name, diff --git a/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py index 7ead4a8b33d..8f3af37a525 100644 --- a/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py +++ b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py @@ -20,12 +20,15 @@ """ import os +import shutil import socket +import sqlite3 import subprocess import tempfile import time from datetime import timedelta from textwrap import dedent +from typing import Iterator, List import pandas as pd import pytest @@ -57,6 +60,27 @@ def _port_open(host: str, port: int) -> bool: return s.connect_ex((host, port)) == 0 +def _server_online_tables(repo_path: str) -> List[str]: + """Table names in the server's own SQLite online store. + + Read directly rather than through any Feast API: the point of this test is + that the table physically exists server-side, so asking Feast about it + would beg the question. Opened read-only -- the server process has the + file open too. + """ + db_path = os.path.join(repo_path, "data", "online_store.db") + # SqliteOnlineStore.teardown() unlinks the whole file rather than dropping + # tables one by one, so a missing file means "nothing left", not an error. + if not os.path.exists(db_path): + return [] + con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) + try: + rows = con.execute("SELECT name FROM sqlite_master WHERE type='table'") + return [r[0] for r in rows] + finally: + con.close() + + @pytest.fixture(scope="module") def remote_server(): """`feast init` + `feast apply` + `feast serve`, backed by SQLite.""" @@ -113,16 +137,20 @@ def _server_log() -> str: yield { "url": f"http://127.0.0.1:{port}", "registry_path": registry_path, + "repo_path": repo_path, "server_log": _server_log, } proc.kill() proc.wait(timeout=30) log_file.close() + # ignore_errors: on Windows the just-killed server can still hold a handle + # to the SQLite files for a moment. + shutil.rmtree(tmp, ignore_errors=True) @pytest.fixture(scope="module") -def client_store(remote_server) -> FeatureStore: +def client_store(remote_server) -> Iterator[FeatureStore]: """A client whose online store is the remote feature server.""" tmp = tempfile.mkdtemp(prefix="feast_6693_client_") with open(os.path.join(tmp, "feature_store.yaml"), "w") as f: @@ -141,7 +169,9 @@ def client_store(remote_server) -> FeatureStore: """ ).strip() ) - return FeatureStore(repo_path=tmp) + yield FeatureStore(repo_path=tmp) + + shutil.rmtree(tmp, ignore_errors=True) def _new_feature_view(data_path: str) -> tuple: @@ -165,13 +195,16 @@ def _new_feature_view(data_path: str) -> tuple: @pytest.mark.integration -def test_apply_through_remote_online_store_provisions_the_table( +def test_remote_apply_provisions_the_table_and_teardown_drops_it( client_store, remote_server ): - """A feature view applied through a remote online store must be writable. + """The full remote lifecycle: apply provisions the table, teardown drops it. - Fails before the fix with HTTP 500 / `no such table`, because + Apply fails before the fix with HTTP 500 / `no such table`, because RemoteOnlineStore.update() is a no-op and nothing provisions server-side. + Teardown is the mirror: without RemoteOnlineStore.teardown() the table is + left behind. Both halves are asserted against the server's own SQLite file, + so this covers /update-infra and /teardown-infra end to end. """ # A real parquet file, so nothing fails for want of a source on disk. data_dir = os.path.join(client_store.repo_path, "data") @@ -215,3 +248,18 @@ def test_apply_through_remote_online_store_provisions_the_table( assert features["avg_daily_trips"] == [42] assert round(features["conv_rate"][0], 2) == 0.75 + + # The table is physically there in the server's store, not just implied by + # the write having succeeded. + tables = _server_online_tables(remote_server["repo_path"]) + assert any(NEW_FV_NAME in t for t in tables), ( + f"{NEW_FV_NAME} was never provisioned server-side; tables={tables}" + ) + + # And the mirror image: teardown must drop it again. + client_store.teardown() + + tables = _server_online_tables(remote_server["repo_path"]) + assert not any(NEW_FV_NAME in t for t in tables), ( + f"{NEW_FV_NAME} survived teardown; tables={tables}" + ) From f24aadf144e5a40c39a7b01a177656f76cd95618 Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Tue, 15 Sep 2026 08:48:45 +0530 Subject: [PATCH 4/6] fix: Never unpickle or exec a UDF from an infra-provisioning payload Security fix found in review of the /update-infra and /teardown-infra endpoints added in bd367e48. `decode_infra_object()` called `from_proto()` on client-supplied protobuf bytes without `skip_udf=True`. For StreamFeatureView, that means `dill.loads()` runs on the embedded UDF body; for OnDemandFeatureView with a pandas transformation, `resolve_udf()` runs `exec()` on the UDF source text. Both are documented elsewhere in this codebase as safe only for trusted registry content -- registry_server.py passes `skip_udf=True` in every place it decodes a client-submitted proto for exactly this reason. These two new endpoints decode a raw HTTP request body from an authenticated but untrusted client, so neither unpickling nor exec'ing it is safe. Confirmed exploitable: a crafted StreamFeatureView proto with a poisoned pickle payload, and a crafted OnDemandFeatureView proto with a malicious body_text, both run arbitrary code during decode, before authorization is checked and independent of whether the proto is otherwise valid. `_infra_object_types()` now records which of the five object kinds carry a UDF, so `decode_infra_object()` cannot decode one without passing `skip_udf=True`. Provisioning only ever needs schema and metadata, never the transformation itself, so this has no functional cost. Two regression tests prove both vectors are closed -- each fails against the pre-fix code and passes against the fix. Co-Authored-By: Claude Sonnet 5 Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- .../feast/infra/online_stores/remote.py | 40 ++++++--- .../online_store/test_remote_online_store.py | 90 +++++++++++++++++++ 2 files changed, 118 insertions(+), 12 deletions(-) diff --git a/sdk/python/feast/infra/online_stores/remote.py b/sdk/python/feast/infra/online_stores/remote.py index 4f6c0cc6fd9..c2bb2c3e086 100644 --- a/sdk/python/feast/infra/online_stores/remote.py +++ b/sdk/python/feast/infra/online_stores/remote.py @@ -63,13 +63,21 @@ @lru_cache(maxsize=1) -def _infra_object_types() -> Dict[str, Tuple[Any, Any]]: - """Map type name -> (feast class, proto class) for objects sent to /update-infra. +def _infra_object_types() -> Dict[str, Tuple[Any, Any, bool]]: + """Map type name -> (feast class, proto class, has_udf) for objects sent to /update-infra. Imported lazily: these modules import from `feast` at module scope, and pulling them in at the top of this file would create an import cycle. Cached because `update()` calls this once per object in four lists, and re-running the imports each time is pure overhead. + + `has_udf` marks the types whose `from_proto()` will `dill.loads()` a + user-defined function unless told not to via `skip_udf=True`. It exists + so `decode_infra_object` cannot forget to set that flag: provisioning + never needs the UDF body, and this endpoint decodes payloads an + authenticated-but-untrusted client controls, so unpickling it is a + remote-code-execution hole (the same reason `registry_server.py` always + passes `skip_udf=True` when decoding client-submitted protos). """ from feast.labeling.label_view import LabelView from feast.on_demand_feature_view import OnDemandFeatureView @@ -85,11 +93,11 @@ def _infra_object_types() -> Dict[str, Tuple[Any, Any]]: from feast.stream_feature_view import StreamFeatureView return { - "FeatureView": (FeatureView, FeatureViewProto), - "StreamFeatureView": (StreamFeatureView, StreamFeatureViewProto), - "OnDemandFeatureView": (OnDemandFeatureView, OnDemandFeatureViewProto), - "LabelView": (LabelView, LabelViewProto), - "Entity": (Entity, EntityProto), + "FeatureView": (FeatureView, FeatureViewProto, True), + "StreamFeatureView": (StreamFeatureView, StreamFeatureViewProto, True), + "OnDemandFeatureView": (OnDemandFeatureView, OnDemandFeatureViewProto, True), + "LabelView": (LabelView, LabelViewProto, False), + "Entity": (Entity, EntityProto, False), } @@ -114,17 +122,25 @@ def encode_infra_object(obj: Any) -> Dict[str, str]: def decode_infra_object(payload: Mapping[str, str]) -> Any: - """Inverse of :func:`encode_infra_object`, used by the feature server.""" + """Inverse of :func:`encode_infra_object`, used by the feature server. + + `payload["proto"]` is client-controlled -- it arrives as a raw HTTP + request body, not something the server generated. `skip_udf=True` is + passed for every type that supports it so a decoded FeatureView / + StreamFeatureView / OnDemandFeatureView never triggers `dill.loads()` on + that untrusted input. See `_infra_object_types` for why. + """ type_name = payload["type"] types = _infra_object_types() if type_name not in types: raise ValueError( f"Unknown object type {type_name!r}; expected one of {sorted(types)}" ) - feast_class, proto_class = types[type_name] - return feast_class.from_proto( - proto_class.FromString(base64.b64decode(payload["proto"])) - ) + feast_class, proto_class, has_udf = types[type_name] + proto = proto_class.FromString(base64.b64decode(payload["proto"])) + if has_udf: + return feast_class.from_proto(proto, skip_udf=True) + return feast_class.from_proto(proto) def _json_safe(val: Any) -> Any: diff --git a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py index 23c13549c48..c0fc5838c13 100644 --- a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py @@ -1,5 +1,8 @@ +import base64 import inspect import json +import os +import pickle from datetime import datetime, timedelta from unittest.mock import Mock, patch @@ -15,6 +18,12 @@ encode_infra_object, ) from feast.online_response import OnlineResponse +from feast.protos.feast.core.OnDemandFeatureView_pb2 import ( + OnDemandFeatureView as OnDemandFeatureViewProto, +) +from feast.protos.feast.core.StreamFeatureView_pb2 import ( + StreamFeatureView as StreamFeatureViewProto, +) from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.types import Float32, Int64, String, UnixTimestamp @@ -839,6 +848,87 @@ def test_decode_rejects_unknown_type(self): with pytest.raises(ValueError, match="Unknown object type"): decode_infra_object({"type": "NotAFeastObject", "proto": ""}) + def test_decode_never_unpickles_untrusted_stream_udf(self, tmp_path): + """decode_infra_object must not `dill.loads()` a UDF from a client payload. + + `StreamFeatureView.from_proto()` runs `dill.loads()` on the embedded + UDF unless told `skip_udf=True`. This endpoint decodes a raw HTTP + request body -- an authenticated-but-untrusted client's bytes, not + registry content -- so unpickling it is remote code execution, not a + metadata read (#6693 follow-up). A pickled object's `__reduce__` runs + during `loads()`, before the caller does anything with the result, so + a directory appearing on disk proves the payload executed. + """ + marker_dir = tmp_path / "should_never_be_created" + + class _Payload: + def __reduce__(self): + return (os.mkdir, (str(marker_dir),)) + + proto = StreamFeatureViewProto() + proto.spec.name = "malicious_sfv" + proto.spec.user_defined_function.body = pickle.dumps(_Payload()) + + try: + decode_infra_object( + { + "type": "StreamFeatureView", + "proto": base64.b64encode(proto.SerializeToString()).decode( + "ascii" + ), + } + ) + except Exception: + # This minimal proto omits an unrelated required field (a batch + # or stream source); that's fine -- the property under test is + # that the pickled UDF body never gets unpickled, independent of + # whether decoding otherwise succeeds. + pass + + assert not marker_dir.exists(), ( + "decode_infra_object unpickled a UDF body from an untrusted " + "proto -- skip_udf is not being passed through" + ) + + def test_decode_never_execs_untrusted_on_demand_udf_source(self, tmp_path): + """decode_infra_object must not exec() a UDF's source from a client payload. + + `OnDemandFeatureView.from_proto()` -> `PandasTransformation.from_proto()` + -> `resolve_udf()` runs `exec()` on the UDF's `body_text` unless told + `skip_udf=True`. That code treats `body_text` as "trusted registry + content written by feast apply" -- but this endpoint decodes a raw + HTTP request body, so exec()-ing it is remote code execution. + """ + marker_dir = tmp_path / "should_never_be_created_2" + + proto = OnDemandFeatureViewProto() + proto.spec.name = "malicious_odfv" + proto.spec.mode = "pandas" + proto.spec.feature_transformation.user_defined_function.body_text = ( + f"import os\nos.mkdir(r'{marker_dir}')\ndef fn(df):\n return df\n" + ) + + try: + decode_infra_object( + { + "type": "OnDemandFeatureView", + "proto": base64.b64encode(proto.SerializeToString()).decode( + "ascii" + ), + } + ) + except ValueError: + # This minimal proto omits unrelated required fields (sources), + # so full object construction fails -- irrelevant here. The + # property under test is that the UDF source never executes, + # independent of whether decoding otherwise succeeds. + pass + + assert not marker_dir.exists(), ( + "decode_infra_object exec()'d a UDF body from an untrusted " + "proto -- skip_udf is not being passed through" + ) + @patch("feast.infra.online_stores.remote.post_remote_update_infra") def test_update_posts_tables_to_the_feature_server( self, mock_post, remote_store, config, feature_view, entity From 51813b8b45c8edf662f5e168650e768bb0764e90 Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Tue, 15 Sep 2026 11:01:27 +0530 Subject: [PATCH 5/6] docs: List Entity as an authorized resource on infra endpoints `/update-infra` and `/teardown-infra` have authorized entities alongside feature views since 70459ce8, but this table was written in the commit before that (bd367e48) and was never updated to match. Co-Authored-By: Claude Sonnet 5 Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- docs/reference/feature-servers/python-feature-server.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/feature-servers/python-feature-server.md b/docs/reference/feature-servers/python-feature-server.md index 23d0d97e0e7..ff95c4a3cb3 100644 --- a/docs/reference/feature-servers/python-feature-server.md +++ b/docs/reference/feature-servers/python-feature-server.md @@ -643,8 +643,8 @@ The [PyTorch NLP template](https://github.com/feast-dev/feast/tree/main/sdk/pyth | /write-to-online-store | FeatureView | Write Online | Write features to the online store | | /materialize | FeatureView | Write Online | Materialize features within a specified time range | | /materialize-incremental | FeatureView | Write Online | Incrementally materialize features up to a specified timestamp | -| /update-infra | FeatureView | Create, Delete | Provision online store infrastructure for a remote `feast apply` | -| /teardown-infra | FeatureView | Delete | Drop online store infrastructure for a remote `feast teardown` | +| /update-infra | FeatureView,Entity | Create, Delete | Provision online store infrastructure for a remote `feast apply` | +| /teardown-infra | FeatureView,Entity | Delete | Drop online store infrastructure for a remote `feast teardown` | ## How to configure Authentication and Authorization ? From bc3c19a7bf7c68e55f8c1de88320c77c71b2014d Mon Sep 17 00:00:00 2001 From: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:46:27 +0530 Subject: [PATCH 6/6] fix: Harden remote online store provisioning Signed-off-by: Rishabh <158596025+RishabhCodezZz@users.noreply.github.com> --- .../feature-servers/python-feature-server.md | 14 +- sdk/python/feast/feature_server.py | 150 +++++--- .../feast/infra/online_stores/remote.py | 232 ++++++------- .../online_store/test_remote_online_store.py | 6 + .../test_remote_online_store_provisioning.py | 326 ++++++------------ .../online_store/test_remote_online_store.py | 272 ++++++--------- .../unit/test_feature_server_provisioning.py | 264 ++++++++++++++ 7 files changed, 683 insertions(+), 581 deletions(-) create mode 100644 sdk/python/tests/unit/test_feature_server_provisioning.py diff --git a/docs/reference/feature-servers/python-feature-server.md b/docs/reference/feature-servers/python-feature-server.md index 6bc6852f07d..2b1dcb9c012 100644 --- a/docs/reference/feature-servers/python-feature-server.md +++ b/docs/reference/feature-servers/python-feature-server.md @@ -666,8 +666,18 @@ The [PyTorch NLP template](https://github.com/feast-dev/feast/tree/main/sdk/pyth | /materialize | FeatureView | Write Online | Materialize features within a specified time range | | /materialize-incremental | FeatureView | Write Online | Incrementally materialize features up to a specified timestamp | | /update-infra | FeatureView,Entity | Create, Delete | Provision online store infrastructure for a remote `feast apply` | -| /teardown-infra | FeatureView,Entity | Delete | Drop online store infrastructure for a remote `feast teardown` | +| /teardown-infra | Project,FeatureView,Entity | Delete | Drop online store infrastructure for a remote `feast teardown` | ## How to configure Authentication and Authorization ? -Please refer the [page](./../../../docs/getting-started/concepts/permission.md) for more details on how to configure authentication and authorization. \ No newline at end of file +Remote `feast apply` requires a Python feature server that supports `/update-infra`. +The client and server must use the same project; provisioning requests for another project are rejected. +The provisioning endpoints manage the server's online store; compute-engine infrastructure remains with the client's provider. +Applying or reapplying a view requires `Create` permission on its feature views and entities, in addition to any registry `Describe`/`Update` permissions. +Full teardown also requires `Delete` permission on the server's project because some online stores remove shared infrastructure even when the request lists are empty. +When a remote registry has already removed a deletion target, `/update-infra` requires project-level `Delete` permission to clean up its remaining infrastructure. +Without that permission, the registry deletion can succeed while infrastructure cleanup fails; grant the cleanup actor project-level `Delete` before running the operation. +Resource permissions are checked before decoding source implementations. Authorized provisioning requests can load custom data-source classes installed on the server, so grant provisioning permissions only to trusted infrastructure operators. +Object permissions do not guarantee isolation between feature views that share a physical table in the configured online store. + +Please refer the [page](./../../../docs/getting-started/concepts/permission.md) for more details on how to configure authentication and authorization. diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index 2fb96716661..b9c2eed80bf 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -25,13 +25,14 @@ from datetime import datetime from importlib import resources as importlib_resources from types import SimpleNamespace -from typing import Any, DefaultDict, Dict, List, NamedTuple, Optional, Set, Union +from typing import Any, DefaultDict, Dict, List, NamedTuple, Optional, Set, Union, cast import pandas as pd from dateutil import parser from fastapi import ( Depends, FastAPI, + HTTPException, Query, Request, Response, @@ -43,18 +44,22 @@ from fastapi.logger import logger from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles +from google.protobuf.message import DecodeError from pydantic import BaseModel, Field, field_validator +from typeguard import TypeCheckError import feast from feast import metrics as feast_metrics from feast import proto_json, utils -from feast.constants import DEFAULT_FEATURE_SERVER_REGISTRY_TTL +from feast.constants import DEFAULT_FEATURE_SERVER_REGISTRY_TTL, PROTECTED_PROJECT_TAG from feast.data_source import PushMode from feast.errors import ( FeastError, + FeastObjectNotFoundException, FeatureViewNotFoundException, + ProjectNotFoundException, ) -from feast.feast_object import FeastObject +from feast.feast_object import ALL_FEATURE_VIEW_TYPES, FeastObject from feast.feature_server_utils import convert_response_to_dict from feast.feature_view import FeatureViewState from feast.feature_view_utils import get_feature_view_from_feature_store @@ -85,13 +90,7 @@ class WriteToFeatureStoreRequest(BaseModel): class UpdateInfraRequest(BaseModel): - """Objects to provision, sent by RemoteOnlineStore.update(). - - Each entry is `{"type": , "proto": }`. They are - carried in the body rather than looked up in the registry because - `FeatureStore.apply()` runs `update_infra()` before `registry.commit()`, - so the server cannot see them yet. - """ + """Base64 protos carried before the client's registry commit.""" tables_to_delete: List[Dict[str, str]] = [] tables_to_keep: List[Dict[str, str]] = [] @@ -1011,36 +1010,30 @@ async def write_to_online_store(request: WriteToFeatureStoreRequest) -> None: ) @app.post("/update-infra", dependencies=[Depends(inject_user_details)]) - async def update_infra(request: UpdateInfraRequest) -> None: - """Provision online store infrastructure on behalf of a remote client. - - `feast apply` against `online_store: type: remote` cannot create tables - itself -- the concrete online store lives here. Without this the feature - view is registered but its table never exists (#6693). - """ - # Imported here, not at module scope: feast.infra.online_stores.remote - # imports from `feast`, which is still initializing when this module loads. - from feast.infra.online_stores.remote import decode_infra_object - - tables_to_keep = [decode_infra_object(o) for o in request.tables_to_keep] - tables_to_delete = [decode_infra_object(o) for o in request.tables_to_delete] - entities_to_keep = [decode_infra_object(o) for o in request.entities_to_keep] - entities_to_delete = [ - decode_infra_object(o) for o in request.entities_to_delete - ] - - for table in tables_to_keep: - assert_permissions(resource=table, actions=[AuthzedAction.CREATE]) - for table in tables_to_delete: - assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) - for entity in entities_to_keep: - assert_permissions(resource=entity, actions=[AuthzedAction.CREATE]) - for entity in entities_to_delete: - assert_permissions(resource=entity, actions=[AuthzedAction.DELETE]) - + async def update_infra( + request: UpdateInfraRequest, project: Optional[str] = Query(None) + ) -> None: + if project is not None and project != store.project: + raise HTTPException(400, "Infrastructure belongs to the server project") + tables_to_keep = _decode_authorized( + request.tables_to_keep, AuthzedAction.CREATE + ) + tables_to_delete = _decode_authorized( + request.tables_to_delete, AuthzedAction.DELETE + ) + entities_to_keep = _decode_authorized( + request.entities_to_keep, AuthzedAction.CREATE, entities=True + ) + entities_to_delete = _decode_authorized( + request.entities_to_delete, AuthzedAction.DELETE, entities=True + ) + if not any( + (tables_to_keep, tables_to_delete, entities_to_keep, entities_to_delete) + ): + return await run_in_threadpool( - store._get_provider().update_infra, - project=store.project, + store._get_provider().online_store.update, + config=store.config, tables_to_delete=tables_to_delete, tables_to_keep=tables_to_keep, entities_to_delete=entities_to_delete, @@ -1049,27 +1042,74 @@ async def update_infra(request: UpdateInfraRequest) -> None: ) @app.post("/teardown-infra", dependencies=[Depends(inject_user_details)]) - async def teardown_infra(request: TeardownInfraRequest) -> None: - """Drop online store infrastructure on behalf of a remote client.""" - # Imported here, not at module scope: feast.infra.online_stores.remote - # imports from `feast`, which is still initializing when this module loads. - from feast.infra.online_stores.remote import decode_infra_object - - tables = [decode_infra_object(o) for o in request.tables] - entities = [decode_infra_object(o) for o in request.entities] - - for table in tables: - assert_permissions(resource=table, actions=[AuthzedAction.DELETE]) - for entity in entities: - assert_permissions(resource=entity, actions=[AuthzedAction.DELETE]) - + async def teardown_infra( + request: TeardownInfraRequest, project: Optional[str] = Query(None) + ) -> None: + if project is not None and project != store.project: + raise HTTPException(400, "Infrastructure belongs to the server project") + try: + server_project = store.registry.get_project( + store.project, allow_cache=False + ) + except ProjectNotFoundException: + server_project = feast.Project(name=store.project) + # Some backends remove shared infrastructure even when the lists are empty. + assert_permissions(resource=server_project, actions=[AuthzedAction.DELETE]) + if server_project.tags.get(PROTECTED_PROJECT_TAG) == "true": + raise HTTPException(403, "Cannot tear down a protected project") + tables = _decode_authorized(request.tables, AuthzedAction.DELETE) + entities = _decode_authorized( + request.entities, AuthzedAction.DELETE, entities=True + ) await run_in_threadpool( - store._get_provider().teardown_infra, - project=store.project, + store._get_provider().online_store.teardown, + config=store.config, tables=tables, entities=entities, ) + def _decode_authorized( + payloads: List[Dict[str, str]], action: AuthzedAction, *, entities: bool = False + ) -> List[Any]: + from feast.infra.online_stores.remote import decode_infra_object + + def authorize(obj: Any) -> Optional[Any]: + if not isinstance( + obj, feast.Entity if entities else tuple(ALL_FEATURE_VIEW_TYPES) + ): + raise HTTPException(400, "Unexpected infrastructure resource type") + resource = obj + replacement = None + if is_auth_necessary(get_security_manager()): + getter = ( + store.registry.get_entity + if entities + else store.registry.get_any_feature_view + ) + try: + existing = cast( + FeastObject, getter(obj.name, store.project, allow_cache=False) + ) + except FeastObjectNotFoundException: + # A remote registry may already have committed the deletion. + if action == AuthzedAction.DELETE: + resource = feast.Project(name=store.project) + else: + if action == AuthzedAction.DELETE: + replacement = resource = existing + else: + assert_permissions(resource=existing, actions=[action]) + assert_permissions(resource=resource, actions=[action]) + return replacement + + objects = [] + for payload in payloads: + try: + objects.append(decode_infra_object(payload, authorize=authorize)) + except (ValueError, KeyError, DecodeError, TypeCheckError) as exc: + raise HTTPException(400, str(exc)) from exc + return objects + @app.get("/health") async def health(): try: diff --git a/sdk/python/feast/infra/online_stores/remote.py b/sdk/python/feast/infra/online_stores/remote.py index c2bb2c3e086..93a745e02bb 100644 --- a/sdk/python/feast/infra/online_stores/remote.py +++ b/sdk/python/feast/infra/online_stores/remote.py @@ -17,7 +17,6 @@ import uuid as uuid_module from collections import defaultdict from datetime import datetime -from functools import lru_cache from typing import ( Any, Callable, @@ -35,13 +34,25 @@ from pydantic import StrictStr from feast import Entity, FeatureView, RepoConfig +from feast.batch_feature_view import BatchFeatureView from feast.feature_service import FeatureService from feast.filter_models import ComparisonFilter, CompoundFilter from feast.infra.online_stores.helpers import _to_naive_utc from feast.infra.online_stores.online_store import OnlineStore from feast.infra.registry.base_registry import BaseRegistry +from feast.labeling.label_view import LabelView +from feast.on_demand_feature_view import OnDemandFeatureView from feast.online_response import OnlineResponse from feast.permissions.client.http_auth_requests_wrapper import HttpSessionManager +from feast.protos.feast.core.Entity_pb2 import Entity as EntityProto +from feast.protos.feast.core.FeatureView_pb2 import FeatureView as FeatureViewProto +from feast.protos.feast.core.LabelView_pb2 import LabelView as LabelViewProto +from feast.protos.feast.core.OnDemandFeatureView_pb2 import ( + OnDemandFeatureView as OnDemandFeatureViewProto, +) +from feast.protos.feast.core.StreamFeatureView_pb2 import ( + StreamFeatureView as StreamFeatureViewProto, +) from feast.protos.feast.serving.ServingService_pb2 import ( FieldStatus, GetOnlineFeaturesResponse, @@ -52,6 +63,7 @@ from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import FeastConfigBaseModel from feast.rest_error_handler import rest_error_handling_decorator +from feast.stream_feature_view import StreamFeatureView from feast.type_map import ( feast_value_type_to_python_type, python_values_to_proto_values, @@ -62,58 +74,32 @@ logger = logging.getLogger(__name__) -@lru_cache(maxsize=1) -def _infra_object_types() -> Dict[str, Tuple[Any, Any, bool]]: - """Map type name -> (feast class, proto class, has_udf) for objects sent to /update-infra. - - Imported lazily: these modules import from `feast` at module scope, and - pulling them in at the top of this file would create an import cycle. - Cached because `update()` calls this once per object in four lists, and - re-running the imports each time is pure overhead. - - `has_udf` marks the types whose `from_proto()` will `dill.loads()` a - user-defined function unless told not to via `skip_udf=True`. It exists - so `decode_infra_object` cannot forget to set that flag: provisioning - never needs the UDF body, and this endpoint decodes payloads an - authenticated-but-untrusted client controls, so unpickling it is a - remote-code-execution hole (the same reason `registry_server.py` always - passes `skip_udf=True` when decoding client-submitted protos). - """ - from feast.labeling.label_view import LabelView - from feast.on_demand_feature_view import OnDemandFeatureView - from feast.protos.feast.core.Entity_pb2 import Entity as EntityProto - from feast.protos.feast.core.FeatureView_pb2 import FeatureView as FeatureViewProto - from feast.protos.feast.core.LabelView_pb2 import LabelView as LabelViewProto - from feast.protos.feast.core.OnDemandFeatureView_pb2 import ( - OnDemandFeatureView as OnDemandFeatureViewProto, - ) - from feast.protos.feast.core.StreamFeatureView_pb2 import ( - StreamFeatureView as StreamFeatureViewProto, - ) - from feast.stream_feature_view import StreamFeatureView - - return { - "FeatureView": (FeatureView, FeatureViewProto, True), - "StreamFeatureView": (StreamFeatureView, StreamFeatureViewProto, True), - "OnDemandFeatureView": (OnDemandFeatureView, OnDemandFeatureViewProto, True), - "LabelView": (LabelView, LabelViewProto, False), - "Entity": (Entity, EntityProto, False), - } +# Never execute UDFs from client payloads: provisioning only needs metadata. +_INFRA_OBJECT_TYPES: Dict[str, Tuple[Any, Any, dict]] = { + "FeatureView": (FeatureView, FeatureViewProto, {"skip_udf": True}), + "BatchFeatureView": (FeatureView, FeatureViewProto, {"skip_udf": True}), + "StreamFeatureView": ( + StreamFeatureView, + StreamFeatureViewProto, + {"skip_udf": True}, + ), + "OnDemandFeatureView": ( + OnDemandFeatureView, + OnDemandFeatureViewProto, + {"skip_udf": True}, + ), + "LabelView": (LabelView, LabelViewProto, {}), + "Entity": (Entity, EntityProto, {}), +} def encode_infra_object(obj: Any) -> Dict[str, str]: - """Serialize a feature view or entity for transport to the feature server. - - The registry is not a usable channel here: `FeatureStore.apply()` calls - `update_infra()` *before* `registry.commit()`, so the server cannot yet see - these objects. They travel in the request body instead. - """ - types = _infra_object_types() + """Send objects in the body because apply provisions before registry.commit().""" type_name = type(obj).__name__ - if type_name not in types: + if type_name not in _INFRA_OBJECT_TYPES: raise ValueError( f"Cannot send {type_name} to the remote online store; " - f"expected one of {sorted(types)}" + f"expected one of {sorted(_INFRA_OBJECT_TYPES)}" ) return { "type": type_name, @@ -121,26 +107,34 @@ def encode_infra_object(obj: Any) -> Dict[str, str]: } -def decode_infra_object(payload: Mapping[str, str]) -> Any: - """Inverse of :func:`encode_infra_object`, used by the feature server. - - `payload["proto"]` is client-controlled -- it arrives as a raw HTTP - request body, not something the server generated. `skip_udf=True` is - passed for every type that supports it so a decoded FeatureView / - StreamFeatureView / OnDemandFeatureView never triggers `dill.loads()` on - that untrusted input. See `_infra_object_types` for why. - """ +def decode_infra_object( + payload: Mapping[str, str], + *, + authorize: Optional[Callable[[Any], Optional[Any]]] = None, +) -> Any: + """Authorize source-free identity before reconstructing allowlisted metadata.""" type_name = payload["type"] - types = _infra_object_types() - if type_name not in types: + if type_name not in _INFRA_OBJECT_TYPES: raise ValueError( - f"Unknown object type {type_name!r}; expected one of {sorted(types)}" + f"Unknown object type {type_name!r}; expected one of {sorted(_INFRA_OBJECT_TYPES)}" ) - feast_class, proto_class, has_udf = types[type_name] - proto = proto_class.FromString(base64.b64decode(payload["proto"])) - if has_udf: - return feast_class.from_proto(proto, skip_udf=True) - return feast_class.from_proto(proto) + feast_class, proto_class, kwargs = _INFRA_OBJECT_TYPES[type_name] + proto = proto_class.FromString(base64.b64decode(payload["proto"], validate=True)) + if authorize is not None: + resource_class = feast_class + if isinstance(proto, FeatureViewProto) and proto.spec.HasField( + "feature_transformation" + ): + resource_class = BatchFeatureView + # Permission matching only needs type/name/tags; constructors can import sources. + identity = object.__new__(resource_class) + identity.name = proto.spec.name + identity.tags = dict(proto.spec.tags) + identity.required_tags = identity.tags + replacement = authorize(identity) + if replacement is not None: + return replacement + return feast_class.from_proto(proto, **kwargs) def _json_safe(val: Any) -> Any: @@ -824,62 +818,37 @@ def update( entities_to_delete: Sequence[Entity], entities_to_keep: Sequence[Entity], partial: bool, - ): - """Provision online store infrastructure through the feature server. - - Table creation happens inside the concrete online store's `update()`. - In remote mode that store lives server-side, so `feast apply` has to ask - the feature server to run it -- otherwise the feature view is registered - but its table never exists, and materialization fails with a missing - table (#6693). - """ - assert isinstance(config.online_store, RemoteOnlineStoreConfig) - config.online_store.__class__ = RemoteOnlineStoreConfig - - req_body = { - "tables_to_delete": [encode_infra_object(t) for t in tables_to_delete], - "tables_to_keep": [encode_infra_object(t) for t in tables_to_keep], - "entities_to_delete": [encode_infra_object(e) for e in entities_to_delete], - "entities_to_keep": [encode_infra_object(e) for e in entities_to_keep], - "partial": partial, - } - - response = post_remote_update_infra(config=config, req_body=req_body) - if response.status_code != 200: - error_msg = ( - "Unable to update online store infrastructure using feature server API. " - f"Error_code={response.status_code}, error_message={response.text}" - ) - logger.error(error_msg) - raise RuntimeError(error_msg) + ) -> None: + """Provision the server's concrete online store.""" + post_remote_infra( + config=config, + endpoint="update-infra", + req_body={ + "tables_to_delete": [encode_infra_object(t) for t in tables_to_delete], + "tables_to_keep": [encode_infra_object(t) for t in tables_to_keep], + "entities_to_delete": [ + encode_infra_object(e) for e in entities_to_delete + ], + "entities_to_keep": [encode_infra_object(e) for e in entities_to_keep], + "partial": partial, + }, + ) def teardown( self, config: RepoConfig, tables: Sequence[FeatureView], entities: Sequence[Entity], - ): - """Drop online store infrastructure through the feature server. - - The mirror of :meth:`update`: without this, `feast teardown` in remote - mode leaves every table behind. - """ - assert isinstance(config.online_store, RemoteOnlineStoreConfig) - config.online_store.__class__ = RemoteOnlineStoreConfig - - req_body = { - "tables": [encode_infra_object(t) for t in tables], - "entities": [encode_infra_object(e) for e in entities], - } - - response = post_remote_teardown_infra(config=config, req_body=req_body) - if response.status_code != 200: - error_msg = ( - "Unable to teardown online store infrastructure using feature server API. " - f"Error_code={response.status_code}, error_message={response.text}" - ) - logger.error(error_msg) - raise RuntimeError(error_msg) + ) -> None: + """Tear down the server's online infrastructure.""" + post_remote_infra( + config=config, + endpoint="teardown-infra", + req_body={ + "tables": [encode_infra_object(t) for t in tables], + "entities": [encode_infra_object(e) for e in entities], + }, + ) async def close(self) -> None: """ @@ -944,22 +913,19 @@ def post_remote_online_write( @rest_error_handling_decorator -def post_remote_update_infra( - session: requests.Session, config: RepoConfig, req_body: dict -) -> requests.Response: - url = f"{config.online_store.path}/update-infra" - if config.online_store.cert: - return session.post(url, json=req_body, verify=config.online_store.cert) - else: - return session.post(url, json=req_body) - - -@rest_error_handling_decorator -def post_remote_teardown_infra( - session: requests.Session, config: RepoConfig, req_body: dict -) -> requests.Response: - url = f"{config.online_store.path}/teardown-infra" - if config.online_store.cert: - return session.post(url, json=req_body, verify=config.online_store.cert) - else: - return session.post(url, json=req_body) +def post_remote_infra( + session: requests.Session, config: RepoConfig, endpoint: str, req_body: dict +) -> None: + """Send a provisioning request with the existing authenticated session.""" + assert isinstance(config.online_store, RemoteOnlineStoreConfig) + response = session.post( + f"{config.online_store.path.rstrip('/')}/{endpoint}", + params={"project": config.project}, + json=req_body, + verify=config.online_store.cert or True, + ) + if response.status_code != 200: + raise RuntimeError( + f"Unable to {endpoint.split('-')[0]} online store infrastructure. " + f"Error_code={response.status_code}, error_message={response.text}" + ) diff --git a/sdk/python/tests/integration/online_store/test_remote_online_store.py b/sdk/python/tests/integration/online_store/test_remote_online_store.py index 3ee3d161d14..d67b30e7413 100644 --- a/sdk/python/tests/integration/online_store/test_remote_online_store.py +++ b/sdk/python/tests/integration/online_store/test_remote_online_store.py @@ -291,6 +291,12 @@ def test_remote_online_store_read_write(auth_config, tls_mode): tempfile.TemporaryDirectory() as remote_client_tmp_dir, ): permissions_list = [ + Permission( + name="online_provision_perm", + types=[FeatureView, Entity], + policy=RoleBasedPolicy(roles=["writer"]), + actions=[AuthzedAction.CREATE], + ), Permission( name="online_list_fv_perm", types=FeatureView, diff --git a/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py index 8f3af37a525..e8c604f776c 100644 --- a/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py +++ b/sdk/python/tests/integration/online_store/test_remote_online_store_provisioning.py @@ -1,265 +1,139 @@ -""" -Regression test for feast-dev/feast#6693. +"""Remote apply must provision a previously unseen feature view (#6693).""" - 'feast apply' does not create online store tables in remote mode. +from __future__ import annotations -Contract under test (holds regardless of how the fix is implemented): - - Applying a NEW feature view through a client whose online store is - `type: remote` must leave that feature view writable. Today it does not: - the feature view lands in the registry, but no table is ever provisioned - server-side, so the write that `feast materialize` performs returns 500. - -Note on the existing coverage: `test_remote_online_store_read_write` in -sdk/python/tests/integration/online_store/test_remote_online_store.py already -applies a feature view through a remote client and writes to it, and passes. -It passes because it applies `driver_hourly_stats` -- a name the server had -already provisioned during its own `feast apply` at setup. The table exists -before the client ever touches it, which masks the bug. This test applies a -feature view the server has never seen. -""" - -import os -import shutil -import socket import sqlite3 import subprocess -import tempfile import time from datetime import timedelta -from textwrap import dedent -from typing import Iterator, List +from pathlib import Path import pandas as pd import pytest +from click.testing import CliRunner -from feast import Entity, FeatureStore, FeatureView, FileSource -from feast.driver_test_data import create_driver_hourly_stats_df -from feast.field import Field +from feast import Entity, FeatureStore, FeatureView, Field, FileSource, RepoConfig +from feast.cli.cli import cli from feast.types import Float32, Int64 from feast.utils import _utc_now +from feast.value_type import ValueType +from tests.utils.http_server import check_port_open, free_port -FEAST_BIN = "feast" PROJECT = "remote_provisioning" - -# A feature view name the server has never applied. This is the whole point. NEW_FV_NAME = "never_applied_server_side" -def _free_port() -> int: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(("", 0)) - port = s.getsockname()[1] - s.close() - return port - - -def _port_open(host: str, port: int) -> bool: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.settimeout(1.0) - return s.connect_ex((host, port)) == 0 - - -def _server_online_tables(repo_path: str) -> List[str]: - """Table names in the server's own SQLite online store. - - Read directly rather than through any Feast API: the point of this test is - that the table physically exists server-side, so asking Feast about it - would beg the question. Opened read-only -- the server process has the - file open too. - """ - db_path = os.path.join(repo_path, "data", "online_store.db") - # SqliteOnlineStore.teardown() unlinks the whole file rather than dropping - # tables one by one, so a missing file means "nothing left", not an error. - if not os.path.exists(db_path): - return [] - con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) +def _server_online_tables(repo: Path) -> set[str]: + db = repo / "data" / "online_store.db" + if not db.exists(): + return set() # SQLite teardown unlinks the database. + con = sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True) try: - rows = con.execute("SELECT name FROM sqlite_master WHERE type='table'") - return [r[0] for r in rows] + return { + row[0] + for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'") + } finally: con.close() -@pytest.fixture(scope="module") -def remote_server(): - """`feast init` + `feast apply` + `feast serve`, backed by SQLite.""" - tmp = tempfile.mkdtemp(prefix="feast_6693_server_") - - subprocess.run( - [FEAST_BIN, "init", PROJECT], cwd=tmp, capture_output=True, check=True - ) - repo_path = os.path.join(tmp, PROJECT, "feature_repo") - subprocess.run( - [FEAST_BIN, "-c", repo_path, "apply"], cwd=tmp, capture_output=True, check=True - ) - - registry_path = os.path.join(repo_path, "data", "registry.db") - assert os.path.exists(registry_path), "server registry was not created" - - port = _free_port() - # Log to files, NOT subprocess.PIPE: `feast serve` is chatty, and an - # undrained pipe fills its 64K OS buffer and deadlocks the server. - log_path = os.path.join(tmp, "server.log") - log_file = open(log_path, "w") - proc = subprocess.Popen( - [ - FEAST_BIN, - "-c", - repo_path, - "serve", - "--host", - "127.0.0.1", - "--port", - str(port), - ], - stdout=log_file, - stderr=subprocess.STDOUT, - text=True, - ) - - def _server_log() -> str: - log_file.flush() - with open(log_path) as f: - return f.read() - - deadline = time.time() + 90 - while time.time() < deadline: - if proc.poll() is not None: - raise RuntimeError(f"feast serve exited early:\n{_server_log()}") - if _port_open("127.0.0.1", port): - break - time.sleep(1) - else: - proc.kill() - raise RuntimeError(f"feast serve did not come up in 90s:\n{_server_log()}") - - yield { - "url": f"http://127.0.0.1:{port}", - "registry_path": registry_path, - "repo_path": repo_path, - "server_log": _server_log, - } - - proc.kill() - proc.wait(timeout=30) - log_file.close() - # ignore_errors: on Windows the just-killed server can still hold a handle - # to the SQLite files for a moment. - shutil.rmtree(tmp, ignore_errors=True) - - -@pytest.fixture(scope="module") -def client_store(remote_server) -> Iterator[FeatureStore]: - """A client whose online store is the remote feature server.""" - tmp = tempfile.mkdtemp(prefix="feast_6693_client_") - with open(os.path.join(tmp, "feature_store.yaml"), "w") as f: - f.write( - dedent( - f""" - project: {PROJECT} - registry: {remote_server["registry_path"]} - provider: local - entity_key_serialization_version: 3 - auth: - type: no_auth - online_store: - type: remote - path: {remote_server["url"]} - """ - ).strip() +@pytest.fixture +async def remote_server(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + result = CliRunner().invoke(cli, ["init", PROJECT]) + assert result.exit_code == 0, result.output + repo = tmp_path / PROJECT / "feature_repo" + subprocess.run(["feast", "-c", str(repo), "apply"], capture_output=True, check=True) + port = free_port() + log_path = tmp_path / "server.log" + # An undrained subprocess.PIPE can deadlock a chatty server. + with log_path.open("w") as log: + proc = subprocess.Popen( + [ + "feast", + "-c", + str(repo), + "serve", + "--host", + "127.0.0.1", + "--port", + str(port), + ], + stdout=log, + stderr=subprocess.STDOUT, ) - yield FeatureStore(repo_path=tmp) - - shutil.rmtree(tmp, ignore_errors=True) - - -def _new_feature_view(data_path: str) -> tuple: - driver = Entity(name="driver_id", description="Driver id") - source = FileSource( - path=data_path, - timestamp_field="event_timestamp", - created_timestamp_column="created", - ) - fv = FeatureView( - name=NEW_FV_NAME, - entities=[driver], - ttl=timedelta(days=1), - schema=[ - Field(name="conv_rate", dtype=Float32), - Field(name="avg_daily_trips", dtype=Int64), - ], - source=source, - ) - return driver, source, fv + try: + deadline = time.monotonic() + 90 + while not check_port_open("127.0.0.1", port): + if proc.poll() is not None or time.monotonic() >= deadline: + pytest.fail( + f"Feature server failed to start:\n{log_path.read_text()}" + ) + time.sleep(0.2) + client = FeatureStore( + config=RepoConfig( + project=PROJECT, + registry=str(repo / "data" / "registry.db"), + provider="local", + entity_key_serialization_version=3, + online_store={"type": "remote", "path": f"http://127.0.0.1:{port}"}, + ) + ) + try: + yield client, repo + except Exception: + print(log_path.read_text()[-4000:]) + raise + finally: + await client.close() + finally: + proc.kill() + proc.wait(timeout=30) @pytest.mark.integration -def test_remote_apply_provisions_the_table_and_teardown_drops_it( - client_store, remote_server -): - """The full remote lifecycle: apply provisions the table, teardown drops it. - - Apply fails before the fix with HTTP 500 / `no such table`, because - RemoteOnlineStore.update() is a no-op and nothing provisions server-side. - Teardown is the mirror: without RemoteOnlineStore.teardown() the table is - left behind. Both halves are asserted against the server's own SQLite file, - so this covers /update-infra and /teardown-infra end to end. - """ - # A real parquet file, so nothing fails for want of a source on disk. - data_dir = os.path.join(client_store.repo_path, "data") - os.makedirs(data_dir, exist_ok=True) - data_path = os.path.join(data_dir, "driver_stats.parquet") - end = _utc_now().replace(microsecond=0, second=0, minute=0) - create_driver_hourly_stats_df([1001], end - timedelta(days=1), end).to_parquet( - path=data_path, allow_truncated_timestamps=True - ) - - driver, source, fv = _new_feature_view(data_path) - client_store.apply([driver, fv]) - - # The registry accepted it -- the feature view genuinely exists. - assert NEW_FV_NAME in [v.name for v in client_store.list_feature_views()] - +def test_remote_apply_materialize_and_teardown(remote_server, tmp_path): + client, repo = remote_server now = pd.Timestamp(_utc_now()).round("ms") - df = pd.DataFrame( + source_path = tmp_path / "new_features.parquet" + pd.DataFrame( { "driver_id": [1001], "conv_rate": [0.75], "avg_daily_trips": [42], "event_timestamp": [now], - "created": [now], } + ).to_parquet(source_path) + driver = Entity(name="driver_id", value_type=ValueType.INT64) + view = FeatureView( + name=NEW_FV_NAME, + entities=[driver], + ttl=timedelta(days=1), + schema=[ + Field(name="conv_rate", dtype=Float32), + Field(name="avg_daily_trips", dtype=Int64), + ], + source=FileSource(path=str(source_path), timestamp_field="event_timestamp"), ) - - # This is what `feast materialize` does through the feature server. - try: - client_store.write_to_online_store(feature_view_name=NEW_FV_NAME, df=df) - except Exception: - print("\n------------------- server log (tail) -------------------") - print(remote_server["server_log"]()[-4000:]) - print("---------------------------------------------------------") - raise - - features = client_store.get_online_features( + table = f"{PROJECT}_{NEW_FV_NAME}" + assert table not in _server_online_tables(repo) + client.apply([driver, view]) + assert NEW_FV_NAME in [fv.name for fv in client.list_feature_views()] + assert table in _server_online_tables(repo) + + client.materialize( + now - timedelta(hours=1), now + timedelta(seconds=1), [NEW_FV_NAME] + ) + features = client.get_online_features( features=[f"{NEW_FV_NAME}:conv_rate", f"{NEW_FV_NAME}:avg_daily_trips"], entity_rows=[{"driver_id": 1001}], ).to_dict() - + assert features["conv_rate"] == pytest.approx([0.75]) assert features["avg_daily_trips"] == [42] - assert round(features["conv_rate"][0], 2) == 0.75 - # The table is physically there in the server's store, not just implied by - # the write having succeeded. - tables = _server_online_tables(remote_server["repo_path"]) - assert any(NEW_FV_NAME in t for t in tables), ( - f"{NEW_FV_NAME} was never provisioned server-side; tables={tables}" - ) - - # And the mirror image: teardown must drop it again. - client_store.teardown() - - tables = _server_online_tables(remote_server["repo_path"]) - assert not any(NEW_FV_NAME in t for t in tables), ( - f"{NEW_FV_NAME} survived teardown; tables={tables}" - ) + client.apply([], objects_to_delete=[view], partial=False) + assert table not in _server_online_tables(repo) + client.apply([driver, view]) + assert table in _server_online_tables(repo) + client.teardown() + assert table not in _server_online_tables(repo) diff --git a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py index c0fc5838c13..0465dfd49e0 100644 --- a/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_remote_online_store.py @@ -7,8 +7,9 @@ from unittest.mock import Mock, patch import pytest +from typeguard import TypeCheckError -from feast import Entity, FeatureView, Field, FileSource, RepoConfig +from feast import BatchFeatureView, Entity, FeatureView, Field, FileSource, RepoConfig from feast.feature_service import FeatureService from feast.infra.online_stores.online_store import OnlineStore from feast.infra.online_stores.remote import ( @@ -16,8 +17,10 @@ RemoteOnlineStoreConfig, decode_infra_object, encode_infra_object, + post_remote_infra, ) from feast.online_response import OnlineResponse +from feast.protos.feast.core.FeatureView_pb2 import FeatureView as FeatureViewProto from feast.protos.feast.core.OnDemandFeatureView_pb2 import ( OnDemandFeatureView as OnDemandFeatureViewProto, ) @@ -796,24 +799,12 @@ def test_unix_timestamp_value_serialized_as_int( class TestRemoteOnlineStoreUpdateInfra: - """Tests for RemoteOnlineStore.update / teardown. - - Both were no-ops, so `feast apply` and `feast teardown` in remote mode never - provisioned or dropped anything server-side (#6693). - """ - - @pytest.fixture - def remote_store(self): - return RemoteOnlineStore() - @pytest.fixture def config(self): return RepoConfig( project="test_project", - online_store=RemoteOnlineStoreConfig( - type="remote", path="http://localhost:6566" - ), registry="dummy_registry", + online_store=RemoteOnlineStoreConfig(path="http://localhost:6566"), ) @pytest.fixture @@ -825,7 +816,6 @@ def feature_view(self, entity): return FeatureView( name="test_feature_view", entities=[entity], - ttl=timedelta(days=1), schema=[ Field(name="user_id", dtype=Int64), Field(name="feature1", dtype=String), @@ -834,175 +824,127 @@ def feature_view(self, entity): ) def test_infra_object_round_trip(self, feature_view, entity): - """Objects must survive the base64 proto hop to the feature server.""" - for original in (feature_view, entity): + batch = BatchFeatureView( + name="batch", + entities=[entity], + source=feature_view.batch_source, + schema=feature_view.schema, + online=True, + udf=lambda df: df, + ) + for original in (feature_view, entity, batch): decoded = decode_infra_object(encode_infra_object(original)) assert type(decoded) is type(original) assert decoded.name == original.name + if isinstance(original, FeatureView): + assert decoded.schema == original.schema + assert decoded.online == original.online + assert decode_infra_object(encode_infra_object(batch)).udf is None - def test_encode_rejects_unsupported_type(self): + def test_rejects_unsupported_types(self): with pytest.raises(ValueError, match="Cannot send"): encode_infra_object(object()) - - def test_decode_rejects_unknown_type(self): with pytest.raises(ValueError, match="Unknown object type"): decode_infra_object({"type": "NotAFeastObject", "proto": ""}) - def test_decode_never_unpickles_untrusted_stream_udf(self, tmp_path): - """decode_infra_object must not `dill.loads()` a UDF from a client payload. + @pytest.mark.parametrize("type_name", ["FeatureView", "BatchFeatureView"]) + @pytest.mark.parametrize("transformed", [False, True]) + def test_authorization_uses_reconstructed_view_type(self, type_name, transformed): + proto = FeatureViewProto() + proto.spec.name = "new_view" + proto.spec.tags["team"] = "features" + if transformed: + proto.spec.feature_transformation.SetInParent() + authorize = Mock(side_effect=lambda identity: identity) + identity = decode_infra_object( + { + "type": type_name, + "proto": base64.b64encode(proto.SerializeToString()).decode("ascii"), + }, + authorize=authorize, + ) + assert type(identity) is (BatchFeatureView if transformed else FeatureView) + assert identity.name == "new_view" + assert identity.tags == identity.required_tags == {"team": "features"} + authorize.assert_called_once_with(identity) - `StreamFeatureView.from_proto()` runs `dill.loads()` on the embedded - UDF unless told `skip_udf=True`. This endpoint decodes a raw HTTP - request body -- an authenticated-but-untrusted client's bytes, not - registry content -- so unpickling it is remote code execution, not a - metadata read (#6693 follow-up). A pickled object's `__reduce__` runs - during `loads()`, before the caller does anything with the result, so - a directory appearing on disk proves the payload executed. - """ - marker_dir = tmp_path / "should_never_be_created" + @pytest.mark.parametrize("kind", ["StreamFeatureView", "OnDemandFeatureView"]) + def test_decode_never_executes_untrusted_udf(self, kind, tmp_path): + marker = tmp_path / "must_not_exist" - class _Payload: + class Payload: def __reduce__(self): - return (os.mkdir, (str(marker_dir),)) - - proto = StreamFeatureViewProto() - proto.spec.name = "malicious_sfv" - proto.spec.user_defined_function.body = pickle.dumps(_Payload()) - - try: - decode_infra_object( - { - "type": "StreamFeatureView", - "proto": base64.b64encode(proto.SerializeToString()).decode( - "ascii" - ), - } + return os.mkdir, (str(marker),) + + if kind == "StreamFeatureView": + proto = StreamFeatureViewProto() + proto.spec.user_defined_function.body = pickle.dumps(Payload()) + else: + proto = OnDemandFeatureViewProto() + proto.spec.mode = "pandas" + proto.spec.feature_transformation.user_defined_function.body_text = ( + f"import os\nos.mkdir(r'{marker}')\ndef fn(df):\n return df\n" ) - except Exception: - # This minimal proto omits an unrelated required field (a batch - # or stream source); that's fine -- the property under test is - # that the pickled UDF body never gets unpickled, independent of - # whether decoding otherwise succeeds. - pass - - assert not marker_dir.exists(), ( - "decode_infra_object unpickled a UDF body from an untrusted " - "proto -- skip_udf is not being passed through" - ) - - def test_decode_never_execs_untrusted_on_demand_udf_source(self, tmp_path): - """decode_infra_object must not exec() a UDF's source from a client payload. - - `OnDemandFeatureView.from_proto()` -> `PandasTransformation.from_proto()` - -> `resolve_udf()` runs `exec()` on the UDF's `body_text` unless told - `skip_udf=True`. That code treats `body_text` as "trusted registry - content written by feast apply" -- but this endpoint decodes a raw - HTTP request body, so exec()-ing it is remote code execution. - """ - marker_dir = tmp_path / "should_never_be_created_2" - - proto = OnDemandFeatureViewProto() - proto.spec.name = "malicious_odfv" - proto.spec.mode = "pandas" - proto.spec.feature_transformation.user_defined_function.body_text = ( - f"import os\nos.mkdir(r'{marker_dir}')\ndef fn(df):\n return df\n" - ) - + proto.spec.name = "untrusted" try: decode_infra_object( { - "type": "OnDemandFeatureView", + "type": kind, "proto": base64.b64encode(proto.SerializeToString()).decode( "ascii" ), } ) - except ValueError: - # This minimal proto omits unrelated required fields (sources), - # so full object construction fails -- irrelevant here. The - # property under test is that the UDF source never executes, - # independent of whether decoding otherwise succeeds. - pass - - assert not marker_dir.exists(), ( - "decode_infra_object exec()'d a UDF body from an untrusted " - "proto -- skip_udf is not being passed through" - ) - - @patch("feast.infra.online_stores.remote.post_remote_update_infra") - def test_update_posts_tables_to_the_feature_server( - self, mock_post, remote_store, config, feature_view, entity - ): - """update() must send the objects, not silently do nothing.""" - mock_response = Mock() - mock_response.status_code = 200 - mock_post.return_value = mock_response - - remote_store.update( - config=config, - tables_to_delete=[], - tables_to_keep=[feature_view], - entities_to_delete=[], - entities_to_keep=[entity], - partial=False, - ) - - mock_post.assert_called_once() - req_body = mock_post.call_args[1]["req_body"] - - assert [t["type"] for t in req_body["tables_to_keep"]] == ["FeatureView"] - assert [e["type"] for e in req_body["entities_to_keep"]] == ["Entity"] - assert req_body["tables_to_delete"] == [] - assert req_body["partial"] is False - - # The payload must be decodable back into the same feature view. - assert ( - decode_infra_object(req_body["tables_to_keep"][0]).name == feature_view.name + except (ValueError, TypeError, TypeCheckError): + pass # Minimal protos may fail source validation after UDF decoding. + assert not marker.exists(), "Client-supplied UDF executed during decode" + + @pytest.mark.parametrize("operation", ["update", "teardown"]) + def test_forwards_infra_objects(self, operation, config, feature_view, entity): + args = ( + {"tables": [feature_view], "entities": [entity]} + if operation == "teardown" + else { + "tables_to_keep": [feature_view], + "tables_to_delete": [feature_view], + "entities_to_keep": [entity], + "entities_to_delete": [entity], + "partial": True, + } + ) + with patch("feast.infra.online_stores.remote.post_remote_infra") as post: + getattr(RemoteOnlineStore(), operation)(config=config, **args) + post.assert_called_once() + assert post.call_args.kwargs["endpoint"] == f"{operation}-infra" + body = post.call_args.kwargs["req_body"] + for key, objects in args.items(): + if key == "partial": + assert body[key] is True + else: + assert [decode_infra_object(p).name for p in body[key]] == [ + o.name for o in objects + ] + + @pytest.mark.parametrize("operation", ["update", "teardown"]) + @pytest.mark.parametrize("cert", ["", "/path/to/cert.pem"]) + @pytest.mark.parametrize("status", [200, 503]) + def test_infra_http_request(self, operation, cert, status, config): + config.online_store.cert = cert + session = Mock() + session.post.return_value = Mock(status_code=status, text="unavailable") + kwargs = dict( + session=session, config=config, endpoint=f"{operation}-infra", req_body={} + ) + if status == 200: + post_remote_infra.__wrapped__(**kwargs) + else: + with pytest.raises( + RuntimeError, match=f"Unable to {operation} online store" + ): + post_remote_infra.__wrapped__(**kwargs) + session.post.assert_called_once_with( + f"http://localhost:6566/{operation}-infra", + params={"project": config.project}, + json={}, + verify=cert or True, ) - - @patch("feast.infra.online_stores.remote.post_remote_update_infra") - def test_update_raises_on_error_response( - self, mock_post, remote_store, config, feature_view - ): - """A failed provisioning call must not pass silently -- that is the bug.""" - mock_response = Mock() - mock_response.status_code = 500 - mock_response.text = "boom" - mock_post.return_value = mock_response - - with pytest.raises(RuntimeError, match="Unable to update online store"): - remote_store.update( - config=config, - tables_to_delete=[], - tables_to_keep=[feature_view], - entities_to_delete=[], - entities_to_keep=[], - partial=False, - ) - - @patch("feast.infra.online_stores.remote.post_remote_teardown_infra") - def test_teardown_posts_tables_to_the_feature_server( - self, mock_post, remote_store, config, feature_view, entity - ): - mock_response = Mock() - mock_response.status_code = 200 - mock_post.return_value = mock_response - - remote_store.teardown(config=config, tables=[feature_view], entities=[entity]) - - mock_post.assert_called_once() - req_body = mock_post.call_args[1]["req_body"] - assert [t["type"] for t in req_body["tables"]] == ["FeatureView"] - assert [e["type"] for e in req_body["entities"]] == ["Entity"] - - @patch("feast.infra.online_stores.remote.post_remote_teardown_infra") - def test_teardown_raises_on_error_response( - self, mock_post, remote_store, config, feature_view - ): - mock_response = Mock() - mock_response.status_code = 503 - mock_response.text = "unavailable" - mock_post.return_value = mock_response - - with pytest.raises(RuntimeError, match="Unable to teardown online store"): - remote_store.teardown(config=config, tables=[feature_view], entities=[]) diff --git a/sdk/python/tests/unit/test_feature_server_provisioning.py b/sdk/python/tests/unit/test_feature_server_provisioning.py new file mode 100644 index 00000000000..6a0ee84b154 --- /dev/null +++ b/sdk/python/tests/unit/test_feature_server_provisioning.py @@ -0,0 +1,264 @@ +"""Authorization and infrastructure scope of remote provisioning endpoints.""" + +from __future__ import annotations + +import base64 +from unittest.mock import Mock + +import httpx +import pytest + +from feast import ( + Entity, + FeatureStore, + FeatureView, + Field, + FileSource, + Project, + RepoConfig, + data_source, +) +from feast.constants import PROTECTED_PROJECT_TAG +from feast.feature_server import get_app +from feast.infra.online_stores.remote import encode_infra_object +from feast.permissions import security_manager +from feast.permissions.action import AuthzedAction +from feast.permissions.permission import Permission +from feast.permissions.policy import RoleBasedPolicy +from feast.permissions.server.rest import inject_user_details +from feast.permissions.user import User +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.types import Int64 +from feast.value_type import ValueType + + +@pytest.fixture +async def infra_client(tmp_path, monkeypatch): + entity = Entity(name="id", value_type=ValueType.INT64) + view = FeatureView( + name="victim", + entities=[entity], + schema=[Field(name="id", dtype=Int64), Field(name="value", dtype=Int64)], + source=FileSource(path="unused.parquet", timestamp_field="ts"), + ) + store = FeatureStore( + config=RepoConfig( + project="test", + provider="local", + registry=str(tmp_path / "registry.db"), + online_store={"type": "sqlite", "path": str(tmp_path / "online.db")}, + ) + ) + monkeypatch.setattr(security_manager, "_sm", None) + store.apply([entity, view]) + registry = Mock(wraps=store.registry) + registry.list_permissions.return_value = [] + sm = security_manager.SecurityManager(project=store.project, registry=registry) + monkeypatch.setattr(security_manager, "_sm", sm) + app = get_app(store) + + async def identify(): + sm.set_current_user(User("tester", roles=["test"])) + + app.dependency_overrides[inject_user_details] = identify + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app, raise_app_exceptions=False), + base_url="http://test", + ) as client: + yield client, store, registry, view + await store.close() + + +def grant(registry, resource_type, action): + registry.list_permissions.return_value = [ + Permission( + name="test", + types=resource_type, + actions=[action], + policy=RoleBasedPolicy(roles=["test"]), + ) + ] + + +@pytest.mark.parametrize("body", [{}, {"tables": [{"type": "Entity", "proto": ""}]}]) +async def test_teardown_requires_project_delete(infra_client, body): + client, store, registry, _ = infra_client + grant(registry, Entity, AuthzedAction.DELETE) + response = await client.post("/teardown-infra", json=body) + assert response.status_code == 403 + assert ( + store._get_provider() + .online_store._get_conn(store.config) + .execute("SELECT name FROM sqlite_master WHERE name='test_victim'") + .fetchone() + ) + + +async def test_table_list_rejects_entities(infra_client): + client, store, registry, view = infra_client + grant(registry, Entity, AuthzedAction.DELETE) + response = await client.post( + "/update-infra", + json={ + "tables_to_delete": [ + encode_infra_object(Entity(name=view.name, value_type=ValueType.INT64)) + ] + }, + ) + assert response.status_code == 400 + assert ( + store._get_provider() + .online_store._get_conn(store.config) + .execute("SELECT name FROM sqlite_master WHERE name='test_victim'") + .fetchone() + ) + + +@pytest.mark.parametrize("operation", ["update", "teardown"]) +async def test_provisioning_only_calls_online_store( + infra_client, operation, monkeypatch +): + client, store, registry, view = infra_client + grant( + registry, + [FeatureView, Entity, Project], + AuthzedAction.CREATE if operation == "update" else AuthzedAction.DELETE, + ) + provider = store._get_provider() + online_call = Mock() + batch = Mock() + monkeypatch.setattr(provider.online_store, operation, online_call) + monkeypatch.setattr(provider, "_batch_engine", batch) + body = { + "tables_to_keep" if operation == "update" else "tables": [ + encode_infra_object(view) + ] + } + response = await client.post(f"/{operation}-infra", json=body) + assert response.status_code == 200, response.text + online_call.assert_called_once() + assert not batch.mock_calls + + +@pytest.mark.parametrize( + "action, field", + [ + (AuthzedAction.CREATE, "tables_to_keep"), + (AuthzedAction.DELETE, "tables_to_delete"), + ], +) +async def test_checks_registry_resource_type(infra_client, action, field): + client, store, registry, view = infra_client + from feast.labeling.label_view import LabelView + + grant(registry, LabelView, action) + forged = LabelView( + name=view.name, + entities=[], + source=view.batch_source, + schema=[Field(name="value", dtype=Int64)], + ) + response = await client.post( + "/update-infra", json={field: [encode_infra_object(forged)]} + ) + assert response.status_code == 403 + + +async def test_delete_uses_server_owned_metadata(infra_client, monkeypatch): + client, store, registry, view = infra_client + grant(registry, FeatureView, AuthzedAction.DELETE) + forged = view.__copy__() + forged.entities = ["victim_entity_group"] + update = Mock() + monkeypatch.setattr(store._get_provider().online_store, "update", update) + response = await client.post( + "/update-infra", json={"tables_to_delete": [encode_infra_object(forged)]} + ) + assert response.status_code == 200 + assert update.call_args.kwargs["tables_to_delete"][0].entities == view.entities + + +@pytest.mark.parametrize("scope, expected", [(FeatureView, 403), (Project, 200)]) +async def test_missing_delete_target_requires_project_permission( + infra_client, scope, expected +): + client, store, registry, view = infra_client + store.registry.delete_feature_view(view.name, project=store.project) + grant(registry, scope, AuthzedAction.DELETE) + response = await client.post( + "/update-infra", json={"tables_to_delete": [encode_infra_object(view)]} + ) + assert response.status_code == expected + + +async def test_protected_project_cannot_be_torn_down(infra_client): + client, store, registry, _ = infra_client + store.registry.apply_project( + Project(name=store.project, tags={PROTECTED_PROJECT_TAG: "true"}) + ) + grant(registry, Project, AuthzedAction.DELETE) + response = await client.post("/teardown-infra", json={}) + assert response.status_code == 403 + + +@pytest.mark.parametrize("endpoint", ["update", "teardown"]) +async def test_provisioning_rejects_other_project(infra_client, endpoint, monkeypatch): + client, store, registry, _ = infra_client + grant(registry, [FeatureView, Entity, Project], AuthzedAction.DELETE) + online = store._get_provider().online_store + operation = Mock() + monkeypatch.setattr(online, endpoint, operation) + response = await client.post(f"/{endpoint}-infra?project=other", json={}) + assert response.status_code == 400 + operation.assert_not_called() + + +@pytest.mark.parametrize("allowed", [False, True]) +async def test_first_creation_authorizes_before_source_import( + infra_client, allowed, monkeypatch +): + client, store, registry, template = infra_client + view = template.__copy__() + view.name = "first_authenticated_creation" + proto = view.to_proto() + proto.spec.batch_source.type = DataSourceProto.CUSTOM_SOURCE + source_type = ( + f"{FileSource.__module__}.{FileSource.__name__}" + if allowed + else "untrusted_module.CustomSource" + ) + proto.spec.batch_source.data_source_class_type = source_type + load_source = Mock(wraps=data_source.get_data_source_class_from_type) + monkeypatch.setattr(data_source, "get_data_source_class_from_type", load_source) + grant( + registry, + FeatureView if allowed else Entity, + AuthzedAction.CREATE, + ) + response = await client.post( + "/update-infra?project=test", + json={ + "tables_to_keep": [ + { + "type": "FeatureView", + "proto": base64.b64encode(proto.SerializeToString()).decode( + "ascii" + ), + } + ] + }, + ) + assert response.status_code == (200 if allowed else 403), response.text + row = ( + store._get_provider() + .online_store._get_conn(store.config) + .execute( + "SELECT name FROM sqlite_master WHERE name='test_first_authenticated_creation'" + ) + .fetchone() + ) + assert bool(row) == allowed + if allowed: + load_source.assert_any_call(source_type) + else: + load_source.assert_not_called()