vs-security-db 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """RDBMS adapters for vs-security, using vs-db's task-local transaction handling."""
2
+
3
+ from vs_security_db.store.login_attempt_store import VsDbLoginAttemptStore
4
+ from vs_security_db.store.permission_store import VsDbPermissionStore
5
+ from vs_security_db.store.policy_store import VsDbPolicyStore
6
+ from vs_security_db.store.role_store import VsDbRoleStore
7
+ from vs_security_db.store.revocation_store import VsDbRevocationStore
8
+ from vs_security_db.store.token_store import VsDbTokenStore
9
+ from vs_security_db.store.user_role_store import VsDbUserRoleStore
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = ["VsDbUserRoleStore", "VsDbRoleStore", "VsDbPolicyStore", "VsDbPermissionStore", "VsDbTokenStore", "VsDbRevocationStore", "VsDbLoginAttemptStore"]
@@ -0,0 +1 @@
1
+ """Pass this package to VsDbSessionFactory's entity scanner."""
@@ -0,0 +1,64 @@
1
+ from sqlalchemy import BigInteger, CheckConstraint, Double, Index, String
2
+ from sqlalchemy.dialects.mysql import CHAR
3
+ from sqlalchemy.orm import Mapped, mapped_column
4
+ from vs_db.base.vs_db_base import VsDbBase
5
+ from vs_db.decorator.vs_db_decorator import entity
6
+
7
+ from vs_security_db.entity.catalog import NAMESPACE
8
+
9
+ # Fingerprints compare byte-for-byte, including when MySQL prefers casual spelling.
10
+ DIGEST = String(64).with_variant(CHAR(64, collation="ascii_bin"), "mysql")
11
+
12
+
13
+ class ExpiringFields:
14
+ """Double-precision epoch timestamps retain fractional-second cutoffs."""
15
+
16
+ namespace: Mapped[str] = mapped_column(NAMESPACE, nullable=False)
17
+ expires_at: Mapped[float] = mapped_column(Double, nullable=False)
18
+
19
+
20
+ @entity("vs_security_refresh_tokens")
21
+ class RefreshTokenRow(ExpiringFields, VsDbBase):
22
+ """Refresh-token fingerprints; raw tokens never enter this table."""
23
+
24
+ __tablename__ = "vs_security_refresh_tokens"
25
+ __table_args__ = (Index("ix_security_refresh_expiry", "namespace", "expires_at"),)
26
+ # Owner hashes include the namespace; another application gets another key.
27
+ owner_key: Mapped[str] = mapped_column(DIGEST, primary_key=True)
28
+ token_hash: Mapped[str] = mapped_column(DIGEST, primary_key=True)
29
+
30
+
31
+ @entity("vs_security_session_revocations")
32
+ class SessionRevocationRow(ExpiringFields, VsDbBase):
33
+ """Per-session access revocation until every matching token has expired."""
34
+
35
+ __tablename__ = "vs_security_session_revocations"
36
+ __table_args__ = (Index("ix_security_session_expiry", "namespace", "expires_at"),)
37
+ owner_key: Mapped[str] = mapped_column(DIGEST, primary_key=True)
38
+ session_key: Mapped[str] = mapped_column(DIGEST, primary_key=True)
39
+
40
+
41
+ @entity("vs_security_user_revocations")
42
+ class UserRevocationRow(ExpiringFields, VsDbBase):
43
+ """A user-wide issuance cutoff, independent of application user-table schemas."""
44
+
45
+ __tablename__ = "vs_security_user_revocations"
46
+ __table_args__ = (Index("ix_security_user_expiry", "namespace", "expires_at"),)
47
+ owner_key: Mapped[str] = mapped_column(DIGEST, primary_key=True)
48
+ cutoff: Mapped[float] = mapped_column(Double, nullable=False)
49
+
50
+
51
+ @entity("vs_security_login_attempts")
52
+ class LoginAttemptRow(ExpiringFields, VsDbBase):
53
+ """Shared, row-serialized failed-login counters without raw usernames or IPs."""
54
+
55
+ __tablename__ = "vs_security_login_attempts"
56
+ __table_args__ = (
57
+ CheckConstraint("failures >= 0", name="ck_security_login_failures"),
58
+ Index("ix_security_login_expiry", "namespace", "expires_at"),
59
+ )
60
+ key_hash: Mapped[str] = mapped_column(DIGEST, primary_key=True)
61
+ # Epoch seconds need double precision; minutes-long rounding is no clock feature.
62
+ failures: Mapped[int] = mapped_column(BigInteger, nullable=False)
63
+ window_started_at: Mapped[float] = mapped_column(Double, nullable=False)
64
+ locked_until: Mapped[float] = mapped_column(Double, nullable=False)
@@ -0,0 +1,56 @@
1
+ from sqlalchemy import Boolean, ForeignKeyConstraint, String, Text
2
+ from sqlalchemy.dialects.mysql import VARCHAR
3
+ from sqlalchemy.orm import Mapped, mapped_column
4
+ from vs_db.base.vs_db_base import VsDbBase
5
+ from vs_db.decorator.vs_db_decorator import entity
6
+
7
+ # MySQL's usual case-insensitive collation must not merge distinct permission codes.
8
+ CODE = String(255).with_variant(VARCHAR(255, collation="utf8mb4_bin"), "mysql")
9
+ NAMESPACE = String(128).with_variant(VARCHAR(128, collation="utf8mb4_bin"), "mysql")
10
+
11
+
12
+ class CatalogFields:
13
+ """Catalog data preserves the upstream models without inventing application roles."""
14
+
15
+ namespace: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
16
+ code: Mapped[str] = mapped_column(CODE, primary_key=True)
17
+ # Upstream IDs are payload fields; uniqueness belongs to the permission code.
18
+ id: Mapped[str] = mapped_column(Text, nullable=False)
19
+ name: Mapped[str] = mapped_column(Text, nullable=False)
20
+ description: Mapped[str] = mapped_column(Text, nullable=False)
21
+ active: Mapped[bool] = mapped_column(Boolean, nullable=False)
22
+
23
+
24
+ @entity("vs_security_features")
25
+ class FeatureRow(CatalogFields, VsDbBase):
26
+ """Features scoped to an application's catalog namespace."""
27
+
28
+ __tablename__ = "vs_security_features"
29
+
30
+
31
+ @entity("vs_security_actions")
32
+ class ActionRow(CatalogFields, VsDbBase):
33
+ """Reusable actions scoped to an application's catalog namespace."""
34
+
35
+ __tablename__ = "vs_security_actions"
36
+
37
+
38
+ @entity("vs_security_permissions")
39
+ class PermissionRow(VsDbBase):
40
+ """One unique feature/action pair with database-enforced parent references."""
41
+
42
+ __tablename__ = "vs_security_permissions"
43
+ # A permission needs real parents; imaginary features get no VIP pass.
44
+ __table_args__ = (
45
+ ForeignKeyConstraint(["namespace", "feature_code"],
46
+ ["vs_security_features.namespace", "vs_security_features.code"], name="fk_security_permission_feature"),
47
+ ForeignKeyConstraint(["namespace", "action_code"],
48
+ ["vs_security_actions.namespace", "vs_security_actions.code"], name="fk_security_permission_action"),
49
+ )
50
+ namespace: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
51
+ feature_code: Mapped[str] = mapped_column(CODE, primary_key=True)
52
+ action_code: Mapped[str] = mapped_column(CODE, primary_key=True)
53
+ # The computed feature:action key stays in vs-security, where its rules live.
54
+ id: Mapped[str] = mapped_column(Text, nullable=False)
55
+ description: Mapped[str] = mapped_column(Text, nullable=False)
56
+ active: Mapped[bool] = mapped_column(Boolean, nullable=False)
@@ -0,0 +1,34 @@
1
+ from sqlalchemy import ForeignKeyConstraint, Index
2
+ from sqlalchemy.orm import Mapped, mapped_column
3
+ from vs_db.base.vs_db_base import VsDbBase
4
+ from vs_db.decorator.vs_db_decorator import entity
5
+
6
+ from vs_security_db.entity.catalog import CODE, NAMESPACE, CatalogFields
7
+
8
+
9
+ @entity("vs_security_policies")
10
+ class PolicyRow(CatalogFields, VsDbBase):
11
+ """Policy metadata with a short natural code for portable assignment indexes."""
12
+
13
+ __tablename__ = "vs_security_policies"
14
+ # 128 policy characters leave room for feature and action in MySQL's index budget.
15
+ code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
16
+
17
+
18
+ @entity("vs_security_policy_permissions")
19
+ class PolicyPermissionRow(VsDbBase):
20
+ """One grant held by one policy: an exact permission or a wildcard ("users:*", "*:*").
21
+ Wildcards aren't catalog rows, so only the policy has a foreign key; the store checks the rest."""
22
+
23
+ __tablename__ = "vs_security_policy_permissions"
24
+ # Natural composite keys reject duplicate grants even outside this adapter.
25
+ __table_args__ = (
26
+ ForeignKeyConstraint(["namespace", "policy_code"],
27
+ ["vs_security_policies.namespace", "vs_security_policies.code"], name="fk_security_policy_permission_policy"),
28
+ Index("ix_security_policy_permission_catalog", "namespace", "feature_code", "action_code"),
29
+ )
30
+ namespace: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
31
+ policy_code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
32
+ # A feature or action code, or '*' for "any"; the store validates which.
33
+ feature_code: Mapped[str] = mapped_column(CODE, primary_key=True)
34
+ action_code: Mapped[str] = mapped_column(CODE, primary_key=True)
@@ -0,0 +1,32 @@
1
+ from sqlalchemy import ForeignKeyConstraint, Index
2
+ from sqlalchemy.orm import Mapped, mapped_column
3
+ from vs_db.base.vs_db_base import VsDbBase
4
+ from vs_db.decorator.vs_db_decorator import entity
5
+
6
+ from vs_security_db.entity.catalog import NAMESPACE, CatalogFields
7
+
8
+
9
+ @entity("vs_security_roles")
10
+ class RoleRow(CatalogFields, VsDbBase):
11
+ """Role metadata with namespace-scoped, case-sensitive natural codes."""
12
+
13
+ __tablename__ = "vs_security_roles"
14
+ code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
15
+
16
+
17
+ @entity("vs_security_role_policies")
18
+ class RolePolicyRow(VsDbBase):
19
+ """Unique role/policy assignments with database-enforced namespace consistency."""
20
+
21
+ __tablename__ = "vs_security_role_policies"
22
+ # A policy cannot cross namespaces just because someone knows its code.
23
+ __table_args__ = (
24
+ ForeignKeyConstraint(["namespace", "role_code"],
25
+ ["vs_security_roles.namespace", "vs_security_roles.code"], name="fk_security_role_policy_role"),
26
+ ForeignKeyConstraint(["namespace", "policy_code"],
27
+ ["vs_security_policies.namespace", "vs_security_policies.code"], name="fk_security_role_policy_policy"),
28
+ Index("ix_security_role_policy_catalog", "namespace", "policy_code"),
29
+ )
30
+ namespace: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
31
+ role_code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
32
+ policy_code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
@@ -0,0 +1,27 @@
1
+ from sqlalchemy import ForeignKeyConstraint, Index, String
2
+ from sqlalchemy.dialects.mysql import VARCHAR
3
+ from sqlalchemy.orm import Mapped, mapped_column
4
+ from vs_db.base.vs_db_base import VsDbBase
5
+ from vs_db.decorator.vs_db_decorator import entity
6
+
7
+ from vs_security_db.entity.catalog import NAMESPACE
8
+
9
+ # Subjects compare exactly; "Ravi" and "ravi" are two people as far as we can tell.
10
+ SUBJECT = String(255).with_variant(VARCHAR(255, collation="utf8mb4_bin"), "mysql")
11
+
12
+
13
+ @entity("vs_security_user_roles")
14
+ class UserRoleRow(VsDbBase):
15
+ """One subject holding one role. Subjects are plain ids, not hashes, so admins can list
16
+ who holds a role; there is no foreign key to any application user table."""
17
+
18
+ __tablename__ = "vs_security_user_roles"
19
+ # The role must exist in the same namespace; nobody gets a crown from another kingdom.
20
+ __table_args__ = (
21
+ ForeignKeyConstraint(["namespace", "role_code"],
22
+ ["vs_security_roles.namespace", "vs_security_roles.code"], name="fk_security_user_role_role"),
23
+ Index("ix_security_user_role_role", "namespace", "role_code"),
24
+ )
25
+ namespace: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
26
+ subject: Mapped[str] = mapped_column(SUBJECT, primary_key=True)
27
+ role_code: Mapped[str] = mapped_column(NAMESPACE, primary_key=True)
File without changes
@@ -0,0 +1 @@
1
+ """Database implementations of the existing vs-security store interfaces."""
@@ -0,0 +1,84 @@
1
+ import hashlib
2
+ import json
3
+ import math
4
+ import time
5
+ from typing import Callable
6
+
7
+ from sqlalchemy import delete
8
+ from sqlalchemy.dialects.mysql import insert as mysql_insert
9
+ from sqlalchemy.dialects.postgresql import insert as postgres_insert
10
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
11
+ from vs_db.base.vs_db_session_aware import VsDbSessionAware
12
+ from vs_security.schema.vs_auth_context import VsAuthContext
13
+
14
+ SubjectResolver = Callable[[VsAuthContext], str]
15
+
16
+
17
+ def subject_from_context(context: VsAuthContext) -> str:
18
+ """Resolve the standard JWT subject; custom contexts can inject another resolver."""
19
+ subject = context.to_claims().get("sub")
20
+ if not isinstance(subject, str) or not subject:
21
+ raise ValueError("Auth context must expose a nonempty sub claim, or provide subject_resolver")
22
+ return subject
23
+
24
+
25
+ class VsDbStore(VsDbSessionAware):
26
+ """Task-local vs-db sessions, namespace isolation, and portable lock helpers."""
27
+
28
+ def __init__(self, *, data_source=None, namespace="default", subject_resolver=None):
29
+ """Bind to an existing factory without opening connections or creating tables."""
30
+ if not isinstance(namespace, str) or not namespace or len(namespace) > 128:
31
+ raise ValueError("namespace must contain between 1 and 128 characters")
32
+ if subject_resolver is not None and not callable(subject_resolver):
33
+ raise TypeError("subject_resolver must be callable")
34
+ self.data_source, self.namespace = data_source, namespace
35
+ # Identity schemas stay in the application; this adapter just needs a stable key.
36
+ self.subject_resolver = subject_resolver or subject_from_context
37
+
38
+ def _key(self, kind: str, value: str) -> str:
39
+ """Hash an unambiguous namespace/kind/value tuple without logging its contents."""
40
+ if not isinstance(value, str) or not value:
41
+ raise ValueError("Store keys must be nonempty strings")
42
+ payload = json.dumps([self.namespace, kind, value], ensure_ascii=False)
43
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
44
+
45
+ def _owner(self, context: VsAuthContext) -> str:
46
+ """Use only the stable subject; rotating claims never rename the account."""
47
+ if not context.is_authenticated:
48
+ raise ValueError("Store operations require an authenticated context")
49
+ return self._key("owner", self.subject_resolver(context))
50
+
51
+ @staticmethod
52
+ def _duration(seconds: float) -> float:
53
+ """Reject negative, infinite, and NaN retention values before storing them."""
54
+ value = float(seconds)
55
+ if not math.isfinite(value) or value < 0:
56
+ raise ValueError("Retention seconds must be finite and nonnegative")
57
+ return value
58
+
59
+ async def _ensure_row(self, model, values: dict) -> None:
60
+ """Insert or no-op update to acquire the row's database write lock."""
61
+ table = model.__table__
62
+ dialect = self.db.get_bind().dialect.name
63
+ first_key = next(iter(table.primary_key.columns))
64
+ # Even an existing row gets a write lock; SQLite's FOR UPDATE is decorative.
65
+ if dialect == "mysql":
66
+ query = mysql_insert(table).values(**values)
67
+ query = query.on_duplicate_key_update(**{first_key.name: first_key})
68
+ elif dialect in ("postgresql", "sqlite"):
69
+ builder = postgres_insert if dialect == "postgresql" else sqlite_insert
70
+ query = builder(table).values(**values).on_conflict_do_update(
71
+ index_elements=list(table.primary_key.columns), set_={first_key.name: first_key})
72
+ else:
73
+ raise NotImplementedError("Security stores support MySQL, PostgreSQL, and SQLite")
74
+ await self.db.execute(query)
75
+
76
+ async def _purge(self, *models) -> int:
77
+ """Remove only expired rows in this namespace during explicit maintenance."""
78
+ removed, now = 0, time.time()
79
+ for model in models:
80
+ # Live revocations and counters never join the cleanup parade.
81
+ query = delete(model).where(model.namespace == self.namespace, model.expires_at <= now)
82
+ result = await self.db.execute(query)
83
+ removed += result.rowcount
84
+ return removed
@@ -0,0 +1,84 @@
1
+ from sqlalchemy import select, update
2
+ from sqlalchemy.exc import IntegrityError
3
+ from vs_security.error.vs_permission_error import VsPermissionConflictError
4
+ from vs_security.permission.vs_permission_model import validate_code
5
+
6
+ from vs_security_db.store.base import VsDbStore
7
+
8
+
9
+ class VsDbCatalogStore(VsDbStore):
10
+ """Shared catalog persistence helpers for the permission and policy adapters."""
11
+
12
+ @staticmethod
13
+ def _code(code: str) -> str:
14
+ """Preserve upstream code validation and enforce the indexed storage bound."""
15
+ validate_code(code)
16
+ if len(code) > 255:
17
+ raise ValueError("Catalog codes cannot exceed 255 characters")
18
+ return code
19
+
20
+ async def _save(self, row, kind: str, key: str) -> None:
21
+ """Use a unique constraint and savepoint to report only genuine catalog conflicts."""
22
+ if not await self._insert_once(row):
23
+ raise VsPermissionConflictError(kind, key)
24
+
25
+ async def _insert_once(self, row) -> bool:
26
+ """Insert in a savepoint; False if the unique key already has the row.
27
+ Any other integrity failure, such as a missing parent, is raised."""
28
+ try:
29
+ # Duplicate inserts lose their savepoint, not the caller's entire transaction.
30
+ async with self.db.begin_nested():
31
+ self.db.add(row)
32
+ await self.db.flush()
33
+ except IntegrityError as error:
34
+ # Driver codes recognize a duplicate even when a transaction has an older snapshot.
35
+ if self._unique_conflict(error):
36
+ return False
37
+ raise
38
+ return True
39
+
40
+ async def _insert_then_check(self, row, check_parents) -> bool:
41
+ """Write first, then validate: True if added, False if it was already there.
42
+ `check_parents` raises VsCatalogNotFoundError for a missing parent, which rolls
43
+ the insert back. Writing first matters on SQLite: a transaction that reads and
44
+ then writes can't upgrade its lock while another writer works, and fails at once,
45
+ whereas one that writes first just waits its turn."""
46
+ try:
47
+ added = await self._insert_once(row)
48
+ except IntegrityError:
49
+ # a foreign key refused it; say which parent is missing, or re-raise
50
+ await check_parents()
51
+ raise
52
+ # foreign keys may be off (SQLite without the pragma), and wildcards have none
53
+ await check_parents()
54
+ return added
55
+
56
+ @staticmethod
57
+ def _unique_conflict(error: IntegrityError) -> bool:
58
+ """Distinguish unique violations from missing parents and other integrity failures."""
59
+ original = error.orig
60
+ state = getattr(original, "sqlstate", None) or getattr(original, "pgcode", None)
61
+ if state == "23505":
62
+ return True
63
+ # MySQL uses 1062; SQLite names primary-key and unique failures separately.
64
+ arguments = getattr(original, "args", ())
65
+ return (bool(arguments) and arguments[0] == 1062) or getattr(original, "sqlite_errorcode", None) in (1555, 2067)
66
+
67
+ async def _get(self, model, response, **filters):
68
+ """Map one namespace-scoped row to an independent upstream value object."""
69
+ row = await self.db.scalar(select(model).filter_by(namespace=self.namespace, **filters))
70
+ return response.model_validate(row, from_attributes=True) if row is not None else None
71
+
72
+ async def _list(self, model, response, *order, **filters):
73
+ """Read catalog rows in stable order without filtering activation flags."""
74
+ query = select(model).filter_by(namespace=self.namespace, **filters).order_by(*order)
75
+ rows = (await self.db.execute(query)).scalars().all()
76
+ return [response.model_validate(row, from_attributes=True) for row in rows]
77
+
78
+ async def _switch(self, model, active: bool, **filters) -> bool:
79
+ """Return matched-row existence even when the active value was already set."""
80
+ if not isinstance(active, bool):
81
+ raise TypeError("active must be a bool")
82
+ query = update(model).filter_by(namespace=self.namespace, **filters).values(active=active)
83
+ # SQLAlchemy's MySQL dialect reports matched rows, including unchanged switches.
84
+ return (await self.db.execute(query)).rowcount == 1
@@ -0,0 +1,68 @@
1
+ import math
2
+ import time
3
+ from dataclasses import replace
4
+
5
+ from sqlalchemy import delete, select
6
+ from vs_db.decorator.vs_db_decorator import Propagation, transactional
7
+ from vs_security.auth.vs_login_attempt_store import VsLoginAttemptChange, VsLoginAttempts, VsLoginAttemptStore
8
+
9
+ from vs_security_db.entity.auth import LoginAttemptRow
10
+ from vs_security_db.store.base import VsDbStore
11
+
12
+
13
+ class VsDbLoginAttemptStore(VsDbStore, VsLoginAttemptStore):
14
+ """Cross-worker login counters, serialized by database locks rather than process locks."""
15
+
16
+ @transactional(propagation=Propagation.REQUIRES_NEW, read_only=True)
17
+ async def get(self, key: str) -> VsLoginAttempts | None:
18
+ """Read a live counter without reviving expired bookkeeping."""
19
+ query = select(LoginAttemptRow).where(LoginAttemptRow.key_hash == self._key("login", key),
20
+ LoginAttemptRow.expires_at > time.time())
21
+ row = await self.db.scalar(query)
22
+ return self._attempts(row) if row is not None else None
23
+
24
+ @transactional(propagation=Propagation.REQUIRES_NEW)
25
+ async def update(self, key: str, change: VsLoginAttemptChange, ttl_seconds: float) -> VsLoginAttempts:
26
+ """Apply a pure callback under a write lock and commit before returning."""
27
+ retention, key_hash = self._duration(ttl_seconds), self._key("login", key)
28
+ await self._ensure_row(LoginAttemptRow, dict(namespace=self.namespace, key_hash=key_hash,
29
+ failures=0, window_started_at=0.0, locked_until=0.0, expires_at=0.0))
30
+ # Existing and missing keys both take a write lock before reading the count.
31
+ query = select(LoginAttemptRow).where(LoginAttemptRow.key_hash == key_hash)
32
+ row = (await self.db.execute(query.with_for_update().execution_options(populate_existing=True))).scalar_one()
33
+ current = self._attempts(row) if row.expires_at > time.time() else None
34
+ attempts = change(current)
35
+ self._validate_attempts(attempts)
36
+ # The callback gets its own value object; shared mutable state stays outside.
37
+ row.failures, row.window_started_at = attempts.failures, attempts.window_started_at
38
+ row.locked_until, row.expires_at = attempts.locked_until, time.time() + retention
39
+ await self.db.flush()
40
+ return replace(attempts)
41
+
42
+ @transactional(propagation=Propagation.REQUIRES_NEW)
43
+ async def delete(self, key: str) -> None:
44
+ """Persist successful-login cleanup even if the caller rolls back afterwards."""
45
+ await self.db.execute(delete(LoginAttemptRow).where(LoginAttemptRow.key_hash == self._key("login", key)))
46
+
47
+ @staticmethod
48
+ def _attempts(row: LoginAttemptRow) -> VsLoginAttempts:
49
+ """Copy a row into the value object required by vs-security."""
50
+ return VsLoginAttempts(failures=row.failures, window_started_at=row.window_started_at,
51
+ locked_until=row.locked_until)
52
+
53
+ @staticmethod
54
+ def _validate_attempts(attempts: VsLoginAttempts) -> None:
55
+ """Reject invalid callback results before they can corrupt shared counters."""
56
+ if not isinstance(attempts, VsLoginAttempts):
57
+ raise TypeError("Login-attempt callback must return VsLoginAttempts")
58
+ if type(attempts.failures) is not int or not 0 <= attempts.failures <= 2**63 - 1:
59
+ raise ValueError("Login failure count must be a nonnegative signed 64-bit integer")
60
+ # Timestamps are clocks, not creative containers for NaN or infinity.
61
+ if any(not math.isfinite(value) or value < 0 for value in
62
+ (attempts.window_started_at, attempts.locked_until)):
63
+ raise ValueError("Login timestamps must be finite nonnegative epoch seconds")
64
+
65
+ @transactional(propagation=Propagation.REQUIRES_NEW)
66
+ async def purge_expired(self) -> int:
67
+ """Remove expired login counters for this namespace explicitly."""
68
+ return await self._purge(LoginAttemptRow)
@@ -0,0 +1,92 @@
1
+ from vs_db.decorator.vs_db_decorator import transactional
2
+ from vs_security.error.vs_permission_error import VsPermissionConflictError, VsPermissionNotFoundError
3
+ from vs_security.permission.vs_permission_model import VsAction, VsFeature, VsPermission
4
+ from vs_security.permission.vs_permission_store import VsPermissionStore
5
+
6
+ from vs_security_db.entity.catalog import ActionRow, FeatureRow, PermissionRow
7
+ from vs_security_db.store.catalog_store import VsDbCatalogStore
8
+
9
+
10
+ class VsDbPermissionStore(VsDbCatalogStore, VsPermissionStore):
11
+ """Database catalog implementing every feature/action/permission store operation."""
12
+
13
+ @transactional
14
+ async def save_feature(self, feature: VsFeature) -> None:
15
+ """Insert a feature with database-enforced namespace/code uniqueness."""
16
+ self._code(feature.code)
17
+ await self._save(FeatureRow(namespace=self.namespace, **feature.model_dump()), "Feature", feature.code)
18
+
19
+ @transactional(read_only=True)
20
+ async def get_feature(self, code: str) -> VsFeature | None:
21
+ """Read one feature without exposing a mutable ORM row."""
22
+ return await self._get(FeatureRow, VsFeature, code=self._code(code))
23
+
24
+ @transactional(read_only=True)
25
+ async def list_features(self) -> list[VsFeature]:
26
+ """List this namespace's features in stable code order."""
27
+ return await self._list(FeatureRow, VsFeature, FeatureRow.code)
28
+
29
+ @transactional
30
+ async def set_feature_active(self, code: str, active: bool) -> bool:
31
+ """Switch a feature; return False only when its code does not exist."""
32
+ return await self._switch(FeatureRow, active, code=self._code(code))
33
+
34
+ @transactional
35
+ async def save_action(self, action: VsAction) -> None:
36
+ """Insert an action with database-enforced namespace/code uniqueness."""
37
+ self._code(action.code)
38
+ await self._save(ActionRow(namespace=self.namespace, **action.model_dump()), "Action", action.code)
39
+
40
+ @transactional(read_only=True)
41
+ async def get_action(self, code: str) -> VsAction | None:
42
+ """Read one action without coupling callers to the database schema."""
43
+ return await self._get(ActionRow, VsAction, code=self._code(code))
44
+
45
+ @transactional(read_only=True)
46
+ async def list_actions(self) -> list[VsAction]:
47
+ """List this namespace's actions in stable code order."""
48
+ return await self._list(ActionRow, VsAction, ActionRow.code)
49
+
50
+ @transactional
51
+ async def set_action_active(self, code: str, active: bool) -> bool:
52
+ """Switch an action; return False only when its code does not exist."""
53
+ return await self._switch(ActionRow, active, code=self._code(code))
54
+
55
+ @transactional
56
+ async def save_permission(self, permission: VsPermission) -> None:
57
+ """Insert a unique feature/action pair; its feature and action must exist.
58
+ A duplicate raises VsCatalogConflictError, a missing parent VsCatalogNotFoundError."""
59
+ feature, action = self._code(permission.feature_code), self._code(permission.action_code)
60
+ row = PermissionRow(namespace=self.namespace, **permission.model_dump())
61
+
62
+ async def check_parents():
63
+ # foreign keys guard this too; the reads just name the missing parent
64
+ if await self._get(FeatureRow, VsFeature, code=feature) is None:
65
+ raise VsPermissionNotFoundError("Feature", feature)
66
+ if await self._get(ActionRow, VsAction, code=action) is None:
67
+ raise VsPermissionNotFoundError("Action", action)
68
+
69
+ # write first, then validate: parallel seeding queues instead of failing on SQLite
70
+ if not await self._insert_then_check(row, check_parents):
71
+ raise VsPermissionConflictError("Permission", permission.key)
72
+
73
+ @transactional(read_only=True)
74
+ async def get_permission(self, key: str) -> VsPermission | None:
75
+ """Read a permission using vs-security's feature:action key format."""
76
+ feature, action = VsPermission.split_key(key)
77
+ return await self._get(PermissionRow, VsPermission,
78
+ feature_code=self._code(feature), action_code=self._code(action))
79
+
80
+ @transactional(read_only=True)
81
+ async def list_permissions(self, feature_code: str | None = None) -> list[VsPermission]:
82
+ """List all catalog grants or only those belonging to one feature."""
83
+ filters = {} if feature_code is None else {"feature_code": self._code(feature_code)}
84
+ return await self._list(PermissionRow, VsPermission,
85
+ PermissionRow.feature_code, PermissionRow.action_code, **filters)
86
+
87
+ @transactional
88
+ async def set_permission_active(self, key: str, active: bool) -> bool:
89
+ """Switch a permission without overriding its feature/action activation flags."""
90
+ feature, action = VsPermission.split_key(key)
91
+ return await self._switch(PermissionRow, active,
92
+ feature_code=self._code(feature), action_code=self._code(action))