Metadata-Version: 2.4
Name: sso-nebus
Version: 1.0.2
Summary: Python клиент для взаимодействия с MS Auth Service API
License: LICENSE
License-File: LICENSE
Author: Артем Костюченко
Author-email: kostyuchenko.work@gmail.com
Requires-Python: >=3.12
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Provides-Extra: dev
Requires-Dist: aiohttp (>=3.13.2,<4.0.0)
Requires-Dist: pydantic (>=2.12.5,<3.0.0)
Requires-Dist: pytest (>=8.0.0) ; extra == "dev"
Requires-Dist: pytest-asyncio (>=0.24.0) ; extra == "dev"
Requires-Dist: python-dotenv (>=1.0.0) ; extra == "dev"
Description-Content-Type: text/markdown

# SSO Nebus Client

Python клиент для взаимодействия с MS Auth Service API. Предоставляет удобные классы для работы с OAuth 2.0 Authorization Code Flow с PKCE (для пользователей) и Client Credentials Grant (для микросервисов).

Совместим с SSO **1.7+**: MFA TOTP на логине, `GET /introspect` для сервисных токенов.

## Установка

```bash
pip install sso-nebus
```

Локально из репозитория:

```bash
pip install -e .
```

## Быстрый старт

### Для пользователей (UserClient)

```python
import asyncio
from sso_nebus import UserClient, MfaRequiredError

async def main():
    client = UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id",
        redirect_uri="http://localhost:3000/callback",
    )

    # Если у пользователя включён TOTP — передайте код из Authenticator
    token_response = await client.full_auth_flow(
        login="user@example.com",
        password="password123",
        scope="sso.admin.read sso.admin.create",
        totp_code="123456",  # опционально; без MFA можно не передавать
    )

    print(f"Access token: {token_response.access_token}")
    print(f"Refresh token: {token_response.refresh_token}")

    user_info = await client.get_current_user()
    print(f"Пользователь: {user_info.name} {user_info.surname}")
    print(f"MFA: {user_info.mfa_enabled}")

    new_token = await client.refresh_access_token()
    print(f"Новый access token: {new_token.access_token}")

    await client.close()

asyncio.run(main())
```

Если MFA включена, а `totp_code` не передан, `full_auth_flow` поднимает `MfaRequiredError` с полями `mfa_token`, `session_id`, `methods` — можно допросить код у пользователя и вызвать `login_mfa()`.

### Пошаговая авторизация (в том числе MFA)

```python
import asyncio
from sso_nebus import UserClient

async def main():
    client = UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id",
    )

    pkce_params = await client.get_pkce_params()
    auth_response = await client.authorize(
        scope="sso.admin.read",
        pkce_params=pkce_params,
    )

    login_response = await client.login(
        login="user@example.com",
        password="password123",
        session_id=auth_response.session_id,
    )

    if login_response.mfa_required:
        login_response = await client.login_mfa(
            session_id=auth_response.session_id,
            mfa_token=login_response.mfa_token,
            code="123456",  # TOTP из приложения или recovery-код
        )

    token_response = await client.exchange_code_for_tokens(
        authorization_code=login_response.authorization_code,
        pkce_params=pkce_params,
    )
    print(f"Токены получены: {token_response.access_token}")

    await client.close()

asyncio.run(main())
```

Это **не** «вход через Google». Google Authenticator (или любое RFC 6238 приложение) только генерирует локальный код из секрета SSO.

### Привязка TOTP

Нужен уже выданный **пользовательский** access token (например вход через клиент без `mfa_required`).

```python
enroll = await client.enroll_totp()
# enroll.otpauth_uri — QR для Authenticator (issuer Nebus, метка Sfera:<login>)
# enroll.secret — запасной ввод вручную

confirm = await client.confirm_totp(code="123456")
# confirm.recovery_codes — показать пользователю один раз

# Отключение (свой пароль):
await client.disable_totp(password="password123")
```

### Для микросервисов (ServiceClient)

```python
import asyncio
from sso_nebus import ServiceClient

async def main():
    client = ServiceClient(
        base_url="http://localhost:8000",
        client_id="service_id",
        client_secret="service_secret",
    )

    token_response = await client.get_access_token(
        scope="system.client.read system.client.edit",
    )
    print(f"Access token: {token_response.access_token}")

    # GET /introspect — не /me (пользовательский /me для M2M-токена даёт 403)
    info = await client.introspect()
    print(info.service_name, info.scopes)

    data = await client.request_with_auth(
        method="GET",
        endpoint="admin/users",
        params={"skip": 0, "limit": 10},
    )

    await client.close()

asyncio.run(main())
```

`get_current_user()` у `ServiceClient` сохраняет legacy-поведение: для **пользовательского** JWT — `GET /me`, для **client_credentials** — `GET /introspect` с маппингом в `UserInfo`. Явный M2M — метод `introspect()`.

## Использование с async context manager

```python
import asyncio
from sso_nebus import UserClient

async def main():
    async with UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id",
    ) as client:
        token_response = await client.full_auth_flow(
            login="user@example.com",
            password="password123",
        )

asyncio.run(main())
```

Пример dependency FastAPI для **пользовательского** токена:

```python
from typing import Optional

from fastapi import Depends, FastAPI, Header, HTTPException

from sso_nebus import UserClient
from sso_nebus.exceptions import AuthenticationError, AuthorizationError

app = FastAPI()

user_sso = UserClient(
    base_url="http://localhost:8000",
    client_id="your_client_id",
)


async def get_current_user(authorization: Optional[str] = Header(None)):
    if not authorization:
        raise HTTPException(status_code=401, detail="Токен не предоставлен")
    try:
        token = authorization.split(" ")[1]
    except IndexError:
        raise HTTPException(status_code=401, detail="Неверный формат токена")
    try:
        return await user_sso.get_current_user(access_token=token)
    except AuthenticationError:
        raise HTTPException(status_code=401, detail="Невалидный токен")
    except AuthorizationError:
        raise HTTPException(status_code=403, detail="Нужен токен пользователя, не микросервиса")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Ошибка при проверке токена: {e}")


@app.get("/protected")
async def protected_endpoint(current_user=Depends(get_current_user)):
    return {
        "message": f"Привет, {current_user.name} {current_user.surname}!",
        "user_id": current_user.id,
        "email": current_user.email,
        "scopes": current_user.scopes,
        "mfa_enabled": current_user.mfa_enabled,
    }
```

Для входящего **сервисного** JWT вызывайте `ServiceClient.introspect(access_token=...)`, не `/me`.

## API Reference

### UserClient

Класс для пользовательского взаимодействия с OAuth 2.0 Authorization Code Flow с PKCE.

#### Методы

- `get_pkce_params()` — PKCE параметры от сервера
- `authorize(scope, redirect_uri, pkce_params)` — инициировать OAuth 2.0 flow
- `login(login, password, session_id)` — пароль; может вернуть MFA challenge
- `login_mfa(session_id, mfa_token, code)` — TOTP / recovery после challenge
- `enroll_totp()` / `confirm_totp(code)` / `disable_totp(password)` — привязка и сброс TOTP
- `exchange_code_for_tokens(authorization_code, redirect_uri, pkce_params)` — обмен кода на токены
- `refresh_access_token(refresh_token)` — обновить access token
- `get_current_user(access_token)` — `GET /me` (только пользовательский JWT)
- `logout(refresh_token)` — выйти из системы
- `get_available_services()` — список доступных микросервисов
- `full_auth_flow(login, password, scope, redirect_uri, totp_code)` — полный цикл; при MFA без кода — `MfaRequiredError`

### ServiceClient

Класс для микросервисного взаимодействия с Client Credentials Grant.

#### Методы

- `get_access_token(scope)` — получить access token
- `introspect(access_token)` — `GET /introspect` (только JWT микросервиса)
- `get_current_user(access_token)` — legacy: user JWT → `/me`, M2M → `/introspect` → `UserInfo`
- `request_with_auth(method, endpoint, json_data, params, auto_refresh)` — запрос с авторизацией

## Исключения

- `SSOClientError` — базовое исключение
- `AuthenticationError` — ошибка аутентификации (401)
- `AuthorizationError` — ошибка авторизации (403)
- `APIError` — ошибка API (4xx, 5xx)
- `TokenError` — ошибка работы с токенами
- `MfaRequiredError` — после пароля нужен TOTP; поля `mfa_token`, `session_id`, `methods`

## Лицензия

MIT

