Metadata-Version: 2.4
Name: baobab-auth-database
Version: 0.3.0
Summary: Adaptateur de persistance SQLAlchemy/Alembic pour baobab-auth-core.
Project-URL: Homepage, https://github.com/baobabgit/baobab-auth-database
Project-URL: Repository, https://github.com/baobabgit/baobab-auth-database
Project-URL: Documentation, https://github.com/baobabgit/baobab-auth-database/tree/main/docs
Project-URL: Issues, https://github.com/baobabgit/baobab-auth-database/issues
Author-email: Patrick ANDRIANAIVO <patrick.andri@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Michel ANDRIANAIVO
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: alembic,auth,baobab,database,sqlalchemy
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: alembic<2.0,>=1.13
Requires-Dist: baobab-auth-core<0.5.0,>=0.4.0
Requires-Dist: pydantic-settings<3.0,>=2.0
Requires-Dist: sqlalchemy<3.0,>=2.0
Provides-Extra: dev
Requires-Dist: bandit[sarif,toml]>=1.7; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pip-audit>=2.10.1; extra == 'dev'
Requires-Dist: pre-commit>=3.8; extra == 'dev'
Requires-Dist: pytest-cov>=7.1.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: docs
Requires-Dist: furo>=2024.0; extra == 'docs'
Requires-Dist: sphinx>=7.0; extra == 'docs'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]<4.0,>=3.2; extra == 'postgres'
Provides-Extra: testcontainers
Requires-Dist: psycopg[binary]<4.0,>=3.2; extra == 'testcontainers'
Requires-Dist: testcontainers>=4.0; extra == 'testcontainers'
Description-Content-Type: text/markdown

# baobab-auth-database

[![CI](https://github.com/baobabgit/baobab-auth-database/actions/workflows/ci.yml/badge.svg)](https://github.com/baobabgit/baobab-auth-database/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)

Adaptateur de persistance SQLAlchemy/Alembic pour `baobab-auth-core`.
La librairie fournit la future couche database de l'écosystème `baobab-auth` :
modèles ORM, repositories, Unit of Work, migrations embarquées, bootstrap
roles/permissions et outils de test.

## Table des matières

- [À propos](#à-propos)
- [Périmètre](#périmètre)
- [Hors périmètre](#hors-périmètre)
- [Fonctionnalités ciblées](#fonctionnalités-ciblées)
- [Stack technique](#stack-technique)
- [Architecture](#architecture)
- [Structure du projet](#structure-du-projet)
- [Démarrage rapide](#démarrage-rapide)
- [Configuration](#configuration)
- [Qualité](#qualité)
- [Documentation](#documentation)
- [Sécurité](#sécurité)
- [Workflow de contribution](#workflow-de-contribution)
- [Roadmap](#roadmap)
- [Licence](#licence)
- [Auteur](#auteur)

## À propos

`baobab-auth-database` est une brique technique réutilisable. Elle ne porte pas
la logique métier d'authentification : celle-ci reste dans `baobab-auth-core`.
Ce dépôt implémente uniquement l'adaptateur SQL nécessaire aux applications et
services qui consommeront l'authentification Baobab.

## Périmètre

La version cible `0.1.0` doit couvrir la persistance des identités, profils,
rôles, permissions, sessions, empreintes de refresh tokens, événements d'audit
et clés JWKS optionnelles. Elle doit aussi fournir les migrations Alembic, une
Unit of Work transactionnelle et une CLI minimale `baobab-auth-db`.

## Hors périmètre

Cette librairie n'expose pas d'API HTTP, ne dépend pas de FastAPI, ne hashe pas
les mots de passe, ne génère pas de JWT, ne valide pas de JWT et ne contient
aucune logique métier d'application consommatrice.

## Fonctionnalités ciblées

- Configuration database via `pydantic-settings`.
- Factories SQLAlchemy pour engine et sessions.
- Modèles ORM SQLAlchemy 2.x typed style.
- Mappers ORM vers les entités de `baobab-auth-core`.
- Repositories SQLAlchemy alignés sur les ports du core.
- `SqlAlchemyAuthUnitOfWork` avec commit, rollback et context manager.
- Migrations Alembic embarquées sans `alembic.ini` externe obligatoire.
- Bootstrap idempotent des rôles `USER`, `ADMIN`, `SUPER_ADMIN` et permissions système.
- Helpers de test SQLite et integration PostgreSQL.

## Stack technique

| Domaine | Outil |
| --- | --- |
| Langage | Python >= 3.12 |
| Persistance | SQLAlchemy 2.x, Alembic |
| Base cible | PostgreSQL |
| Base dev/test | SQLite |
| Configuration | pydantic-settings |
| Lint et format | Ruff |
| Typage | mypy strict |
| Tests | pytest, pytest-cov |
| Documentation | Sphinx, reStructuredText |
| CI | GitHub Actions |

## Architecture

Le sens des dépendances est volontairement simple :

```text
baobab-auth-core
        ↑
        │
baobab-auth-database
        ↑
        │
baobab-auth-api / baobab-auth-service
```

`baobab-auth-database` dépend du core et implémente ses ports de persistance.
Le core ne depend jamais de cette librairie.

## Structure du projet

```text
.
├── src/baobab_auth_database/   # package Python
├── tests/baobab_auth_database/ # tests miroir
├── docs/
│   ├── specifications/         # cahier des charges, US, FEAT
│   ├── api/                    # référence autodoc
│   ├── guides/                 # tutorials + how-to
│   └── workflow/               # roles, gates, handoff
├── pyproject.toml              # configuration projet
├── AGENTS.md                   # règles de développement
└── .github/                    # CI, release, templates issues/PR
```

## Démarrage rapide

```bash
git clone https://github.com/baobabgit/baobab-auth-database.git
cd baobab-auth-database

python -m venv .venv
# Windows PowerShell
.venv\Scripts\Activate.ps1

python -m pip install --upgrade pip
pip install -e ".[dev,docs]"
pre-commit install

ruff check .
mypy
pytest
```

## Configuration

La configuration runtime passe par `AuthDatabaseSettings`, validée par
`pydantic-settings` et chargée depuis les variables `BAOBAB_AUTH_*`.

```python
from baobab_auth_database import AuthDatabaseSettings
from baobab_auth_database import AuthEngineFactory, AuthSessionFactory

settings = AuthDatabaseSettings()
engine = AuthEngineFactory.create_auth_engine(settings)
SessionLocal = AuthSessionFactory.create_auth_session_factory(engine)
```

Exemple local sans secret :

```env
BAOBAB_AUTH_DATABASE_URL=sqlite+pysqlite:///:memory:
BAOBAB_AUTH_DATABASE_ECHO=false
BAOBAB_AUTH_DATABASE_POOL_SIZE=5
BAOBAB_AUTH_DATABASE_MAX_OVERFLOW=10
BAOBAB_AUTH_DATABASE_POOL_PRE_PING=true
BAOBAB_AUTH_DATABASE_SCHEMA=
BAOBAB_AUTH_ALEMBIC_VERSION_TABLE=auth_alembic_version
BAOBAB_AUTH_ENABLE_SQL_LOGGING=false
```

`database_url` est obligatoire et doit être une URL SQLAlchemy valide. Les
valeurs par défaut couvrent le pool SQLAlchemy, la table Alembic et le logging
SQL ; les secrets réels restent hors du dépôt, dans `.env`.

## Usage consommateur

### Migrations

```bash
baobab-auth-db upgrade head
baobab-auth-db current
```

```python
from baobab_auth_database import AuthDatabaseSettings, MigrationRunner

MigrationRunner.from_settings(AuthDatabaseSettings()).upgrade("head")
```

### Bootstrap rôles et permissions

```bash
baobab-auth-db seed-defaults
```

```python
from baobab_auth_database.bootstrap import SeedDefaults
from baobab_auth_database.repositories import SqlAlchemyAuthUnitOfWork

with SqlAlchemyAuthUnitOfWork(session_factory) as uow:
    SeedDefaults.seed_default_roles_and_permissions(uow)
    uow.commit()
```

### Unit of Work et repositories

```python
from baobab_auth_core.domain.value_objects.auth_subject import AuthSubject

from baobab_auth_database.repositories import SqlAlchemyAuthUnitOfWork

with SqlAlchemyAuthUnitOfWork(session_factory) as uow:
    user = uow.users.get_by_auth_subject(AuthSubject("subject-1"))
    uow.commit()
```

### Tests d'intégration

```python
from baobab_auth_database.testing import (
    AuthSchemaAssertions,
    AuthSqliteTestHelper,
    AuthTestFactories,
)

engine = AuthSqliteTestHelper.create_memory_engine()
session_factory = AuthSqliteTestHelper.create_session_factory(engine)
user = AuthTestFactories.user()
AuthSchemaAssertions.assert_table_exists(engine, "auth_users")
```

Guides détaillés : `docs/guides/` (tutoriels, how-to, référence). Référence
**compatibilité core** : `docs/guides/reference/compatibilite-core.rst`. Documentation
Sphinx : `sphinx-build -b html docs docs/_build/html`.

## Qualité

Les commandes de référence sont :

```bash
ruff check .
ruff format --check .
mypy
pytest
sphinx-build -b html -W docs docs/_build/html
```

La couverture minimale imposée est de 90 %. Les tests suivent l'arborescence
miroir de `src/`.

## Documentation

- **Spécifications** : `docs/specifications/` (US, FEAT, cahier des charges).
- **Guides Diátaxis** : `docs/guides/` (tutoriels, how-to, référence architecture/schéma/UoW/compatibilité core).
- **API** : `docs/api/` (autodoc Sphinx depuis les docstrings RST).
- **Workflow multi-IA** : `docs/workflow/` (Markdown).

## Sécurité

Aucun secret ne doit être commité. Les valeurs sensibles stockées par la librairie
sont opaques : `password_hash`, `refresh_token_hash` et `private_key_encrypted` ne
sont jamais calculés ni déchiffrés ici.

Documentation détaillée : `docs/security_storage.rst` (Sphinx) — responsabilités,
règles de non-exposition (`repr`, logs, exceptions) et tests de non-régression.

Les URLs database affichées dans les erreurs publiques sont masquées via
`DatabaseUrlMasker`. Une erreur SQLAlchemy enveloppée conserve sa cause technique
avec `raise ... from exc`, sans exposer le mot de passe de connexion.

## Workflow de contribution

Le workflow est décrit dans `docs/workflow/` : Orchestrateur, Product Owner,
Architecte, Développeur, Relecteur, Sécurité et Release Manager. Les changements
suivent la chaine `US-001 -> FEAT-001.1 -> TASK-001.1.1`, avec commits
Conventional Commits portant l'identifiant de specification.

## Roadmap

- [x] Découper le cahier des charges en US et FEAT.
- [x] Settings, engine, session factory et exceptions.
- [x] Schéma SQLAlchemy, migrations Alembic embarquées.
- [x] Repositories, mappers et Unit of Work transactionnelle.
- [x] Bootstrap idempotent, CLI `baobab-auth-db`, utilitaires de test.
- [ ] Documentation sécurité de stockage et release `0.1.0` (US-008).

## Licence

Distribué sous licence MIT. Voir [LICENSE](LICENSE).

## Auteur

Michel ANDRIANAIVO - [patrick.andri@gmail.com](mailto:patrick.andri@gmail.com)
