🤖 ldap2nextcloud : synchronisation LDAP vers un carnet Nextcloud (CardDAV)
Historique regroupé en un seul commit pour ne pas publier de données de production. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
f6a01b85e1
42 files changed
+5538
No files matched your search
@@ -0,0 +1,476 @@
|
||||
# Synchronisation LDAP → Nextcloud — plan d'implémentation
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Un outil Python `ldap2nextcloud` qui synchronise de façon incrémentale l'annuaire LDAP vers un carnet CardDAV Nextcloud dédié.
|
||||
|
||||
**Architecture:** Chaque fiche LDAP devient une fiche normalisée (`Contact`) avec une empreinte de sa source. Un planificateur compare trois sources : les fiches voulues, l'état du serveur (`PROPFIND` href + ETag) et la base SQLite. Il produit des actions (créer, mettre à jour, vérifier, supprimer), puis l'orchestrateur les applique en CardDAV. Les modules sont purs et testables isolément ; seuls `ldap_source` et `carddav` touchent le réseau.
|
||||
|
||||
**Tech Stack:** Python ≥ 3.11, `truststore`, `ldap3`, `requests`, `vobject`, `Pillow`, `PyYAML`, `python-dotenv`, `sqlite3` ; tests `pytest`, `responses`.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-16-ldap-nextcloud-sync-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Python ≥ 3.11 ; paquet `src/ldap2nextcloud`, commande `ldap2nextcloud`.
|
||||
- TLS : `truststore` obligatoire (un proxy inspecte le HTTPS). `truststore.inject_into_ssl()` est appelé au tout début de `cli.main()`, avant toute connexion, pour que `requests` et `ldap3` valident les certificats avec le magasin du système. Les variables `HTTPS_PROXY`/`NO_PROXY` sont respectées (comportement par défaut de `requests`).
|
||||
- vCard **3.0** ; fins de ligne CRLF ; `PRODID:-//ldap2nextcloud//FR`.
|
||||
- `UID` = `uuid5(NAMESPACE, cle)` avec `NAMESPACE = uuid.UUID("6f1c2a4e-3b7d-4e8a-9c51-2d0f6b8e7a13")` ; href = `<UID>.vcf`.
|
||||
- Photos : réduction si plus grand que `PHOTO_MAX_SIZE` (512), JPEG qualité `PHOTO_QUALITY` (80), sans agrandissement, sans métadonnées.
|
||||
- `MAX_DELETE_RATIO` par défaut 0.10.
|
||||
- Téléphone : chiffres seuls de longueur `internal_length` (4) → préfixe `+3312345` ; sinon numéro conservé sans espaces ni points.
|
||||
- Logs : jamais de nom, téléphone, email ni date de naissance ; seulement la clé LDAP (uid), l'href et l'action.
|
||||
- `FORMAT_VERSION = 1` entre dans l'empreinte ; l'incrémenter force un renvoi général.
|
||||
- Toute donnée de test LDAP provient de `test-data/example.anon.ldif` ; ne jamais lire un `.ldif` non anonymisé.
|
||||
- Messages de commit préfixés par 🤖 et terminés par `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. Fiche LDAP incomplète (sans `mail`, `telephoneNumber`, `jpegPhoto` ou `usrDirectionId`) → la fiche est produite sans ces champs ; une fiche sans clé `uid` est ignorée avec un avertissement (Task 2).
|
||||
2. Date de naissance `19680615000000Z` → `BDAY:1968-06-15`, sans décalage de fuseau ; une valeur illisible fait omettre `BDAY` (Task 2).
|
||||
3. Hrefs renvoyés par `PROPFIND` en chemin absolu, encodés (`%40`), avec la collection elle-même dans la réponse → normalisés en nom de fichier seul, collection exclue (Task 6).
|
||||
4. `PUT` qui reçoit `412 Precondition Failed` ou une erreur 5xx → erreur journalisée pour cette fiche, base non mise à jour, la synchro continue (Task 9).
|
||||
5. Noms accentués (encodés en base64 dans le LDIF) et lignes de plus de 75 octets → vCard UTF-8 correctement pliée, relisible par `vobject` (Task 4).
|
||||
|
||||
---
|
||||
|
||||
## Structure des fichiers
|
||||
|
||||
```
|
||||
pyproject.toml, .gitignore, .env.example, mapping.yaml, directions.yaml
|
||||
src/ldap2nextcloud/
|
||||
__init__.py __version__
|
||||
config.py Settings (.env), Mapping (mapping.yaml), directions
|
||||
model.py Contact, fingerprint(), contact_href()
|
||||
mapping.py entry_to_contact(), format_phone(), parse_birthday()
|
||||
photo.py resize_photo()
|
||||
vcard.py render_vcard(), read_sync_hash()
|
||||
state.py StateDB (SQLite)
|
||||
carddav.py CardDavClient
|
||||
ldap_source.py LdapSource
|
||||
planner.py Plan, compute_plan(), check_guards()
|
||||
sync.py run_sync(), Summary
|
||||
cli.py main()
|
||||
tests/ (un fichier test_<module>.py par module, ldif_loader.py, conftest.py)
|
||||
deploy/ Dockerfile, docker-compose.yml, crontab.example, fr.ldap2nextcloud.plist
|
||||
README.md
|
||||
```
|
||||
|
||||
Type commun : `RawEntry = dict[str, list[bytes]]` (attribut → valeurs brutes, noms d'attributs tels que renvoyés par LDAP, comparaison insensible à la casse côté mapping).
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Squelette du projet et configuration
|
||||
|
||||
**Files:**
|
||||
- Create: `pyproject.toml`, `.gitignore`, `.env.example`, `mapping.yaml`, `directions.yaml`, `src/ldap2nextcloud/__init__.py`, `src/ldap2nextcloud/config.py`
|
||||
- Test: `tests/test_config.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) class Settings` : `ldap_url: str, ldap_bind_dn: str|None, ldap_bind_password: str|None, ldap_base_dn: str, ldap_filter: str, ldap_birthday_filter: str|None, ldap_group_dns: list[str], ldap_ca_cert: str|None, nextcloud_url: str, nextcloud_user: str, nextcloud_app_password: str, nextcloud_addressbook: str, state_db: Path, mapping_file: Path, directions_file: Path, photo_max_size: int = 512, photo_quality: int = 80, max_delete_ratio: float = 0.10, log_level: str = "INFO"`, et la propriété `addressbook_url -> str` = `f"{nextcloud_url.rstrip('/')}/remote.php/dav/addressbooks/users/{nextcloud_user}/{nextcloud_addressbook}/"`.
|
||||
- `load_settings(env_file: Path|None = None) -> Settings` ; lève `ConfigError(message)` qui nomme la variable manquante.
|
||||
- `@dataclass(frozen=True) class PhoneRule: attr: str, type: str, prefix: str|None, internal_length: int|None`
|
||||
- `@dataclass(frozen=True) class EmailRule: attr: str, type: str, preferred_domain: str|None`
|
||||
- `@dataclass(frozen=True) class Mapping: key: str, organization: str|None, given_name: str, family_name: str, full_name: str, title: str|None, emails: list[EmailRule], phones: list[PhoneRule], group_attr: str|None, photo: str|None, birthday_attr: str|None`
|
||||
- `load_mapping(path: Path) -> Mapping`, `load_directions(path: Path) -> dict[str, str]`
|
||||
- `ConfigError(Exception)`
|
||||
|
||||
- [ ] **Step 1: Initialiser le dépôt et le paquet**
|
||||
|
||||
`git init` ; `pyproject.toml` (setuptools, `src` layout, dépendances de la stack, extra `test` = `pytest`, `responses`, script `ldap2nextcloud = "ldap2nextcloud.cli:main"`). `.gitignore` : `.env`, `state/`, `test-data/` (en entier : le LDIF anonymisé contient encore `usrMotifAbsence` en clair), `__pycache__/`, `.venv/`. Les tests qui lisent `test-data/example.anon.ldif` sont marqués `pytest.mark.skipif` quand le fichier est absent. Créer `python3 -m venv .venv && .venv/bin/pip install -e '.[test]'`.
|
||||
|
||||
- [ ] **Step 2: Écrire les fichiers d'exemple**
|
||||
|
||||
`.env.example` et `mapping.yaml` exactement comme dans la section « Configuration » de la spec (avec `LDAP_BIRTHDAY_FILTER=(usrDirectionId=620)` et une variable `LDAP_GROUP_DNS=` vide, liste séparée par `;`). `directions.yaml` contient les 24 entrées :
|
||||
|
||||
```yaml
|
||||
"100": "Direction générale"
|
||||
"240": "Direction financière"
|
||||
"620": "Direction des systèmes d'information"
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Écrire les tests**
|
||||
|
||||
```python
|
||||
def test_load_settings_reads_env_file(tmp_path): ...
|
||||
# .env minimal complet → settings.addressbook_url == "https://cloud.test/remote.php/dav/addressbooks/users/annuaire/annuaire/"
|
||||
# photo_max_size == 512, photo_quality == 80, max_delete_ratio == 0.10
|
||||
def test_load_settings_missing_variable_names_it(tmp_path, monkeypatch):
|
||||
# sans NEXTCLOUD_APP_PASSWORD → pytest.raises(ConfigError, match="NEXTCLOUD_APP_PASSWORD")
|
||||
def test_load_settings_group_dns_split_on_semicolon(tmp_path): ... # "cn=a,dc=x;cn=b,dc=x" → 2 éléments
|
||||
def test_load_mapping_example_file():
|
||||
m = load_mapping(Path("mapping.yaml"))
|
||||
assert m.key == "uid" and m.organization == "Exemple" and m.group_attr == "usrDirectionId"
|
||||
assert m.phones == [PhoneRule("telephoneNumber", "work", "+3312345", 4)]
|
||||
assert m.emails == [EmailRule("mail", "work", "example.org")]
|
||||
assert m.birthday_attr == "usrDateNaissance"
|
||||
def test_load_directions_example_file():
|
||||
d = load_directions(Path("directions.yaml"))
|
||||
assert len(d) == 3 and d["620"] == "Direction des systèmes d'information"
|
||||
```
|
||||
|
||||
Les tests de `load_settings` doivent isoler l'environnement (`monkeypatch.delenv` sur toutes les variables connues) ; les valeurs du `.env` ne surchargent pas une variable déjà présente dans l'environnement (comportement `python-dotenv` par défaut, utile pour Docker).
|
||||
|
||||
- [ ] **Step 4: Lancer, constater l'échec** — `.venv/bin/pytest tests/test_config.py -v` → FAIL (import).
|
||||
- [ ] **Step 5: Implémenter `config.py`.**
|
||||
- [ ] **Step 6: Lancer, constater le succès** — même commande → PASS.
|
||||
- [ ] **Step 7: Commit** — `🤖 Initialise le projet et la configuration`.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Fiche normalisée et correspondance LDAP
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/model.py`, `src/ldap2nextcloud/mapping.py`
|
||||
- Test: `tests/test_model.py`, `tests/test_mapping.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `Mapping`, `PhoneRule`, `EmailRule` (Task 1).
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) class Phone: number: str, type: str`
|
||||
- `@dataclass(frozen=True) class Email: address: str, type: str, preferred: bool`
|
||||
- `@dataclass(frozen=True) class Contact: key: str, given_name: str, family_name: str, full_name: str, organization: str|None, title: str|None, emails: tuple[Email, ...], phones: tuple[Phone, ...], category: str|None, birthday: date|None, photo: bytes|None` (photo = octets bruts LDAP).
|
||||
- `FORMAT_VERSION = 1`
|
||||
- `contact_uid(key: str) -> str` (uuid5, voir Global Constraints), `contact_href(key: str) -> str` = `f"{contact_uid(key)}.vcf"`.
|
||||
- `fingerprint(contact: Contact, photo_max_size: int, photo_quality: int) -> str` : SHA-256 hex d'une sérialisation JSON triée de tous les champs (photo remplacée par son SHA-256, date en ISO) + `FORMAT_VERSION`, `photo_max_size`, `photo_quality`.
|
||||
- `format_phone(raw: str, rule: PhoneRule) -> str`
|
||||
- `parse_birthday(raw: str) -> date|None`
|
||||
- `entry_to_contact(entry: RawEntry, mapping: Mapping, directions: dict[str, str], with_birthday: bool) -> Contact|None` ; `RawEntry` défini ici (`dict[str, list[bytes]]`).
|
||||
|
||||
- [ ] **Step 1: Tests `test_model.py`**
|
||||
|
||||
```python
|
||||
def test_href_is_stable_and_derived_from_key():
|
||||
assert contact_href("omalmare") == contact_href("omalmare")
|
||||
assert contact_href("omalmare").endswith(".vcf") and contact_href("omalmare") != contact_href("cbarssac")
|
||||
def test_fingerprint_stable_for_equal_contacts(): ... # deux Contact égaux → même empreinte
|
||||
def test_fingerprint_changes_with_any_field(): ... # changer category, photo, birthday → empreinte différente
|
||||
def test_fingerprint_changes_with_photo_settings(): ... # 512 vs 720 → différente
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Tests `test_mapping.py`** (entrées construites à la main, octets UTF-8)
|
||||
|
||||
```python
|
||||
def test_internal_number_gets_prefix():
|
||||
assert format_phone("9052", PhoneRule("telephoneNumber", "work", "+3312345", 4)) == "+33123459052"
|
||||
def test_full_number_is_kept_without_spaces():
|
||||
assert format_phone("01 23 45 90 52", RULE) == "0123459052"
|
||||
assert format_phone("+33 1 23.45.90.52", RULE) == "+33123459052"
|
||||
def test_parse_birthday_generalized_time():
|
||||
assert parse_birthday("19680615000000Z") == date(1968, 6, 15)
|
||||
def test_parse_birthday_invalid_returns_none():
|
||||
assert parse_birthday("pas une date") is None
|
||||
def test_full_entry_maps_all_fields():
|
||||
# entrée type omalmare : cn, sn, givenName, mail, telephoneNumber "9052", usrDirectionId "620",
|
||||
# usrCadre, usrDateNaissance, jpegPhoto → Contact complet ; category == "Direction des systèmes d'information";
|
||||
# organization == "Exemple"; emails == (Email("o.malmare@example.org", "work", True),)
|
||||
def test_birthday_only_when_requested():
|
||||
# with_birthday=False → contact.birthday is None
|
||||
def test_unknown_direction_code_gives_no_category(caplog):
|
||||
# usrDirectionId "999" → category None, un WARNING qui contient "999" et l'uid, aucun nom
|
||||
def test_missing_optional_attributes():
|
||||
# sans mail, telephoneNumber, jpegPhoto, usrDirectionId → emails == (), phones == (), photo is None, category is None
|
||||
def test_entry_without_key_is_skipped(caplog):
|
||||
# sans uid → None + WARNING
|
||||
def test_accented_names_decoded():
|
||||
# givenName "Cédric".encode() → contact.given_name == "Cédric"
|
||||
def test_preferred_email_domain():
|
||||
# mail ["x@autre.fr", "x@example.org"] → seul example.org a preferred=True, il vient en premier
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Lancer** — `.venv/bin/pytest tests/test_model.py tests/test_mapping.py -v` → FAIL.
|
||||
- [ ] **Step 4: Implémenter `model.py` puis `mapping.py`.** Recherche d'attribut insensible à la casse ; `full_name` retombe sur `"{given_name} {family_name}"` si `cn` absent.
|
||||
- [ ] **Step 5: Lancer** → PASS.
|
||||
- [ ] **Step 6: Commit** — `🤖 Ajoute la fiche normalisée et la correspondance LDAP`.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Traitement des photos
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/photo.py`
|
||||
- Test: `tests/test_photo.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `resize_photo(data: bytes, max_size: int, quality: int) -> bytes|None` (JPEG ; `None` si illisible).
|
||||
|
||||
- [ ] **Step 1: Tests** (images générées avec Pillow)
|
||||
|
||||
```python
|
||||
def test_large_photo_is_reduced_keeping_ratio():
|
||||
out = resize_photo(jpeg(1200, 900), 512, 80); assert Image.open(BytesIO(out)).size == (512, 384)
|
||||
def test_small_photo_is_not_enlarged():
|
||||
assert Image.open(BytesIO(resize_photo(jpeg(300, 300), 512, 80))).size == (300, 300)
|
||||
def test_png_with_alpha_becomes_jpeg():
|
||||
assert Image.open(BytesIO(resize_photo(png_rgba(600, 600), 512, 80))).format == "JPEG"
|
||||
def test_exif_orientation_applied():
|
||||
# JPEG 400x200 avec EXIF Orientation=6 → sortie 200x400 (ou réduite proportionnellement), sans EXIF
|
||||
def test_output_has_no_exif(): ...
|
||||
def test_invalid_data_returns_none():
|
||||
assert resize_photo(b"pas une image", 512, 80) is None
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter** (`ImageOps.exif_transpose`, `convert("RGB")`, `thumbnail((max_size, max_size), Image.LANCZOS)`, `save(format="JPEG", quality=quality, optimize=True)`). **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute le retaillage des photos`.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Génération vCard
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/vcard.py`
|
||||
- Test: `tests/test_vcard.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `Contact`, `contact_uid` (Task 2).
|
||||
- Produces:
|
||||
- `render_vcard(contact: Contact, photo_jpeg: bytes|None, sync_hash: str, now: datetime) -> str`
|
||||
- `read_sync_hash(vcard_text: str) -> str|None` (valeur de `X-LDAPSYNC-HASH`, `None` si absente ou carte illisible).
|
||||
|
||||
- [ ] **Step 1: Tests**
|
||||
|
||||
```python
|
||||
def test_render_contains_expected_properties():
|
||||
card = vobject.readOne(render_vcard(FULL_CONTACT, b"\xff\xd8jpeg", "abc", NOW))
|
||||
assert card.version.value == "3.0"
|
||||
assert card.uid.value == contact_uid(FULL_CONTACT.key)
|
||||
assert card.n.value.family == "MALMARE" and card.n.value.given == "Oscar"
|
||||
assert card.org.value == ["Exemple"] and card.title.value == "Ingénieur"
|
||||
assert card.tel.value == "+33123459052" and set(card.tel.params["TYPE"]) == {"VOICE", "WORK"}
|
||||
assert card.email.value == "o.malmare@example.org" and "PREF" in card.email.params["TYPE"]
|
||||
assert card.categories.value == ["Direction des systèmes d'information"]
|
||||
assert card.bday.value == "1968-06-15"
|
||||
assert card.photo.value == b"\xff\xd8jpeg"
|
||||
assert card.x_ldapsync_hash.value == "abc"
|
||||
def test_optional_fields_omitted():
|
||||
# Contact sans title/phones/emails/category/birthday/photo → aucune de ces propriétés dans le texte
|
||||
def test_no_legacy_properties():
|
||||
text = render_vcard(FULL_CONTACT, None, "abc", NOW)
|
||||
assert "KIND" not in text and "X-ABUID" not in text and "ADR" not in text
|
||||
def test_accents_and_long_lines_roundtrip():
|
||||
# full_name de 120 caractères accentués → vobject.readOne(text).fn.value == full_name ; lignes ≤ 75 octets
|
||||
def test_crlf_line_endings(): assert "\r\n" in text and "\n" not in text.replace("\r\n", "")
|
||||
def test_read_sync_hash_roundtrip(): assert read_sync_hash(render_vcard(..., "abc", NOW)) == "abc"
|
||||
def test_read_sync_hash_absent(): assert read_sync_hash(LEGACY_CARD_TEXT) is None
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter** avec `vobject` (`vCard()`, `serialize()`), `PRODID` et `REV` (`now` au format `%Y%m%dT%H%M%SZ`). **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute la génération des vCards`.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Base d'état SQLite
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/state.py`
|
||||
- Test: `tests/test_state.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) class StateRow: href: str, key: str, fingerprint: str, etag: str|None`
|
||||
- `class StateDB` : `__init__(path: Path)` (crée dossier et table `contacts(href TEXT PRIMARY KEY, key TEXT NOT NULL, fingerprint TEXT NOT NULL, etag TEXT, updated_at TEXT NOT NULL)`), `all() -> dict[str, StateRow]`, `upsert(row: StateRow) -> None`, `set_etag(href: str, etag: str) -> None`, `delete(href: str) -> None`, `close()`, gestionnaire de contexte. Chaque écriture est commitée immédiatement (reprise d'un premier passage interrompu).
|
||||
|
||||
- [ ] **Step 1: Tests** — `test_upsert_then_all`, `test_upsert_overwrites`, `test_set_etag`, `test_delete`, `test_persists_across_reopen` (fermer, rouvrir, retrouver la ligne), `test_creates_parent_directory`.
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter.** **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute la base d'état locale`.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Client CardDAV
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/carddav.py`
|
||||
- Test: `tests/test_carddav.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `class CardDavError(Exception)` avec `status: int|None`.
|
||||
- `class CardDavClient` : `__init__(addressbook_url: str, user: str, password: str, timeout: float = 30)`
|
||||
- `list_etags() -> dict[str, str]` : `PROPFIND Depth: 1` demandant `getetag` ; clés = nom de fichier seul décodé (`unquote(path.rsplit("/", 1)[-1])`), collection exclue, ETag sans guillemets.
|
||||
- `multiget(hrefs: list[str]) -> dict[str, str]` : `REPORT addressbook-multiget` (`getetag` + `address-data`), par lots de 50.
|
||||
- `put(href: str, vcard: str, etag: str|None) -> str|None` : `If-Match: "<etag>"` si `etag`, sinon `If-None-Match: *` ; `Content-Type: text/vcard; charset=utf-8` ; renvoie l'ETag de la réponse sans guillemets ou `None`.
|
||||
- `delete(href: str, etag: str|None) -> None` ; 404 traité comme succès.
|
||||
- Toute réponse hors 2xx (et hors 404 pour delete) → `CardDavError`.
|
||||
|
||||
- [ ] **Step 1: Tests** (`responses`, réponses XML multistatus réalistes de Nextcloud)
|
||||
|
||||
```python
|
||||
def test_list_etags_normalizes_hrefs():
|
||||
# réponse avec "/remote.php/dav/addressbooks/users/annuaire/annuaire/" (collection)
|
||||
# et ".../a%40b.vcf" etag "\"123\"" → {"a@b.vcf": "123"}
|
||||
def test_list_etags_empty_addressbook(): ... # seule la collection → {}
|
||||
def test_put_create_sends_if_none_match(): ... # en-tête If-None-Match == "*", renvoie "e1"
|
||||
def test_put_update_sends_if_match(): ... # If-Match == "\"e0\""
|
||||
def test_put_without_etag_in_response_returns_none(): ...
|
||||
def test_put_412_raises_with_status():
|
||||
with pytest.raises(CardDavError) as e: client.put("x.vcf", "...", "old")
|
||||
assert e.value.status == 412
|
||||
def test_delete_404_is_success(): ...
|
||||
def test_multiget_batches_by_50(): ... # 120 hrefs → 3 requêtes REPORT, dictionnaire fusionné
|
||||
def test_basic_auth_sent(): ...
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter** (`requests.Session`, XML via `xml.etree.ElementTree`, espaces de noms `DAV:` et `urn:ietf:params:xml:ns:carddav`). **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute le client CardDAV`.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Lecture LDAP
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/ldap_source.py`, `tests/ldif_loader.py`
|
||||
- Test: `tests/test_ldap_source.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `Settings`, `Mapping` (Task 1), `RawEntry` (Task 2).
|
||||
- Produces:
|
||||
- `required_attributes(mapping: Mapping) -> list[str]` (clé + tous les attributs du mapping).
|
||||
- `class LdapSource` : `__init__(settings: Settings, connection: ldap3.Connection|None = None)` (connexion fournie en test, sinon créée depuis `settings`, TLS avec `ldap_ca_cert` si renseigné, bind anonyme si `ldap_bind_dn` vide).
|
||||
- `fetch_entries(attributes: list[str]) -> list[RawEntry]` : recherche paginée (taille de page 500) `ldap_base_dn` + `ldap_filter` ; si `ldap_group_dns` non vide, ne garde que les DN présents dans `uniqueMember`/`member` d'au moins un de ces groupes.
|
||||
- `fetch_birthday_keys(key_attr: str) -> set[str]` : `(&<ldap_filter><ldap_birthday_filter>)`, ne demande que la clé ; ensemble vide si `ldap_birthday_filter` absent.
|
||||
- `tests/ldif_loader.py` : `load_ldif(path: Path) -> list[tuple[str, dict[str, list[bytes]]]]` (lignes repliées, `::` base64, `:` texte), pour alimenter un `ldap3` `MOCK_SYNC`.
|
||||
|
||||
- [ ] **Step 1: Tests** (serveur `ldap3.Server("mock")`, `Connection(client_strategy=MOCK_SYNC)`, entrées ajoutées depuis `test-data/example.anon.ldif`)
|
||||
|
||||
```python
|
||||
def test_fetch_all_entries_from_anonymized_ldif():
|
||||
entries = source.fetch_entries(required_attributes(MAPPING)); assert len(entries) == 70
|
||||
assert all(isinstance(v, bytes) for e in entries for vals in e.values() for v in vals)
|
||||
def test_only_requested_attributes_returned(): ... # aucune clé "usrMotifAbsence"
|
||||
def test_birthday_keys_filtered_by_direction():
|
||||
keys = source.fetch_birthday_keys("uid")
|
||||
# == ensemble des uid dont usrDirectionId == "620" calculé depuis load_ldif
|
||||
def test_group_dns_restrict_population(): ... # groupe mock avec 2 uniqueMember → 2 entrées
|
||||
def test_photo_returned_as_raw_bytes(): ... # jpegPhoto d'une entrée == octets décodés du LDIF
|
||||
```
|
||||
|
||||
Si le mode MOCK de `ldap3` ne gère pas le contrôle de pagination, `fetch_entries` utilise `connection.extend.standard.paged_search(..., generator=False)`, que le mock supporte.
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter.** **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute la lecture de l'annuaire LDAP`.
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Planification des actions et garde-fous
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/planner.py`
|
||||
- Test: `tests/test_planner.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `StateRow` (Task 5).
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) class Desired: href: str, key: str, fingerprint: str`
|
||||
- `@dataclass class Plan: create: list[str], update: list[str], verify: list[str], delete: list[str], unchanged: list[str]` (listes d'hrefs triées).
|
||||
- `compute_plan(desired: dict[str, Desired], server: dict[str, str], state: dict[str, StateRow]) -> Plan` :
|
||||
- dans `desired`, pas dans `server` → `create` ;
|
||||
- dans les deux, dans `state` : empreinte ≠ `state.fingerprint` ou `server[href] != state.etag` → `update`, sinon `unchanged` ;
|
||||
- dans les deux, pas dans `state` → `verify` ;
|
||||
- dans `server`, pas dans `desired` → `delete`.
|
||||
- `class GuardError(Exception)`
|
||||
- `check_guards(desired_count: int, server_count: int, plan: Plan, max_delete_ratio: float, force: bool, initial: bool) -> None` : `GuardError` si `desired_count == 0` (toujours, même avec `force`) ; `GuardError` si `len(plan.delete) > max_delete_ratio * server_count` et ni `force` ni `initial`.
|
||||
|
||||
- [ ] **Step 1: Tests** — un test par cas ci-dessus (`test_new_contact_is_created`, `test_changed_fingerprint_is_updated`, `test_server_etag_drift_is_updated`, `test_unchanged_contact`, `test_missing_state_is_verified`, `test_unknown_server_card_is_deleted` avec un href hérité `ldap2vcard-x.vcf`), plus :
|
||||
|
||||
```python
|
||||
def test_guard_empty_ldap_always_aborts():
|
||||
with pytest.raises(GuardError): check_guards(0, 1270, Plan([], [], [], [], []), 0.10, force=True, initial=True)
|
||||
def test_guard_too_many_deletions():
|
||||
plan = Plan([], [], [], delete=[f"{i}.vcf" for i in range(128)], unchanged=[])
|
||||
with pytest.raises(GuardError): check_guards(1142, 1270, plan, 0.10, False, False)
|
||||
def test_guard_deletions_under_ratio_pass(): check_guards(1143, 1270, plan_127_deletes, 0.10, False, False)
|
||||
def test_guard_initial_allows_mass_deletion(): check_guards(1270, 1270, plan_1270_deletes, 0.10, False, True)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter.** **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute la planification et les garde-fous`.
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Orchestration de la synchro
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/sync.py`
|
||||
- Test: `tests/test_sync.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: tout ce qui précède.
|
||||
- Produces:
|
||||
- `@dataclass class Summary: created: int = 0, updated: int = 0, verified: int = 0, deleted: int = 0, unchanged: int = 0, errors: int = 0`
|
||||
- `run_sync(settings: Settings, mapping: Mapping, directions: dict[str, str], source: LdapSource, client: CardDavClient, state: StateDB, *, dry_run: bool = False, force: bool = False, initial: bool = False, now: datetime|None = None) -> Summary` ; lève `GuardError` avant toute écriture.
|
||||
|
||||
Déroulé : lecture LDAP → `entry_to_contact` (clés anniversaire) → `Desired` + `Contact` par href → `client.list_etags()` → `state.all()` → `compute_plan` → `check_guards` → en `dry_run`, journaliser les actions et renvoyer le résumé sans écrire → sinon :
|
||||
- `verify` : `multiget`, puis pour chaque href, si `read_sync_hash == empreinte` → `state.upsert(StateRow(href, key, fp, server_etag))` et compter `verified`, sinon le basculer en `update` ;
|
||||
- `create` / `update` : `resize_photo` si photo, `render_vcard`, `client.put(href, text, etag_serveur_ou_None)`, puis `state.upsert` avec l'ETag renvoyé ;
|
||||
- `delete` : `client.delete(href, server_etag)`, puis `state.delete(href)` ;
|
||||
- `CardDavError` sur une fiche → log ERROR (href, uid, statut), `errors += 1`, base inchangée pour cette fiche, on continue ;
|
||||
- à la fin, les fiches écrites sans ETag reçoivent l'ETag d'un nouveau `list_etags()` via `state.set_etag`.
|
||||
|
||||
- [ ] **Step 1: Tests** (faux `source`, faux `client` en mémoire implémentant `list_etags/multiget/put/delete`, vraie `StateDB` dans `tmp_path`)
|
||||
|
||||
```python
|
||||
def test_first_run_creates_all_and_purges_legacy():
|
||||
# client contient "ldap2vcard-old.vcf" ; 3 entrées LDAP ; initial=True
|
||||
# → summary.created == 3, summary.deleted == 1, state.all() a 3 lignes avec etag
|
||||
def test_second_run_without_change_does_nothing():
|
||||
# relancer → summary.unchanged == 3, aucun put ni delete
|
||||
def test_changed_entry_is_updated_only():
|
||||
# modifier usrDirectionId d'une entrée → summary.updated == 1, put avec If-Match de l'etag connu
|
||||
def test_lost_state_rebuilds_without_put():
|
||||
# supprimer le fichier SQLite, relancer → summary.verified == 3, aucun put
|
||||
def test_dry_run_writes_nothing(): ... # aucun put/delete, base vide
|
||||
def test_put_error_is_counted_and_not_stored():
|
||||
# le faux client lève CardDavError(status=412) pour un href → errors == 1, href absent de state, les autres créés
|
||||
def test_guard_error_before_any_write(): ... # 128 suppressions sur 1270 sans force → GuardError, aucun appel put/delete
|
||||
def test_missing_etag_in_put_response_is_refreshed(): ... # put renvoie None → etag de list_etags final en base
|
||||
def test_logs_contain_no_personal_data(caplog):
|
||||
# après un run complet, aucun nom, mail, numéro ni date de naissance des entrées dans caplog.text
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter.** **Step 4: Lancer** → PASS ; `.venv/bin/pytest -q` → tout PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute l'orchestration de la synchronisation`.
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Ligne de commande
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ldap2nextcloud/cli.py`
|
||||
- Test: `tests/test_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `load_settings`, `load_mapping`, `load_directions`, `LdapSource`, `CardDavClient`, `StateDB`, `run_sync`, `GuardError`, `ConfigError`.
|
||||
- Produces: `main(argv: list[str]|None = None) -> int` ; options `--dry-run`, `--force`, `--initial`, `--env FICHIER`, `-v/--verbose` (DEBUG).
|
||||
|
||||
Codes retour : 0 succès ; 1 erreurs sur des fiches ; 2 garde-fou déclenché ; 3 configuration invalide ; 4 exécution déjà en cours. Verrou : `fcntl.flock` non bloquant sur `<state_db>.lock`. Logs : `logging` vers stderr, format `%(asctime)s %(levelname)s %(message)s`. Le résumé final est une ligne INFO : `créées=… mises_à_jour=… vérifiées=… supprimées=… inchangées=… erreurs=…`.
|
||||
|
||||
- [ ] **Step 1: Tests** — `test_truststore_injected_before_anything` (`monkeypatch` de `truststore.inject_into_ssl` par un espion : appelé une fois, avant `load_settings`), `test_config_error_returns_3` (env vide), `test_guard_error_returns_2`, `test_card_errors_return_1`, `test_success_returns_0`, `test_lock_held_returns_4` (verrou pris par le test), en remplaçant `run_sync`, `LdapSource` et `CardDavClient` par `monkeypatch`.
|
||||
- [ ] **Step 2: Lancer** → FAIL. **Step 3: Implémenter.** **Step 4: Lancer** → PASS.
|
||||
- [ ] **Step 5: Commit** — `🤖 Ajoute la ligne de commande`.
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Déploiement et documentation
|
||||
|
||||
**Files:**
|
||||
- Create: `deploy/Dockerfile`, `deploy/docker-compose.yml`, `deploy/crontab.example`, `deploy/fr.ldap2nextcloud.plist`, `README.md`
|
||||
|
||||
- [ ] **Step 1: Dockerfile** — `python:3.12-slim`, installation du paquet, utilisateur non root, `WORKDIR /app`, copie des certificats d'autorité de `deploy/certs/*.crt` (dossier facultatif, ignoré par git, pour l'autorité du proxy) dans `/usr/local/share/ca-certificates/` suivie de `update-ca-certificates` (truststore lit le magasin système du container), volume `/app/state`, `ENTRYPOINT ["ldap2nextcloud"]`. `docker-compose.yml` : service `sync` avec `env_file: ../.env`, montages `../mapping.yaml`, `../directions.yaml` (lecture seule) et `../state`, variables `STATE_DB=/app/state/sync.sqlite`, `MAPPING_FILE=/app/mapping.yaml`, `DIRECTIONS_FILE=/app/directions.yaml`.
|
||||
- [ ] **Step 2: Planification** — `crontab.example` : toutes les heures de 7 h à 20 h en semaine, `cd <chemin> && .venv/bin/ldap2nextcloud >> state/sync.log 2>&1`, et la variante `docker compose -f deploy/docker-compose.yml run --rm sync`. Plist launchd équivalent (`StartCalendarInterval`).
|
||||
- [ ] **Step 3: README** — installation, configuration (`.env`, `mapping.yaml`, `directions.yaml`), premier passage (`--dry-run --initial` puis `--initial`), codes retour, réglage DAVx5 « groupes = catégories ».
|
||||
- [ ] **Step 4: Vérifier** — `docker build -f deploy/Dockerfile -t ldap2nextcloud .` réussit ; `docker run --rm ldap2nextcloud --help` affiche les options.
|
||||
- [ ] **Step 5: Vérifier l'ensemble** — `.venv/bin/pytest -q` → tout PASS.
|
||||
- [ ] **Step 6: Commit** — `🤖 Ajoute le déploiement et la documentation`.
|
||||
|
||||
---
|
||||
|
||||
### Task 12: Recette sur le compte Nextcloud de test
|
||||
|
||||
Réalisée avec l'utilisateur, qui fournit le compte de test (mot de passe d'application dans `.env`, jamais dans le dépôt ni dans la conversation).
|
||||
|
||||
- [ ] **Step 1:** `ldap2nextcloud --dry-run --initial` contre l'annuaire réel et le carnet de test : vérifier les nombres annoncés (~1 270 créations).
|
||||
- [ ] **Step 2:** `ldap2nextcloud --initial` : code retour 0 ; durée et taille du carnet notées.
|
||||
- [ ] **Step 3:** Relancer sans option : `inchangées≈1270`, aucune écriture.
|
||||
- [ ] **Step 4:** Supprimer `state/sync.sqlite`, relancer : `vérifiées≈1270`, aucune création.
|
||||
- [ ] **Step 5:** Sur le téléphone (DAVx5) : groupes par Direction visibles, photo nette pendant un appel, numéro au format `+3312345xxxx`, dates de naissance présentes pour la Direction 620 seulement.
|
||||
Reference in new issue
Block a user