Skip to content

Commit f4fb537

Browse files
committed
fix: Improve projects context for servers
Signed-off-by: ntkathole <nikhilkathole2683@gmail.com>
1 parent 69ac7b0 commit f4fb537

6 files changed

Lines changed: 562 additions & 46 deletions

File tree

‎sdk/python/feast/api/registry/rest/compute_engines.py‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,54 @@
22
from typing import Any, Dict, List, Optional
33

44
from fastapi import APIRouter, Depends, Query
5+
from pydantic import BaseModel
56

67
from feast.api.registry.rest.rest_utils import (
78
get_pagination_params,
89
get_sorting_params,
910
grpc_call,
1011
)
12+
from feast.permissions.action import AuthzedAction
13+
from feast.permissions.security_manager import assert_permissions, get_security_manager
1114
from feast.protos.feast.registry import RegistryServer_pb2
1215
from feast.repo_config import BATCH_ENGINE_CLASS_FOR_TYPE
1316

1417
logger = logging.getLogger(__name__)
1518

1619

20+
class ComputeEngineConfigResponse(BaseModel):
21+
"""High-level, non-secret compute engine settings returned by the REST API.
22+
23+
This is the explicit, fail-closed contract for the ``config`` block: only
24+
these fields are ever exposed, so credentials, connection identity,
25+
location/URL values and nested settings are never returned.
26+
"""
27+
28+
type: str
29+
region: Optional[str] = None
30+
namespace: Optional[str] = None
31+
warehouse: Optional[str] = None
32+
database: Optional[str] = None
33+
catalog: Optional[str] = None
34+
parallelism: Optional[int] = None
35+
partitions: Optional[int] = None
36+
37+
38+
def _engine_config_response(
39+
engine_type: str, engine_config: Dict[str, Any]
40+
) -> Dict[str, Any]:
41+
"""Project a raw engine config onto the public response fields."""
42+
scalar_types = (str, int, float, bool)
43+
known = {
44+
name: engine_config[name]
45+
for name in ComputeEngineConfigResponse.model_fields
46+
if name != "type" and isinstance(engine_config.get(name), scalar_types)
47+
}
48+
return ComputeEngineConfigResponse.model_construct(
49+
type=engine_type, **known
50+
).model_dump(exclude_none=True)
51+
52+
1753
def _extract_engine_info(store) -> Dict[str, Any]:
1854
"""Extract compute engine configuration from the FeatureStore."""
1955
config = getattr(store, "config", None)
@@ -58,7 +94,7 @@ def _extract_engine_info(store) -> Dict[str, Any]:
5894
return {
5995
"engineType": engine_type,
6096
"engineClass": engine_class,
61-
"config": engine_config,
97+
"config": _engine_config_response(engine_type, engine_config),
6298
}
6399

64100

@@ -132,6 +168,17 @@ def get_compute_engine(
132168
project: str = Query(...),
133169
allow_cache: bool = Query(default=True),
134170
):
171+
sm = get_security_manager()
172+
if sm is not None and store is not None:
173+
project_obj = store.registry.get_project(
174+
name=project, allow_cache=allow_cache
175+
)
176+
project_token = sm.set_current_project(project)
177+
try:
178+
assert_permissions(project_obj, actions=[AuthzedAction.DESCRIBE])
179+
finally:
180+
sm.reset_current_project(project_token)
181+
135182
engine_info = (
136183
_extract_engine_info(store)
137184
if store

‎sdk/python/feast/api/registry/rest/rest_registry_server.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
PushSourceNotFoundException,
1616
)
1717
from feast.permissions.auth.auth_manager import get_auth_manager
18-
from feast.permissions.server.rest import inject_user_details
18+
from feast.permissions.server.rest import build_auth_dependency
1919
from feast.permissions.server.utils import (
2020
ServerType,
2121
init_auth_manager,
@@ -57,7 +57,7 @@ def __init__(self, store: FeatureStore):
5757
self.app = FastAPI(
5858
title="Feast REST Registry Server",
5959
description="Feast REST Registry Server",
60-
dependencies=[Depends(inject_user_details)],
60+
dependencies=[Depends(build_auth_dependency(scope_to_query_project=True))],
6161
version="1.0.0",
6262
openapi_url="/openapi.json",
6363
root_path="/api/v1",

‎sdk/python/feast/permissions/server/rest.py‎

Lines changed: 71 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
A module with utility functions to support authorizing the REST servers using the FastAPI framework.
33
"""
44

5-
from typing import Any, AsyncIterator, Optional
5+
from typing import Any, AsyncIterator, Callable, Optional
66

77
from fastapi import HTTPException
88
from fastapi.requests import Request
@@ -26,48 +26,78 @@ def _extract_project_from_request(request: Request) -> Optional[str]:
2626
return None
2727

2828

29-
async def inject_user_details(request: Request) -> AsyncIterator[Any]:
30-
"""
31-
Extract the authorization token from a user request, propagate user details
32-
to the security manager, and scope permissions to the request project when
33-
available (query param ``project``).
29+
def build_auth_dependency(
30+
scope_to_query_project: bool = False,
31+
) -> Callable[[Request], AsyncIterator[Any]]:
32+
"""Build the FastAPI auth dependency that authenticates the caller and
33+
sets up the security-manager context for the request.
34+
35+
Args:
36+
scope_to_query_project: Controls which project's permissions are
37+
checked for the request.
38+
39+
``False`` (default, safe): the request is authorized against the
40+
server's own project (``SecurityManager._project``, i.e.
41+
``store.project``). Use this for every server that serves a single
42+
project and always acts on its own project regardless of the
43+
request, such as the feature server. The caller-supplied
44+
``?project=`` query parameter must NOT be able to change which
45+
project's permissions are enforced here, otherwise a user with
46+
rights in some other project (or a non-existent one, which has no
47+
permissions and therefore grants all authenticated users access)
48+
could read and write this project's data.
49+
50+
``True``: the request is authorized against the project named in
51+
the ``project`` query parameter. Use this ONLY for servers that
52+
serve many projects and act on the requested project, i.e. the
53+
registry REST server and anything that mounts its routes (UI
54+
server). There the requested project is also the project whose
55+
data is touched, so checking its permissions is correct.
3456
35-
Yields so project context is reset after the request completes.
57+
Yields so any project context is reset after the request completes.
3658
"""
37-
sm = get_security_manager()
38-
current_user = None
39-
project_token = None
40-
if sm is not None:
41-
try:
42-
auth_manager = get_auth_manager()
43-
access_token = auth_manager.token_extractor.extract_access_token(
44-
request=request
45-
)
46-
if not access_token:
47-
raise HTTPException(
48-
status_code=401, detail="Missing authentication token"
59+
60+
async def inject_user_details(request: Request) -> AsyncIterator[Any]:
61+
sm = get_security_manager()
62+
current_user = None
63+
project_token = None
64+
if sm is not None:
65+
try:
66+
auth_manager = get_auth_manager()
67+
access_token = auth_manager.token_extractor.extract_access_token(
68+
request=request
4969
)
70+
if not access_token:
71+
raise HTTPException(
72+
status_code=401, detail="Missing authentication token"
73+
)
5074

51-
current_user = (
52-
await auth_manager.token_parser.user_details_from_access_token(
53-
access_token=access_token
75+
current_user = (
76+
await auth_manager.token_parser.user_details_from_access_token(
77+
access_token=access_token
78+
)
5479
)
55-
)
56-
57-
sm.set_current_user(current_user)
58-
sm.set_current_request_token(access_token)
59-
project = _extract_project_from_request(request)
60-
if project is not None:
61-
project_token = sm.set_current_project(project)
62-
except HTTPException:
63-
raise
64-
except Exception:
65-
raise HTTPException(
66-
status_code=401, detail="Invalid or expired access token"
67-
)
68-
69-
try:
70-
yield current_user
71-
finally:
72-
if sm is not None and project_token is not None:
73-
sm.reset_current_project(project_token)
80+
81+
sm.set_current_user(current_user)
82+
sm.set_current_request_token(access_token)
83+
if scope_to_query_project:
84+
project = _extract_project_from_request(request)
85+
if project is not None:
86+
project_token = sm.set_current_project(project)
87+
except HTTPException:
88+
raise
89+
except Exception:
90+
raise HTTPException(
91+
status_code=401, detail="Invalid or expired access token"
92+
)
93+
94+
try:
95+
yield current_user
96+
finally:
97+
if sm is not None and project_token is not None:
98+
sm.reset_current_project(project_token)
99+
100+
return inject_user_details
101+
102+
103+
inject_user_details = build_auth_dependency(scope_to_query_project=False)

‎sdk/python/feast/ui_server.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def _setup_rest_mode(app: FastAPI, store: "feast.FeatureStore"):
117117
auth_cfg = store.config.auth_config
118118
dependencies = []
119119
if auth_cfg and auth_cfg.type != "no_auth":
120-
from feast.permissions.server.rest import inject_user_details
120+
from feast.permissions.server.rest import build_auth_dependency
121121

122122
auth_type = str_to_auth_manager_type(auth_cfg.type)
123123
init_security_manager(auth_type=auth_type, fs=store)
@@ -126,7 +126,7 @@ def _setup_rest_mode(app: FastAPI, store: "feast.FeatureStore"):
126126
server_type=ServerType.REST,
127127
auth_config=auth_cfg,
128128
)
129-
dependencies.append(Depends(inject_user_details))
129+
dependencies.append(Depends(build_auth_dependency(scope_to_query_project=True)))
130130

131131
rest_app = FastAPI(root_path="/api/v1", dependencies=dependencies)
132132

0 commit comments

Comments
 (0)