-
Notifications
You must be signed in to change notification settings - Fork 168
feat(BA-4905): add LoginSecurityPolicy model, login_sessions table, and repository layer #9720
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
Open
HyeockJinKim
wants to merge
6
commits into
main
Choose a base branch
from
BA-4905
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+741
−0
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
78d22fb
feat(BA-4905): add LoginSecurityPolicy model and LoginSessionExpiryRe…
HyeockJinKim d5be241
feat(BA-4905): add login_security_policy column to UserRow and UserData
HyeockJinKim a9e5cb0
feat(BA-4905): add LoginSessionRow ORM model for login_sessions table
HyeockJinKim 10d16ee
feat(BA-4905): add alembic migration for login_sessions table and log…
HyeockJinKim a2cc747
feat(BA-4905): add LoginSessionRepository and LoginSessionService
HyeockJinKim c966801
changelog: add news fragment for PR #9720
HyeockJinKim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Deviation Report: BA-4905 | ||
|
|
||
| | Item | Type | Reason / Alternative | | ||
| |------|------|----------------------| | ||
| | Task 1: `LoginSecurityPolicy(BaseModel)` placed in `data/login_session/types.py` | Alternative applied | `data/` CLAUDE.md prohibits Pydantic imports. Pydantic models used with PydanticColumn follow the `models/{domain}/types.py` pattern (see `models/scaling_group/types.py`, `models/resource_slot/types.py`). `LoginSecurityPolicy` placed in `models/login_session/types.py` instead. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add LoginSecurityPolicy model, login_sessions table, LoginSessionRepository (Valkey Sorted Set + DB), and LoginSessionService for concurrent login session management. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import enum | ||
| from dataclasses import dataclass, field | ||
| from datetime import datetime | ||
| from uuid import UUID | ||
|
|
||
|
|
||
| class LoginSessionExpiryReason(enum.StrEnum): | ||
| LOGOUT = "logout" | ||
| EVICTED = "evicted" | ||
| EXPIRED = "expired" | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class LoginSessionData: | ||
| id: UUID | ||
| user_uuid: UUID | ||
| session_token: str | ||
| client_ip: str | ||
| created_at: datetime | ||
| expired_at: datetime | None = field(default=None) | ||
| reason: LoginSessionExpiryReason | None = field(default=None) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
...odels/alembic/versions/ba49050abc12_add_login_sessions_table_and_login_security_policy.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Add login_sessions table and login_security_policy column to users | ||
|
|
||
| Revision ID: ba49050abc12 | ||
| Revises: ffcf0ed13a26 | ||
| Create Date: 2026-03-06 00:00:00.000000 | ||
|
|
||
| """ | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
|
|
||
| from ai.backend.manager.models.base import GUID | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "ba49050abc12" | ||
| down_revision = "ffcf0ed13a26" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| op.create_table( | ||
| "login_sessions", | ||
| sa.Column( | ||
| "id", | ||
| GUID(), | ||
| server_default=sa.text("uuid_generate_v4()"), | ||
| nullable=False, | ||
| ), | ||
| sa.Column("user_uuid", GUID(), nullable=False), | ||
| sa.Column("session_token", sa.String(length=512), nullable=False), | ||
| sa.Column("client_ip", sa.String(length=64), nullable=False), | ||
| sa.Column( | ||
| "created_at", | ||
| sa.DateTime(timezone=True), | ||
| server_default=sa.func.now(), | ||
| nullable=False, | ||
| ), | ||
| sa.Column("expired_at", sa.DateTime(timezone=True), nullable=True), | ||
| sa.Column("reason", sa.String(length=64), nullable=True), | ||
| sa.ForeignKeyConstraint( | ||
| ["user_uuid"], | ||
| ["users.uuid"], | ||
| name=op.f("fk_login_sessions_user_uuid_users"), | ||
| ondelete="CASCADE", | ||
| ), | ||
| sa.PrimaryKeyConstraint("id", name=op.f("pk_login_sessions")), | ||
| sa.UniqueConstraint("session_token", name=op.f("uq_login_sessions_session_token")), | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_login_sessions_user_uuid"), | ||
| "login_sessions", | ||
| ["user_uuid"], | ||
| unique=False, | ||
| ) | ||
| op.add_column( | ||
| "users", | ||
| sa.Column( | ||
| "login_security_policy", | ||
| sa.dialects.postgresql.JSONB(none_as_null=True), | ||
| nullable=True, | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| op.drop_column("users", "login_security_policy") | ||
| op.drop_index(op.f("ix_login_sessions_user_uuid"), table_name="login_sessions") | ||
| op.drop_table("login_sessions") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from ai.backend.manager.models.login_session.row import LoginSessionRow | ||
|
|
||
| __all__ = ("LoginSessionRow",) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import uuid | ||
| from collections.abc import Sequence | ||
| from datetime import datetime | ||
|
|
||
| import sqlalchemy as sa | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
|
|
||
| from ai.backend.manager.data.login_session.types import LoginSessionData, LoginSessionExpiryReason | ||
| from ai.backend.manager.models.base import ( | ||
| GUID, | ||
| Base, | ||
| StrEnumType, | ||
| ) | ||
|
|
||
| __all__: Sequence[str] = ("LoginSessionRow",) | ||
|
|
||
|
|
||
| class LoginSessionRow(Base): # type: ignore[misc] | ||
| __tablename__ = "login_sessions" | ||
| __table_args__ = ( | ||
| sa.UniqueConstraint("session_token", name="uq_login_sessions_session_token"), | ||
| sa.Index("ix_login_sessions_user_uuid", "user_uuid"), | ||
| ) | ||
|
|
||
| id: Mapped[uuid.UUID] = mapped_column( | ||
| "id", GUID, primary_key=True, server_default=sa.text("uuid_generate_v4()") | ||
| ) | ||
| user_uuid: Mapped[uuid.UUID] = mapped_column( | ||
| "user_uuid", | ||
| GUID, | ||
| sa.ForeignKey("users.uuid", ondelete="CASCADE"), | ||
| nullable=False, | ||
| ) | ||
| session_token: Mapped[str] = mapped_column( | ||
| "session_token", | ||
| sa.String(length=512), | ||
| nullable=False, | ||
| ) | ||
| client_ip: Mapped[str] = mapped_column( | ||
| "client_ip", | ||
| sa.String(length=64), | ||
| nullable=False, | ||
| ) | ||
| created_at: Mapped[datetime] = mapped_column( | ||
| "created_at", | ||
| sa.DateTime(timezone=True), | ||
| server_default=sa.func.now(), | ||
| nullable=False, | ||
| ) | ||
| expired_at: Mapped[datetime | None] = mapped_column( | ||
| "expired_at", | ||
| sa.DateTime(timezone=True), | ||
| nullable=True, | ||
| ) | ||
| reason: Mapped[LoginSessionExpiryReason | None] = mapped_column( | ||
| "reason", | ||
| StrEnumType(LoginSessionExpiryReason), | ||
| nullable=True, | ||
| ) | ||
|
|
||
| def to_dataclass(self) -> LoginSessionData: | ||
| return LoginSessionData( | ||
| id=self.id, | ||
| user_uuid=self.user_uuid, | ||
| session_token=self.session_token, | ||
| client_ip=self.client_ip, | ||
| created_at=self.created_at, | ||
| expired_at=self.expired_at, | ||
| reason=self.reason, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from pydantic import BaseModel, ConfigDict | ||
|
|
||
| __all__ = ("LoginSecurityPolicy",) | ||
|
|
||
|
|
||
| class LoginSecurityPolicy(BaseModel): | ||
| """Login security policy for controlling concurrent session limits. | ||
|
|
||
| Stored as JSONB in the users table via PydanticColumn. | ||
| """ | ||
|
|
||
| model_config = ConfigDict(frozen=True) | ||
|
|
||
| max_concurrent_logins: int | None = None | ||
| """Maximum number of concurrent login sessions allowed. | ||
|
|
||
| None means unlimited. | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,9 +30,11 @@ | |
| Base, | ||
| EnumValueType, | ||
| IPColumn, | ||
| PydanticColumn, | ||
| ) | ||
| from ai.backend.manager.models.hasher import PasswordHasherFactory | ||
| from ai.backend.manager.models.hasher.types import HashInfo, PasswordColumn, PasswordInfo | ||
| from ai.backend.manager.models.login_session.types import LoginSecurityPolicy | ||
| from ai.backend.manager.models.types import ( | ||
| QueryCondition, | ||
| QueryOption, | ||
|
|
@@ -237,6 +239,9 @@ class UserRow(Base): # type: ignore[misc] | |
| container_gids: Mapped[list[int] | None] = mapped_column( | ||
| "container_gids", sa.ARRAY(sa.Integer), nullable=True, server_default=sa.null() | ||
| ) | ||
| login_security_policy: Mapped[LoginSecurityPolicy | None] = mapped_column( | ||
| "login_security_policy", PydanticColumn(LoginSecurityPolicy), nullable=True | ||
| ) | ||
|
Comment on lines
+242
to
+244
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use the default value rather than leaving it optional. |
||
|
|
||
| # Relationships | ||
| sessions: Mapped[list[SessionRow]] = relationship( | ||
|
|
@@ -431,6 +436,9 @@ def to_data(self) -> UserData: | |
| container_uid=self.container_uid, | ||
| container_main_gid=self.container_main_gid, | ||
| container_gids=self.container_gids, | ||
| login_security_policy=self.login_security_policy.model_dump() | ||
| if self.login_security_policy is not None | ||
| else None, | ||
| ) | ||
|
|
||
|
|
||
|
|
||
5 changes: 5 additions & 0 deletions
5
src/ai/backend/manager/repositories/login_session/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """Login session repository module.""" | ||
|
|
||
| from .repository import LoginSessionRepository | ||
|
|
||
| __all__ = ["LoginSessionRepository"] |
1 change: 1 addition & 0 deletions
1
src/ai/backend/manager/repositories/login_session/cache_source/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Cache source for login session repository.""" |
70 changes: 70 additions & 0 deletions
70
src/ai/backend/manager/repositories/login_session/cache_source/cache_source.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Cache source for login session repository operations using Valkey Sorted Sets.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from uuid import UUID | ||
|
|
||
| from ai.backend.common.clients.valkey_client.valkey_stat.client import ValkeyStatClient | ||
| from ai.backend.logging.utils import BraceStyleAdapter | ||
|
|
||
| log = BraceStyleAdapter(logging.getLogger(__spec__.name)) | ||
|
|
||
| _KEY_PREFIX = "login_session" | ||
|
|
||
|
|
||
| class LoginSessionCacheSource: | ||
| """ | ||
| Cache source for login session operations. | ||
| Uses Valkey Sorted Set keyed by `login_session:{user_uuid}`. | ||
| Score = UNIX timestamp of session creation. | ||
| Member = session_token. | ||
| """ | ||
|
|
||
| _valkey_stat: ValkeyStatClient | ||
|
|
||
| def __init__(self, valkey_stat: ValkeyStatClient) -> None: | ||
| self._valkey_stat = valkey_stat | ||
|
|
||
| def _key(self, user_uuid: UUID) -> str: | ||
| return f"{_KEY_PREFIX}:{user_uuid}" | ||
|
|
||
| async def add_session(self, user_uuid: UUID, session_token: str, score: float) -> None: | ||
| """Register a session in the sorted set (ZADD).""" | ||
| await self._valkey_stat.execute_command([ | ||
| "ZADD", | ||
| self._key(user_uuid), | ||
| str(score), | ||
| session_token, | ||
| ]) | ||
|
|
||
| async def session_score(self, user_uuid: UUID, session_token: str) -> float | None: | ||
| """Check if session exists and return its score (ZSCORE). Returns None if not found.""" | ||
| result = await self._valkey_stat.execute_command([ | ||
| "ZSCORE", | ||
| self._key(user_uuid), | ||
| session_token, | ||
| ]) | ||
| if result is None: | ||
| return None | ||
| return float(result) | ||
|
|
||
| async def count_sessions(self, user_uuid: UUID) -> int: | ||
| """Return number of active sessions for user (ZCARD).""" | ||
| result = await self._valkey_stat.execute_command(["ZCARD", self._key(user_uuid)]) | ||
| return int(result) if result is not None else 0 | ||
|
|
||
| async def pop_oldest_session(self, user_uuid: UUID) -> str | None: | ||
| """Evict the oldest session (lowest score) and return its token (ZPOPMIN).""" | ||
| result = await self._valkey_stat.execute_command(["ZPOPMIN", self._key(user_uuid)]) | ||
| if not result: | ||
| return None | ||
| # ZPOPMIN returns [member, score] interleaved; first element is the member | ||
| member = result[0] | ||
| if isinstance(member, bytes): | ||
| return member.decode() | ||
| return str(member) | ||
|
|
||
| async def remove_session(self, user_uuid: UUID, session_token: str) -> None: | ||
| """Remove a session from the sorted set (ZREM).""" | ||
| await self._valkey_stat.execute_command(["ZREM", self._key(user_uuid), session_token]) |
1 change: 1 addition & 0 deletions
1
src/ai/backend/manager/repositories/login_session/db_source/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Database source for login session repository.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid using
dict. We recommend handling data throughPydanticModelordataclass.