Skip to content

Commit ff8abe0

Browse files
patelchaitanyntkathole
authored andcommitted
fix: Use TokenReview for service accounts in the Kubernetes token parser
KubernetesTokenParser now takes the caller's identity from the Kubernetes TokenReview response, the same way OidcTokenParser handles service account tokens. One TokenReview call returns the username, groups and namespaces, and the service account namespace and name are read from that username. The unused _get_username_from_token_review helper is removed. The test mocks now return the TokenReview username. Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>
1 parent 7677fab commit ff8abe0

3 files changed

Lines changed: 131 additions & 65 deletions

File tree

‎sdk/python/feast/permissions/auth/kubernetes_token_parser.py‎

Lines changed: 28 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,20 @@ async def user_details_from_access_token(self, access_token: str) -> User:
5050
if secret and claims and claims.get("sub") == f":::{secret}":
5151
return User(username=secret, roles=[], groups=[], namespaces=[])
5252

53-
# First, try to extract user information using Token Access Review
54-
groups, namespaces = self._extract_groups_and_namespaces_from_token(
53+
# The user details all come from one Token Access Review call.
54+
username, groups, namespaces = self._extract_groups_and_namespaces_from_token(
5555
access_token
5656
)
57+
if not username:
58+
raise AuthenticationError("Could not extract username from token")
5759

58-
# Try to determine if this is a service account or regular user
59-
try:
60-
# Attempt to decode as JWT (for service accounts)
61-
sa_namespace, sa_name = _decode_token(access_token)
62-
current_user = f"{sa_namespace}:{sa_name}"
60+
if username.startswith("system:serviceaccount:"):
61+
parts = username.split(":")
62+
if len(parts) != 4 or not parts[2] or not parts[3]:
63+
raise AuthenticationError(
64+
f"Invalid service account username: {username}"
65+
)
66+
_, _, sa_namespace, sa_name = parts
6367
logger.info(
6468
f"Request received from ServiceAccount: {sa_name} in namespace: {sa_namespace}"
6569
)
@@ -78,31 +82,21 @@ async def user_details_from_access_token(self, access_token: str) -> User:
7882
logger.info(f"Roles: {roles}")
7983

8084
return User(
81-
username=current_user,
85+
username=f"{sa_namespace}:{sa_name}",
8286
roles=roles,
8387
groups=groups,
8488
namespaces=namespaces,
8589
)
8690

87-
except AuthenticationError as e:
88-
# If JWT decoding fails, this is likely a user token
89-
# Use Token Access Review to get user information
90-
logger.info(f"Token is not a JWT (likely a user token): {e}")
91-
92-
# Get username from Token Access Review
93-
username = self._get_username_from_token_review(access_token)
94-
if not username:
95-
raise AuthenticationError("Could not extract username from token")
91+
logger.info(f"Request received from User: {username}")
9692

97-
logger.info(f"Request received from User: {username}")
93+
# Extract roles for the user from RoleBindings and ClusterRoleBindings
94+
logger.info(f"Extracting roles for user {username} with groups: {groups}")
95+
roles = self.get_user_roles(username, groups)
9896

99-
# Extract roles for the user from RoleBindings and ClusterRoleBindings
100-
logger.info(f"Extracting roles for user {username} with groups: {groups}")
101-
roles = self.get_user_roles(username, groups)
102-
103-
return User(
104-
username=username, roles=roles, groups=groups, namespaces=namespaces
105-
)
97+
return User(
98+
username=username, roles=roles, groups=groups, namespaces=namespaces
99+
)
106100

107101
def _read_namespace_from_file(self):
108102
try:
@@ -190,23 +184,25 @@ def get_user_roles(self, username: str, groups: list[str]) -> list[str]:
190184

191185
def _extract_groups_and_namespaces_from_token(
192186
self, access_token: str
193-
) -> tuple[list[str], list[str]]:
187+
) -> tuple[str, list[str], list[str]]:
194188
"""
195-
Extract groups and namespaces from the token using Kubernetes Token Access Review.
189+
Extract the username, groups and namespaces from the token using Kubernetes Token Access Review.
196190
197191
Args:
198-
access_token: The JWT token to analyze
192+
access_token: The token to analyze
199193
200194
Returns:
201-
tuple[list[str], list[str]]: A tuple containing (groups, namespaces)
195+
tuple[str, list[str], list[str]]: A tuple containing (username, groups, namespaces).
196+
The username is empty if the Token Access Review did not authenticate the token.
202197
"""
198+
username = ""
199+
groups: list[str] = []
200+
namespaces: list[str] = []
203201
try:
204202
# Create TokenReview object
205203
token_review = client.V1TokenReview(
206204
spec=client.V1TokenReviewSpec(token=access_token)
207205
)
208-
groups: list[str] = []
209-
namespaces: list[str] = []
210206

211207
# Call Token Access Review API
212208
response = self.auth_v1.create_token_review(token_review)
@@ -270,7 +266,7 @@ def _extract_groups_and_namespaces_from_token(
270266
# Remove duplicates
271267
groups = sorted(list(set(groups)))
272268
namespaces = sorted(list(set(namespaces)))
273-
return groups, namespaces
269+
return username, groups, namespaces
274270

275271
def _extract_namespace_access_groups(self, namespace: str) -> list[str]:
276272
"""
@@ -385,35 +381,6 @@ def _extract_user_project_namespaces(self, username: str) -> list[str]:
385381

386382
return user_namespaces
387383

388-
def _get_username_from_token_review(self, access_token: str) -> str:
389-
"""
390-
Extract username from Token Access Review.
391-
392-
Args:
393-
access_token: The access token to review
394-
395-
Returns:
396-
str: The username from the token review, or empty string if not found
397-
"""
398-
try:
399-
token_review = client.V1TokenReview(
400-
spec=client.V1TokenReviewSpec(token=access_token)
401-
)
402-
403-
response = self.auth_v1.create_token_review(token_review)
404-
405-
if response.status.authenticated and response.status.user:
406-
username = getattr(response.status.user, "username", "") or ""
407-
logger.debug(f"Extracted username from Token Access Review: {username}")
408-
return username
409-
else:
410-
logger.warning(f"Token Access Review failed: {response.status.error}")
411-
return ""
412-
413-
except Exception as e:
414-
logger.error(f"Failed to get username from Token Access Review: {e}")
415-
return ""
416-
417384
def _cluster_role_binding_grants_namespace_access(
418385
self, cluster_role_binding, namespace: str
419386
) -> bool:

‎sdk/python/tests/unit/permissions/auth/server/mock_utils.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,7 @@ def mock_kubernetes(request, monkeypatch):
7979
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._read_namespace_from_file",
8080
lambda self: my_namespace,
8181
)
82+
monkeypatch.setattr(
83+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._extract_groups_and_namespaces_from_token",
84+
lambda self, token: (subject, [], []),
85+
)

‎sdk/python/tests/unit/permissions/auth/test_token_parser.py‎

Lines changed: 99 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -849,13 +849,11 @@ def test_oidc_default_supports_v1_tokens_against_v2_discovery(
849849

850850
# TODO RBAC: Move role bindings to a reusable fixture
851851
@patch("feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config")
852-
@patch("feast.permissions.auth.kubernetes_token_parser.jwt.decode")
853852
@patch(
854853
"feast.permissions.auth.kubernetes_token_parser.client.RbacAuthorizationV1Api.list_namespaced_role_binding"
855854
)
856855
def test_k8s_token_validation_success(
857856
mock_rb,
858-
mock_jwt,
859857
mock_config,
860858
rolebindings,
861859
monkeypatch,
@@ -868,7 +866,11 @@ def test_k8s_token_validation_success(
868866
lambda self: my_namespace,
869867
)
870868
subject = f"system:serviceaccount:{sa_namespace}:{sa_name}"
871-
mock_jwt.return_value = {"sub": subject}
869+
# TokenReview authenticates the token as this service account.
870+
monkeypatch.setattr(
871+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._extract_groups_and_namespaces_from_token",
872+
lambda self, token: (subject, [], []),
873+
)
872874

873875
mock_rb.return_value = rolebindings["items"]
874876

@@ -889,6 +891,95 @@ def test_k8s_token_validation_success(
889891
assertpy.assert_that(user.has_matching_role(["foo"])).is_false()
890892

891893

894+
@patch("feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config")
895+
@patch(
896+
"feast.permissions.auth.kubernetes_token_parser.client.AuthenticationV1Api.create_token_review"
897+
)
898+
def test_k8s_sa_token_requires_token_review(mock_token_review, mock_config):
899+
# TokenReview reports the token as not authenticated.
900+
mock_token_review.return_value = MagicMock(
901+
status=MagicMock(authenticated=False, user=None, error="invalid token")
902+
)
903+
904+
token_parser = KubernetesTokenParser()
905+
with pytest.raises(AuthenticationError):
906+
asyncio.run(
907+
token_parser.user_details_from_access_token(access_token="aaa-bbb-ccc")
908+
)
909+
910+
911+
@pytest.mark.parametrize(
912+
"username",
913+
[
914+
"system:serviceaccount:",
915+
"system:serviceaccount:my-ns",
916+
"system:serviceaccount::my-name",
917+
"system:serviceaccount:my-ns:",
918+
"system:serviceaccount:my-ns:my-name:extra",
919+
],
920+
)
921+
@patch("feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config")
922+
def test_k8s_malformed_sa_username_is_rejected(mock_config, username, monkeypatch):
923+
monkeypatch.setattr(
924+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._extract_groups_and_namespaces_from_token",
925+
lambda self, token: (username, [], []),
926+
)
927+
928+
token_parser = KubernetesTokenParser()
929+
with pytest.raises(AuthenticationError):
930+
asyncio.run(
931+
token_parser.user_details_from_access_token(access_token="aaa-bbb-ccc")
932+
)
933+
934+
935+
@patch("feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config")
936+
@patch("feast.permissions.auth.kubernetes_token_parser.jwt.decode")
937+
@patch(
938+
"feast.permissions.auth.kubernetes_token_parser.client.AuthenticationV1Api.create_token_review"
939+
)
940+
@patch(
941+
"feast.permissions.auth.kubernetes_token_parser.client.RbacAuthorizationV1Api.list_namespaced_role_binding"
942+
)
943+
def test_k8s_sa_identity_comes_from_token_review(
944+
mock_rb,
945+
mock_token_review,
946+
mock_jwt,
947+
mock_config,
948+
rolebindings,
949+
monkeypatch,
950+
my_namespace,
951+
sa_name,
952+
sa_namespace,
953+
):
954+
# The token's sub claim names the service account that has roles, but
955+
# TokenReview authenticates it as another one. The user details must
956+
# follow TokenReview.
957+
monkeypatch.setattr(
958+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._read_namespace_from_file",
959+
lambda self: my_namespace,
960+
)
961+
monkeypatch.setattr(
962+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._extract_namespace_access_groups",
963+
lambda self, namespace: [],
964+
)
965+
mock_jwt.return_value = {"sub": f"system:serviceaccount:{sa_namespace}:{sa_name}"}
966+
mock_rb.return_value = rolebindings["items"]
967+
reviewed_user = MagicMock(groups=[])
968+
reviewed_user.username = f"system:serviceaccount:{sa_namespace}:other-sa"
969+
mock_token_review.return_value = MagicMock(
970+
status=MagicMock(authenticated=True, user=reviewed_user)
971+
)
972+
973+
token_parser = KubernetesTokenParser()
974+
user = asyncio.run(
975+
token_parser.user_details_from_access_token(access_token="aaa-bbb-ccc")
976+
)
977+
978+
assertpy.assert_that(user.username).is_equal_to(f"{sa_namespace}:other-sa")
979+
assertpy.assert_that(user.roles).is_empty()
980+
assertpy.assert_that(user.has_matching_role(rolebindings["roles"])).is_false()
981+
982+
892983
@patch("feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config")
893984
@patch("feast.permissions.auth.kubernetes_token_parser.jwt.decode")
894985
def test_k8s_token_validation_failure(mock_jwt, mock_config):
@@ -940,6 +1031,10 @@ def test_k8s_inter_server_comm(
9401031
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._read_namespace_from_file",
9411032
lambda self: my_namespace,
9421033
)
1034+
monkeypatch.setattr(
1035+
"feast.permissions.auth.kubernetes_token_parser.KubernetesTokenParser._extract_groups_and_namespaces_from_token",
1036+
lambda self, token: (subject, [], []),
1037+
)
9431038

9441039
monkeypatch.setattr(
9451040
"feast.permissions.auth.kubernetes_token_parser.config.load_incluster_config",
@@ -994,7 +1089,7 @@ async def reject(self, access_token):
9941089
monkeypatch.setattr(
9951090
KubernetesTokenParser,
9961091
"_extract_groups_and_namespaces_from_token",
997-
lambda self, token: ([], []),
1092+
lambda self, token: ("", [], []),
9981093
)
9991094
monkeypatch.setattr(
10001095
KubernetesTokenParser, "_read_namespace_from_file", lambda self: "feast"

0 commit comments

Comments
 (0)