Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,42 @@
from keep.identitymanager.authenticatedentity import AuthenticatedEntity
from keep.identitymanager.authverifierbase import AuthVerifierBase, oauth2_scheme
from keycloak import KeycloakOpenID, KeycloakOpenIDConnection
from keycloak.connection import ConnectionManager
from keycloak.keycloak_uma import KeycloakUMA
from keycloak.uma_permissions import UMAPermission

logger = logging.getLogger(__name__)


# PATCH TO MONKEYPATCH KEYCLOAK VERIFY BUG
# https://github.com/marcospereirampj/python-keycloak/issues/645

original_init = ConnectionManager.__init__


def patched_init(
self,
base_url: str,
headers: dict = None,
timeout: int = 60,
verify: bool = None,
proxies: dict = None,
):
if verify is None:
verify = os.environ.get("KEYCLOAK_VERIFY_CERT", "true").lower() == "true"
logger.warning(
"Using KEYCLOAK_VERIFY_CERT environment variable to set verify. ",
extra={"KEYCLOAK_VERIFY_CERT": verify},
)

if headers is None:
headers = {}
original_init(self, base_url, headers, timeout, verify, proxies)


ConnectionManager.__init__ = patched_init


class KeycloakAuthVerifier(AuthVerifierBase):
"""Handles authentication and authorization for Keycloak"""

Expand Down Expand Up @@ -99,9 +129,11 @@ def _authorize(self, authenticated_entity: AuthenticatedEntity) -> None:
resource=self.protected_resource,
scope=self.scopes[0], # todo: handle multiple scopes per resource
)
self.logger.info(f"Checking permission {permission}")
allowed = self.keycloak_uma.permissions_check(
token=authenticated_entity.token, permissions=[permission]
)
self.logger.info(f"Permission check result: {allowed}")
if not allowed:
raise HTTPException(status_code=401, detail="Permission check failed")
# secure fallback
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ def _scope_name_to_id(self, all_scopes, scope_name: str) -> str:
(scope for scope in all_scopes if scope["name"] == scope_name),
None,
)
if not scope:
self.logger.error(
"Scope %s not found in Keycloak",
scope_name,
extra={"scopes": all_scopes},
)
return []
return [scope["id"]]

def get_permission_by_name(self, permission_name):
Expand Down