Skip to content

Commit 2cf8292

Browse files
committed
k8s: add can_delete_pods function
We use this to check if the current user can delete pods.
1 parent 2bb87ec commit 2cf8292

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/warnet/k8s.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,3 +424,37 @@ def get_service_accounts_in_namespace(namespace):
424424
# skip the default service account created by k8s
425425
service_accounts = run_command(command).split()
426426
return [sa for sa in service_accounts if sa != "default"]
427+
428+
429+
def can_delete_pods(namespace: Optional[str] = None) -> bool:
430+
namespace = get_default_namespace_or(namespace)
431+
432+
get_static_client()
433+
auth_api = client.AuthorizationV1Api()
434+
435+
# Define the SelfSubjectAccessReview request for deleting pods
436+
access_review = client.V1SelfSubjectAccessReview(
437+
spec=client.V1SelfSubjectAccessReviewSpec(
438+
resource_attributes=client.V1ResourceAttributes(
439+
namespace=namespace,
440+
verb="delete", # Action: 'delete'
441+
resource="pods", # Resource: 'pods'
442+
)
443+
)
444+
)
445+
446+
try:
447+
# Perform the SelfSubjectAccessReview check
448+
review_response = auth_api.create_self_subject_access_review(body=access_review)
449+
450+
# Check the result and return
451+
if review_response.status.allowed:
452+
print(f"Service account can delete pods in namespace '{namespace}'.")
453+
return True
454+
else:
455+
print(f"Service account CANNOT delete pods in namespace '{namespace}'.")
456+
return False
457+
458+
except ApiException as e:
459+
print(f"An error occurred: {e}")
460+
return False

0 commit comments

Comments
 (0)