Metadata-Version: 2.4
Name: vs-security
Version: 0.2.1
Summary: Security library for Viveka Sutra — authentication, JWT, and authorization
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Project-URL: Homepage, https://vivekasutra.com/
Project-URL: Source, https://github.com/vivekasutra/viveka-mula
Keywords: security,auth,jwt,authentication,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: pydantic>=2.0
Requires-Dist: pyjwt>=2.8
Requires-Dist: bcrypt>=4.0
Requires-Dist: vs-common>=0.2.1
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == "fastapi"
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: redis>=5.0; extra == "dev"
Requires-Dist: fakeredis>=2.20; extra == "dev"
Dynamic: license-file

# vs-security

Authentication and authorization library for the Viveka Sutra platform. It provides a provider-based authentication model, generic session handling, JWT token management, and a framework-agnostic security filter — all wired together without boilerplate.

---

## Installation

```bash
pip install vs-security
```

**Dependencies:**

| Package | Version | Purpose |
|---|---|---|
| `pydantic` | `>=2.0` | Schema validation |
| `pyjwt` | `>=2.8` | JWT encoding/decoding |
| `bcrypt` | `>=4.0` | Password hashing |
| `vs-common` | `>=0.2.1` | Config, logging, base exceptions |

---

## Shared request authentication

`VsRequestAuthenticator` is the transport-independent interface used by HTTP and MCP adapters:

```python
from vs_security import (
    VsRequestAuthenticator, VsAuthRequest, VsAuthContext,
    VsBearerTokenAuthenticator, VsJWTProvider,
    get_auth_context,
)

# Built-in adapter: extract Authorization: Bearer <token>, then validate the session.
authenticator = VsBearerTokenAuthenticator(VsJWTProvider(config))
# Pass authenticator=authenticator to VsAgentServer or VsFastMcpServer.
# For an existing session, use VsBearerTokenAuthenticator(session).
```

For stdio bearer credentials, pass `VsBearerTokenAuthenticator(session, stdio_token_env="VS_AGENT_TOKEN")`. The launcher supplies the token through that explicitly named environment variable. Each stdio request validates it through the same session; no token source is inferred. These credentials identify the launched process. Custom authenticators receive empty headers, `transport="stdio"`, and the MCP method name.

For custom authentication, subclass `VsRequestAuthenticator` and implement `async authenticate(self, request: VsAuthRequest) -> VsAuthContext`. Validate credentials before returning identity. Raise `VsAuthenticationError` for rejected credentials or `VsInsufficientRolesError` for insufficient permissions. Unexpected infrastructure and programming errors must propagate unchanged; do not convert them to credential rejection. The adapters log them and propagate server failures. Cancellation also propagates.

`VsAuthRequest` contains `headers`, `transport`, `path`, and `method`. Transport is validated at runtime and must be `http`, `mcp`, `stdio`, or `queue`; a typo such as `htpp` raises `ValueError`. Queue requests additionally expose `topic`, `message_id`, `reply_to`, and `correlation_id`; `get_header(name)` is case-insensitive. Headers are copied into an immutable mapping and omitted from its representation. The optional `payload` field (since 0.1.17) contains a detached, recursively read-only snapshot of request data: mappings become immutable mappings and arrays become tuples. It defaults to `None` and is omitted from representations. Read values with `request.payload.get(...)` after checking for a mapping; the snapshot does not alter action input. Payload fields are unvalidated request data and must not replace authenticated identity. The interface imports without FastAPI or MCP. Implementations must support concurrent requests across transport threads and event loops.

Return a context rather than modifying a `ContextVar`. HTTP/MCP adapters set the single shared context for the request and reset it in `finally`. Handlers and guards use `get_auth_context()`; old imports from `vs_security.guard.vs_security` and `vs_mcp_agent.auth.vs_mcp_auth` read the same context. Roles are supplied by your `VsAuthContext` subclass; the base context grants no roles.

---

## Legacy compatibility

The existing `VsBearerTokenFilter` delegates bearer parsing and session validation to `VsBearerTokenAuthenticator`. Its `enrich(context)` extension still runs after authentication, so existing applications can continue fetching fresh user details there.

`from vs_security import *` exports the framework-independent API without loading FastAPI. The deprecated `VsSecurity` dependency is intentionally excluded from star imports. Existing explicit imports (`from vs_security import VsSecurity`) still work when the FastAPI extra is installed.

---

## Architecture Overview

The library is built around three independent concerns that compose together:

**Authentication** — who are you? A `VsAuthProvider` receives credentials (username/password, OAuth token, API key — anything) and returns a `VsAuthContext` confirming the user's identity.

**Session** — what do we give back, and how do we verify it? A `VsSession[T]` has two responsibilities: `generate()` produces a session of type `T` after login, and `validate()` verifies an incoming token and returns the `VsAuthContext`. Both live in one class so the generate and validate logic stays together. `VsJWTProvider` is the built-in implementation — it returns `VsTokenPair`.

**Authorization** — are you allowed? A `VsSecurityFilter` (in `vs-server`) runs as middleware on every request, validates credentials, and stores `VsAuthContext` in a `ContextVar`. Route guards then read that context to enforce roles — with no dependency on any HTTP framework. For fine-grained checks, `VsPermissionResolver` answers "may this user do `users:create`?" from features, permissions, policies and roles kept in stores you choose; see [Authorization](#authorization--features-permissions-policies-and-roles).

```
┌──────────────────────────────────────────────────────────┐
│  LOGIN FLOW                                              │
│                                                          │
│  credentials ──► VsAuthProvider ──► VsAuthContext        │
│                                          │               │
│                                   VsSession.generate()   │
│                                          │               │
│                                          T               │
│                                  (VsTokenPair, etc.)     │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│  REQUEST FLOW                                            │
│                                                          │
│  Incoming request                                        │
│         │                                                │
│  VsSecurityFilter.process()  (middleware, in vs-server)  │
│         │  calls do_filter() → validate → set context    │
│         ▼                                                │
│  VsAuthContext stored in ContextVar                      │
│         │                                                │
│  Route guard reads get_auth_context() → checks roles     │
└──────────────────────────────────────────────────────────┘
```

| Class | Role | Extend? |
|---|---|---|
| `VsAuthManager` | Coordinator — routes credentials to the right provider and calls the session | No |
| `VsAuthProvider` | Verifies credentials, returns `VsAuthContext` | Yes — one per auth mechanism |
| `VsSession[T]` | Abstract base — implement `generate()` and `validate()` to define what a session looks like and how it is verified | Yes — to change the session format |
| `VsUserLoader` | Loads a user from your database for username/password auth | Yes — required for `VsUsernamePasswordAuthProvider` |
| `VsJWTProvider` | Built-in `VsSession[VsTokenPair]` — mints, verifies, refreshes, and revokes JWTs. Accepts `context_class` to control which subclass is reconstructed on decode | No — use as-is |
| `VsPermissionResolver` | Answers permission checks through roles, policies and the catalog | No — pick a `VsRoleSource` and stores |
| `VsPermissionStore`, `VsPolicyStore`, `VsRoleStore`, `VsUserRoleStore` | Where authorization data lives | Yes — or use vs-security-db |
| `VsSecurity` | ~~FastAPI dependency that guards routes~~ **Deprecated** — use `VsSecurityFilter` + `get_auth_context()` via `vs-server` | — |

---

## Quick Start — Complete Example

### Step 1 — Define your auth context

`VsAuthContext` is a base class with a `metadata: Dict[str, Any]` bag for arbitrary extra data. Subclass it to add your own typed fields and control how they serialize into the JWT.

```python
from uuid import UUID
from typing import List
from vs_security.schema.vs_auth_context import VsAuthContext

class AppAuthContext(VsAuthContext):
    user_id: UUID
    username: str
    roles: List[str] = []
    provider: str = ""

    def get_roles(self) -> List[str]:
        return self.roles

    def to_claims(self) -> dict:
        return {
            "sub": str(self.user_id),
            "username": self.username,
            "roles": self.roles,
            "provider": self.provider,
        }

    @classmethod
    def from_claims(cls, payload: dict) -> "AppAuthContext":
        return cls(
            user_id=UUID(payload["sub"]),
            username=payload.get("username", ""),
            roles=payload.get("roles", []),
            provider=payload.get("provider", ""),
        )
```

### Step 2 — Implement your user loader

```python
from vs_security.auth.vs_user_loader import VsUserLoader

class MyUserLoader(VsUserLoader):

    def __init__(self):
        self._repo = UserIdentityRepo()

    async def load(self, username: str):
        identity = await self._repo.find_by_email(username)
        if not identity:
            return None
        context = AppAuthContext(
            user_id=identity.user_id,
            username=identity.email,
            roles=identity.roles,
            provider="email",
        )
        return context, identity.hashed_password

    def verify_password(self, plain: str, stored: str) -> bool:
        import bcrypt
        return bcrypt.checkpw(plain.encode(), stored.encode())
```

### Step 3 — Wire everything at startup

Pass `context_class` to `VsJWTProvider` so it knows which subclass to reconstruct on token decode.

```python
from vs_security.auth.vs_auth_manager import VsAuthManager
from vs_security.auth.vs_jwt_provider import VsJWTProvider
from vs_security.auth.vs_username_password_provider import VsUsernamePasswordAuthProvider

jwt_provider = VsJWTProvider(config=config, context_class=AppAuthContext)

VsAuthManager.init(session=jwt_provider)
VsAuthManager.register("username_password", VsUsernamePasswordAuthProvider(
    user_loader=MyUserLoader()
))

# Controllers are imported after this point so VsSecurity.from_manager() resolves correctly
from app.controller.auth_controller import AuthController
from app.controller.user_controller import UserController
```

### Step 4 — Add a login endpoint

`authenticate()` returns whatever `T` your `VsSession` produces. With `VsJWTProvider`, that is `VsTokenPair`.

```python
from vs_security.auth.vs_auth_manager import VsAuthManager
from vs_security.schema.vs_credentials import VsUsernamePasswordCredentials
from vs_security.schema.vs_token_pair import VsTokenPair
from vs_security.error.vs_auth_error import VsAuthenticationError
from vs_server.decorator.vs_controller_decorator import controller, post

@controller("/auth")
class AuthController:

    @post("/login", response_model=VsTokenPair)
    async def login(self, body: LoginRequest):
        try:
            return await VsAuthManager.get_instance().authenticate(
                "username_password",
                VsUsernamePasswordCredentials(
                    username=body.username,
                    password=body.password,
                ),
            )
        except VsAuthenticationError as e:
            raise HTTPException(status_code=401, detail=str(e))
```

### Step 5 — Enable security on the server

In your app startup, call `enable_security()` on the server. The default uses Bearer token auth — pass a custom `VsSecurityFilter` subclass for any other mechanism.

```python
from vs_server.filter.vs_security_filter import VsSecurityFilter
from vs_server.filter.vs_request import VsRequest

# custom filter — or skip this and use the default VsBearerTokenFilter
class MyFilter(VsSecurityFilter):
    async def do_filter(self, request: VsRequest) -> None:
        from vs_security.auth.vs_auth_manager import VsAuthManager
        from vs_security.error.vs_auth_error import VsAuthenticationError
        from vs_security.guard.vs_security import set_auth_context

        token = (request.get_header("Authorization") or "").removeprefix("Bearer ").strip()
        if not token:
            raise VsAuthenticationError("Missing token")
        context = await VsAuthManager.get_instance().session.validate(token)
        set_auth_context(context)

server = VsServerFactory.get("fastapi", config)
server.enable_security()                              # default: VsBearerTokenFilter
# server.enable_security(MyFilter(exclude_paths=["/health"]))  # custom filter
server.run()
```

### Step 6 — Access context in handlers

```python
from vs_security.guard.vs_security import get_auth_context
from vs_server.decorator.vs_controller_decorator import controller, get

@controller("/users")
class UserController:

    @get("/me")
    async def get_me(self):
        context: AppAuthContext = get_auth_context()
        return {
            "user_id": str(context.user_id),
            "username": context.username,
            "roles": context.roles,
        }
```

---

## Configuration (`config.ini`)

```ini
[auth]
secret_key              = your-very-secret-key-here
algorithm               = HS256
access_expiry_minutes   = 15
refresh_expiry_days     = 7
login_attempt_limit     = 5
login_lockout_minutes   = 15
```

| Key | Default | Description |
|-----|---------|-------------|
| `auth.secret_key` | required | JWT signing secret. Must be at least as long as the hash: 32 bytes for HS256, 48 for HS384, 64 for HS512; the provider refuses to start otherwise. Generate one with `python -c "import secrets; print(secrets.token_urlsafe(48))"` |
| `auth.algorithm` | `HS256` | JWT signing algorithm |
| `auth.access_expiry_minutes` | `15` | Access token lifetime |
| `auth.refresh_expiry_days` | `7` | Refresh token lifetime |
| `auth.revoke_all_on_refresh_reuse` | `true` | When a refresh token that was already spent or revoked is presented again, sign the user out everywhere. Turn off only if your clients race their own refreshes and you accept losing theft detection |
| `auth.login_attempt_limit` | `5` | Failed logins per username before lockout. `0` turns lockout off. Read by `VsLoginAttemptLimiter.from_config()` |
| `auth.login_lockout_minutes` | `15` | How long a locked username stays locked, and the window failures are counted in |
| `auth.login_username_attempt_limit` | `50` | Failed logins on one username from all addresses together. Only used when the client IP is supplied. `0` turns it off |
| `auth.login_ip_attempt_limit` | `100` | Failed logins from one address across all usernames. Only used when the client IP is supplied. `0` turns it off |
| `auth.issuer` | unset | When set, tokens are stamped with this `iss` and tokens without it, or with another, are refused |
| `auth.audience` | unset | When set, tokens are stamped with this `aud` and tokens without it, or with another, are refused. A service with no audience configured ignores the claim |

**Turning on `auth.issuer` / `auth.audience`.** Tokens minted before the setting carry neither claim and are refused by any service that has it — including the issuing service, which checks its own refresh tokens the same way — so users log in once. Set both values on every service that shares the secret in the same deployment. Every service accepts the same user token, so use one shared audience value, not one per service.

**Login limits and the client IP.** Pass the caller's address in the credentials and one caller can no longer lock a real user out:

```python
credentials = VsUsernamePasswordCredentials(
    username=body.username, password=body.password,
    client_ip=request.client.host,   # from the connection or a proxy header you trust — never from the body
)
```

| Count | Limit | Locks |
|-------|-------|-------|
| username + IP | `auth.login_attempt_limit` | that address on that account only |
| username | `auth.login_username_attempt_limit` | the account, when many addresses guess at it |
| IP | `auth.login_ip_attempt_limit` | that address, when it tries many accounts |

Successful logins are taken back off the counts, so an office behind one address is not locked by logging in. IPv6 is counted by its /64 network. Without `client_ip` there is only the per-username count, as before.

**Sharing the counts between workers.** The default store lives in one process: each worker keeps its own count and a restart clears it. In production use Redis:

```python
from vs_security.auth.vs_redis_login_attempt_store import VsRedisLoginAttemptStore   # pip install vs-security[redis]

limiter = VsLoginAttemptLimiter.from_config(config, store=VsRedisLoginAttemptStore(redis_client))  # redis.asyncio.Redis
provider = VsUsernamePasswordAuthProvider(user_loader, limiter)
```

---

## Login Lockout

`VsUsernamePasswordAuthProvider` locks a username after repeated failed logins. By
default 5 failures within 15 minutes lock it for 15 minutes. While locked, every login
for that username raises `VsAccountLockedError` (429) without checking the password, so
guessing the right one during the lockout does not help. A successful login clears the
count. Each attempt is counted *before* its password is checked, in one atomic store
update, so simultaneous guesses each take their own turn: with a limit of 5, at most 5
passwords are checked per window, however many requests arrive at once. A login that
fails for another reason (the user loader raising, say) still uses up its attempt. Usernames are compared ignoring case and surrounding spaces, and unknown
usernames are counted and locked the same way, so lockout does not reveal which
accounts exist.

```python
from vs_security import VsLoginAttemptLimiter

# from [auth] login_attempt_limit / login_lockout_minutes
provider = VsUsernamePasswordAuthProvider(MyUserLoader(), VsLoginAttemptLimiter.from_config(config))

# or in code; limit=0 turns lockout off
provider = VsUsernamePasswordAuthProvider(MyUserLoader(), VsLoginAttemptLimiter(limit=0))
```

Counts are kept in memory per process by default, so with several workers each one
counts separately. To share one count, implement `VsLoginAttemptStore` on Redis or your
database and pass it as `store=`:

| Method | Must do |
|---|---|
| `get(key)` | Return the record, or `None` if there is none or it has expired |
| `update(key, change, ttl_seconds)` | **Atomically** read the record, call `change(record_or_None)`, store what it returns for `ttl_seconds`, and return it. Lock the row (`SELECT ... FOR UPDATE`) or retry on conflict (Redis `WATCH`/`MULTI`); `change` has no side effects, so calling it again on a retry is safe |
| `delete(key)` | Remove the record |

If `update` is not atomic, parallel guesses read the same count and each is checked as
if it were the first.

### A database-backed store with vs-db

A wrong password is **counted and then answered with a 401**. With vs-db 0.3.0 or later,
`VsDbMiddleware` rolls a request's transaction back on any response of 400 or above, so a
store that writes inside the request's transaction loses every count: the account never
locks, and nothing reports it. `update` and `delete` must commit on their own, with
`REQUIRES_NEW`. `update` locks the row so parallel logins for one username queue up:

```python
import time

from sqlalchemy import Double, String, delete, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from vs_db.base.vs_db_base import VsDbBase
from vs_db.base.vs_db_session_aware import VsDbSessionAware
from vs_db.decorator.vs_db_decorator import Propagation, entity, transactional
from vs_security import VsLoginAttemptStore
from vs_security.auth.vs_login_attempt_store import VsLoginAttempts


@entity("login_attempts")
class LoginAttemptRow(VsDbBase):
    key: Mapped[str] = mapped_column(String(320), primary_key=True)
    failures: Mapped[int]
    window_started_at: Mapped[float] = mapped_column(Double)   # epoch seconds: needs double precision
    locked_until: Mapped[float] = mapped_column(Double)
    expires_at: Mapped[float] = mapped_column(Double, index=True)


class DbLoginAttemptStore(VsDbSessionAware, VsLoginAttemptStore):
    """Failed-login counts in the database, shared by every worker."""

    @transactional(read_only=True)
    async def get(self, key):
        return _attempts(await self.db.get(LoginAttemptRow, key))

    @transactional(propagation=Propagation.REQUIRES_NEW)   # must survive the 401 that follows
    async def update(self, key, change, ttl_seconds):
        row = await self._locked_row(key)
        if row is None:
            # first attempt for this key: create it, unless a parallel login just did
            try:
                async with self.db.begin_nested():
                    self.db.add(LoginAttemptRow(key=key, failures=0, window_started_at=0.0,
                                                locked_until=0.0, expires_at=0.0))
            except IntegrityError:
                pass
            row = await self._locked_row(key)
        attempts = change(_attempts(row))
        row.failures, row.window_started_at, row.locked_until = (
            attempts.failures, attempts.window_started_at, attempts.locked_until)
        row.expires_at = time.time() + ttl_seconds
        return attempts

    @transactional(propagation=Propagation.REQUIRES_NEW)
    async def delete(self, key):
        await self.db.execute(delete(LoginAttemptRow).where(LoginAttemptRow.key == key))

    async def _locked_row(self, key):
        """The row, locked until this transaction ends: parallel logins queue here."""
        query = (select(LoginAttemptRow).where(LoginAttemptRow.key == key)
                 .with_for_update().execution_options(populate_existing=True))
        return (await self.db.execute(query)).scalar_one_or_none()


def _attempts(row):
    if row is None or row.expires_at <= time.time():
        return None
    return VsLoginAttempts(row.failures, row.window_started_at, row.locked_until)


provider = VsUsernamePasswordAuthProvider(
    MyUserLoader(), VsLoginAttemptLimiter.from_config(config, store=DbLoginAttemptStore())
)
```

Points that matter:

- **Lock the row in `update`.** Without `with_for_update()`, parallel logins read the same
  count and the limit stops working for them. The savepoint around the insert lets the
  loser of a race for a brand-new username carry on with the row the winner created.
- **Without `REQUIRES_NEW` lockout silently does nothing.** With a plain `@transactional`,
  every failure is rolled back along with its 401. (With vs-db before 0.3.0 the middleware
  happened to commit error responses, which hid this.)
- **Use double-precision columns for the timestamps.** They are epoch seconds. A
  single-precision column (`Float` on MySQL) rounds them by minutes, so every failure
  looks like the start of a new window and the count never passes 1.
- **Rows for expired windows are not deleted automatically** — `get` ignores them, but
  they stay in the table, and unknown usernames create rows too. Purge them regularly,
  for example `DELETE FROM login_attempts WHERE expires_at < <now>`.

Against this store on MariaDB with a limit of 3, 20 simultaneous wrong guesses for one
username had exactly 3 passwords checked; the other 17 got a 429, with no errors.

Lockout is per account. Anyone who knows a username can lock it out, which is the
usual trade-off of account lockout.

---

## Authorization — Features, Permissions, Policies and Roles

Authentication says **who** the user is. Authorization says **what they may do**.
vs-security models it in layers:

```
Feature  (users, reports, billing)  ─┐
Action   (view, create, delete)     ─┴─> Permission  "users:create"
                                              │
Policy   "user-admin"  = a set of grants:  users:*, reports:view
                                              │
Role     "admin"       = a set of policies: user-admin, read-only
                                              │
User     "user-42"     = a set of roles:    admin
```

Every layer has an **active** switch, every layer lives in a **store you choose**,
and one question answers it all:

```python
await resolver.has_permission(context, "users:create")   # True / False
```

vs-security holds the rules and the logic; it has no tables and no user model.
The stores are interfaces: use the in-memory ones for tests and small apps,
[`vs-security-db`](../vs-security-db) for MySQL, MariaDB, PostgreSQL or SQLite, or write
your own (Redis, an HR system, a directory service).

The walkthrough below builds a small CRM: features `users`, `reports` and
`billing`; actions `view`, `create`, `delete` and `export`.

### Step 1 — Wire the managers at startup

```python
from vs_security import (
    VsActionManager, VsFeatureManager, VsPermissionManager, VsPolicyManager, VsRoleManager,
    VsUserRoleManager, VsPermissionResolver, VsStoreRoleSource,
    VsInMemoryPermissionStore, VsInMemoryPolicyStore, VsInMemoryRoleStore, VsInMemoryUserRoleStore,
)

# Stores: swap these for VsDb*Store from vs-security-db in production.
catalog_store = VsInMemoryPermissionStore()
user_role_store = VsInMemoryUserRoleStore()

features = VsFeatureManager.init(catalog_store)
actions = VsActionManager.init(catalog_store)
permissions = VsPermissionManager.init(catalog_store)
policies = VsPolicyManager.init(VsInMemoryPolicyStore(), permission_manager=permissions)
roles = VsRoleManager.init(VsInMemoryRoleStore(), policy_manager=policies)
user_roles = VsUserRoleManager.init(user_role_store, role_manager=roles)

# The one object request handlers talk to.
resolver = VsPermissionResolver(
    role_source=VsStoreRoleSource(user_role_store),
    role_manager=roles, policy_manager=policies, permission_manager=permissions,
)
```

Each manager is a per-class singleton (`init` once, `get_instance()` anywhere), the
same pattern as `VsAuthManager`. Constructing one directly also works, which keeps
tests independent. All managers must share one logical catalog: the same stores,
or database stores with the same data source and namespace.

### Step 2 — Seed the catalog

Seeding is the application's job, typically on every start. `create` refuses a
code that already exists with `VsCatalogConflictError`, so make seeding
idempotent by catching it:

```python
from vs_security import VsCatalogConflictError

async def ensure(create, *args):
    """Create if missing; an earlier start already did it otherwise."""
    try:
        await create(*args)
    except VsCatalogConflictError:
        pass

async def seed_catalog():
    for code, name in [("users", "Users"), ("reports", "Reports"), ("billing", "Billing")]:
        await ensure(features.create, code, name)
    for code, name in [("view", "View"), ("create", "Create"), ("delete", "Delete"), ("export", "Export")]:
        await ensure(actions.create, code, name)
    for feature in ("users", "reports", "billing"):
        for action in ("view", "create", "delete", "export"):
            await ensure(permissions.create, feature, action)   # "users:view", ...
```

A permission needs its feature and action to exist first, otherwise
`VsCatalogNotFoundError`.

**Startup logs on database stores.** vs-db logs every refused insert at `ERROR`,
even when the code catches it, so a restart that re-runs this seed logs one line
per existing row. The data is correct; to keep restart logs quiet, check first and
keep the `except` for two workers starting at the same moment:

```python
if await features.get("users") is None:
    await ensure(features.create, "users", "Users")
```

### Step 3 — Group permissions into policies

A policy is a set of **grants**. A grant is an exact permission key or a wildcard:

| Grant | Covers |
| --- | --- |
| `users:create` | exactly that permission |
| `users:*` | every action on `users` |
| `*:view` | `view` on every feature |
| `*:*` | everything (use sparingly) |

```python
async def seed_policies():
    await ensure(policies.create, "user-admin", "Manage users")
    await policies.add_permission("user-admin", "users:*")

    await ensure(policies.create, "read-only", "Read everything")
    await policies.add_permission("read-only", "*:view")

    await ensure(policies.create, "finance", "Billing and exports")
    await policies.add_permission("finance", "billing:*")
    await policies.add_permission("finance", "reports:export")
```

`add_permission` returns `True` when it adds a grant and `False` when the policy
already has it, so it is safe to run on every start. A grant must point at
something real: `users:fly` needs the permission, `users:*` needs the feature
`users`, `*:view` needs the action `view`; otherwise `VsCatalogNotFoundError`.

```python
await policies.list_grants("read-only")                           # ["*:view"]
[p.key for p in await policies.list_permissions("read-only")]     # ["billing:view", "reports:view", "users:view"]
await policies.allows("finance", "billing:delete")                # True
```

### Step 4 — Group policies into roles

```python
async def seed_roles():
    await ensure(roles.create, "viewer", "Viewer")
    await roles.add_policy("viewer", "read-only")

    await ensure(roles.create, "admin", "Administrator")
    for policy in ("user-admin", "read-only", "finance"):
        await roles.add_policy("admin", policy)
```

A role's permissions are the union of its policies' permissions, without
duplicates. Role names carry no magic: `admin` can do exactly what its policies
grant, nothing more.

### Step 5 — Assign roles to users

Users are identified by a **subject**: the stable user id, normally the token's
`sub` claim. vs-security never sees your user table.

```python
await user_roles.assign("user-42", "viewer")        # True; False if already assigned
await user_roles.list_role_codes("user-42")         # ["viewer"]
await user_roles.list_subjects("viewer")            # ["user-42"]
await user_roles.revoke("user-42", "viewer")        # True; False if not assigned
```

`assign` checks that the role exists (`VsCatalogNotFoundError` otherwise).
Subjects are case sensitive, at most 255 characters, with no leading or trailing
spaces.

### Step 6 — Check permissions in a request

```python
from vs_security import get_auth_context

async def require(permission_key: str) -> None:
    """Raise 403 unless the current user may do `permission_key`."""
    context = get_auth_context()
    if not await resolver.has_permission(context, permission_key):
        raise HTTPException(status_code=403, detail=f"Missing permission {permission_key}")

@post("/users")
async def create_user(body: NewUser):
    await require("users:create")
    ...
```

The resolver goes subject → roles → active policies → grants → live catalog, so a
change takes effect on the **next request**: no new token, no restart.

```python
user = AppUser(sub="user-42")                 # your VsAuthContext subclass
await user_roles.assign("user-42", "viewer")
await resolver.has_permission(user, "reports:view")                  # True
await resolver.has_permission(user, "users:delete")                  # False

await user_roles.assign("user-42", "admin")   # promoted by an administrator
await resolver.has_permission(user, "users:delete")                  # True, immediately
```

Checks accept wildcards too, which suits menus and buttons:

```python
await resolver.has_permission(user, "billing:*")       # "show the Billing menu?"
await resolver.has_permission(user, "*:export")        # "show any Export button?"
await resolver.has_any_permission(user, "reports:export", "billing:export")
await resolver.has_all_permissions(user, "users:view", "users:create")
await resolver.permissions_for(user)                   # {"users:view", "reports:view", ...}
```

`has_any_permission` and `has_all_permissions` read the user's permissions once
for all keys. To answer many checks in one request, call `permissions_for` once and
test the set yourself.

### Where roles come from

The resolver asks a `VsRoleSource`. Pick one at startup; the permission logic never
changes.

| Source | Roles come from | Use when |
| --- | --- | --- |
| `VsStoreRoleSource(user_role_store)` | the user-role store | **Recommended.** Revocations apply on the next request. |
| `VsTokenRoleSource()` | `context.get_roles()`, i.e. the token | An identity provider (Okta, Azure AD, Keycloak) owns the roles. Changes apply only after the token refreshes. |
| `VsCompositeRoleSource(a, b)` | the union of several sources | IdP groups plus roles assigned in the app. |

```python
from vs_security import VsCompositeRoleSource, VsStoreRoleSource, VsTokenRoleSource

# Context keeps its id somewhere other than "sub":
source = VsStoreRoleSource(user_role_store, subject_resolver=lambda c: str(c.user_id))

# Identity-provider groups plus app-assigned roles:
source = VsCompositeRoleSource(VsTokenRoleSource(), VsStoreRoleSource(user_role_store))
```

Token roles that are not catalog roles (for example an IdP group called
"Domain Users") are skipped, not treated as errors. Anonymous users have no roles.
`context.has_role()` still reads the token only; use the resolver for decisions
that must follow revocations.

### Switching things off

Every layer has `enable(code)` / `disable(code)`. A permission counts only if
**everything on its path is on**: the role, the policy, the permission, its feature
and its action. Disabling keeps all assignments, so enabling restores them.

```python
await features.disable("billing")             # billing is off for everyone, even with "*:*"
await permissions.disable("users:delete")     # nobody can delete users
await policies.disable("finance")             # every role using finance loses it
await roles.disable("admin")                  # every admin loses admin's grants
```

### Rules and limits

- **Codes** (features, actions, policies, roles) are chosen by the app, case
  sensitive, not empty, without `:` or whitespace, and never `*`. Features and
  actions are at most 255 characters, policies and roles at most 128. A bad code
  raises `ValueError` before any store is called.
- **Permission keys** are `feature:action`. A check or grant with a malformed key
  raises `ValueError`.
- **Unknown means no.** An unknown role, policy or permission never grants
  anything; `has_permission` returns `False` rather than raising.
- **No caching** inside vs-security: every check reads the stores. Cache in your
  store if you need to, and invalidate on changes.
- **Cost of a check:** about one store call per role and per policy, plus three
  catalog reads (features, actions, permissions).

### Errors

| Exception | HTTP | When |
| --- | --- | --- |
| `VsCatalogNotFoundError` | 404 | Unknown feature, action, permission, policy or role; `kind` and `code` say which |
| `VsCatalogConflictError` | 409 | A code (or permission key) that already exists |
| `VsCatalogError` | 400 | Base class of both |
| `ValueError` | — | Malformed code, key or subject |

The 0.2.0 names `VsPermissionError`, `VsPermissionNotFoundError` and
`VsPermissionConflictError` still work: they are the same classes.

### Manager reference

| Manager | Methods |
| --- | --- |
| `VsFeatureManager`, `VsActionManager` | `create(code, name, description)`, `get`, `require`, `list_all(active_only)`, `is_active`, `enable`, `disable` |
| `VsPermissionManager` | `create(feature, action, description)`, `get(key)`, `require`, `list_all(feature_code, active_only)`, `is_active`, `enable`, `disable`, `list_effective()`, `expand(grants)`, `require_grant(grant)` |
| `VsPolicyManager` | the catalog methods, plus `add_permission`, `remove_permission`, `list_grants`, `list_permissions(active_only)`, `allows(code, key)` |
| `VsRoleManager` | the catalog methods, plus `add_policy`, `remove_policy`, `list_policies(active_only)`, `list_permissions(active_only)`, `allows(code, key)` |
| `VsUserRoleManager` | `assign`, `revoke`, `list_role_codes(subject)`, `list_roles(subject, active_only)`, `list_subjects(role)` |
| `VsPermissionResolver` | `has_permission`, `has_any_permission`, `has_all_permissions`, `permissions_for`, `grants_for` |

### Writing your own store

Implement the interface and pass it to the manager. Four contracts cover authorization:

| Interface | Holds |
| --- | --- |
| `VsPermissionStore` | features, actions, permissions |
| `VsPolicyStore` | policies and their grants (wildcards included, returned unchanged) |
| `VsRoleStore` | roles and their policy codes |
| `VsUserRoleStore` | which subject holds which role codes |

The rules every store must follow:

- `save_*` refuses an existing code **atomically** (a unique index, not
  check-then-insert) by raising `VsCatalogConflictError`.
- `set_*_active` returns `False` when nothing has that code.
- Membership writes (`add_permission`, `add_policy`, `assign`) return `False` for a
  pair that already exists, also under concurrency.
- Return copies, never live objects a caller could edit.

For example, roles kept in an HR system:

```python
from vs_security import VsUserRoleStore

class HrUserRoleStore(VsUserRoleStore):
    """Roles come from the HR service; this app never writes them."""

    def __init__(self, hr_client):
        self._hr = hr_client

    async def list_role_codes(self, subject):
        return sorted(await self._hr.roles_of(subject))

    async def list_subjects(self, role_code):
        return sorted(await self._hr.members_of(role_code))

    async def assign(self, subject, role_code):
        raise NotImplementedError("Roles are managed in the HR system")

    async def revoke(self, subject, role_code):
        raise NotImplementedError("Roles are managed in the HR system")

source = VsStoreRoleSource(HrUserRoleStore(hr_client))
```

---

## VsAuthManager — In Depth

`VsAuthManager` is a singleton coordinator. It routes credentials to the correct provider and hands the resulting `VsAuthContext` to `VsSession.generate()`.

```python
# Initialize once at startup — pass a VsSession[T] implementation
VsAuthManager.init(session=VsJWTProvider(config=config))

# Register providers — call before importing controllers
VsAuthManager.register("username_password", VsUsernamePasswordAuthProvider(...))
VsAuthManager.register("google", GoogleAuthProvider(...))
VsAuthManager.register("api_key", ApiKeyAuthProvider(...))

# Retrieve anywhere in the app
auth_manager = VsAuthManager.get_instance()

# At login time
token_pair = await auth_manager.authenticate(
    "username_password",
    VsUsernamePasswordCredentials(username=..., password=...),
)
```

---

## VsAuthProvider — In Depth

`VsAuthProvider` verifies credentials and returns who the user is. It knows nothing about sessions or tokens.

```python
class VsAuthProvider(ABC):

    @abstractmethod
    async def authenticate(self, credentials: VsCredentials) -> VsAuthContext: ...
```

**Rules:**
- Return `VsAuthContext` on success.
- Raise `VsAuthenticationError` (or a subclass) on failure — never return `None`.

**Custom provider example — API key:**

```python
from vs_security.auth.vs_auth_provider import VsAuthProvider
from vs_security.schema.vs_auth_context import VsAuthContext
from vs_security.schema.vs_credentials import VsCredentials
from vs_security.error.vs_auth_error import VsInvalidCredentialsError

class ApiKeyCredentials(VsCredentials):
    api_key: str

class ApiKeyAuthProvider(VsAuthProvider):

    def __init__(self, key_repo):
        self._repo = key_repo

    async def authenticate(self, credentials: VsCredentials) -> VsAuthContext:
        if not isinstance(credentials, ApiKeyCredentials):
            raise TypeError("Expected ApiKeyCredentials")

        record = await self._repo.find_by_key(credentials.api_key)
        if not record or not record.is_active:
            raise VsInvalidCredentialsError()

        return AppAuthContext(
            user_id=record.owner_id,
            roles=record.roles,
            provider="api_key",
        )

VsAuthManager.register("api_key", ApiKeyAuthProvider(key_repo=ApiKeyRepo()))
```

---

## VsSession — In Depth

`VsSession[T]` is the abstract base for both session generation (login) and token validation (requests). Implement it when you want a session format other than JWT.

```python
class VsSession(ABC, Generic[T]):

    @abstractmethod
    async def generate(self, context: VsAuthContext) -> T:
        """Called after login — produce a session from the authenticated context."""
        ...

    @abstractmethod
    async def validate(self, token: str) -> VsAuthContext:
        """Called on each request — verify the token and return the auth context."""
        ...
```

**Custom example — Redis session store:**

```python
from vs_security.schema.vs_session import VsSession
from vs_security.schema.vs_auth_context import VsAuthContext
from pydantic import BaseModel
import uuid

class RedisSessionData(BaseModel):
    session_id: str
    expires_in: int

class RedisSession(VsSession[RedisSessionData]):

    def __init__(self, redis_client, ttl: int = 3600):
        self._redis = redis_client
        self._ttl = ttl

    async def generate(self, context: VsAuthContext) -> RedisSessionData:
        session_id = str(uuid.uuid4())
        await self._redis.setex(f"session:{session_id}", self._ttl, context.model_dump_json())
        return RedisSessionData(session_id=session_id, expires_in=self._ttl)

    async def validate(self, token: str) -> VsAuthContext:
        data = await self._redis.get(f"session:{token}")
        if not data:
            raise VsAuthenticationError("Session not found or expired")
        return AppAuthContext.model_validate_json(data)

# Wire it in
VsAuthManager.init(session=RedisSession(redis_client=redis))
```

---

## VsJWTProvider — Token Lifecycle

`VsJWTProvider` is the built-in `VsSession[VsTokenPair]`. It handles minting, verifying, refreshing, and revoking JWTs.

```python
jwt_provider = VsJWTProvider(config=config, context_class=AppAuthContext, token_store=token_store)
VsAuthManager.init(session=jwt_provider)
```

`context_class` tells the provider which subclass to reconstruct when decoding a token — defaults to `VsAuthContext`.

A service that only validates access tokens needs nothing more. A service that also refreshes them needs two things:

- `token_store` — `refresh_token()` raises `RuntimeError` without one, because a refresh token that is stored nowhere cannot be revoked and renews itself forever. Pass `allow_stateless_refresh=True` to accept that knowingly.
- `context_reloader` — called on every refresh with the context decoded from the old token. Return the user's current context, or `None` if the user is gone or deactivated; `None` revokes all of that user's refresh tokens and raises `VsTokenRevokedError`. Without it, new tokens are minted from the old token's claims, so role changes and deactivations are never picked up (a warning is logged once).

```python
async def reload_context(old: AppAuthContext) -> AppAuthContext | None:
    user = await user_repo.find_by_id(old.user_id)
    if user is None or not user.active:
        return None
    return AppAuthContext(user_id=user.id, roles=user.roles)

jwt_provider = VsJWTProvider(config=config, context_class=AppAuthContext,
                             token_store=token_store, context_reloader=reload_context)
```

**Refresh a token:**

```python
@post("/auth/refresh")
async def refresh(body: RefreshRequest):
    try:
        pair = await jwt_provider.refresh_token(body.refresh_token)
        return pair
    except VsAuthenticationError as e:
        raise HTTPException(status_code=401, detail=str(e))
```

**Revoke tokens (logout):**

`revoke_token` and `revoke_all_tokens` take the `VsAuthContext` — your `VsTokenStore` implementation knows how to extract the key from it.

```python
@post("/auth/logout")
async def logout(body: LogoutRequest):
    context = get_auth_context()
    await jwt_provider.revoke_token(context, body.refresh_token)

@post("/auth/logout-all")
async def logout_all():
    context = get_auth_context()
    await jwt_provider.revoke_all_tokens(context)
```

**Implementing `VsTokenStore`:**

Your implementation receives the full `VsAuthContext` subclass and decides how to key the tokens — no coupling to a specific field type.

Three rules:

- **You are given fingerprints, not tokens.** `VsJWTProvider` passes the SHA-256 hex digest (64 characters) of each refresh token, so a leaked table cannot be replayed. Treat the string as opaque. Rows written by a version before this one hold raw tokens and no longer match: those users log in once more.
- **Override `consume` with one atomic statement.** It spends a token and reports whether it was there. The inherited version reads then deletes, which lets two simultaneous refreshes both succeed.
- **`consume` and `delete_all` must commit on their own.** On a replay the provider calls `delete_all` and then raises; a request transaction that rolls back on errors would undo the revocation. With vs-db use `@transactional(propagation=Propagation.REQUIRES_NEW)`.

**Rotation and replay.** Every refresh spends the presented token and issues a new one. A correctly signed refresh token that is no longer in the store has been spent or revoked already, so someone is replaying it; the provider then deletes all of that user's refresh tokens and raises `VsTokenRevokedError`. This is the same rule as Spring Security's `PersistentTokenBasedRememberMeServices` (`CookieTheftException` → `removeUserTokens`). A client that fires two refreshes with the same token will trip it, so refresh from one place.

```python
from vs_security.auth.vs_token_store import VsTokenStore
from vs_security.schema.vs_auth_context import VsAuthContext

class RedisTokenStore(VsTokenStore):

    def __init__(self, redis_client):
        self._redis = redis_client

    async def save(self, context: AppAuthContext, refresh_token: str) -> None:
        await self._redis.sadd(f"tokens:{context.user_id}", refresh_token)

    async def get_all(self, context: AppAuthContext) -> list[str]:
        return list(await self._redis.smembers(f"tokens:{context.user_id}"))

    async def delete(self, context: AppAuthContext, refresh_token: str) -> None:
        await self._redis.srem(f"tokens:{context.user_id}", refresh_token)

    async def delete_all(self, context: AppAuthContext) -> None:
        await self._redis.delete(f"tokens:{context.user_id}")

    async def consume(self, context: AppAuthContext, refresh_token: str) -> bool:
        # SREM is atomic and returns how many members it removed
        return await self._redis.srem(f"tokens:{context.user_id}", refresh_token) == 1
```

**Revoking access tokens — `VsRevocationStore`:**

A JWT access token is valid until it expires, so by default logout only stops the *next* refresh. Pass a `revocation_store` and `validate()` also rejects access tokens whose session was logged out (`revoke_token`), or that were issued before a logout-everywhere (`revoke_all_tokens`, a replayed refresh token, or a `context_reloader` returning `None`). Every token of one login shares a `sid` claim, which is what a single logout revokes.

Every service that validates tokens must be given the same store, and it is read on every request, so use Redis or similar. Entries only need to live for the access-token lifetime.

```python
from vs_security import VsRevocationStore

class RedisRevocationStore(VsRevocationStore):

    def __init__(self, redis_client):
        self._redis = redis_client

    async def revoke_session(self, context: AppAuthContext, session_id: str, ttl_seconds: float) -> None:
        await self._redis.set(f"revoked:sid:{session_id}", "1", ex=int(ttl_seconds))

    async def revoke_all(self, context: AppAuthContext, ttl_seconds: float) -> None:
        await self._redis.set(f"revoked:user:{context.user_id}", repr(time.time()), ex=int(ttl_seconds))

    async def is_revoked(self, context: AppAuthContext, session_id: str, issued_at: float) -> bool:
        gone, cutoff = await self._redis.mget(f"revoked:sid:{session_id}", f"revoked:user:{context.user_id}")
        return gone is not None or (cutoff is not None and issued_at <= float(cutoff))

jwt_provider = VsJWTProvider(config=config, context_class=AppAuthContext, revocation_store=RedisRevocationStore(redis))
```

**Extra checks on access tokens — `token_validators`:**

The counterpart of Spring Security's `OAuth2TokenValidator<Jwt>`: callables that receive the verified claims of each access token and raise `VsAuthenticationError` to reject it.

```python
def only_this_tenant(claims):
    if claims.get("tenant") != "acme":
        raise VsAuthenticationError("Wrong tenant")

jwt_provider = VsJWTProvider(config=config, token_validators=[only_this_tenant])
```

---

## Security Filter (vs-server)

Authentication is handled by `VsSecurityFilter` in `vs-server`, not in `vs-security`. This keeps `vs-security` free of any HTTP framework dependency.

See the `vs-server` README for full documentation on `VsSecurityFilter`, `VsRequest`, `VsBearerTokenFilter`, and `enable_security()`.

**Accessing the auth context inside a handler:**

```python
from vs_security.guard.vs_security import get_auth_context

@get("/me")
async def get_me(self):
    context: AppAuthContext = get_auth_context()
    return {"user_id": str(context.user_id), "username": context.username}
```

`get_auth_context()` uses Python's `contextvars` — safe in async, always returns the context for the current request.

---

## VsSecurity — Deprecated

`VsSecurity` is kept for backwards compatibility but raises a `DeprecationWarning` on use. Migrate to `VsSecurityFilter` + `get_auth_context()`.

```python
# old — deprecated
from vs_security.guard.vs_security import VsSecurity
@controller("/users", guards=[VsSecurity.from_manager()])

# new — use enable_security() on the server at startup
server.enable_security()
```

---

## VsAuthContext Reference

`VsAuthContext` is a minimal base class. It has no `user_id`, `username`, or `roles` fields — those belong in your subclass so you control the types. The base provides:

```python
context.metadata                      # Dict[str, Any] — arbitrary extra data bag

context.get_roles() -> List[str]      # override to expose roles for VsSecurity guard
context.has_role("admin")
context.has_any_role("admin", "moderator")
context.has_all_roles("admin", "moderator")

context.to_claims() -> dict           # override to control JWT payload
VsAuthContext.from_claims(payload)    # override to reconstruct from JWT payload
```

**Subclass example:**

```python
from uuid import UUID
from typing import List
from vs_security.schema.vs_auth_context import VsAuthContext

class AppAuthContext(VsAuthContext):
    user_id: UUID
    username: str
    roles: List[str] = []

    def get_roles(self) -> List[str]:
        return self.roles

    def to_claims(self) -> dict:
        return {
            "sub": str(self.user_id),
            "username": self.username,
            "roles": self.roles,
        }

    @classmethod
    def from_claims(cls, payload: dict) -> "AppAuthContext":
        return cls(
            user_id=UUID(payload["sub"]),
            username=payload.get("username", ""),
            roles=payload.get("roles", []),
        )
```

The JWT provider uses `to_claims()` to build the token payload and `from_claims()` to reconstruct the context on decode. If you use `VsTokenStore`, `to_claims()` must include a `"sub"` key — that string is used as the token store key.

---

## Error Reference

All auth exceptions extend `VsAuthenticationError`, which extends `VsBaseException` from `vs-common`. `VsAuthenticationError` defines `status_code` as its own attribute (not inherited from `VsBaseException`, which has no HTTP concepts). When using `vs-server`, its global handler reads `status_code` via duck-typing and produces the correct HTTP response automatically — no try/catch needed in your controllers.

| Exception | HTTP Status | Raised By | When |
|-----------|-------------|-----------|------|
| `VsAuthenticationError` | 401 | Any provider or session | Generic auth failure — base class for all auth errors |
| `VsInvalidCredentialsError` | 401 | `VsUsernamePasswordAuthProvider` | Wrong username or password |
| `VsTokenExpiredError` | 401 | `VsJWTProvider` | JWT has expired |
| `VsTokenRevokedError` | 401 | `VsJWTProvider` | Refresh token was explicitly revoked |
| `VsUserNotFoundError` | 401 | Any provider | Username not found |
| `VsInactiveError` | 401 | Any provider | User account is inactive |
| `VsInsufficientRolesError` | 403 | `VsSecurity` | User authenticated but lacks required roles |
| `VsAccountLockedError` | 429 | `VsUsernamePasswordAuthProvider` | Too many failed logins for this username; `retry_after` holds the seconds left |
| `VsCatalogNotFoundError` | 404 | Authorization managers | Unknown feature, action, permission, policy or role |
| `VsCatalogConflictError` | 409 | Authorization managers | A code that already exists, e.g. seeding twice |

When using `vs-server`, all of these are handled globally — your login endpoint needs no try/catch:

```python
@post("/auth/login", response_model=LoginResponse)
async def login(body: LoginRequest):
    session = await VsAuthManager.get_instance().authenticate(body.type, body)
    return LoginResponse(access_token=session.access_token, refresh_token=session.refresh_token)
```

If you are **not** using `vs-server`, catch them explicitly:

```python
try:
    return await VsAuthManager.get_instance().authenticate(...)
except VsInvalidCredentialsError:
    raise HTTPException(status_code=401, detail="Invalid credentials")
except VsAuthenticationError as e:
    raise HTTPException(status_code=401, detail=str(e))
```

Queue adapters authenticate the same way using message headers and routing metadata. Reply destinations require separate authorization through the agent's `queue_reply_guard`; invalid credentials never authorize a response destination.
