Skip to content

Commit

Permalink
feat: improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
shahargl committed Oct 1, 2024
1 parent ab4c204 commit e57f1de
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 1 deletion.
5 changes: 5 additions & 0 deletions keep/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,11 @@ async def log_middleware(request: Request, call_next):
f"Request started: {request.method} {request.url.path}",
extra={"tenant_id": identity},
)

# for debugging purposes, log the payload
if os.environ.get("LOG_AUTH_PAYLOAD", "false") == "true":
logger.info(f"Request headers: {request.headers}")

start_time = time.time()
request.state.tenant_id = identity
response = await call_next(request)
Expand Down
16 changes: 16 additions & 0 deletions keep/api/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,22 @@ def create_user(tenant_id, username, password, role):
return user


def update_user_last_sign_in(tenant_id, username):
from keep.api.models.db.user import User

with Session(engine) as session:
user = session.exec(
select(User)
.where(User.tenant_id == tenant_id)
.where(User.username == username)
).first()
if user:
user.last_sign_in = datetime.utcnow()
session.add(user)
session.commit()
return user


def save_workflow_results(tenant_id, workflow_execution_id, workflow_results):
with Session(engine) as session:
workflow_execution = session.exec(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from fastapi.security import HTTPAuthorizationCredentials

from keep.api.core.config import config
from keep.api.core.db import create_user, user_exists
from keep.api.core.db import create_user, update_user_last_sign_in, user_exists
from keep.api.core.dependencies import SINGLE_TENANT_UUID
from keep.identitymanager.authenticatedentity import AuthenticatedEntity
from keep.identitymanager.authverifierbase import AuthVerifierBase
Expand Down Expand Up @@ -74,20 +74,28 @@ def authenticate(

mapped_role = None
for priority_role in role_priority:
self.logger.debug(f"Checking for role {priority_role}")
for role in roles:
self.logger.debug(f"Checking for role {role}")
# map the role if its a mapped one, or just use the role
mapped_role_name = self.role_mappings.get(role, role)
self.logger.debug(f"Checking for mapped role {mapped_role_name}")
if mapped_role_name == priority_role:
try:
self.logger.debug(f"Getting role {mapped_role_name}")
mapped_role = get_role_by_role_name(mapped_role_name)
self.logger.debug(f"Role {mapped_role_name} found")
break
except HTTPException:
self.logger.debug(f"Role {mapped_role_name} not found")
continue
if mapped_role:
self.logger.debug(f"Role {mapped_role_name} found")
break

# if no valid role was found, throw a 403 exception
if not mapped_role:
self.logger.debug(f"No valid role found among {roles}")
raise HTTPException(
status_code=403,
detail=f"No valid role found among {roles}",
Expand All @@ -105,6 +113,19 @@ def authenticate(
password="",
)
self.logger.info(f"User {user_name} created")
elif user_exists(tenant_id=SINGLE_TENANT_UUID, username=user_name):
# update last login
self.logger.debug(f"Updating last login for user: {user_name}")
try:
update_user_last_sign_in(
tenant_id=SINGLE_TENANT_UUID, username=user_name
)
self.logger.debug(f"Last login updated for user: {user_name}")
except Exception:
self.logger.warning(
f"Failed to update last login for user: {user_name}"
)
pass

self.logger.info(f"User {user_name} authenticated with role {mapped_role}")
return AuthenticatedEntity(
Expand Down
38 changes: 38 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,41 @@ def test_oauth_proxy(db_session, client, test_app):
json={"email": "shahar", "role": "admin"},
)
assert response.status_code == 403


@pytest.mark.parametrize(
"test_app",
[
{
"AUTH_TYPE": "OAUTH2PROXY",
"KEEP_OAUTH2_PROXY_USER_HEADER": "x-forwarded-email",
"KEEP_OAUTH2_PROXY_USER_ROLE": "X-Forwarded-Groups",
"KEEP_OAUTH2_PROXY_ADMIN_ROLE": "[email protected]",
"KEEP_OAUTH2_PROXY_NOC_ROLE": "[email protected]",
"KEEP_OAUTH2_PROXY_WEBHOOK_ROLE": "[email protected]",
},
],
indirect=True,
)
def test_oauth_proxy2(db_session, client, test_app):
"""Tests the oauth2proxy impersonation with different environment settings"""
response = client.post(
"/auth/users",
headers={
"x-forwarded-email": "shahar",
"X-Forwarded-Groups": "[email protected],[email protected],[email protected],[email protected]",
},
json={"email": "shahar", "role": "admin"},
)
# admin role should be able to create users, noc would fail
assert response.status_code == 200

response = client.post(
"/auth/users",
headers={
"x-forwarded-email": "shahar",
"x-forwarded-groups": "[email protected],[email protected]",
},
json={"email": "shahar", "role": "admin"},
)
assert response.status_code == 403

0 comments on commit e57f1de

Please sign in to comment.