Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(BA-781): Let Auth API handler check all keypairs owned by user #3780

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions changes/3780.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Let Auth API handler check all keypairs owned by user
2 changes: 1 addition & 1 deletion docs/manager/rest-reference/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"info": {
"title": "Backend.AI Manager API",
"description": "Backend.AI Manager REST API specification",
"version": "25.2.0",
"version": "25.3.0",
"contact": {
"name": "Lablup Inc.",
"url": "https://docs.backend.ai",
Expand Down
26 changes: 10 additions & 16 deletions src/ai/backend/manager/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from ..models.user import (
INACTIVE_USER_STATUSES,
UserRole,
UserRow,
UserStatus,
check_credential,
compare_to_hashed_password,
Expand Down Expand Up @@ -727,33 +728,26 @@ async def authorize(request: web.Request, params: Any) -> web.Response:
raise AuthorizationFailed("This account needs email verification.")
if user["status"] in INACTIVE_USER_STATUSES:
raise AuthorizationFailed("User credential mismatch.")
async with root_ctx.db.begin() as conn:
query = (
sa.select([keypairs.c.access_key, keypairs.c.secret_key])
.select_from(keypairs)
.where(
(keypairs.c.user == user["uuid"]) & (keypairs.c.is_active),
)
.order_by(sa.desc(keypairs.c.is_admin))
)
result = await conn.execute(query)
keypair = result.first()
if keypair is None:
raise AuthorizationFailed("No API keypairs found.")
await check_password_age(root_ctx.db, user, root_ctx.shared_config["auth"])
async with root_ctx.db.begin_session() as db_session:
user_row = await UserRow.query_user_by_uuid(user["uuid"], db_session)
assert user_row is not None
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use assert.

main_keypair_row = user_row.get_main_keypair_row()
if main_keypair_row is None:
raise AuthorizationFailed("No API keypairs found.")
# [Hooking point for POST_AUTHORIZE]
# The hook handlers should accept a tuple of the request, user, and keypair objects.
hook_result = await root_ctx.hook_plugin_ctx.dispatch(
"POST_AUTHORIZE",
(request, params, user, keypair),
(request, params, user, main_keypair_row.mapping),
return_when=FIRST_COMPLETED,
)
if hook_result.status != PASSED:
raise RejectedByHook.from_hook_result(hook_result)
return web.json_response({
"data": {
"access_key": keypair["access_key"],
"secret_key": keypair["secret_key"],
"access_key": main_keypair_row.access_key,
"secret_key": main_keypair_row.secret_key,
"role": user["role"],
"status": user["status"],
},
Expand Down
21 changes: 21 additions & 0 deletions src/ai/backend/manager/models/keypair.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ class KeyPairRow(Base):

user_row = relationship("UserRow", back_populates="keypairs", foreign_keys=keypairs.c.user)

@property
def mapping(self) -> dict[str, Any]:
return {
"user_id": self.user_id,
"access_key": self.access_key,
"secret_key": self.secret_key,
"is_active": self.is_active,
"is_admin": self.is_admin,
"created_at": self.created_at,
"modified_at": self.modified_at,
"last_used": self.last_used,
"rate_limit": self.rate_limit,
"num_queries": self.num_queries,
"ssh_public_key": self.ssh_public_key,
"ssh_private_key": self.ssh_private_key,
"user": self.user,
"resource_policy": self.resource_policy,
"dotfiles": self.dotfiles,
"bootstrap_script": self.bootstrap_script,
}


class UserInfo(graphene.ObjectType):
email = graphene.String()
Expand Down
40 changes: 38 additions & 2 deletions src/ai/backend/manager/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import enum
import logging
from typing import TYPE_CHECKING, Any, Dict, Iterable, Mapping, Optional, Sequence, cast
from typing import TYPE_CHECKING, Any, Dict, Iterable, Mapping, Optional, Self, Sequence, cast
from uuid import UUID, uuid4

import aiotools
Expand All @@ -18,7 +18,7 @@
from sqlalchemy.ext.asyncio import AsyncConnection as SAConnection
from sqlalchemy.ext.asyncio import AsyncEngine as SAEngine
from sqlalchemy.ext.asyncio import AsyncSession as SASession
from sqlalchemy.orm import joinedload, load_only, noload, relationship
from sqlalchemy.orm import joinedload, load_only, noload, relationship, selectinload
from sqlalchemy.sql.expression import bindparam
from sqlalchemy.types import VARCHAR, TypeDecorator

Expand Down Expand Up @@ -48,6 +48,7 @@

if TYPE_CHECKING:
from .gql import GraphQueryContext
from .keypair import KeyPairRow
from .storage import StorageSessionManager

log = BraceStyleAdapter(logging.getLogger(__spec__.name))
Expand Down Expand Up @@ -191,6 +192,41 @@ class UserRow(Base):
primaryjoin="UserRow.uuid == foreign(VFolderRow.user)",
)

@classmethod
async def query_user_by_uuid(
cls,
user_uuid: UUID,
db_session: SASession,
) -> Optional[Self]:
user_query = (
sa.select(UserRow)
.where(UserRow.uuid == user_uuid)
.options(
joinedload(UserRow.main_keypair),
selectinload(UserRow.keypairs),
)
)
user_row = await db_session.scalar(user_query)
return user_row

def get_main_keypair_row(self) -> Optional[KeyPairRow]:
# `cast()` requires import of KeyPairRow
from .keypair import KeyPairRow

keypair_candidate: Optional[KeyPairRow] = None
main_keypair_row = cast(Optional[KeyPairRow], self.main_keypair)
if main_keypair_row is None:
keypair_rows = cast(list[KeyPairRow], self.keypairs)
active_keypairs = [row for row in keypair_rows if row.is_active]
for row in active_keypairs:
if keypair_candidate is None or not keypair_candidate.is_admin:
keypair_candidate = row
if keypair_candidate is not None:
self.main_keypair = keypair_candidate
else:
keypair_candidate = main_keypair_row
return keypair_candidate


class UserGroup(graphene.ObjectType):
id = graphene.UUID()
Expand Down
Loading