🤖 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,24 @@
|
|||||||
|
# Annuaire LDAP
|
||||||
|
LDAP_URL=ldaps://ldap.example.org
|
||||||
|
LDAP_BIND_DN= # vide = bind anonyme
|
||||||
|
LDAP_BIND_PASSWORD=
|
||||||
|
LDAP_BASE_DN=ou=personnes,dc=example,dc=org
|
||||||
|
LDAP_FILTER=(objectClass=inetOrgPerson)
|
||||||
|
LDAP_BIRTHDAY_FILTER=(usrDirectionId=620)
|
||||||
|
LDAP_GROUP_DNS= # facultatif, DN séparés par ";"
|
||||||
|
LDAP_CA_CERT= # facultatif
|
||||||
|
|
||||||
|
# Nextcloud
|
||||||
|
NEXTCLOUD_URL=https://cloud.example.org
|
||||||
|
NEXTCLOUD_USER=annuaire
|
||||||
|
NEXTCLOUD_APP_PASSWORD=
|
||||||
|
NEXTCLOUD_ADDRESSBOOK=annuaire
|
||||||
|
|
||||||
|
# Fonctionnement
|
||||||
|
STATE_DB=./state/sync.sqlite
|
||||||
|
MAPPING_FILE=./mapping.yaml
|
||||||
|
DIRECTIONS_FILE=./directions.yaml
|
||||||
|
PHOTO_MAX_SIZE=512
|
||||||
|
PHOTO_QUALITY=80
|
||||||
|
MAX_DELETE_RATIO=0.10
|
||||||
|
LOG_LEVEL=INFO
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
.env
|
||||||
|
state/
|
||||||
|
test-data/*
|
||||||
|
!test-data/*.anon.ldif
|
||||||
|
!test-data/*.anon.vcf
|
||||||
|
deploy/certs/*
|
||||||
|
!deploy/certs/.gitkeep
|
||||||
|
__pycache__/
|
||||||
|
*.egg-info/
|
||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
.superpowers/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
mapping.yaml
|
||||||
|
directions.yaml
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# ldap2nextcloud
|
||||||
|
|
||||||
|
Synchronise l'annuaire LDAP vers un carnet d'adresses Nextcloud, en CardDAV. Seules les fiches créées, modifiées ou supprimées dans l'annuaire sont envoyées. Le carnet doit appartenir à un utilisateur Nextcloud dédié : l'outil en est seul maître et écrase toute modification manuelle.
|
||||||
|
|
||||||
|
Conception : [docs/superpowers/specs/2026-11-16-ldap-nextcloud-sync-design.md](docs/superpowers/specs/2026-11-16-ldap-nextcloud-sync-design.md)
|
||||||
|
|
||||||
|
## Ce qui est synchronisé
|
||||||
|
|
||||||
|
| Fiche Nextcloud | Attribut LDAP |
|
||||||
|
|---|---|
|
||||||
|
| Nom, prénom, nom affiché | `sn`, `givenName`, `cn` |
|
||||||
|
| Organisation | constante définie dans `mapping.yaml` |
|
||||||
|
| Fonction | `usrCadre` |
|
||||||
|
| Email | `mail` (l'adresse du domaine `preferred_domain` est marquée préférée) |
|
||||||
|
| Téléphone | `telephoneNumber`, numéro interne à 4 chiffres préfixé selon `mapping.yaml` |
|
||||||
|
| Groupe | `usrDirectionId`, traduit en libellé par `directions.yaml` |
|
||||||
|
| Photo | `jpegPhoto`, réduite à 512 × 512 au plus, JPEG qualité 80 |
|
||||||
|
| Date de naissance | `usrDateNaissance`, seulement pour les fiches retenues par `LDAP_BIRTHDAY_FILTER` |
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Python 3.11 ou plus récent :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/pip install .
|
||||||
|
```
|
||||||
|
|
||||||
|
Les connexions TLS (Nextcloud et LDAPS) sont validées avec le magasin de certificats du système, grâce à `truststore`. Un proxy qui inspecte le HTTPS est donc accepté dès que son autorité de certification est installée sur la machine. Les variables `HTTPS_PROXY` et `NO_PROXY` sont respectées.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
1. Copier `.env.example` en `.env` et le remplir. Pour Nextcloud, utiliser un mot de passe d'application (Paramètres personnels › Sécurité). Le carnet `NEXTCLOUD_ADDRESSBOOK` doit déjà exister.
|
||||||
|
2. `mapping.yaml` (copier `mapping.example.yaml`) : correspondance entre attributs LDAP et champs vCard.
|
||||||
|
3. `directions.yaml` (copier `directions.example.yaml`) : libellé de chaque code Direction. Une Direction inconnue est signalée dans le journal, et la fiche part sans groupe.
|
||||||
|
|
||||||
|
`LDAP_FILTER` délimite la population synchronisée. Si l'appartenance aux groupes n'est pas portée par les fiches, `LDAP_GROUP_DNS` restreint la synchro aux membres de ces groupes (DN séparés par `;`).
|
||||||
|
|
||||||
|
## Premier passage
|
||||||
|
|
||||||
|
Le carnet contient encore les fiches de l'ancien script. Elles sont supprimées puis recréées une seule fois :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/ldap2nextcloud --dry-run --initial
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/ldap2nextcloud --initial
|
||||||
|
```
|
||||||
|
|
||||||
|
Les passages suivants se lancent sans option.
|
||||||
|
|
||||||
|
## Options et codes retour
|
||||||
|
|
||||||
|
| Option | Effet |
|
||||||
|
|---|---|
|
||||||
|
| `--dry-run` | affiche les actions prévues sans rien écrire |
|
||||||
|
| `--initial` | autorise la purge massive du premier passage |
|
||||||
|
| `--force` | passe outre la limite de suppressions (`MAX_DELETE_RATIO`, 10 % par défaut) |
|
||||||
|
| `--env FICHIER` | fichier de configuration (défaut : `./.env`) |
|
||||||
|
| `-v` | journal détaillé |
|
||||||
|
|
||||||
|
| Code | Signification |
|
||||||
|
|---|---|
|
||||||
|
| 0 | succès |
|
||||||
|
| 1 | des fiches n'ont pas pu être envoyées, ou l'annuaire ou Nextcloud est injoignable |
|
||||||
|
| 2 | garde-fou déclenché : l'annuaire est vide, ou il y a trop de suppressions |
|
||||||
|
| 3 | configuration invalide |
|
||||||
|
| 4 | une autre exécution est en cours |
|
||||||
|
|
||||||
|
Pendant les écritures, l'avancement s'affiche sans aucune donnée personnelle. Dans un terminal, c'est une barre de progression, et les avertissements s'affichent au-dessus. Hors terminal (cron, launchd, `docker compose run -T`), une ligne `Progression : 300/1381` est journalisée toutes les 100 fiches.
|
||||||
|
|
||||||
|
Si la base locale `state/sync.sqlite` est perdue, rien n'est renvoyé au serveur : l'outil relit le carnet une fois pour la reconstruire.
|
||||||
|
|
||||||
|
## Planification
|
||||||
|
|
||||||
|
- cron (Linux ou macOS) : voir `deploy/crontab.example`.
|
||||||
|
- launchd (macOS) : voir `deploy/fr.ldap2nextcloud.plist`.
|
||||||
|
- Docker : déposer l'autorité du proxy dans `deploy/certs/*.crt` si besoin, puis :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f deploy/docker-compose.yml build
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f deploy/docker-compose.yml run --rm sync --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
## Lenteur des créations sur Nextcloud (26 Summer)
|
||||||
|
|
||||||
|
### Symptôme
|
||||||
|
|
||||||
|
Sur un carnet déjà rempli, chaque création de fiche (`PUT`) prend 15 à 25 secondes. Les lectures et les suppressions restent instantanées. Sur un carnet vide, la même création prend 0,2 s. Le premier passage, qui crée environ 1 400 fiches, dure alors 6 à 8 heures. Avec un délai réseau de 30 s, certaines fiches finissent même en erreur « read timeout ».
|
||||||
|
|
||||||
|
### Cause
|
||||||
|
|
||||||
|
À chaque création, Nextcloud vérifie qu'aucune autre fiche du carnet ne porte le même `UID` :
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM oc_cards WHERE addressbookid = ? AND uid = ? LIMIT 1
|
||||||
|
```
|
||||||
|
|
||||||
|
La table `oc_cards` n'a qu'un index sur `(addressbookid, uri)`, aucun sur `uid`. MariaDB parcourt donc toutes les fiches du carnet. Comme la requête demande toutes les colonnes (`SELECT *`), chaque fiche est lue en entier, vCard et photo comprises. Le coût grandit avec la taille du carnet, et il est maximal pendant le premier passage, quand le carnet contient à la fois les anciennes fiches et les nouvelles. Sur disque mécanique, avec un cache InnoDB trop petit pour la table, chaque création relit plusieurs centaines de Mo.
|
||||||
|
|
||||||
|
Ni l'outil, ni le réseau, ni le proxy ne sont en cause. Le journal des requêtes lentes de MariaDB l'a confirmé.
|
||||||
|
|
||||||
|
### Solution
|
||||||
|
|
||||||
|
Ajouter un index sur `(addressbookid, uid)`, après une sauvegarde de la base. `LOCK=NONE` laisse Nextcloud fonctionner pendant la création de l'index :
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE oc_cards ADD INDEX cards_abid_uid_local (addressbookid, uid), ALGORITHM=INPLACE, LOCK=NONE;
|
||||||
|
```
|
||||||
|
|
||||||
|
Une création passe alors à 0,1-0,3 s, et le premier passage à quelques minutes. Pour vérifier que l'index est utilisé, remplacer `<id>` par l'identifiant du carnet :
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN SELECT * FROM oc_cards WHERE addressbookid = <id> AND uid = 'test' LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
On doit obtenir `key = cards_abid_uid_local` et `rows = 1`.
|
||||||
|
|
||||||
|
Cet index n'appartient pas au schéma de Nextcloud. Avant chaque montée de version majeure, vérifier si Nextcloud ajoute un index équivalent sur `oc_cards`, et supprimer alors `cards_abid_uid_local`.
|
||||||
|
|
||||||
|
Autre réglage utile : vérifier que `innodb_buffer_pool_size` est à la mesure des données. La valeur par défaut de 128 Mo est souvent trop petite pour un serveur qui héberge Nextcloud.
|
||||||
|
|
||||||
|
### Diagnostiquer
|
||||||
|
|
||||||
|
Si les écritures restent lentes :
|
||||||
|
|
||||||
|
1. **Situer la lenteur.** Comparer un `PROPFIND` et un `PUT` de fiche de test, puis un `PUT` sur un carnet vide. Si seul le `PUT` est lent, et seulement sur un carnet rempli, c'est le serveur.
|
||||||
|
2. **Activer le journal des requêtes lentes à chaud**, sans toucher à la configuration :
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SET GLOBAL slow_query_log = 1;
|
||||||
|
SET GLOBAL long_query_time = 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Le lire sans exposer de données personnelles.** Le journal brut contient les vCards insérées. `mariadb-dumpslow` remplace les valeurs par `N` et `'S'` :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mariadb-dumpslow -s t -t 10 /var/lib/mysql/mariadb-slow.log
|
||||||
|
```
|
||||||
|
|
||||||
|
## Android (DAVx5)
|
||||||
|
|
||||||
|
Dans le compte DAVx5 de l'utilisateur dédié, régler la méthode des groupes sur « Les groupes sont des catégories par contact ».
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/pip install -e '.[test]'
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Les tests LDAP utilisent `test-data/example.anon.ldif`, un export anonymisé et réduit aux attributs du mapping. Seuls les fichiers `test-data/*.anon.ldif` et `*.anon.vcf` sont versionnés.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
# Autorité de certification du proxy (facultatif) : déposer les .crt dans deploy/certs/.
|
||||||
|
# truststore valide le TLS avec le magasin système du container.
|
||||||
|
COPY deploy/certs/ /usr/local/share/ca-certificates/
|
||||||
|
RUN update-ca-certificates
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY pyproject.toml ./
|
||||||
|
COPY src ./src
|
||||||
|
RUN pip install --no-cache-dir --root-user-action=ignore . \
|
||||||
|
&& useradd --create-home --uid 1000 ldapsync \
|
||||||
|
&& mkdir -p /app/state && chown ldapsync /app/state
|
||||||
|
|
||||||
|
USER ldapsync
|
||||||
|
VOLUME ["/app/state"]
|
||||||
|
ENV STATE_DB=/app/state/sync.sqlite \
|
||||||
|
MAPPING_FILE=/app/mapping.yaml \
|
||||||
|
DIRECTIONS_FILE=/app/directions.yaml
|
||||||
|
ENTRYPOINT ["ldap2nextcloud"]
|
||||||
Whitespace-only changes.
@@ -0,0 +1,8 @@
|
|||||||
|
# Synchronisation toutes les heures, de 7 h à 20 h, du lundi au vendredi.
|
||||||
|
# Remplacer /chemin/vers/nextlsynch par le dossier d'installation.
|
||||||
|
|
||||||
|
# Installation Python (venv) :
|
||||||
|
0 7-20 * * 1-5 cd /chemin/vers/nextlsynch && .venv/bin/ldap2nextcloud >> state/sync.log 2>&1
|
||||||
|
|
||||||
|
# Variante Docker :
|
||||||
|
# 0 7-20 * * 1-5 cd /chemin/vers/nextlsynch && docker compose -f deploy/docker-compose.yml run --rm sync >> state/sync.log 2>&1
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
services:
|
||||||
|
sync:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: deploy/Dockerfile
|
||||||
|
image: ldap2nextcloud
|
||||||
|
env_file: ../.env
|
||||||
|
environment:
|
||||||
|
STATE_DB: /app/state/sync.sqlite
|
||||||
|
MAPPING_FILE: /app/mapping.yaml
|
||||||
|
DIRECTIONS_FILE: /app/directions.yaml
|
||||||
|
volumes:
|
||||||
|
- ../mapping.yaml:/app/mapping.yaml:ro
|
||||||
|
- ../directions.yaml:/app/directions.yaml:ro
|
||||||
|
- ../state:/app/state
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<!--
|
||||||
|
Agent launchd (macOS) : synchronisation toutes les heures de 7 h à 20 h, du lundi au vendredi.
|
||||||
|
Remplacer /chemin/vers/nextlsynch, copier dans ~/Library/LaunchAgents/ puis :
|
||||||
|
launchctl load ~/Library/LaunchAgents/fr.ldap2nextcloud.plist
|
||||||
|
-->
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>fr.ldap2nextcloud</string>
|
||||||
|
<key>WorkingDirectory</key>
|
||||||
|
<string>/chemin/vers/nextlsynch</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>/chemin/vers/nextlsynch/.venv/bin/ldap2nextcloud</string>
|
||||||
|
</array>
|
||||||
|
<key>StandardOutPath</key>
|
||||||
|
<string>/chemin/vers/nextlsynch/state/sync.log</string>
|
||||||
|
<key>StandardErrorPath</key>
|
||||||
|
<string>/chemin/vers/nextlsynch/state/sync.log</string>
|
||||||
|
<key>StartCalendarInterval</key>
|
||||||
|
<array>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>7</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>8</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>9</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>10</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>12</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>14</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>15</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>16</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>17</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>18</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>19</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>1</integer><key>Hour</key><integer>20</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>7</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>8</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>9</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>10</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>12</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>14</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>15</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>16</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>17</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>18</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>19</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>2</integer><key>Hour</key><integer>20</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>7</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>8</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>9</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>10</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>12</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>14</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>15</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>16</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>17</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>18</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>19</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>20</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>7</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>8</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>9</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>10</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>12</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>14</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>15</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>16</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>17</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>18</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>19</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>4</integer><key>Hour</key><integer>20</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>7</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>8</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>9</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>10</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>12</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>14</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>15</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>16</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>17</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>18</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>19</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
<dict><key>Weekday</key><integer>5</integer><key>Hour</key><integer>20</integer><key>Minute</key><integer>0</integer></dict>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Code de Direction -> libellé affiché comme groupe de contacts.
|
||||||
|
# Copier en directions.yaml et compléter avec les codes de votre annuaire.
|
||||||
|
"100": "Direction générale"
|
||||||
|
"240": "Direction financière"
|
||||||
|
"620": "Direction des systèmes d'information"
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
# Synchronisation LDAP → Nextcloud (CardDAV) — conception
|
||||||
|
|
||||||
|
Date : 2026-11-16 · Projet vault : [[Synchronisation LDAP vers Nextcloud]]
|
||||||
|
|
||||||
|
## Intention
|
||||||
|
|
||||||
|
Aujourd'hui, le script bash `LDAP2vCard/ldap2vcard.sh` exporte l'annuaire LDAP
|
||||||
|
dans un fichier `.vcf` unique (~1 270 fiches, **~185 Mo**, chaque fiche avec sa
|
||||||
|
photo pleine taille), puis le carnet Nextcloud est vidé et rechargé. C'est lent,
|
||||||
|
cela fait transiter toutes les photos à chaque passage, et DAVx5 re-télécharge
|
||||||
|
tout le carnet sur Android.
|
||||||
|
|
||||||
|
Le nouvel outil, en Python, ne pousse vers Nextcloud que les fiches créées,
|
||||||
|
modifiées ou supprimées dans l'annuaire, avec des photos retaillées. Le carnet
|
||||||
|
appartient à un utilisateur Nextcloud dédié et est consommé sur Android via
|
||||||
|
DAVx5, en parallèle du carnet perso de l'utilisateur.
|
||||||
|
|
||||||
|
## Objectifs
|
||||||
|
|
||||||
|
- Synchroniser depuis LDAP : nom, prénom, photo, téléphone, email, Direction
|
||||||
|
(comme groupe de contacts) et, pour une partie des fiches seulement, la date
|
||||||
|
de naissance (fiches sélectionnées par un filtre LDAP).
|
||||||
|
- Conserver ce que l'export actuel apporte d'utile : organisation (« Exemple »)
|
||||||
|
et fonction (`usrCadre`).
|
||||||
|
- N'envoyer que les différences (création / mise à jour / suppression).
|
||||||
|
- Se réparer seul si le serveur diverge de l'état local (approche C).
|
||||||
|
- Tourner sans surveillance : cron (Linux), cron/launchd (macOS) ou Docker.
|
||||||
|
- Paramétrage par `.env` (connexions, secrets), un fichier de mapping
|
||||||
|
attributs LDAP → champs vCard et une table code Direction → libellé.
|
||||||
|
- Retailler les photos trop volumineuses.
|
||||||
|
|
||||||
|
## Non-objectifs
|
||||||
|
|
||||||
|
- Synchronisation Nextcloud → LDAP : jamais.
|
||||||
|
- Conservation de modifications manuelles faites dans Nextcloud : le carnet
|
||||||
|
appartient au script, toute modification manuelle est écrasée.
|
||||||
|
- Plusieurs carnets ou plusieurs annuaires dans une même exécution.
|
||||||
|
- Interface graphique, service permanent (daemon).
|
||||||
|
- Messageries instantanées, fax, adresse postale (vides ou absents de
|
||||||
|
l'annuaire actuel).
|
||||||
|
|
||||||
|
## Anti-objectifs (échecs même si « ça marche »)
|
||||||
|
|
||||||
|
- **Vider le carnet suite à un incident LDAP** (annuaire injoignable, filtre
|
||||||
|
qui ne renvoie rien, base DN erronée) : le script doit refuser.
|
||||||
|
- Ré-uploader tout le carnet sans raison (mise à jour d'une librairie, perte de
|
||||||
|
la base locale) : DAVx5 re-téléchargerait tout, ce qu'on veut éviter.
|
||||||
|
- Exposer des données personnelles dans les logs.
|
||||||
|
|
||||||
|
## Contexte et contraintes
|
||||||
|
|
||||||
|
- Volume : ~1 270 fiches, quasiment toutes avec photo.
|
||||||
|
- Nextcloud : **utilisateur dédié**, carnet exclusivement géré par le script,
|
||||||
|
authentification par mot de passe d'application.
|
||||||
|
- DAVx5 : méthode de groupes = **catégories par contact** (`CATEGORIES`).
|
||||||
|
- Android limite les photos de contact à 720 px.
|
||||||
|
- L'annuaire stocke le **numéro interne** à 4 chiffres (`telephoneNumber`) ;
|
||||||
|
le numéro public s'obtient en préfixant `+3312345` (paramètre `-T` du script
|
||||||
|
actuel).
|
||||||
|
- La Direction est un **code** (`usrDirectionId`, ex. `620`) ; le libellé vient
|
||||||
|
d'une table de correspondance (24 codes dans le script actuel).
|
||||||
|
- Date de naissance : `usrDateNaissance`, format GeneralizedTime
|
||||||
|
(`19680615000000Z`).
|
||||||
|
- Population exportée aujourd'hui : membres des groupes `Fonctionnaires` et
|
||||||
|
`Contractuels` (`groupOfUniqueNames` sous `ou=groupes`).
|
||||||
|
- Données personnelles : pendant le développement, aucun export LDAP n'est lu
|
||||||
|
en clair ; le jeu de test est `test-data/example.anon.ldif` (70 fiches
|
||||||
|
anonymisées ; photos remplacées par des images factices).
|
||||||
|
- Plateformes : macOS et Linux, Python ≥ 3.11 ; image Docker acceptée.
|
||||||
|
- Réseau : un proxy inspecte le trafic HTTPS. Toutes les connexions TLS
|
||||||
|
utilisent le magasin de certificats du système via `truststore`
|
||||||
|
(`truststore.inject_into_ssl()` au démarrage). Dans le container, l'autorité
|
||||||
|
du proxy est ajoutée au magasin système.
|
||||||
|
|
||||||
|
## Approches envisagées
|
||||||
|
|
||||||
|
| | Principe | Pour | Contre |
|
||||||
|
|---|---|---|---|
|
||||||
|
| A. Base locale seule | Empreinte de chaque fiche en SQLite, comparaison locale, aucune lecture serveur | Simple, très léger | Ne voit pas les divergences serveur (suppression manuelle, restauration) |
|
||||||
|
| B. Sans état | Télécharger tout le carnet et comparer au LDAP | Jamais de divergence | Rapatrie toutes les photos à chaque passage : même coût que l'existant |
|
||||||
|
| **C. Hybride (retenue)** | A + un `PROPFIND` léger (href + ETag, sans contenu) à chaque passage | Léger **et** auto-réparateur ; base perdue reconstructible sans ré-upload | Un peu plus de logique |
|
||||||
|
|
||||||
|
**Choix : C**, validé par l'utilisateur.
|
||||||
|
|
||||||
|
## Conception
|
||||||
|
|
||||||
|
### Identité des fiches
|
||||||
|
|
||||||
|
- Clé source : attribut LDAP stable, configurable (`uid` par défaut).
|
||||||
|
- `UID` vCard = `uuid5(NAMESPACE_FIXE, valeur_cle)` ; href = `<UID>.vcf`.
|
||||||
|
L'href est **déductible** de la fiche LDAP : la base locale mémorise
|
||||||
|
empreintes et ETags, pas la correspondance.
|
||||||
|
- Chaque vCard porte `X-LDAPSYNC-HASH:<empreinte source>`.
|
||||||
|
|
||||||
|
### Flux d'une exécution
|
||||||
|
|
||||||
|
1. Charger `.env`, `mapping.yaml`, `directions.yaml` ; valider (échec clair si
|
||||||
|
un paramètre manque).
|
||||||
|
2. Verrou fichier : une seule exécution à la fois.
|
||||||
|
3. **LDAP** : recherche paginée (Simple Paged Results) avec `LDAP_BASE_DN` +
|
||||||
|
`LDAP_FILTER`, en ne demandant que les attributs du mapping. Seconde
|
||||||
|
recherche avec `(&LDAP_FILTER LDAP_BIRTHDAY_FILTER)` ne renvoyant que la
|
||||||
|
clé : l'ensemble des fiches dont la date de naissance est publiée.
|
||||||
|
4. **Construire** pour chaque entrée une fiche normalisée et son **empreinte
|
||||||
|
source** : SHA-256 de la fiche normalisée (champs triés, octets bruts de la
|
||||||
|
photo LDAP) + paramètres de rendu (taille/qualité photo, version du format
|
||||||
|
de sortie). L'empreinte porte sur la source, pas sur le JPEG produit : une
|
||||||
|
mise à jour de Pillow ne déclenche pas de ré-upload.
|
||||||
|
5. **Serveur** : `PROPFIND Depth: 1` sur le carnet → `{href: etag}`.
|
||||||
|
6. **Base locale** (SQLite) : `contacts(cle_ldap, href, empreinte, etag, maj_le)`.
|
||||||
|
7. **Calcul des actions** :
|
||||||
|
- présent LDAP, absent serveur → **créer** (`PUT` + `If-None-Match: *`) ;
|
||||||
|
- présent des deux côtés, empreinte ≠ base **ou** ETag serveur ≠ ETag base
|
||||||
|
→ **mettre à jour** (`PUT` + `If-Match`) ;
|
||||||
|
- présent des deux côtés mais absent de la base (base perdue ou neuve) →
|
||||||
|
**reconstruction** : la fiche est relue (`REPORT addressbook-multiget`,
|
||||||
|
par lots), `X-LDAPSYNC-HASH` est comparé ; s'il correspond, seule la base
|
||||||
|
est complétée, sans `PUT`. *(Choix du concepteur : une perte de base
|
||||||
|
coûte un téléchargement, jamais un ré-upload.)*
|
||||||
|
- présent serveur, absent LDAP → **supprimer** (`DELETE`). Inclut les
|
||||||
|
fiches de l'ancien script (hrefs non conformes), purgées au premier
|
||||||
|
passage.
|
||||||
|
8. **Garde-fous** avant d'appliquer :
|
||||||
|
- LDAP renvoie 0 entrée → abandon ;
|
||||||
|
- suppressions > `MAX_DELETE_RATIO` (défaut 10 %, soit ~127 fiches) du
|
||||||
|
carnet → abandon, sauf `--force` ou premier passage (`--initial`).
|
||||||
|
9. **Appliquer**, séquentiellement (≈1 270 `PUT` au premier passage, quelques
|
||||||
|
minutes ; pas de parallélisme). Après chaque `PUT` réussi, enregistrer
|
||||||
|
empreinte et ETag ; sans ETag dans la réponse, relire les ETags manquants
|
||||||
|
par un `PROPFIND` final. La base est mise à jour fiche par fiche : un
|
||||||
|
premier passage interrompu reprend là où il s'est arrêté. Une erreur sur
|
||||||
|
une fiche est journalisée sans arrêter l'exécution ; la fiche sera retentée
|
||||||
|
au passage suivant.
|
||||||
|
10. Résumé : créations / mises à jour / suppressions / reconstructions /
|
||||||
|
erreurs. Code retour ≠ 0 si erreur ou abandon.
|
||||||
|
|
||||||
|
### Génération de la vCard
|
||||||
|
|
||||||
|
Format **vCard 3.0**, comme l'export actuel (confirmé sur la fiche Nextcloud de
|
||||||
|
référence). Champs :
|
||||||
|
|
||||||
|
| vCard | Source | Remarque |
|
||||||
|
|---|---|---|
|
||||||
|
| `UID` | uuid5(`uid`) | |
|
||||||
|
| `N` | `sn` ; `givenName` | |
|
||||||
|
| `FN` | `cn` (ou gabarit) | |
|
||||||
|
| `ORG` | constante `Exemple` | paramètre du mapping |
|
||||||
|
| `TITLE` | `usrCadre` | comme l'export actuel |
|
||||||
|
| `EMAIL;TYPE=INTERNET,PREF` | `mail` | adresse du domaine principal en PREF, autres sans PREF |
|
||||||
|
| `TEL;TYPE=VOICE,WORK` | `telephoneNumber` | préfixé, voir ci-dessous |
|
||||||
|
| `CATEGORIES` | `usrDirectionId` → libellé | via `directions.yaml` |
|
||||||
|
| `PHOTO;ENCODING=b;TYPE=JPEG` | `jpegPhoto` | retaillée |
|
||||||
|
| `BDAY` | `usrDateNaissance` → `AAAA-MM-JJ` | seulement si retenue par le filtre anniversaire |
|
||||||
|
| `REV` | date de génération | hors empreinte |
|
||||||
|
| `X-LDAPSYNC-HASH` | empreinte source | |
|
||||||
|
| `PRODID` | nom/version de l'outil | |
|
||||||
|
|
||||||
|
Abandonnés par rapport à l'export actuel : `ADR` (toujours vide), `KIND`
|
||||||
|
(`KIND:organization` est une propriété vCard 4 et désigne une organisation, pas
|
||||||
|
une personne), `X-ABUID`, `CHARSET=UTF-8` (implicite). *(Choix du concepteur.)*
|
||||||
|
Champ facultatif sans valeur → omis.
|
||||||
|
|
||||||
|
### Téléphones
|
||||||
|
|
||||||
|
- Règle de préfixe par numéro dans le mapping : un numéro **composé
|
||||||
|
uniquement de chiffres et de longueur `internal_length` (4)** reçoit le
|
||||||
|
préfixe (`+3312345`) ; un numéro commençant par `+` ou `0` est conservé tel
|
||||||
|
quel (normalisé sans espaces). Résultat : `9052` → `+33123459052`.
|
||||||
|
- Format E.164 sans espace : c'est ce qu'Android rapproche le mieux du numéro
|
||||||
|
affiché lors d'un appel entrant.
|
||||||
|
|
||||||
|
### Directions
|
||||||
|
|
||||||
|
- `directions.yaml` : `{code: libellé}`, initialisé avec les codes du script
|
||||||
|
actuel (voir `directions.example.yaml`).
|
||||||
|
- Code inconnu → fiche sans catégorie + avertissement (code seul dans le log).
|
||||||
|
- Une seule Direction par personne (`usrDirectionId` mono-valué).
|
||||||
|
- Changer un libellé change l'empreinte des fiches concernées (le libellé
|
||||||
|
entre dans la fiche normalisée) : elles sont renvoyées, ce qui est voulu.
|
||||||
|
|
||||||
|
### Photos
|
||||||
|
|
||||||
|
- Source : `jpegPhoto` (configurable).
|
||||||
|
- Traitement : orientation EXIF appliquée, conversion RGB, réduction si plus
|
||||||
|
grande que **512 × 512** (proportions conservées, pas d'agrandissement),
|
||||||
|
JPEG qualité **80**, métadonnées supprimées. ~30–50 Ko par photo, contre
|
||||||
|
~145 Ko en moyenne aujourd'hui.
|
||||||
|
- Pourquoi 512 : net en plein écran lors d'un appel sur Android (plafond
|
||||||
|
720 px), poids divisé par 2 à 3 par rapport à 720 px. Paramétrable
|
||||||
|
(`PHOTO_MAX_SIZE`, `PHOTO_QUALITY`).
|
||||||
|
- Photo absente ou illisible → fiche sans photo, avertissement.
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
`.env` (exemple fourni en `.env.example`, jamais commité) :
|
||||||
|
|
||||||
|
```
|
||||||
|
LDAP_URL=ldaps://ldap.example.org
|
||||||
|
LDAP_BIND_DN= # vide = bind anonyme
|
||||||
|
LDAP_BIND_PASSWORD=
|
||||||
|
LDAP_BASE_DN=ou=personnes,dc=example,dc=org
|
||||||
|
LDAP_FILTER=(&(objectClass=usrPersonne)(usrSorti=non)(|(memberOf=...)(...))) # à ajuster
|
||||||
|
LDAP_BIRTHDAY_FILTER=(usrDirectionId=620) # dates de naissance publiées pour cette Direction seulement
|
||||||
|
LDAP_CA_CERT= # facultatif
|
||||||
|
NEXTCLOUD_URL=https://cloud.example.org
|
||||||
|
NEXTCLOUD_USER=annuaire
|
||||||
|
NEXTCLOUD_APP_PASSWORD=...
|
||||||
|
NEXTCLOUD_ADDRESSBOOK=annuaire # slug du carnet ; doit exister
|
||||||
|
STATE_DB=./state/sync.sqlite
|
||||||
|
MAPPING_FILE=./mapping.yaml
|
||||||
|
DIRECTIONS_FILE=./directions.yaml
|
||||||
|
PHOTO_MAX_SIZE=512
|
||||||
|
PHOTO_QUALITY=80
|
||||||
|
MAX_DELETE_RATIO=0.10
|
||||||
|
LOG_LEVEL=INFO
|
||||||
|
```
|
||||||
|
|
||||||
|
Le filtre de population doit reproduire l'export actuel (groupes
|
||||||
|
Fonctionnaires + Contractuels). Si l'appartenance n'est portée que par les
|
||||||
|
groupes (`uniqueMember`) et non par la fiche, l'outil supporte en option une
|
||||||
|
liste `LDAP_GROUP_DNS` : les membres de ces groupes sont lus puis croisés avec
|
||||||
|
la recherche principale.
|
||||||
|
|
||||||
|
`mapping.yaml` :
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
key: uid
|
||||||
|
organization: "Exemple"
|
||||||
|
fields:
|
||||||
|
given_name: givenName
|
||||||
|
family_name: sn
|
||||||
|
full_name: cn
|
||||||
|
title: usrCadre
|
||||||
|
emails:
|
||||||
|
- {attr: mail, type: work, preferred_domain: example.org}
|
||||||
|
phones:
|
||||||
|
- {attr: telephoneNumber, type: work, prefix: "+3312345", internal_length: 4}
|
||||||
|
group: {attr: usrDirectionId, labels: directions}
|
||||||
|
photo: jpegPhoto
|
||||||
|
birthday: {attr: usrDateNaissance, format: generalized_time}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Ligne de commande
|
||||||
|
|
||||||
|
`ldap2nextcloud [--dry-run] [--force] [--initial] [--env FICHIER] [-v]`
|
||||||
|
|
||||||
|
- `--dry-run` : calcule et affiche les actions, n'écrit rien.
|
||||||
|
- `--initial` : autorise la purge massive du premier passage.
|
||||||
|
|
||||||
|
### Exploitation
|
||||||
|
|
||||||
|
- Logs sur stdout/stderr ; ne mentionnent que la clé LDAP et l'action, jamais
|
||||||
|
nom, téléphone, email ou date de naissance.
|
||||||
|
- Fournis : ligne crontab, plist launchd, `Dockerfile` + `docker-compose.yml`
|
||||||
|
(volume pour base et configuration ; planification par le cron de l'hôte
|
||||||
|
appelant `docker compose run`).
|
||||||
|
|
||||||
|
### Stack
|
||||||
|
|
||||||
|
`ldap3`, `requests` (CardDAV écrit à la main : `PROPFIND`, `REPORT`, `PUT`,
|
||||||
|
`DELETE`), `vobject`, `Pillow`, `PyYAML`, `python-dotenv`, SQLite (stdlib).
|
||||||
|
Tests : `pytest`, `responses`. Paquet installable (`pyproject.toml`).
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
- Unitaires : mapping → fiche normalisée, préfixe téléphone, libellé Direction
|
||||||
|
(connu / inconnu), conversion date de naissance, rendu vCard, stabilité de
|
||||||
|
l'empreinte, traitement photo (images générées), calcul des actions (tous
|
||||||
|
les cas du §7), garde-fous.
|
||||||
|
- Entrée réaliste : `test-data/example.anon.ldif` chargé dans un annuaire
|
||||||
|
simulé (`ldap3` MOCK_SYNC).
|
||||||
|
- CardDAV : client testé contre un serveur simulé (`responses`).
|
||||||
|
- Recette : compte Nextcloud de test fourni par l'utilisateur.
|
||||||
|
|
||||||
|
## Décisions de l'utilisateur
|
||||||
|
|
||||||
|
- Python, exécution autonome en cron (macOS/Linux) ou Docker.
|
||||||
|
- Paramétrage `.env` + mapping + table des Directions.
|
||||||
|
- Base locale autorisée, format libre.
|
||||||
|
- Carnet dédié sur un utilisateur Nextcloud dédié ; le script en est seul
|
||||||
|
maître (suppressions et écrasements acceptés).
|
||||||
|
- Approche C (hybride).
|
||||||
|
- DAVx5 en mode « groupes = catégories ».
|
||||||
|
- Numéro interne à préfixer ; Direction = code `usrDirectionId` + table de
|
||||||
|
libellés.
|
||||||
|
|
||||||
|
## Laissé au constructeur
|
||||||
|
|
||||||
|
- Structure interne des modules, nommage, gestion fine des erreurs HTTP.
|
||||||
|
- Namespace UUID, format exact des logs.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Correspondance attributs LDAP -> champs vCard.
|
||||||
|
# Copier en mapping.yaml et adapter aux attributs de votre annuaire.
|
||||||
|
key: uid
|
||||||
|
organization: "Exemple"
|
||||||
|
fields:
|
||||||
|
given_name: givenName
|
||||||
|
family_name: sn
|
||||||
|
full_name: cn
|
||||||
|
title: usrCadre
|
||||||
|
emails:
|
||||||
|
# L'adresse de ce domaine est marquée préférée.
|
||||||
|
- {attr: mail, type: work, preferred_domain: example.org}
|
||||||
|
phones:
|
||||||
|
# Un numéro interne de 4 chiffres reçoit le préfixe ; un numéro complet est gardé tel quel.
|
||||||
|
- {attr: telephoneNumber, type: work, prefix: "+3312345", internal_length: 4}
|
||||||
|
# Code de Direction, traduit en libellé par directions.yaml, affiché comme groupe.
|
||||||
|
group: {attr: usrDirectionId, labels: directions}
|
||||||
|
photo: jpegPhoto
|
||||||
|
birthday: {attr: usrDateNaissance, format: generalized_time}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=68"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "ldap2nextcloud"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Synchronisation incrémentale d'un annuaire LDAP vers un carnet CardDAV Nextcloud"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"truststore>=0.10",
|
||||||
|
"ldap3>=2.9",
|
||||||
|
"requests>=2.32",
|
||||||
|
"vobject>=0.9.8",
|
||||||
|
"Pillow>=10.4",
|
||||||
|
"PyYAML>=6.0",
|
||||||
|
"python-dotenv>=1.0",
|
||||||
|
"tqdm>=4.66",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
test = ["pytest>=8", "responses>=0.25"]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
ldap2nextcloud = "ldap2nextcloud.cli:main"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
pythonpath = ["tests"]
|
||||||
|
filterwarnings = ["ignore::DeprecationWarning:ldap3.*"]
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Synchronisation LDAP → Nextcloud (CardDAV)."""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Client CardDAV minimal : liste des ETags, lecture groupée, écriture, suppression."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from urllib.parse import quote, unquote, urlsplit
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
DAV = "{DAV:}"
|
||||||
|
CARD = "{urn:ietf:params:xml:ns:carddav}"
|
||||||
|
MULTIGET_BATCH = 50
|
||||||
|
|
||||||
|
PROPFIND_BODY = (
|
||||||
|
'<?xml version="1.0" encoding="utf-8"?>'
|
||||||
|
'<d:propfind xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></d:propfind>'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_etag(raw: str | None) -> str | None:
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
value = raw.strip().removeprefix("W/").strip('"')
|
||||||
|
return value or None
|
||||||
|
|
||||||
|
|
||||||
|
class CardDavError(Exception):
|
||||||
|
def __init__(self, message: str, status: int | None = None):
|
||||||
|
super().__init__(message)
|
||||||
|
self.status = status
|
||||||
|
|
||||||
|
|
||||||
|
class CardDavClient:
|
||||||
|
def __init__(self, addressbook_url: str, user: str, password: str, timeout: float = 30):
|
||||||
|
self.addressbook_url = addressbook_url if addressbook_url.endswith("/") else addressbook_url + "/"
|
||||||
|
self._book_path = urlsplit(self.addressbook_url).path
|
||||||
|
self._timeout = timeout
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._session.auth = (user, password)
|
||||||
|
self._session.headers["User-Agent"] = "ldap2nextcloud"
|
||||||
|
|
||||||
|
# -- requêtes -------------------------------------------------------------
|
||||||
|
|
||||||
|
def _request(self, method: str, url: str, expected: tuple[int, ...], **kwargs) -> requests.Response:
|
||||||
|
try:
|
||||||
|
response = self._session.request(method, url, timeout=self._timeout, **kwargs)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
raise CardDavError(f"{method} {url} : {exc}") from exc
|
||||||
|
if response.status_code not in expected:
|
||||||
|
raise CardDavError(f"{method} {url} : HTTP {response.status_code}", response.status_code)
|
||||||
|
return response
|
||||||
|
|
||||||
|
def _card_url(self, href: str) -> str:
|
||||||
|
return self.addressbook_url + quote(href, safe="")
|
||||||
|
|
||||||
|
def _name(self, href: str) -> str | None:
|
||||||
|
"""Nom de fichier d'une fiche à partir d'un href ; None pour la collection."""
|
||||||
|
path = urlsplit(href).path
|
||||||
|
if path.rstrip("/") == self._book_path.rstrip("/") or path.endswith("/"):
|
||||||
|
return None
|
||||||
|
return unquote(path.rsplit("/", 1)[-1])
|
||||||
|
|
||||||
|
def _parse(self, body: bytes) -> dict[str, tuple[str | None, str | None]]:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(body)
|
||||||
|
except ET.ParseError as exc:
|
||||||
|
raise CardDavError("Réponse XML illisible") from exc
|
||||||
|
result: dict[str, tuple[str | None, str | None]] = {}
|
||||||
|
for response in root.iter(f"{DAV}response"):
|
||||||
|
href_el = response.find(f"{DAV}href")
|
||||||
|
if href_el is None or not href_el.text:
|
||||||
|
continue
|
||||||
|
name = self._name(href_el.text.strip())
|
||||||
|
if name is None:
|
||||||
|
continue
|
||||||
|
etag_el = response.find(f".//{DAV}getetag")
|
||||||
|
data_el = response.find(f".//{CARD}address-data")
|
||||||
|
etag = _normalize_etag(etag_el.text) if etag_el is not None else None
|
||||||
|
data = data_el.text if data_el is not None else None
|
||||||
|
result[name] = (etag, data)
|
||||||
|
return result
|
||||||
|
|
||||||
|
# -- API ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def list_etags(self) -> dict[str, str]:
|
||||||
|
response = self._request(
|
||||||
|
"PROPFIND", self.addressbook_url, (207,),
|
||||||
|
data=PROPFIND_BODY.encode("utf-8"),
|
||||||
|
headers={"Depth": "1", "Content-Type": "application/xml; charset=utf-8"},
|
||||||
|
)
|
||||||
|
return {name: etag for name, (etag, _) in self._parse(response.content).items() if etag}
|
||||||
|
|
||||||
|
def multiget(self, hrefs: list[str]) -> dict[str, str]:
|
||||||
|
cards: dict[str, str] = {}
|
||||||
|
for start in range(0, len(hrefs), MULTIGET_BATCH):
|
||||||
|
batch = hrefs[start:start + MULTIGET_BATCH]
|
||||||
|
refs = "".join(
|
||||||
|
f"<d:href>{escape(self._book_path + quote(h, safe=''))}</d:href>" for h in batch
|
||||||
|
)
|
||||||
|
body = (
|
||||||
|
'<?xml version="1.0" encoding="utf-8"?>'
|
||||||
|
'<card:addressbook-multiget xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">'
|
||||||
|
f"<d:prop><d:getetag/><card:address-data/></d:prop>{refs}"
|
||||||
|
"</card:addressbook-multiget>"
|
||||||
|
)
|
||||||
|
response = self._request(
|
||||||
|
"REPORT", self.addressbook_url, (207,),
|
||||||
|
data=body.encode("utf-8"),
|
||||||
|
headers={"Depth": "1", "Content-Type": "application/xml; charset=utf-8"},
|
||||||
|
)
|
||||||
|
for name, (_, data) in self._parse(response.content).items():
|
||||||
|
if data:
|
||||||
|
cards[name] = data
|
||||||
|
return cards
|
||||||
|
|
||||||
|
def put(self, href: str, vcard: str, etag: str | None) -> str | None:
|
||||||
|
headers = {"Content-Type": "text/vcard; charset=utf-8"}
|
||||||
|
if etag:
|
||||||
|
headers["If-Match"] = f'"{etag}"'
|
||||||
|
else:
|
||||||
|
headers["If-None-Match"] = "*"
|
||||||
|
response = self._request(
|
||||||
|
"PUT", self._card_url(href), (200, 201, 204), data=vcard.encode("utf-8"), headers=headers
|
||||||
|
)
|
||||||
|
return _normalize_etag(response.headers.get("ETag"))
|
||||||
|
|
||||||
|
def delete(self, href: str, etag: str | None) -> None:
|
||||||
|
headers = {"If-Match": f'"{etag}"'} if etag else {}
|
||||||
|
self._request("DELETE", self._card_url(href), (200, 204, 404), headers=headers)
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""Point d'entrée en ligne de commande."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import fcntl
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import truststore
|
||||||
|
from ldap3.core.exceptions import LDAPException
|
||||||
|
|
||||||
|
from . import __version__
|
||||||
|
from .carddav import CardDavClient, CardDavError
|
||||||
|
from .config import ConfigError, load_directions, load_mapping, load_settings
|
||||||
|
from .ldap_source import LdapSource
|
||||||
|
from .planner import GuardError
|
||||||
|
from .progress import make_progress
|
||||||
|
from .state import StateDB
|
||||||
|
from .sync import run_sync
|
||||||
|
|
||||||
|
EXIT_OK = 0
|
||||||
|
EXIT_ERRORS = 1
|
||||||
|
EXIT_GUARD = 2
|
||||||
|
EXIT_CONFIG = 3
|
||||||
|
EXIT_LOCKED = 4
|
||||||
|
|
||||||
|
log = logging.getLogger("ldap2nextcloud")
|
||||||
|
|
||||||
|
|
||||||
|
def _parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="ldap2nextcloud",
|
||||||
|
description="Synchronise l'annuaire LDAP vers un carnet d'adresses Nextcloud (CardDAV).",
|
||||||
|
)
|
||||||
|
parser.add_argument("--env", type=Path, help="fichier .env (défaut : ./.env s'il existe)")
|
||||||
|
parser.add_argument("--dry-run", action="store_true", help="afficher les actions sans rien écrire")
|
||||||
|
parser.add_argument("--force", action="store_true", help="passer outre la limite de suppressions")
|
||||||
|
parser.add_argument("--initial", action="store_true", help="premier passage : autorise la purge du carnet")
|
||||||
|
parser.add_argument("-v", "--verbose", action="store_true", help="journal détaillé")
|
||||||
|
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
# Le proxy inspecte le HTTPS : on valide avec le magasin de certificats du système.
|
||||||
|
truststore.inject_into_ssl()
|
||||||
|
args = _parser().parse_args(argv)
|
||||||
|
logging.basicConfig(
|
||||||
|
stream=sys.stderr, format="%(asctime)s %(levelname)s %(message)s", force=True,
|
||||||
|
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||||
|
)
|
||||||
|
|
||||||
|
env_file = args.env
|
||||||
|
if env_file is None and Path(".env").is_file():
|
||||||
|
env_file = Path(".env")
|
||||||
|
try:
|
||||||
|
settings = load_settings(env_file)
|
||||||
|
mapping = load_mapping(settings.mapping_file)
|
||||||
|
directions = load_directions(settings.directions_file)
|
||||||
|
except ConfigError as exc:
|
||||||
|
log.error("Configuration : %s", exc)
|
||||||
|
return EXIT_CONFIG
|
||||||
|
if not args.verbose:
|
||||||
|
logging.getLogger().setLevel(settings.log_level)
|
||||||
|
|
||||||
|
lock_path = Path(f"{settings.state_db}.lock")
|
||||||
|
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(lock_path, "w") as lock:
|
||||||
|
try:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError:
|
||||||
|
log.error("Une synchronisation est déjà en cours (%s)", lock_path)
|
||||||
|
return EXIT_LOCKED
|
||||||
|
try:
|
||||||
|
source = LdapSource(settings)
|
||||||
|
client = CardDavClient(
|
||||||
|
settings.addressbook_url, settings.nextcloud_user, settings.nextcloud_app_password
|
||||||
|
)
|
||||||
|
with StateDB(settings.state_db) as state:
|
||||||
|
summary = run_sync(
|
||||||
|
settings, mapping, directions, source, client, state,
|
||||||
|
dry_run=args.dry_run, force=args.force, initial=args.initial,
|
||||||
|
progress=make_progress(sys.stderr.isatty()),
|
||||||
|
)
|
||||||
|
except GuardError as exc:
|
||||||
|
log.error("Garde-fou : %s", exc)
|
||||||
|
return EXIT_GUARD
|
||||||
|
except (CardDavError, LDAPException) as exc:
|
||||||
|
log.error("Synchronisation interrompue : %s", exc)
|
||||||
|
return EXIT_ERRORS
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"%scréées=%d mises_à_jour=%d vérifiées=%d supprimées=%d inchangées=%d erreurs=%d",
|
||||||
|
"[simulation] " if args.dry_run else "",
|
||||||
|
summary.created, summary.updated, summary.verified,
|
||||||
|
summary.deleted, summary.unchanged, summary.errors,
|
||||||
|
)
|
||||||
|
return EXIT_ERRORS if summary.errors else EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
"""Chargement de la configuration : .env, mapping.yaml et directions.yaml."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
from dotenv import dotenv_values
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigError(Exception):
|
||||||
|
"""Configuration absente ou invalide."""
|
||||||
|
|
||||||
|
|
||||||
|
@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"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def addressbook_url(self) -> str:
|
||||||
|
return (
|
||||||
|
f"{self.nextcloud_url.rstrip('/')}/remote.php/dav/addressbooks/users/"
|
||||||
|
f"{self.nextcloud_user}/{self.nextcloud_addressbook}/"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PhoneRule:
|
||||||
|
attr: str
|
||||||
|
type: str
|
||||||
|
prefix: str | None = None
|
||||||
|
internal_length: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class EmailRule:
|
||||||
|
attr: str
|
||||||
|
type: str
|
||||||
|
preferred_domain: str | None = 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] = field(default_factory=list)
|
||||||
|
phones: list[PhoneRule] = field(default_factory=list)
|
||||||
|
group_attr: str | None = None
|
||||||
|
photo: str | None = None
|
||||||
|
birthday_attr: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _values(env_file: Path | None) -> dict[str, str | None]:
|
||||||
|
values: dict[str, str | None] = {}
|
||||||
|
if env_file is not None:
|
||||||
|
if not Path(env_file).is_file():
|
||||||
|
raise ConfigError(f"Fichier de configuration introuvable : {env_file}")
|
||||||
|
values.update(dotenv_values(env_file))
|
||||||
|
# L'environnement réel est prioritaire (utile en container).
|
||||||
|
values.update(os.environ)
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def load_settings(env_file: Path | None = None) -> Settings:
|
||||||
|
values = _values(env_file)
|
||||||
|
|
||||||
|
def opt(name: str) -> str | None:
|
||||||
|
value = values.get(name)
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
value = value.strip()
|
||||||
|
return value or None
|
||||||
|
|
||||||
|
def req(name: str) -> str:
|
||||||
|
value = opt(name)
|
||||||
|
if value is None:
|
||||||
|
raise ConfigError(f"Variable obligatoire manquante : {name}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
def num(name: str, default, cast):
|
||||||
|
raw = opt(name)
|
||||||
|
if raw is None:
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return cast(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError(f"Valeur invalide pour {name} : nombre attendu") from exc
|
||||||
|
|
||||||
|
group_dns = opt("LDAP_GROUP_DNS")
|
||||||
|
return Settings(
|
||||||
|
ldap_url=req("LDAP_URL"),
|
||||||
|
ldap_bind_dn=opt("LDAP_BIND_DN"),
|
||||||
|
ldap_bind_password=opt("LDAP_BIND_PASSWORD"),
|
||||||
|
ldap_base_dn=req("LDAP_BASE_DN"),
|
||||||
|
ldap_filter=req("LDAP_FILTER"),
|
||||||
|
ldap_birthday_filter=opt("LDAP_BIRTHDAY_FILTER"),
|
||||||
|
ldap_group_dns=[dn.strip() for dn in group_dns.split(";") if dn.strip()] if group_dns else [],
|
||||||
|
ldap_ca_cert=opt("LDAP_CA_CERT"),
|
||||||
|
nextcloud_url=req("NEXTCLOUD_URL"),
|
||||||
|
nextcloud_user=req("NEXTCLOUD_USER"),
|
||||||
|
nextcloud_app_password=req("NEXTCLOUD_APP_PASSWORD"),
|
||||||
|
nextcloud_addressbook=req("NEXTCLOUD_ADDRESSBOOK"),
|
||||||
|
state_db=Path(opt("STATE_DB") or "./state/sync.sqlite"),
|
||||||
|
mapping_file=Path(opt("MAPPING_FILE") or "./mapping.yaml"),
|
||||||
|
directions_file=Path(opt("DIRECTIONS_FILE") or "./directions.yaml"),
|
||||||
|
photo_max_size=num("PHOTO_MAX_SIZE", 512, int),
|
||||||
|
photo_quality=num("PHOTO_QUALITY", 80, int),
|
||||||
|
max_delete_ratio=num("MAX_DELETE_RATIO", 0.10, float),
|
||||||
|
log_level=(opt("LOG_LEVEL") or "INFO").upper(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_yaml(path: Path) -> dict:
|
||||||
|
try:
|
||||||
|
with open(path, encoding="utf-8") as handle:
|
||||||
|
data = yaml.safe_load(handle)
|
||||||
|
except OSError as exc:
|
||||||
|
raise ConfigError(f"Fichier illisible : {path}") from exc
|
||||||
|
except yaml.YAMLError as exc:
|
||||||
|
raise ConfigError(f"YAML invalide : {path}") from exc
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise ConfigError(f"Contenu inattendu dans {path} : dictionnaire attendu")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _attr(spec) -> str | None:
|
||||||
|
"""Un champ du mapping est soit un nom d'attribut, soit {attr: ...}."""
|
||||||
|
if spec is None:
|
||||||
|
return None
|
||||||
|
if isinstance(spec, dict):
|
||||||
|
return spec.get("attr")
|
||||||
|
return str(spec)
|
||||||
|
|
||||||
|
|
||||||
|
def load_mapping(path: Path) -> Mapping:
|
||||||
|
data = _read_yaml(path)
|
||||||
|
if not data.get("key"):
|
||||||
|
raise ConfigError(f"{path} : la clé « key » est obligatoire")
|
||||||
|
fields = data.get("fields") or {}
|
||||||
|
for name in ("given_name", "family_name"):
|
||||||
|
if not fields.get(name):
|
||||||
|
raise ConfigError(f"{path} : le champ « fields.{name} » est obligatoire")
|
||||||
|
try:
|
||||||
|
emails = [
|
||||||
|
EmailRule(e["attr"], e.get("type", "work"), e.get("preferred_domain"))
|
||||||
|
for e in fields.get("emails") or []
|
||||||
|
]
|
||||||
|
phones = [
|
||||||
|
PhoneRule(
|
||||||
|
p["attr"],
|
||||||
|
p.get("type", "work"),
|
||||||
|
str(p["prefix"]) if p.get("prefix") is not None else None,
|
||||||
|
int(p["internal_length"]) if p.get("internal_length") is not None else None,
|
||||||
|
)
|
||||||
|
for p in fields.get("phones") or []
|
||||||
|
]
|
||||||
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
|
raise ConfigError(f"{path} : règle email ou téléphone invalide") from exc
|
||||||
|
return Mapping(
|
||||||
|
key=str(data["key"]),
|
||||||
|
organization=data.get("organization"),
|
||||||
|
given_name=_attr(fields["given_name"]),
|
||||||
|
family_name=_attr(fields["family_name"]),
|
||||||
|
full_name=_attr(fields.get("full_name")) or "cn",
|
||||||
|
title=_attr(fields.get("title")),
|
||||||
|
emails=emails,
|
||||||
|
phones=phones,
|
||||||
|
group_attr=_attr(fields.get("group")),
|
||||||
|
photo=_attr(fields.get("photo")),
|
||||||
|
birthday_attr=_attr(fields.get("birthday")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_directions(path: Path) -> dict[str, str]:
|
||||||
|
data = _read_yaml(path)
|
||||||
|
return {str(code): str(label) for code, label in data.items()}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""Lecture de l'annuaire LDAP."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import ssl
|
||||||
|
|
||||||
|
from ldap3 import BASE, NONE, SUBTREE, Connection, Server, Tls
|
||||||
|
|
||||||
|
from .config import Mapping, Settings
|
||||||
|
from .mapping import RawEntry
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PAGE_SIZE = 500
|
||||||
|
|
||||||
|
|
||||||
|
def required_attributes(mapping: Mapping) -> list[str]:
|
||||||
|
names = [
|
||||||
|
mapping.key, mapping.given_name, mapping.family_name, mapping.full_name,
|
||||||
|
mapping.title, mapping.group_attr, mapping.photo, mapping.birthday_attr,
|
||||||
|
*(rule.attr for rule in mapping.emails),
|
||||||
|
*(rule.attr for rule in mapping.phones),
|
||||||
|
]
|
||||||
|
seen: dict[str, str] = {}
|
||||||
|
for name in names:
|
||||||
|
if name and name.lower() not in seen:
|
||||||
|
seen[name.lower()] = name
|
||||||
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_dn(dn: str) -> str:
|
||||||
|
return ",".join(part.strip() for part in dn.split(",")).lower()
|
||||||
|
|
||||||
|
|
||||||
|
class LdapSource:
|
||||||
|
def __init__(self, settings: Settings, connection: Connection | None = None):
|
||||||
|
self._settings = settings
|
||||||
|
self._conn = connection if connection is not None else self._connect()
|
||||||
|
|
||||||
|
def _connect(self) -> Connection:
|
||||||
|
s = self._settings
|
||||||
|
tls = None
|
||||||
|
if s.ldap_url.lower().startswith("ldaps://") or s.ldap_ca_cert:
|
||||||
|
tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=s.ldap_ca_cert)
|
||||||
|
# Pas de lecture du schéma : on ne manipule que des valeurs brutes.
|
||||||
|
server = Server(s.ldap_url, tls=tls, get_info=NONE, connect_timeout=30)
|
||||||
|
conn = Connection(
|
||||||
|
server, user=s.ldap_bind_dn, password=s.ldap_bind_password,
|
||||||
|
receive_timeout=120, read_only=True, raise_exceptions=True,
|
||||||
|
)
|
||||||
|
if not s.ldap_url.lower().startswith("ldaps://") and s.ldap_ca_cert:
|
||||||
|
conn.open()
|
||||||
|
conn.start_tls()
|
||||||
|
conn.bind()
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def _search(self, search_filter: str, attributes: list[str]) -> list[dict]:
|
||||||
|
results = self._conn.extend.standard.paged_search(
|
||||||
|
search_base=self._settings.ldap_base_dn,
|
||||||
|
search_filter=search_filter,
|
||||||
|
search_scope=SUBTREE,
|
||||||
|
attributes=attributes,
|
||||||
|
paged_size=PAGE_SIZE,
|
||||||
|
generator=False,
|
||||||
|
)
|
||||||
|
return [r for r in results if r.get("type") == "searchResEntry"]
|
||||||
|
|
||||||
|
def _group_members(self) -> set[str]:
|
||||||
|
members: set[str] = set()
|
||||||
|
for group_dn in self._settings.ldap_group_dns:
|
||||||
|
self._conn.search(
|
||||||
|
group_dn, "(objectClass=*)", search_scope=BASE,
|
||||||
|
attributes=["uniqueMember", "member"],
|
||||||
|
)
|
||||||
|
if not self._conn.entries and not self._conn.response:
|
||||||
|
log.warning("Groupe introuvable : %s", group_dn)
|
||||||
|
continue
|
||||||
|
for result in self._conn.response:
|
||||||
|
raw = result.get("raw_attributes", {})
|
||||||
|
for name in ("uniqueMember", "member"):
|
||||||
|
for value in raw.get(name, []):
|
||||||
|
members.add(_normalize_dn(value.decode("utf-8")))
|
||||||
|
return members
|
||||||
|
|
||||||
|
def fetch_entries(self, attributes: list[str]) -> list[RawEntry]:
|
||||||
|
results = self._search(self._settings.ldap_filter, attributes)
|
||||||
|
if self._settings.ldap_group_dns:
|
||||||
|
members = self._group_members()
|
||||||
|
results = [r for r in results if _normalize_dn(r["dn"]) in members]
|
||||||
|
wanted = {a.lower() for a in attributes}
|
||||||
|
entries: list[RawEntry] = []
|
||||||
|
for result in results:
|
||||||
|
raw = result.get("raw_attributes", {})
|
||||||
|
entries.append(
|
||||||
|
{name: list(values) for name, values in raw.items() if name.lower() in wanted and values}
|
||||||
|
)
|
||||||
|
return entries
|
||||||
|
|
||||||
|
def fetch_birthday_keys(self, key_attr: str) -> set[str]:
|
||||||
|
birthday_filter = self._settings.ldap_birthday_filter
|
||||||
|
if not birthday_filter:
|
||||||
|
return set()
|
||||||
|
combined = f"(&{self._settings.ldap_filter}{birthday_filter})"
|
||||||
|
keys: set[str] = set()
|
||||||
|
for result in self._search(combined, [key_attr]):
|
||||||
|
for name, values in result.get("raw_attributes", {}).items():
|
||||||
|
if name.lower() == key_attr.lower() and values:
|
||||||
|
keys.add(values[0].decode("utf-8"))
|
||||||
|
return keys
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Conversion d'une entrée LDAP brute en fiche normalisée."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from .config import Mapping, PhoneRule
|
||||||
|
from .model import Contact, Email, Phone
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
RawEntry = dict[str, list[bytes]]
|
||||||
|
|
||||||
|
_GENERALIZED_TIME = re.compile(r"^(\d{4})(\d{2})(\d{2})")
|
||||||
|
|
||||||
|
|
||||||
|
def format_phone(raw: str, rule: PhoneRule) -> str:
|
||||||
|
number = re.sub(r"[\s.\-()]", "", raw)
|
||||||
|
if (
|
||||||
|
rule.prefix
|
||||||
|
and rule.internal_length
|
||||||
|
and number.isdigit()
|
||||||
|
and len(number) == rule.internal_length
|
||||||
|
):
|
||||||
|
return f"{rule.prefix}{number}"
|
||||||
|
return number
|
||||||
|
|
||||||
|
|
||||||
|
def parse_birthday(raw: str) -> date | None:
|
||||||
|
match = _GENERALIZED_TIME.match(raw.strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date(int(match[1]), int(match[2]), int(match[3]))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _raw_values(entry: RawEntry, attr: str | None) -> list[bytes]:
|
||||||
|
if not attr:
|
||||||
|
return []
|
||||||
|
lowered = attr.lower()
|
||||||
|
for name, values in entry.items():
|
||||||
|
if name.lower() == lowered:
|
||||||
|
return list(values)
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _texts(entry: RawEntry, attr: str | None) -> list[str]:
|
||||||
|
out = []
|
||||||
|
for value in _raw_values(entry, attr):
|
||||||
|
text = value.decode("utf-8", errors="replace").strip()
|
||||||
|
if text:
|
||||||
|
out.append(text)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _first(entry: RawEntry, attr: str | None) -> str | None:
|
||||||
|
values = _texts(entry, attr)
|
||||||
|
return values[0] if values else None
|
||||||
|
|
||||||
|
|
||||||
|
def _emails(entry: RawEntry, mapping: Mapping) -> tuple[Email, ...]:
|
||||||
|
result: list[Email] = []
|
||||||
|
for rule in mapping.emails:
|
||||||
|
addresses = _texts(entry, rule.attr)
|
||||||
|
if not addresses:
|
||||||
|
continue
|
||||||
|
preferred = addresses[0]
|
||||||
|
if rule.preferred_domain:
|
||||||
|
suffix = "@" + rule.preferred_domain.lower()
|
||||||
|
matching = [a for a in addresses if a.lower().endswith(suffix)]
|
||||||
|
if matching:
|
||||||
|
preferred = matching[0]
|
||||||
|
ordered = [preferred] + [a for a in addresses if a != preferred]
|
||||||
|
has_pref = any(e.preferred for e in result)
|
||||||
|
for index, address in enumerate(ordered):
|
||||||
|
result.append(Email(address, rule.type, index == 0 and not has_pref))
|
||||||
|
return tuple(result)
|
||||||
|
|
||||||
|
|
||||||
|
def entry_to_contact(
|
||||||
|
entry: RawEntry, mapping: Mapping, directions: dict[str, str], with_birthday: bool
|
||||||
|
) -> Contact | None:
|
||||||
|
key = _first(entry, mapping.key)
|
||||||
|
if key is None:
|
||||||
|
log.warning("Entrée ignorée : attribut clé « %s » absent", mapping.key)
|
||||||
|
return None
|
||||||
|
|
||||||
|
given_name = _first(entry, mapping.given_name) or ""
|
||||||
|
family_name = _first(entry, mapping.family_name) or ""
|
||||||
|
full_name = _first(entry, mapping.full_name) or f"{given_name} {family_name}".strip()
|
||||||
|
|
||||||
|
phones = tuple(
|
||||||
|
Phone(format_phone(raw, rule), rule.type)
|
||||||
|
for rule in mapping.phones
|
||||||
|
for raw in _texts(entry, rule.attr)
|
||||||
|
)
|
||||||
|
|
||||||
|
category = None
|
||||||
|
code = _first(entry, mapping.group_attr)
|
||||||
|
if code is not None:
|
||||||
|
category = directions.get(code)
|
||||||
|
if category is None:
|
||||||
|
log.warning("%s : code Direction inconnu %s, fiche sans groupe", key, code)
|
||||||
|
|
||||||
|
birthday = None
|
||||||
|
if with_birthday and mapping.birthday_attr:
|
||||||
|
raw = _first(entry, mapping.birthday_attr)
|
||||||
|
if raw is not None:
|
||||||
|
birthday = parse_birthday(raw)
|
||||||
|
if birthday is None:
|
||||||
|
log.warning("%s : date de naissance illisible, ignorée", key)
|
||||||
|
|
||||||
|
photos = _raw_values(entry, mapping.photo)
|
||||||
|
photo = photos[0] if photos and photos[0] else None
|
||||||
|
|
||||||
|
return Contact(
|
||||||
|
key=key,
|
||||||
|
given_name=given_name,
|
||||||
|
family_name=family_name,
|
||||||
|
full_name=full_name,
|
||||||
|
organization=mapping.organization,
|
||||||
|
title=_first(entry, mapping.title),
|
||||||
|
emails=_emails(entry, mapping),
|
||||||
|
phones=phones,
|
||||||
|
category=category,
|
||||||
|
birthday=birthday,
|
||||||
|
photo=photo,
|
||||||
|
)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Fiche de contact normalisée, identité et empreinte."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
|
||||||
|
# Ne jamais changer : l'UID et le nom de fichier de chaque fiche en dépendent.
|
||||||
|
NAMESPACE = uuid.UUID("6f1c2a4e-3b7d-4e8a-9c51-2d0f6b8e7a13")
|
||||||
|
|
||||||
|
|
||||||
|
@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
|
||||||
|
|
||||||
|
|
||||||
|
def contact_uid(key: str) -> str:
|
||||||
|
return str(uuid.uuid5(NAMESPACE, key))
|
||||||
|
|
||||||
|
|
||||||
|
def contact_href(key: str) -> str:
|
||||||
|
return f"{contact_uid(key)}.vcf"
|
||||||
|
|
||||||
|
|
||||||
|
def fingerprint(contact: Contact, photo_max_size: int, photo_quality: int) -> str:
|
||||||
|
"""Empreinte de la source : change si une donnée ou un réglage de rendu change."""
|
||||||
|
payload = {
|
||||||
|
"format": FORMAT_VERSION,
|
||||||
|
"photo_max_size": photo_max_size,
|
||||||
|
"photo_quality": photo_quality,
|
||||||
|
"key": contact.key,
|
||||||
|
"given_name": contact.given_name,
|
||||||
|
"family_name": contact.family_name,
|
||||||
|
"full_name": contact.full_name,
|
||||||
|
"organization": contact.organization,
|
||||||
|
"title": contact.title,
|
||||||
|
"emails": [[e.address, e.type, e.preferred] for e in contact.emails],
|
||||||
|
"phones": [[p.number, p.type] for p in contact.phones],
|
||||||
|
"category": contact.category,
|
||||||
|
"birthday": contact.birthday.isoformat() if contact.birthday else None,
|
||||||
|
"photo": hashlib.sha256(contact.photo).hexdigest() if contact.photo else None,
|
||||||
|
}
|
||||||
|
text = json.dumps(payload, sort_keys=True, ensure_ascii=False)
|
||||||
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Retaillage des photos de contact."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
|
||||||
|
def resize_photo(data: bytes, max_size: int, quality: int) -> bytes | None:
|
||||||
|
"""JPEG d'au plus max_size × max_size, sans métadonnées ; None si illisible."""
|
||||||
|
try:
|
||||||
|
with Image.open(BytesIO(data)) as source:
|
||||||
|
image = ImageOps.exif_transpose(source)
|
||||||
|
if image.mode != "RGB":
|
||||||
|
background = Image.new("RGB", image.size, (255, 255, 255))
|
||||||
|
rgba = image.convert("RGBA")
|
||||||
|
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||||
|
image = background
|
||||||
|
image.thumbnail((max_size, max_size), Image.LANCZOS)
|
||||||
|
out = BytesIO()
|
||||||
|
image.save(out, format="JPEG", quality=quality, optimize=True)
|
||||||
|
return out.getvalue()
|
||||||
|
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
|
||||||
|
return None
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Calcul des actions de synchronisation et garde-fous."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from .state import StateRow
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Desired:
|
||||||
|
href: str
|
||||||
|
key: str
|
||||||
|
fingerprint: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Plan:
|
||||||
|
create: list[str] = field(default_factory=list)
|
||||||
|
update: list[str] = field(default_factory=list)
|
||||||
|
verify: list[str] = field(default_factory=list)
|
||||||
|
delete: list[str] = field(default_factory=list)
|
||||||
|
unchanged: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class GuardError(Exception):
|
||||||
|
"""Synchronisation refusée par un garde-fou."""
|
||||||
|
|
||||||
|
|
||||||
|
def compute_plan(
|
||||||
|
desired: dict[str, Desired], server: dict[str, str], state: dict[str, StateRow]
|
||||||
|
) -> Plan:
|
||||||
|
plan = Plan()
|
||||||
|
for href in sorted(desired):
|
||||||
|
if href not in server:
|
||||||
|
plan.create.append(href)
|
||||||
|
continue
|
||||||
|
row = state.get(href)
|
||||||
|
if row is None:
|
||||||
|
plan.verify.append(href)
|
||||||
|
elif row.fingerprint != desired[href].fingerprint or row.etag != server[href]:
|
||||||
|
plan.update.append(href)
|
||||||
|
else:
|
||||||
|
plan.unchanged.append(href)
|
||||||
|
plan.delete = sorted(href for href in server if href not in desired)
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
def check_guards(
|
||||||
|
desired_count: int,
|
||||||
|
server_count: int,
|
||||||
|
plan: Plan,
|
||||||
|
max_delete_ratio: float,
|
||||||
|
force: bool,
|
||||||
|
initial: bool,
|
||||||
|
) -> None:
|
||||||
|
if desired_count == 0:
|
||||||
|
raise GuardError("L'annuaire n'a renvoyé aucune fiche : synchronisation annulée")
|
||||||
|
if force or initial:
|
||||||
|
return
|
||||||
|
limit = max_delete_ratio * server_count
|
||||||
|
if len(plan.delete) > limit:
|
||||||
|
raise GuardError(
|
||||||
|
f"{len(plan.delete)} suppressions prévues sur {server_count} fiches "
|
||||||
|
f"(limite {max_delete_ratio:.0%}) : relancer avec --force si c'est voulu"
|
||||||
|
)
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Suivi de l'avancement des écritures, sans aucune donnée personnelle."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import ExitStack
|
||||||
|
from typing import Protocol, TextIO
|
||||||
|
|
||||||
|
from tqdm import tqdm
|
||||||
|
from tqdm.contrib.logging import logging_redirect_tqdm
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Progress(Protocol):
|
||||||
|
def start(self, total: int) -> None: ...
|
||||||
|
def advance(self) -> None: ...
|
||||||
|
def close(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class LogProgress:
|
||||||
|
"""Hors terminal (cron, Docker) : une ligne de journal toutes les `every` fiches."""
|
||||||
|
|
||||||
|
def __init__(self, every: int = 100):
|
||||||
|
self._every = every
|
||||||
|
self._total = 0
|
||||||
|
self._done = 0
|
||||||
|
|
||||||
|
def start(self, total: int) -> None:
|
||||||
|
self._total, self._done = total, 0
|
||||||
|
|
||||||
|
def advance(self) -> None:
|
||||||
|
self._done += 1
|
||||||
|
if self._done % self._every == 0:
|
||||||
|
log.info("Progression : %d/%d", self._done, self._total)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._done and self._done % self._every != 0:
|
||||||
|
log.info("Progression : %d/%d", self._done, self._total)
|
||||||
|
|
||||||
|
|
||||||
|
class BarProgress:
|
||||||
|
"""En terminal : barre de progression, les messages du journal s'affichent au-dessus."""
|
||||||
|
|
||||||
|
def __init__(self, file: TextIO | None = None):
|
||||||
|
self._file = file
|
||||||
|
self._bar: tqdm | None = None
|
||||||
|
self._stack = ExitStack()
|
||||||
|
|
||||||
|
def start(self, total: int) -> None:
|
||||||
|
self._stack.enter_context(logging_redirect_tqdm())
|
||||||
|
self._bar = tqdm(total=total, unit="fiche", desc="Synchro", file=self._file, dynamic_ncols=True)
|
||||||
|
|
||||||
|
def advance(self) -> None:
|
||||||
|
if self._bar is not None:
|
||||||
|
self._bar.update(1)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._bar is not None:
|
||||||
|
self._bar.close()
|
||||||
|
self._bar = None
|
||||||
|
self._stack.close()
|
||||||
|
|
||||||
|
|
||||||
|
def make_progress(interactive: bool) -> Progress:
|
||||||
|
return BarProgress() if interactive else LogProgress()
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""Base d'état locale (SQLite) : empreinte et ETag de chaque fiche envoyée."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class StateRow:
|
||||||
|
href: str
|
||||||
|
key: str
|
||||||
|
fingerprint: str
|
||||||
|
etag: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class StateDB:
|
||||||
|
def __init__(self, path: Path):
|
||||||
|
path = Path(path)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._conn = sqlite3.connect(path)
|
||||||
|
self._conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS contacts ("
|
||||||
|
" href TEXT PRIMARY KEY,"
|
||||||
|
" key TEXT NOT NULL,"
|
||||||
|
" fingerprint TEXT NOT NULL,"
|
||||||
|
" etag TEXT,"
|
||||||
|
" updated_at TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
self._conn.commit()
|
||||||
|
|
||||||
|
def all(self) -> dict[str, StateRow]:
|
||||||
|
rows = self._conn.execute("SELECT href, key, fingerprint, etag FROM contacts")
|
||||||
|
return {row[0]: StateRow(*row) for row in rows}
|
||||||
|
|
||||||
|
def upsert(self, row: StateRow) -> None:
|
||||||
|
self._conn.execute(
|
||||||
|
"INSERT INTO contacts (href, key, fingerprint, etag, updated_at) VALUES (?, ?, ?, ?, ?)"
|
||||||
|
" ON CONFLICT(href) DO UPDATE SET key = excluded.key,"
|
||||||
|
" fingerprint = excluded.fingerprint, etag = excluded.etag,"
|
||||||
|
" updated_at = excluded.updated_at",
|
||||||
|
(row.href, row.key, row.fingerprint, row.etag, _now()),
|
||||||
|
)
|
||||||
|
self._conn.commit()
|
||||||
|
|
||||||
|
def set_etag(self, href: str, etag: str) -> None:
|
||||||
|
self._conn.execute(
|
||||||
|
"UPDATE contacts SET etag = ?, updated_at = ? WHERE href = ?", (etag, _now(), href)
|
||||||
|
)
|
||||||
|
self._conn.commit()
|
||||||
|
|
||||||
|
def delete(self, href: str) -> None:
|
||||||
|
self._conn.execute("DELETE FROM contacts WHERE href = ?", (href,))
|
||||||
|
self._conn.commit()
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._conn.close()
|
||||||
|
|
||||||
|
def __enter__(self) -> "StateDB":
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc) -> None:
|
||||||
|
self.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
"""Orchestration d'une synchronisation complète."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from .carddav import CardDavClient, CardDavError
|
||||||
|
from .config import Mapping, Settings
|
||||||
|
from .ldap_source import LdapSource, required_attributes
|
||||||
|
from .mapping import entry_to_contact
|
||||||
|
from .model import Contact, contact_href, fingerprint
|
||||||
|
from .photo import resize_photo
|
||||||
|
from .planner import Desired, check_guards, compute_plan
|
||||||
|
from .progress import LogProgress, Progress
|
||||||
|
from .state import StateDB, StateRow
|
||||||
|
from .vcard import read_sync_hash, render_vcard
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Summary:
|
||||||
|
created: int = 0
|
||||||
|
updated: int = 0
|
||||||
|
verified: int = 0
|
||||||
|
deleted: int = 0
|
||||||
|
unchanged: int = 0
|
||||||
|
errors: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
def _build_desired(
|
||||||
|
settings: Settings, mapping: Mapping, directions: dict[str, str], source: LdapSource
|
||||||
|
) -> tuple[dict[str, Desired], dict[str, Contact]]:
|
||||||
|
entries = source.fetch_entries(required_attributes(mapping))
|
||||||
|
birthday_keys = source.fetch_birthday_keys(mapping.key)
|
||||||
|
desired: dict[str, Desired] = {}
|
||||||
|
contacts: dict[str, Contact] = {}
|
||||||
|
for entry in entries:
|
||||||
|
contact = entry_to_contact(entry, mapping, directions, False)
|
||||||
|
if contact is None:
|
||||||
|
continue
|
||||||
|
if contact.key in birthday_keys:
|
||||||
|
contact = entry_to_contact(entry, mapping, directions, True)
|
||||||
|
href = contact_href(contact.key)
|
||||||
|
if href in desired:
|
||||||
|
log.warning("%s : clé en double dans l'annuaire, seule la première fiche est gardée", contact.key)
|
||||||
|
continue
|
||||||
|
desired[href] = Desired(
|
||||||
|
href, contact.key, fingerprint(contact, settings.photo_max_size, settings.photo_quality)
|
||||||
|
)
|
||||||
|
contacts[href] = contact
|
||||||
|
log.info("Annuaire : %d fiches (%d avec date de naissance)", len(desired), len(birthday_keys))
|
||||||
|
return desired, contacts
|
||||||
|
|
||||||
|
|
||||||
|
def 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,
|
||||||
|
progress: Progress | None = None,
|
||||||
|
) -> Summary:
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
progress = progress or LogProgress()
|
||||||
|
desired, contacts = _build_desired(settings, mapping, directions, source)
|
||||||
|
server = client.list_etags()
|
||||||
|
log.info("Nextcloud : %d fiches dans le carnet", len(server))
|
||||||
|
plan = compute_plan(desired, server, state.all())
|
||||||
|
check_guards(len(desired), len(server), plan, settings.max_delete_ratio, force, initial)
|
||||||
|
|
||||||
|
summary = Summary(unchanged=len(plan.unchanged))
|
||||||
|
if dry_run:
|
||||||
|
for action, hrefs in (("création", plan.create), ("mise à jour", plan.update),
|
||||||
|
("vérification", plan.verify), ("suppression", plan.delete)):
|
||||||
|
for href in hrefs:
|
||||||
|
key = desired[href].key if href in desired else "-"
|
||||||
|
log.info("[simulation] %s %s (%s)", action, href, key)
|
||||||
|
summary.created, summary.updated = len(plan.create), len(plan.update)
|
||||||
|
summary.verified, summary.deleted = len(plan.verify), len(plan.delete)
|
||||||
|
return summary
|
||||||
|
|
||||||
|
updates = list(plan.update)
|
||||||
|
|
||||||
|
# Base perdue ou neuve : relire les fiches présentes pour éviter un renvoi général.
|
||||||
|
if plan.verify:
|
||||||
|
try:
|
||||||
|
cards = client.multiget(plan.verify)
|
||||||
|
except CardDavError as exc:
|
||||||
|
log.error("Lecture groupée impossible (%s) : les fiches seront renvoyées", exc)
|
||||||
|
cards = {}
|
||||||
|
for href in plan.verify:
|
||||||
|
wanted = desired[href]
|
||||||
|
if read_sync_hash(cards.get(href, "")) == wanted.fingerprint:
|
||||||
|
state.upsert(StateRow(href, wanted.key, wanted.fingerprint, server[href]))
|
||||||
|
summary.verified += 1
|
||||||
|
else:
|
||||||
|
updates.append(href)
|
||||||
|
|
||||||
|
missing_etag: list[str] = []
|
||||||
|
|
||||||
|
def write(href: str, etag: str | None) -> bool:
|
||||||
|
wanted = desired[href]
|
||||||
|
contact = contacts[href]
|
||||||
|
try:
|
||||||
|
photo = None
|
||||||
|
if contact.photo:
|
||||||
|
photo = resize_photo(contact.photo, settings.photo_max_size, settings.photo_quality)
|
||||||
|
if photo is None:
|
||||||
|
log.warning("%s : photo illisible, fiche envoyée sans photo", wanted.key)
|
||||||
|
text = render_vcard(contact, photo, wanted.fingerprint, now)
|
||||||
|
new_etag = client.put(href, text, etag)
|
||||||
|
except CardDavError as exc:
|
||||||
|
log.error("%s (%s) : échec de l'envoi : %s", href, wanted.key, exc)
|
||||||
|
summary.errors += 1
|
||||||
|
return False
|
||||||
|
except Exception as exc: # une fiche ne doit jamais bloquer toute la synchro
|
||||||
|
log.error("%s (%s) : fiche impossible à produire : %s", href, wanted.key, type(exc).__name__)
|
||||||
|
summary.errors += 1
|
||||||
|
return False
|
||||||
|
state.upsert(StateRow(href, wanted.key, wanted.fingerprint, new_etag))
|
||||||
|
if new_etag is None:
|
||||||
|
missing_etag.append(href)
|
||||||
|
log.debug("%s (%s) : envoyée", href, wanted.key)
|
||||||
|
return True
|
||||||
|
|
||||||
|
progress.start(len(plan.create) + len(updates) + len(plan.delete))
|
||||||
|
try:
|
||||||
|
for href in plan.create:
|
||||||
|
if write(href, None):
|
||||||
|
summary.created += 1
|
||||||
|
progress.advance()
|
||||||
|
for href in updates:
|
||||||
|
if write(href, server[href]):
|
||||||
|
summary.updated += 1
|
||||||
|
progress.advance()
|
||||||
|
|
||||||
|
for href in plan.delete:
|
||||||
|
try:
|
||||||
|
client.delete(href, server[href])
|
||||||
|
except CardDavError as exc:
|
||||||
|
log.error("%s : échec de la suppression : %s", href, exc)
|
||||||
|
summary.errors += 1
|
||||||
|
else:
|
||||||
|
state.delete(href)
|
||||||
|
summary.deleted += 1
|
||||||
|
log.debug("%s : supprimée", href)
|
||||||
|
progress.advance()
|
||||||
|
finally:
|
||||||
|
progress.close()
|
||||||
|
|
||||||
|
if missing_etag:
|
||||||
|
try:
|
||||||
|
fresh = client.list_etags()
|
||||||
|
except CardDavError as exc:
|
||||||
|
log.warning("ETags non relus (%s) : ils seront complétés au prochain passage", exc)
|
||||||
|
fresh = {}
|
||||||
|
for href in missing_etag:
|
||||||
|
if href in fresh:
|
||||||
|
state.set_etag(href, fresh[href])
|
||||||
|
|
||||||
|
return summary
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""Rendu vCard 3.0 d'une fiche et lecture de l'empreinte embarquée."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import vobject
|
||||||
|
|
||||||
|
from .model import Contact, contact_uid
|
||||||
|
|
||||||
|
PRODID = "-//ldap2nextcloud//FR"
|
||||||
|
HASH_PROPERTY = "X-LDAPSYNC-HASH"
|
||||||
|
|
||||||
|
|
||||||
|
def render_vcard(contact: Contact, photo_jpeg: bytes | None, sync_hash: str, now: datetime) -> str:
|
||||||
|
card = vobject.vCard()
|
||||||
|
card.add("version").value = "3.0"
|
||||||
|
card.add("prodid").value = PRODID
|
||||||
|
card.add("uid").value = contact_uid(contact.key)
|
||||||
|
card.add("n").value = vobject.vcard.Name(family=contact.family_name, given=contact.given_name)
|
||||||
|
card.add("fn").value = contact.full_name
|
||||||
|
if contact.organization:
|
||||||
|
card.add("org").value = [contact.organization]
|
||||||
|
if contact.title:
|
||||||
|
card.add("title").value = contact.title
|
||||||
|
for email in contact.emails:
|
||||||
|
prop = card.add("email")
|
||||||
|
prop.value = email.address
|
||||||
|
prop.type_paramlist = ["INTERNET", email.type.upper()] + (["PREF"] if email.preferred else [])
|
||||||
|
for phone in contact.phones:
|
||||||
|
prop = card.add("tel")
|
||||||
|
prop.value = phone.number
|
||||||
|
prop.type_paramlist = ["VOICE", phone.type.upper()]
|
||||||
|
if contact.category:
|
||||||
|
card.add("categories").value = [contact.category]
|
||||||
|
if contact.birthday:
|
||||||
|
card.add("bday").value = contact.birthday.isoformat()
|
||||||
|
if photo_jpeg:
|
||||||
|
prop = card.add("photo")
|
||||||
|
prop.encoding_param = "b"
|
||||||
|
prop.type_param = "JPEG"
|
||||||
|
prop.value = photo_jpeg
|
||||||
|
card.add("rev").value = now.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
card.add(HASH_PROPERTY.lower()).value = sync_hash
|
||||||
|
return card.serialize()
|
||||||
|
|
||||||
|
|
||||||
|
def read_sync_hash(vcard_text: str) -> str | None:
|
||||||
|
try:
|
||||||
|
card = vobject.readOne(vcard_text)
|
||||||
|
except Exception: # vobject lève des exceptions variées sur une carte invalide
|
||||||
|
return None
|
||||||
|
prop = card.contents.get(HASH_PROPERTY.lower())
|
||||||
|
if not prop:
|
||||||
|
return None
|
||||||
|
value = prop[0].value
|
||||||
|
return value.strip() if isinstance(value, str) and value.strip() else None
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
|||||||
|
BEGIN:VCARD
|
||||||
|
VERSION:3.0
|
||||||
|
UID:729ede57-285f-4995-a79e-0fd04b02c661
|
||||||
|
ADR;CHARSET=UTF-8;TYPE=WORK:;;;;;;
|
||||||
|
CATEGORIES;CHARSET=UTF-8:Direction des systèmes d'information
|
||||||
|
EMAIL;CHARSET=UTF-8;TYPE=INTERNET,PREF:g.leroy@example.org
|
||||||
|
FN;CHARSET=UTF-8:LEROY Gaëlle
|
||||||
|
KIND:organization
|
||||||
|
N;CHARSET=UTF-8:LEROY;Gaëlle;;;
|
||||||
|
ORG;CHARSET=UTF-8:Example
|
||||||
|
PHOTO;ENCODING=b;TYPE=JPEG:/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYH
|
||||||
|
BwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2w
|
||||||
|
BDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo
|
||||||
|
KCgoKCgoKCgoKCj/wAARCAEAAQADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAw
|
||||||
|
QFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0Kx
|
||||||
|
wRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3
|
||||||
|
R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW
|
||||||
|
19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQ
|
||||||
|
oL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV
|
||||||
|
YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eH
|
||||||
|
l6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna
|
||||||
|
4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDDooor7E9UKKKKACiiigAooooAKKKKAC
|
||||||
|
iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
|
||||||
|
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig
|
||||||
|
AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
|
||||||
|
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo
|
||||||
|
oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACii
|
||||||
|
igAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK
|
||||||
|
KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAo
|
||||||
|
oooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC
|
||||||
|
iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
|
||||||
|
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig
|
||||||
|
AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
|
||||||
|
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo
|
||||||
|
oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACii
|
||||||
|
igAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK
|
||||||
|
KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAo
|
||||||
|
oooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC
|
||||||
|
iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
|
||||||
|
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig
|
||||||
|
AooooA/9k=
|
||||||
|
REV:20260210T114654Z
|
||||||
|
TEL;CHARSET=UTF-8;TYPE=VOICE,WORK:+33102030405
|
||||||
|
TITLE;CHARSET=UTF-8:Informaticiens
|
||||||
|
X-ABUID:ABPerson
|
||||||
|
END:VCARD
|
||||||
Whitespace-only changes.
@@ -0,0 +1,39 @@
|
|||||||
|
"""Lecteur LDIF minimal pour les tests (fichiers anonymisés uniquement)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def load_ldif(path: Path) -> list[tuple[str, dict[str, list[bytes]]]]:
|
||||||
|
text = Path(path).read_text(encoding="utf-8")
|
||||||
|
lines: list[str] = []
|
||||||
|
for line in text.splitlines():
|
||||||
|
if line.startswith(" ") and lines:
|
||||||
|
lines[-1] += line[1:]
|
||||||
|
else:
|
||||||
|
lines.append(line)
|
||||||
|
|
||||||
|
entries: list[tuple[str, dict[str, list[bytes]]]] = []
|
||||||
|
dn: str | None = None
|
||||||
|
attrs: dict[str, list[bytes]] = {}
|
||||||
|
for line in lines + [""]:
|
||||||
|
if not line.strip():
|
||||||
|
if dn is not None:
|
||||||
|
entries.append((dn, attrs))
|
||||||
|
dn, attrs = None, {}
|
||||||
|
continue
|
||||||
|
if line.startswith("#"):
|
||||||
|
continue
|
||||||
|
name, _, rest = line.partition(":")
|
||||||
|
if rest.startswith(":"):
|
||||||
|
value = base64.b64decode(rest[1:].strip())
|
||||||
|
else:
|
||||||
|
value = rest.strip().encode("utf-8")
|
||||||
|
name = name.split(";")[0]
|
||||||
|
if name == "dn":
|
||||||
|
dn = value.decode("utf-8")
|
||||||
|
else:
|
||||||
|
attrs.setdefault(name, []).append(value)
|
||||||
|
return entries
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import base64
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import responses
|
||||||
|
|
||||||
|
from ldap2nextcloud.carddav import CardDavClient, CardDavError
|
||||||
|
|
||||||
|
BOOK = "https://cloud.test/remote.php/dav/addressbooks/users/annuaire/annuaire/"
|
||||||
|
BOOK_PATH = "/remote.php/dav/addressbooks/users/annuaire/annuaire/"
|
||||||
|
|
||||||
|
|
||||||
|
def multistatus(*items):
|
||||||
|
body = "".join(
|
||||||
|
f"""<d:response><d:href>{href}</d:href><d:propstat><d:prop>
|
||||||
|
{f'<d:getetag>{etag}</d:getetag>' if etag else ''}
|
||||||
|
{f'<card:address-data>{data}</card:address-data>' if data else ''}
|
||||||
|
</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"""
|
||||||
|
for href, etag, data in items
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
'<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" '
|
||||||
|
f'xmlns:card="urn:ietf:params:xml:ns:carddav">{body}</d:multistatus>'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
return CardDavClient(BOOK, "annuaire", "secret")
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_list_etags_normalizes_hrefs(client):
|
||||||
|
responses.add(
|
||||||
|
"PROPFIND", BOOK, status=207,
|
||||||
|
body=multistatus(
|
||||||
|
(BOOK_PATH, None, None),
|
||||||
|
(BOOK_PATH + "a%40b.vcf", '"123"', None),
|
||||||
|
(BOOK + "c.vcf", '"456"', None),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assert client.list_etags() == {"a@b.vcf": "123", "c.vcf": "456"}
|
||||||
|
assert responses.calls[0].request.headers["Depth"] == "1"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_list_etags_empty_addressbook(client):
|
||||||
|
responses.add("PROPFIND", BOOK, status=207, body=multistatus((BOOK_PATH, None, None)))
|
||||||
|
assert client.list_etags() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_list_etags_error_raises(client):
|
||||||
|
responses.add("PROPFIND", BOOK, status=401)
|
||||||
|
with pytest.raises(CardDavError) as err:
|
||||||
|
client.list_etags()
|
||||||
|
assert err.value.status == 401
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_put_create_sends_if_none_match(client):
|
||||||
|
responses.add("PUT", BOOK + "x.vcf", status=201, headers={"ETag": '"e1"'})
|
||||||
|
assert client.put("x.vcf", "BEGIN:VCARD", None) == "e1"
|
||||||
|
request = responses.calls[0].request
|
||||||
|
assert request.headers["If-None-Match"] == "*"
|
||||||
|
assert "If-Match" not in request.headers
|
||||||
|
assert request.headers["Content-Type"] == "text/vcard; charset=utf-8"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_put_update_sends_if_match(client):
|
||||||
|
responses.add("PUT", BOOK + "x.vcf", status=204, headers={"ETag": '"e1"'})
|
||||||
|
client.put("x.vcf", "BEGIN:VCARD", "e0")
|
||||||
|
assert responses.calls[0].request.headers["If-Match"] == '"e0"'
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_put_without_etag_in_response_returns_none(client):
|
||||||
|
responses.add("PUT", BOOK + "x.vcf", status=201)
|
||||||
|
assert client.put("x.vcf", "BEGIN:VCARD", None) is None
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_put_412_raises_with_status(client):
|
||||||
|
responses.add("PUT", BOOK + "x.vcf", status=412)
|
||||||
|
with pytest.raises(CardDavError) as err:
|
||||||
|
client.put("x.vcf", "...", "old")
|
||||||
|
assert err.value.status == 412
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_put_encodes_href(client):
|
||||||
|
responses.add("PUT", BOOK + "a%40b.vcf", status=201)
|
||||||
|
client.put("a@b.vcf", "BEGIN:VCARD", None)
|
||||||
|
assert responses.calls[0].request.url == BOOK + "a%40b.vcf"
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_delete_sends_if_match(client):
|
||||||
|
responses.add("DELETE", BOOK + "x.vcf", status=204)
|
||||||
|
client.delete("x.vcf", "e1")
|
||||||
|
assert responses.calls[0].request.headers["If-Match"] == '"e1"'
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_delete_404_is_success(client):
|
||||||
|
responses.add("DELETE", BOOK + "x.vcf", status=404)
|
||||||
|
client.delete("x.vcf", None)
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_delete_error_raises(client):
|
||||||
|
responses.add("DELETE", BOOK + "x.vcf", status=500)
|
||||||
|
with pytest.raises(CardDavError):
|
||||||
|
client.delete("x.vcf", None)
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_multiget_returns_card_text(client):
|
||||||
|
responses.add(
|
||||||
|
"REPORT", BOOK, status=207,
|
||||||
|
body=multistatus((BOOK_PATH + "a.vcf", '"1"', "BEGIN:VCARD \nFN:A \nEND:VCARD")),
|
||||||
|
)
|
||||||
|
assert client.multiget(["a.vcf"]) == {"a.vcf": "BEGIN:VCARD\r\nFN:A\r\nEND:VCARD"}
|
||||||
|
assert BOOK_PATH + "a.vcf" in responses.calls[0].request.body.decode()
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_multiget_batches_by_50(client):
|
||||||
|
hrefs = [f"{i}.vcf" for i in range(120)]
|
||||||
|
|
||||||
|
def reply(request):
|
||||||
|
body = request.body.decode()
|
||||||
|
items = [(BOOK_PATH + h, '"1"', "BEGIN:VCARD") for h in hrefs if f"/{h}<" in body]
|
||||||
|
return 207, {}, multistatus(*items)
|
||||||
|
|
||||||
|
responses.add_callback("REPORT", BOOK, callback=reply)
|
||||||
|
result = client.multiget(hrefs)
|
||||||
|
assert len(responses.calls) == 3
|
||||||
|
assert set(result) == set(hrefs)
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiget_empty_makes_no_request(client):
|
||||||
|
assert client.multiget([]) == {}
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_basic_auth_sent(client):
|
||||||
|
responses.add("PROPFIND", BOOK, status=207, body=multistatus())
|
||||||
|
client.list_etags()
|
||||||
|
expected = "Basic " + base64.b64encode(b"annuaire:secret").decode()
|
||||||
|
assert responses.calls[0].request.headers["Authorization"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_weak_etags_are_normalized_everywhere(client):
|
||||||
|
responses.add("PROPFIND", BOOK, status=207, body=multistatus((BOOK_PATH + "a.vcf", 'W/"123"', None)))
|
||||||
|
responses.add("PUT", BOOK + "a.vcf", status=204, headers={"ETag": 'W/"456"'})
|
||||||
|
assert client.list_etags() == {"a.vcf": "123"}
|
||||||
|
assert client.put("a.vcf", "BEGIN:VCARD", "123") == "456"
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import fcntl
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import truststore
|
||||||
|
|
||||||
|
from ldap2nextcloud import cli
|
||||||
|
from ldap2nextcloud.carddav import CardDavError
|
||||||
|
from ldap2nextcloud.planner import GuardError
|
||||||
|
from ldap2nextcloud.sync import Summary
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
ENV = """\
|
||||||
|
LDAP_URL=ldap://ldap.test
|
||||||
|
LDAP_BASE_DN=dc=test
|
||||||
|
LDAP_FILTER=(objectClass=person)
|
||||||
|
NEXTCLOUD_URL=https://cloud.test
|
||||||
|
NEXTCLOUD_USER=annuaire
|
||||||
|
NEXTCLOUD_APP_PASSWORD=secret
|
||||||
|
NEXTCLOUD_ADDRESSBOOK=annuaire
|
||||||
|
STATE_DB={state}
|
||||||
|
MAPPING_FILE={root}/mapping.example.yaml
|
||||||
|
DIRECTIONS_FILE={root}/directions.example.yaml
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env_file(tmp_path, monkeypatch):
|
||||||
|
for name in ("LDAP_URL", "NEXTCLOUD_APP_PASSWORD", "STATE_DB", "MAPPING_FILE"):
|
||||||
|
monkeypatch.delenv(name, raising=False)
|
||||||
|
path = tmp_path / ".env"
|
||||||
|
path.write_text(ENV.format(state=tmp_path / "state" / "sync.sqlite", root=ROOT))
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def calls(monkeypatch):
|
||||||
|
record = []
|
||||||
|
monkeypatch.setattr(truststore, "inject_into_ssl", lambda: record.append("truststore"))
|
||||||
|
monkeypatch.setattr(cli, "LdapSource", lambda settings: object())
|
||||||
|
monkeypatch.setattr(cli, "CardDavClient", lambda *a, **k: object())
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
def fake_run(result):
|
||||||
|
def run(*args, **kwargs):
|
||||||
|
if isinstance(result, Exception):
|
||||||
|
raise result
|
||||||
|
return result
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
def test_truststore_injected_before_anything(env_file, calls, monkeypatch):
|
||||||
|
real_load = cli.load_settings
|
||||||
|
|
||||||
|
def spy(path):
|
||||||
|
calls.append("settings")
|
||||||
|
return real_load(path)
|
||||||
|
|
||||||
|
monkeypatch.setattr(cli, "load_settings", spy)
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(Summary()))
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 0
|
||||||
|
assert calls[:2] == ["truststore", "settings"]
|
||||||
|
assert calls.count("truststore") == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_returns_0(env_file, calls, monkeypatch):
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(Summary(created=2)))
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_errors_return_1(env_file, calls, monkeypatch):
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(Summary(errors=1)))
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_server_error_returns_1(env_file, calls, monkeypatch):
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(CardDavError("HTTP 401", 401)))
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_error_returns_2(env_file, calls, monkeypatch):
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(GuardError("trop")))
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_error_returns_3(tmp_path, calls, monkeypatch):
|
||||||
|
monkeypatch.delenv("LDAP_URL", raising=False)
|
||||||
|
empty = tmp_path / ".env"
|
||||||
|
empty.write_text("")
|
||||||
|
assert cli.main(["--env", str(empty)]) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_lock_held_returns_4(env_file, calls, monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setattr(cli, "run_sync", fake_run(Summary()))
|
||||||
|
lock_path = tmp_path / "state" / "sync.sqlite.lock"
|
||||||
|
lock_path.parent.mkdir(parents=True)
|
||||||
|
with open(lock_path, "w") as handle:
|
||||||
|
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
assert cli.main(["--env", str(env_file)]) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_options_passed_to_run_sync(env_file, calls, monkeypatch):
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def run(*args, **kwargs):
|
||||||
|
seen.update(kwargs)
|
||||||
|
return Summary()
|
||||||
|
|
||||||
|
monkeypatch.setattr(cli, "run_sync", run)
|
||||||
|
cli.main(["--env", str(env_file), "--dry-run", "--initial", "--force"])
|
||||||
|
assert seen["dry_run"] and seen["initial"] and seen["force"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_progress_follows_terminal(env_file, calls, monkeypatch):
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def run(*args, **kwargs):
|
||||||
|
seen["progress"] = kwargs["progress"]
|
||||||
|
return Summary()
|
||||||
|
|
||||||
|
monkeypatch.setattr(cli, "run_sync", run)
|
||||||
|
monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: False)
|
||||||
|
cli.main(["--env", str(env_file)])
|
||||||
|
from ldap2nextcloud.progress import LogProgress
|
||||||
|
assert isinstance(seen["progress"], LogProgress)
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from ldap2nextcloud.config import (
|
||||||
|
ConfigError,
|
||||||
|
EmailRule,
|
||||||
|
PhoneRule,
|
||||||
|
load_directions,
|
||||||
|
load_mapping,
|
||||||
|
load_settings,
|
||||||
|
)
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
ALL_VARS = [
|
||||||
|
"LDAP_URL", "LDAP_BIND_DN", "LDAP_BIND_PASSWORD", "LDAP_BASE_DN", "LDAP_FILTER",
|
||||||
|
"LDAP_BIRTHDAY_FILTER", "LDAP_GROUP_DNS", "LDAP_CA_CERT", "NEXTCLOUD_URL",
|
||||||
|
"NEXTCLOUD_USER", "NEXTCLOUD_APP_PASSWORD", "NEXTCLOUD_ADDRESSBOOK", "STATE_DB",
|
||||||
|
"MAPPING_FILE", "DIRECTIONS_FILE", "PHOTO_MAX_SIZE", "PHOTO_QUALITY",
|
||||||
|
"MAX_DELETE_RATIO", "LOG_LEVEL",
|
||||||
|
]
|
||||||
|
|
||||||
|
MINIMAL_ENV = """\
|
||||||
|
LDAP_URL=ldap://ldap.test
|
||||||
|
LDAP_BASE_DN=ou=personnes,dc=test
|
||||||
|
LDAP_FILTER=(objectClass=person)
|
||||||
|
NEXTCLOUD_URL=https://cloud.test/
|
||||||
|
NEXTCLOUD_USER=annuaire
|
||||||
|
NEXTCLOUD_APP_PASSWORD=secret
|
||||||
|
NEXTCLOUD_ADDRESSBOOK=annuaire
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def clean_env(monkeypatch):
|
||||||
|
for name in ALL_VARS:
|
||||||
|
monkeypatch.delenv(name, raising=False)
|
||||||
|
|
||||||
|
|
||||||
|
def write_env(tmp_path, content):
|
||||||
|
path = tmp_path / ".env"
|
||||||
|
path.write_text(content)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_settings_reads_env_file(tmp_path):
|
||||||
|
settings = load_settings(write_env(tmp_path, MINIMAL_ENV))
|
||||||
|
assert settings.addressbook_url == (
|
||||||
|
"https://cloud.test/remote.php/dav/addressbooks/users/annuaire/annuaire/"
|
||||||
|
)
|
||||||
|
assert settings.photo_max_size == 512
|
||||||
|
assert settings.photo_quality == 80
|
||||||
|
assert settings.max_delete_ratio == 0.10
|
||||||
|
assert settings.ldap_bind_dn is None
|
||||||
|
assert settings.ldap_birthday_filter is None
|
||||||
|
assert settings.ldap_group_dns == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_settings_missing_variable_names_it(tmp_path):
|
||||||
|
content = MINIMAL_ENV.replace("NEXTCLOUD_APP_PASSWORD=secret\n", "")
|
||||||
|
with pytest.raises(ConfigError, match="NEXTCLOUD_APP_PASSWORD"):
|
||||||
|
load_settings(write_env(tmp_path, content))
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_settings_group_dns_split_on_semicolon(tmp_path):
|
||||||
|
content = MINIMAL_ENV + "LDAP_GROUP_DNS=cn=a,dc=x;cn=b,dc=x\n"
|
||||||
|
settings = load_settings(write_env(tmp_path, content))
|
||||||
|
assert settings.ldap_group_dns == ["cn=a,dc=x", "cn=b,dc=x"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_environment_overrides_env_file(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("NEXTCLOUD_USER", "autre")
|
||||||
|
settings = load_settings(write_env(tmp_path, MINIMAL_ENV))
|
||||||
|
assert settings.nextcloud_user == "autre"
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_number_is_reported(tmp_path):
|
||||||
|
content = MINIMAL_ENV + "PHOTO_MAX_SIZE=grand\n"
|
||||||
|
with pytest.raises(ConfigError, match="PHOTO_MAX_SIZE"):
|
||||||
|
load_settings(write_env(tmp_path, content))
|
||||||
|
|
||||||
|
|
||||||
|
def test_example_env_file_is_loadable(monkeypatch):
|
||||||
|
monkeypatch.setenv("NEXTCLOUD_APP_PASSWORD", "x")
|
||||||
|
settings = load_settings(ROOT / ".env.example")
|
||||||
|
assert settings.ldap_birthday_filter == "(usrDirectionId=620)"
|
||||||
|
assert settings.ldap_bind_dn is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_mapping_example_file():
|
||||||
|
m = load_mapping(ROOT / "mapping.example.yaml")
|
||||||
|
assert m.key == "uid"
|
||||||
|
assert m.organization == "Exemple"
|
||||||
|
assert 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"
|
||||||
|
assert m.photo == "jpegPhoto"
|
||||||
|
assert m.title == "usrCadre"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_mapping_missing_key_is_error(tmp_path):
|
||||||
|
path = tmp_path / "mapping.example.yaml"
|
||||||
|
path.write_text("fields:\n given_name: givenName\n")
|
||||||
|
with pytest.raises(ConfigError, match="key"):
|
||||||
|
load_mapping(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_directions_example_file():
|
||||||
|
d = load_directions(ROOT / "directions.example.yaml")
|
||||||
|
assert len(d) == 3
|
||||||
|
assert d["620"] == "Direction des systèmes d'information"
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
from dataclasses import replace
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from ldap3 import MOCK_SYNC, NONE, Connection, Server
|
||||||
|
|
||||||
|
from ldap2nextcloud.config import Settings, load_mapping
|
||||||
|
from ldap2nextcloud.ldap_source import LdapSource, required_attributes
|
||||||
|
from ldif_loader import load_ldif
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
LDIF = ROOT / "test-data" / "example.anon.ldif"
|
||||||
|
MAPPING = load_mapping(ROOT / "mapping.example.yaml")
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.skipif(not LDIF.is_file(), reason="jeu de test anonymisé absent")
|
||||||
|
|
||||||
|
SETTINGS = Settings(
|
||||||
|
ldap_url="ldap://mock", ldap_bind_dn=None, ldap_bind_password=None,
|
||||||
|
ldap_base_dn="ou=personnes,dc=example,dc=org", ldap_filter="(objectClass=inetOrgPerson)",
|
||||||
|
ldap_birthday_filter="(usrDirectionId=620)", ldap_group_dns=[], ldap_ca_cert=None,
|
||||||
|
nextcloud_url="https://cloud.test", nextcloud_user="u", nextcloud_app_password="p",
|
||||||
|
nextcloud_addressbook="b", state_db=Path("s"), mapping_file=Path("m"),
|
||||||
|
directions_file=Path("d"),
|
||||||
|
)
|
||||||
|
|
||||||
|
GROUP_DN = "cn=Fonctionnaires,ou=groupes,dc=example,dc=org"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def ldif_entries():
|
||||||
|
return load_ldif(LDIF)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def connection(ldif_entries):
|
||||||
|
server = Server("mock", get_info=NONE)
|
||||||
|
conn = Connection(server, client_strategy=MOCK_SYNC)
|
||||||
|
for dn, attrs in ldif_entries:
|
||||||
|
conn.strategy.add_entry(dn, attrs)
|
||||||
|
members = [dn for dn, _ in ldif_entries[:2]]
|
||||||
|
conn.strategy.add_entry(
|
||||||
|
GROUP_DN, {"objectClass": ["groupOfUniqueNames"], "cn": ["Fonctionnaires"],
|
||||||
|
"uniqueMember": members},
|
||||||
|
)
|
||||||
|
conn.bind()
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_all_entries_from_anonymized_ldif(connection):
|
||||||
|
entries = LdapSource(SETTINGS, connection).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(connection):
|
||||||
|
entries = LdapSource(SETTINGS, connection).fetch_entries(required_attributes(MAPPING))
|
||||||
|
names = {name.lower() for e in entries for name in e}
|
||||||
|
assert "usrmotifabsence" not in names
|
||||||
|
assert "uid" in names and "jpegphoto" in names
|
||||||
|
|
||||||
|
|
||||||
|
def test_required_attributes_lists_mapping():
|
||||||
|
attrs = required_attributes(MAPPING)
|
||||||
|
for name in ("uid", "givenName", "sn", "cn", "usrCadre", "mail", "telephoneNumber",
|
||||||
|
"usrDirectionId", "jpegPhoto", "usrDateNaissance"):
|
||||||
|
assert name in attrs
|
||||||
|
|
||||||
|
|
||||||
|
def test_birthday_keys_filtered_by_direction(connection, ldif_entries):
|
||||||
|
keys = LdapSource(SETTINGS, connection).fetch_birthday_keys("uid")
|
||||||
|
expected = {
|
||||||
|
attrs["uid"][0].decode() for _, attrs in ldif_entries
|
||||||
|
if attrs.get("usrDirectionId", [b""])[0] == b"620"
|
||||||
|
}
|
||||||
|
assert keys == expected and keys
|
||||||
|
|
||||||
|
|
||||||
|
def test_birthday_keys_empty_without_filter(connection):
|
||||||
|
source = LdapSource(replace(SETTINGS, ldap_birthday_filter=None), connection)
|
||||||
|
assert source.fetch_birthday_keys("uid") == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_group_dns_restrict_population(connection, ldif_entries):
|
||||||
|
source = LdapSource(replace(SETTINGS, ldap_group_dns=[GROUP_DN]), connection)
|
||||||
|
entries = source.fetch_entries(required_attributes(MAPPING))
|
||||||
|
expected = {attrs["uid"][0] for _, attrs in ldif_entries[:2]}
|
||||||
|
assert {e["uid"][0] for e in entries} == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_photo_returned_as_raw_bytes(connection, ldif_entries):
|
||||||
|
entries = LdapSource(SETTINGS, connection).fetch_entries(required_attributes(MAPPING))
|
||||||
|
by_uid = {e["uid"][0]: e for e in entries}
|
||||||
|
for _, attrs in ldif_entries:
|
||||||
|
if "jpegPhoto" in attrs:
|
||||||
|
assert by_uid[attrs["uid"][0]]["jpegPhoto"] == attrs["jpegPhoto"]
|
||||||
|
break
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import logging
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from ldap2nextcloud.config import PhoneRule, load_directions, load_mapping
|
||||||
|
from ldap2nextcloud.mapping import entry_to_contact, format_phone, parse_birthday
|
||||||
|
from ldap2nextcloud.model import Email, Phone
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAPPING = load_mapping(ROOT / "mapping.example.yaml")
|
||||||
|
DIRECTIONS = load_directions(ROOT / "directions.example.yaml")
|
||||||
|
RULE = PhoneRule("telephoneNumber", "work", "+3312345", 4)
|
||||||
|
|
||||||
|
|
||||||
|
def entry(**attrs):
|
||||||
|
full = {
|
||||||
|
"uid": ["omalmare"],
|
||||||
|
"cn": ["MALMARE Oscar"],
|
||||||
|
"sn": ["MALMARE"],
|
||||||
|
"givenName": ["Oscar"],
|
||||||
|
"mail": ["o.malmare@example.org"],
|
||||||
|
"telephoneNumber": ["9052"],
|
||||||
|
"usrDirectionId": ["620"],
|
||||||
|
"usrCadre": ["Ingénieur"],
|
||||||
|
"usrDateNaissance": ["19680615000000Z"],
|
||||||
|
}
|
||||||
|
full.update(attrs)
|
||||||
|
raw = {k: [v.encode("utf-8") for v in vals] for k, vals in full.items() if vals is not None}
|
||||||
|
raw["jpegPhoto"] = [b"\xff\xd8photo"]
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def test_internal_number_gets_prefix():
|
||||||
|
assert format_phone("9052", RULE) == "+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
|
||||||
|
assert parse_birthday("19681315000000Z") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_entry_maps_all_fields():
|
||||||
|
c = entry_to_contact(entry(), MAPPING, DIRECTIONS, with_birthday=True)
|
||||||
|
assert c.key == "omalmare"
|
||||||
|
assert c.given_name == "Oscar" and c.family_name == "MALMARE"
|
||||||
|
assert c.full_name == "MALMARE Oscar"
|
||||||
|
assert c.organization == "Exemple"
|
||||||
|
assert c.title == "Ingénieur"
|
||||||
|
assert c.emails == (Email("o.malmare@example.org", "work", True),)
|
||||||
|
assert c.phones == (Phone("+33123459052", "work"),)
|
||||||
|
assert c.category == "Direction des systèmes d'information"
|
||||||
|
assert c.birthday == date(1968, 6, 15)
|
||||||
|
assert c.photo == b"\xff\xd8photo"
|
||||||
|
|
||||||
|
|
||||||
|
def test_birthday_only_when_requested():
|
||||||
|
c = entry_to_contact(entry(), MAPPING, DIRECTIONS, with_birthday=False)
|
||||||
|
assert c.birthday is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_direction_code_gives_no_category(caplog):
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
c = entry_to_contact(entry(usrDirectionId=["999"]), MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.category is None
|
||||||
|
assert "999" in caplog.text and "omalmare" in caplog.text
|
||||||
|
assert "Oscar" not in caplog.text and "MALMARE" not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_optional_attributes():
|
||||||
|
raw = entry(mail=None, telephoneNumber=None, usrDirectionId=None, usrCadre=None)
|
||||||
|
del raw["jpegPhoto"]
|
||||||
|
c = entry_to_contact(raw, MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.emails == () and c.phones == ()
|
||||||
|
assert c.photo is None and c.category is None and c.title is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_entry_without_key_is_skipped(caplog):
|
||||||
|
raw = entry()
|
||||||
|
del raw["uid"]
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
assert entry_to_contact(raw, MAPPING, DIRECTIONS, True) is None
|
||||||
|
assert caplog.records
|
||||||
|
|
||||||
|
|
||||||
|
def test_accented_names_decoded():
|
||||||
|
c = entry_to_contact(entry(givenName=["Cédric"]), MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.given_name == "Cédric"
|
||||||
|
|
||||||
|
|
||||||
|
def test_attribute_lookup_is_case_insensitive():
|
||||||
|
raw = entry()
|
||||||
|
raw["givenname"] = raw.pop("givenName")
|
||||||
|
c = entry_to_contact(raw, MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.given_name == "Oscar"
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_name_fallback_without_cn():
|
||||||
|
c = entry_to_contact(entry(cn=None), MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.full_name == "Oscar MALMARE"
|
||||||
|
|
||||||
|
|
||||||
|
def test_preferred_email_domain():
|
||||||
|
c = entry_to_contact(entry(mail=["x@autre.fr", "x@example.org"]), MAPPING, DIRECTIONS, True)
|
||||||
|
assert c.emails == (Email("x@example.org", "work", True), Email("x@autre.fr", "work", False))
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
from dataclasses import replace
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from ldap2nextcloud.model import Contact, Email, Phone, contact_href, contact_uid, fingerprint
|
||||||
|
|
||||||
|
BASE = Contact(
|
||||||
|
key="omalmare",
|
||||||
|
given_name="Oscar",
|
||||||
|
family_name="MALMARE",
|
||||||
|
full_name="MALMARE Oscar",
|
||||||
|
organization="Exemple",
|
||||||
|
title="Ingénieur",
|
||||||
|
emails=(Email("o.malmare@example.org", "work", True),),
|
||||||
|
phones=(Phone("+33123459052", "work"),),
|
||||||
|
category="Direction des systèmes d'information",
|
||||||
|
birthday=date(1968, 6, 15),
|
||||||
|
photo=b"\xff\xd8photo",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_href_is_stable_and_derived_from_key():
|
||||||
|
assert contact_href("omalmare") == contact_href("omalmare")
|
||||||
|
assert contact_href("omalmare") == f"{contact_uid('omalmare')}.vcf"
|
||||||
|
assert contact_href("omalmare") != contact_href("cbarssac")
|
||||||
|
|
||||||
|
|
||||||
|
def test_uid_is_known_uuid5():
|
||||||
|
# Valeur figée : changer le namespace casserait l'identité de toutes les fiches.
|
||||||
|
assert contact_uid("omalmare") == contact_uid("omalmare")
|
||||||
|
assert len(contact_uid("omalmare")) == 36
|
||||||
|
assert contact_uid("omalmare")[14] == "5"
|
||||||
|
|
||||||
|
|
||||||
|
def test_fingerprint_stable_for_equal_contacts():
|
||||||
|
assert fingerprint(BASE, 512, 80) == fingerprint(replace(BASE), 512, 80)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fingerprint_changes_with_any_field():
|
||||||
|
reference = fingerprint(BASE, 512, 80)
|
||||||
|
for changed in (
|
||||||
|
replace(BASE, category="Autre"),
|
||||||
|
replace(BASE, photo=b"autre"),
|
||||||
|
replace(BASE, photo=None),
|
||||||
|
replace(BASE, birthday=None),
|
||||||
|
replace(BASE, phones=()),
|
||||||
|
replace(BASE, title="Chef"),
|
||||||
|
):
|
||||||
|
assert fingerprint(changed, 512, 80) != reference
|
||||||
|
|
||||||
|
|
||||||
|
def test_fingerprint_changes_with_photo_settings():
|
||||||
|
assert fingerprint(BASE, 512, 80) != fingerprint(BASE, 720, 80)
|
||||||
|
assert fingerprint(BASE, 512, 80) != fingerprint(BASE, 512, 90)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from ldap2nextcloud.photo import resize_photo
|
||||||
|
|
||||||
|
|
||||||
|
def jpeg(width, height, exif=None):
|
||||||
|
buffer = BytesIO()
|
||||||
|
image = Image.new("RGB", (width, height), (200, 50, 50))
|
||||||
|
if exif is not None:
|
||||||
|
image.save(buffer, format="JPEG", exif=exif)
|
||||||
|
else:
|
||||||
|
image.save(buffer, format="JPEG")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def png_rgba(width, height):
|
||||||
|
buffer = BytesIO()
|
||||||
|
Image.new("RGBA", (width, height), (0, 0, 255, 128)).save(buffer, format="PNG")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def opened(data):
|
||||||
|
return Image.open(BytesIO(data))
|
||||||
|
|
||||||
|
|
||||||
|
def test_large_photo_is_reduced_keeping_ratio():
|
||||||
|
assert opened(resize_photo(jpeg(1200, 900), 512, 80)).size == (512, 384)
|
||||||
|
|
||||||
|
|
||||||
|
def test_small_photo_is_not_enlarged():
|
||||||
|
assert opened(resize_photo(jpeg(300, 300), 512, 80)).size == (300, 300)
|
||||||
|
|
||||||
|
|
||||||
|
def test_png_with_alpha_becomes_jpeg():
|
||||||
|
assert opened(resize_photo(png_rgba(600, 600), 512, 80)).format == "JPEG"
|
||||||
|
|
||||||
|
|
||||||
|
def test_exif_orientation_applied():
|
||||||
|
exif = Image.Exif()
|
||||||
|
exif[0x0112] = 6 # rotation de 90°
|
||||||
|
out = opened(resize_photo(jpeg(400, 200, exif), 512, 80))
|
||||||
|
assert out.size == (200, 400)
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_has_no_exif():
|
||||||
|
exif = Image.Exif()
|
||||||
|
exif[0x0112] = 6
|
||||||
|
exif[0x010F] = "Fabricant"
|
||||||
|
out = opened(resize_photo(jpeg(400, 200, exif), 512, 80))
|
||||||
|
assert len(out.getexif()) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_data_returns_none():
|
||||||
|
assert resize_photo(b"pas une image", 512, 80) is None
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from ldap2nextcloud.planner import Desired, GuardError, Plan, check_guards, compute_plan
|
||||||
|
from ldap2nextcloud.state import StateRow
|
||||||
|
|
||||||
|
|
||||||
|
def desired(*items):
|
||||||
|
return {href: Desired(href, f"k-{href}", fp) for href, fp in items}
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_contact_is_created():
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {}, {})
|
||||||
|
assert plan.create == ["a.vcf"] and not plan.update and not plan.delete
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_fingerprint_is_updated():
|
||||||
|
state = {"a.vcf": StateRow("a.vcf", "k", "old", "e1")}
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {"a.vcf": "e1"}, state)
|
||||||
|
assert plan.update == ["a.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_server_etag_drift_is_updated():
|
||||||
|
state = {"a.vcf": StateRow("a.vcf", "k", "f1", "e1")}
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {"a.vcf": "e2"}, state)
|
||||||
|
assert plan.update == ["a.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unchanged_contact():
|
||||||
|
state = {"a.vcf": StateRow("a.vcf", "k", "f1", "e1")}
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {"a.vcf": "e1"}, state)
|
||||||
|
assert plan.unchanged == ["a.vcf"]
|
||||||
|
assert not (plan.create or plan.update or plan.verify or plan.delete)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_state_is_verified():
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {"a.vcf": "e1"}, {})
|
||||||
|
assert plan.verify == ["a.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_server_card_is_deleted():
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {"a.vcf": "e1", "ldap2vcard-x.vcf": "e"}, {})
|
||||||
|
assert plan.delete == ["ldap2vcard-x.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_without_server_card_is_recreated():
|
||||||
|
state = {"a.vcf": StateRow("a.vcf", "k", "f1", "e1")}
|
||||||
|
plan = compute_plan(desired(("a.vcf", "f1")), {}, state)
|
||||||
|
assert plan.create == ["a.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lists_are_sorted():
|
||||||
|
plan = compute_plan(desired(("b.vcf", "1"), ("a.vcf", "2")), {}, {})
|
||||||
|
assert plan.create == ["a.vcf", "b.vcf"]
|
||||||
|
|
||||||
|
|
||||||
|
def deletes(n):
|
||||||
|
return Plan(create=[], update=[], verify=[], delete=[f"{i}.vcf" for i in range(n)], unchanged=[])
|
||||||
|
|
||||||
|
|
||||||
|
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():
|
||||||
|
with pytest.raises(GuardError):
|
||||||
|
check_guards(1142, 1270, deletes(128), 0.10, False, False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_deletions_under_ratio_pass():
|
||||||
|
check_guards(1143, 1270, deletes(127), 0.10, False, False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_force_allows_mass_deletion():
|
||||||
|
check_guards(100, 1270, deletes(1170), 0.10, True, False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_initial_allows_mass_deletion():
|
||||||
|
check_guards(1270, 1270, deletes(1270), 0.10, False, True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_empty_server_has_no_ratio_issue():
|
||||||
|
check_guards(10, 0, deletes(0), 0.10, False, False)
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import io
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from ldap2nextcloud.progress import BarProgress, LogProgress, make_progress
|
||||||
|
|
||||||
|
|
||||||
|
def messages(caplog):
|
||||||
|
return [r.getMessage() for r in caplog.records if "Progression" in r.getMessage()]
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_progress_every_100(caplog):
|
||||||
|
progress = LogProgress(every=100)
|
||||||
|
with caplog.at_level(logging.INFO):
|
||||||
|
progress.start(250)
|
||||||
|
for _ in range(250):
|
||||||
|
progress.advance()
|
||||||
|
progress.close()
|
||||||
|
assert messages(caplog) == [
|
||||||
|
"Progression : 100/250", "Progression : 200/250", "Progression : 250/250",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_progress_exact_multiple_has_no_duplicate(caplog):
|
||||||
|
progress = LogProgress(every=100)
|
||||||
|
with caplog.at_level(logging.INFO):
|
||||||
|
progress.start(200)
|
||||||
|
for _ in range(200):
|
||||||
|
progress.advance()
|
||||||
|
progress.close()
|
||||||
|
assert messages(caplog) == ["Progression : 100/200", "Progression : 200/200"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_progress_nothing_to_do_is_silent(caplog):
|
||||||
|
progress = LogProgress()
|
||||||
|
with caplog.at_level(logging.INFO):
|
||||||
|
progress.start(0)
|
||||||
|
progress.close()
|
||||||
|
assert messages(caplog) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_bar_progress_draws_to_stream():
|
||||||
|
stream = io.StringIO()
|
||||||
|
progress = BarProgress(file=stream)
|
||||||
|
progress.start(3)
|
||||||
|
for _ in range(3):
|
||||||
|
progress.advance()
|
||||||
|
progress.close()
|
||||||
|
assert "3/3" in stream.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_bar_progress_keeps_log_messages_visible(caplog):
|
||||||
|
stream = io.StringIO()
|
||||||
|
progress = BarProgress(file=stream)
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
progress.start(2)
|
||||||
|
logging.getLogger("ldap2nextcloud.test").warning("fiche en erreur")
|
||||||
|
progress.advance()
|
||||||
|
progress.close()
|
||||||
|
assert "fiche en erreur" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_progress_depends_on_terminal():
|
||||||
|
assert isinstance(make_progress(interactive=True), BarProgress)
|
||||||
|
assert isinstance(make_progress(interactive=False), LogProgress)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
from ldap2nextcloud.state import StateDB, StateRow
|
||||||
|
|
||||||
|
ROW = StateRow(href="a.vcf", key="alice", fingerprint="f1", etag="e1")
|
||||||
|
|
||||||
|
|
||||||
|
def test_upsert_then_all(tmp_path):
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
db.upsert(ROW)
|
||||||
|
assert db.all() == {"a.vcf": ROW}
|
||||||
|
|
||||||
|
|
||||||
|
def test_upsert_overwrites(tmp_path):
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
db.upsert(ROW)
|
||||||
|
db.upsert(StateRow("a.vcf", "alice", "f2", None))
|
||||||
|
assert db.all()["a.vcf"] == StateRow("a.vcf", "alice", "f2", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_set_etag(tmp_path):
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
db.upsert(StateRow("a.vcf", "alice", "f1", None))
|
||||||
|
db.set_etag("a.vcf", "e9")
|
||||||
|
assert db.all()["a.vcf"].etag == "e9"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete(tmp_path):
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
db.upsert(ROW)
|
||||||
|
db.delete("a.vcf")
|
||||||
|
assert db.all() == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_persists_across_reopen(tmp_path):
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
db.upsert(ROW)
|
||||||
|
with StateDB(tmp_path / "s.sqlite") as db:
|
||||||
|
assert db.all() == {"a.vcf": ROW}
|
||||||
|
|
||||||
|
|
||||||
|
def test_creates_parent_directory(tmp_path):
|
||||||
|
with StateDB(tmp_path / "state" / "deep" / "s.sqlite") as db:
|
||||||
|
db.upsert(ROW)
|
||||||
|
assert (tmp_path / "state" / "deep" / "s.sqlite").is_file()
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import logging
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from ldap2nextcloud.carddav import CardDavError
|
||||||
|
from ldap2nextcloud.config import Settings, load_directions, load_mapping
|
||||||
|
from ldap2nextcloud.model import contact_href
|
||||||
|
from ldap2nextcloud.planner import GuardError
|
||||||
|
from ldap2nextcloud.state import StateDB
|
||||||
|
from ldap2nextcloud.sync import run_sync
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAPPING = load_mapping(ROOT / "mapping.example.yaml")
|
||||||
|
DIRECTIONS = load_directions(ROOT / "directions.example.yaml")
|
||||||
|
|
||||||
|
|
||||||
|
def make_settings(tmp_path):
|
||||||
|
return Settings(
|
||||||
|
ldap_url="ldap://mock", ldap_bind_dn=None, ldap_bind_password=None,
|
||||||
|
ldap_base_dn="dc=x", ldap_filter="(objectClass=*)", ldap_birthday_filter="(x=1)",
|
||||||
|
ldap_group_dns=[], ldap_ca_cert=None, nextcloud_url="https://cloud.test",
|
||||||
|
nextcloud_user="u", nextcloud_app_password="p", nextcloud_addressbook="b",
|
||||||
|
state_db=tmp_path / "state" / "sync.sqlite", mapping_file=Path("m"),
|
||||||
|
directions_file=Path("d"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def photo():
|
||||||
|
buffer = BytesIO()
|
||||||
|
Image.new("RGB", (800, 800), (10, 20, 30)).save(buffer, format="JPEG")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
PEOPLE = [
|
||||||
|
("omalmare", "Oscar", "MALMARE", "9052", "620", "19680615000000Z"),
|
||||||
|
("cbarssac", "Cédric", "BARSSAC", "4136", "620", "19660825000000Z"),
|
||||||
|
("lvernet", "Lucie", "VERNET", "7781", "210", "19790102000000Z"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def raw(uid, given, sn, phone, direction, birth):
|
||||||
|
return {
|
||||||
|
"uid": [uid.encode()], "givenName": [given.encode()], "sn": [sn.encode()],
|
||||||
|
"cn": [f"{sn} {given}".encode()], "mail": [f"{uid}@example.org".encode()],
|
||||||
|
"telephoneNumber": [phone.encode()], "usrDirectionId": [direction.encode()],
|
||||||
|
"usrDateNaissance": [birth.encode()], "jpegPhoto": [photo()],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSource:
|
||||||
|
def __init__(self, people=PEOPLE):
|
||||||
|
self.entries = [raw(*p) for p in people]
|
||||||
|
|
||||||
|
def fetch_entries(self, attributes):
|
||||||
|
return self.entries
|
||||||
|
|
||||||
|
def fetch_birthday_keys(self, key_attr):
|
||||||
|
return {"omalmare"}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, cards=None, return_etag=True):
|
||||||
|
self.cards = dict(cards or {}) # href -> (etag, text)
|
||||||
|
self.counter = 0
|
||||||
|
self.puts = []
|
||||||
|
self.deletes = []
|
||||||
|
self.fail = set()
|
||||||
|
self.return_etag = return_etag
|
||||||
|
|
||||||
|
def list_etags(self):
|
||||||
|
return {href: etag for href, (etag, _) in self.cards.items()}
|
||||||
|
|
||||||
|
def multiget(self, hrefs):
|
||||||
|
return {h: self.cards[h][1] for h in hrefs if h in self.cards}
|
||||||
|
|
||||||
|
def put(self, href, vcard, etag):
|
||||||
|
if href in self.fail:
|
||||||
|
raise CardDavError("refus", 412)
|
||||||
|
if etag is not None and self.cards.get(href, (None,))[0] != etag:
|
||||||
|
raise CardDavError("etag", 412)
|
||||||
|
self.counter += 1
|
||||||
|
new = f"e{self.counter}"
|
||||||
|
self.cards[href] = (new, vcard)
|
||||||
|
self.puts.append((href, etag))
|
||||||
|
return new if self.return_etag else None
|
||||||
|
|
||||||
|
def delete(self, href, etag):
|
||||||
|
self.cards.pop(href, None)
|
||||||
|
self.deletes.append(href)
|
||||||
|
|
||||||
|
|
||||||
|
def run(tmp_path, client, source=None, **kwargs):
|
||||||
|
settings = make_settings(tmp_path)
|
||||||
|
with StateDB(settings.state_db) as state:
|
||||||
|
return run_sync(settings, MAPPING, DIRECTIONS, source or FakeSource(), client, state, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_run_creates_all_and_purges_legacy(tmp_path):
|
||||||
|
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
|
||||||
|
summary = run(tmp_path, client, initial=True)
|
||||||
|
assert (summary.created, summary.deleted, summary.errors) == (3, 1, 0)
|
||||||
|
with StateDB(make_settings(tmp_path).state_db) as state:
|
||||||
|
rows = state.all()
|
||||||
|
assert len(rows) == 3 and all(r.etag for r in rows.values())
|
||||||
|
assert "ldap2vcard-old.vcf" not in client.cards
|
||||||
|
|
||||||
|
|
||||||
|
def test_birthday_only_for_selected_keys(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
run(tmp_path, client)
|
||||||
|
assert "BDAY:1968-06-15" in client.cards[contact_href("omalmare")][1]
|
||||||
|
assert "BDAY" not in client.cards[contact_href("lvernet")][1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_photo_is_resized(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
run(tmp_path, client)
|
||||||
|
import vobject
|
||||||
|
card = vobject.readOne(client.cards[contact_href("omalmare")][1])
|
||||||
|
assert Image.open(BytesIO(card.photo.value)).size == (512, 512)
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_run_without_change_does_nothing(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
run(tmp_path, client)
|
||||||
|
client.puts.clear()
|
||||||
|
summary = run(tmp_path, client)
|
||||||
|
assert summary.unchanged == 3 and not client.puts and not client.deletes
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_entry_is_updated_only(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
run(tmp_path, client)
|
||||||
|
client.puts.clear()
|
||||||
|
source = FakeSource()
|
||||||
|
source.entries[2]["usrDirectionId"] = [b"620"]
|
||||||
|
summary = run(tmp_path, client, source)
|
||||||
|
assert summary.updated == 1 and summary.unchanged == 2
|
||||||
|
href, etag = client.puts[0]
|
||||||
|
assert href == contact_href("lvernet") and etag is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_lost_state_rebuilds_without_put(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
run(tmp_path, client)
|
||||||
|
make_settings(tmp_path).state_db.unlink()
|
||||||
|
client.puts.clear()
|
||||||
|
summary = run(tmp_path, client)
|
||||||
|
assert summary.verified == 3 and not client.puts
|
||||||
|
with StateDB(make_settings(tmp_path).state_db) as state:
|
||||||
|
assert len(state.all()) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_lost_state_with_stale_card_is_updated(tmp_path):
|
||||||
|
href = contact_href("omalmare")
|
||||||
|
client = FakeClient({href: ("e0", "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:x\r\nN:x;;;;\r\nEND:VCARD\r\n")})
|
||||||
|
summary = run(tmp_path, client)
|
||||||
|
assert summary.updated == 1 and summary.created == 2
|
||||||
|
assert (href, "e0") in client.puts
|
||||||
|
|
||||||
|
|
||||||
|
def test_dry_run_writes_nothing(tmp_path):
|
||||||
|
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
|
||||||
|
summary = run(tmp_path, client, dry_run=True, initial=True)
|
||||||
|
assert summary.created == 3 and summary.deleted == 1
|
||||||
|
assert not client.puts and not client.deletes
|
||||||
|
with StateDB(make_settings(tmp_path).state_db) as state:
|
||||||
|
assert state.all() == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_put_error_is_counted_and_not_stored(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
client.fail.add(contact_href("cbarssac"))
|
||||||
|
summary = run(tmp_path, client)
|
||||||
|
assert summary.errors == 1 and summary.created == 2
|
||||||
|
with StateDB(make_settings(tmp_path).state_db) as state:
|
||||||
|
assert contact_href("cbarssac") not in state.all()
|
||||||
|
|
||||||
|
|
||||||
|
def test_guard_error_before_any_write(tmp_path):
|
||||||
|
client = FakeClient({f"old{i}.vcf": ("x", "") for i in range(1270)})
|
||||||
|
with pytest.raises(GuardError):
|
||||||
|
run(tmp_path, client)
|
||||||
|
assert not client.puts and not client.deletes
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_ldap_aborts(tmp_path):
|
||||||
|
client = FakeClient()
|
||||||
|
with pytest.raises(GuardError):
|
||||||
|
run(tmp_path, client, FakeSource(people=[]), force=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_etag_in_put_response_is_refreshed(tmp_path):
|
||||||
|
client = FakeClient(return_etag=False)
|
||||||
|
run(tmp_path, client)
|
||||||
|
with StateDB(make_settings(tmp_path).state_db) as state:
|
||||||
|
rows = state.all()
|
||||||
|
assert all(rows[h].etag == client.cards[h][0] for h in rows)
|
||||||
|
|
||||||
|
|
||||||
|
def test_logs_contain_no_personal_data(tmp_path, caplog):
|
||||||
|
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
|
||||||
|
client.fail.add(contact_href("cbarssac"))
|
||||||
|
with caplog.at_level(logging.DEBUG):
|
||||||
|
run(tmp_path, client, initial=True)
|
||||||
|
for _, given, sn, phone, _, birth in PEOPLE:
|
||||||
|
for secret in (given, sn, phone, birth[:8], "example.org"):
|
||||||
|
assert secret not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_unexpected_photo_failure_does_not_stop_the_run(tmp_path, monkeypatch):
|
||||||
|
from ldap2nextcloud import sync
|
||||||
|
|
||||||
|
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
def flaky(data, size, quality):
|
||||||
|
calls["n"] += 1
|
||||||
|
if calls["n"] == 1:
|
||||||
|
raise RuntimeError("bombe")
|
||||||
|
return b"\xff\xd8ok"
|
||||||
|
|
||||||
|
monkeypatch.setattr(sync, "resize_photo", flaky)
|
||||||
|
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
|
||||||
|
summary = run(tmp_path, client, initial=True)
|
||||||
|
assert summary.errors == 1 and summary.created == 2 and summary.deleted == 1
|
||||||
|
|
||||||
|
|
||||||
|
class RecordingProgress:
|
||||||
|
def __init__(self):
|
||||||
|
self.total = None
|
||||||
|
self.advanced = 0
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
def start(self, total):
|
||||||
|
self.total = total
|
||||||
|
|
||||||
|
def advance(self):
|
||||||
|
self.advanced += 1
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def test_progress_covers_every_write_including_errors(tmp_path):
|
||||||
|
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
|
||||||
|
client.fail.add(contact_href("cbarssac"))
|
||||||
|
progress = RecordingProgress()
|
||||||
|
run(tmp_path, client, initial=True, progress=progress)
|
||||||
|
assert progress.total == 4 and progress.advanced == 4 and progress.closed
|
||||||
|
|
||||||
|
|
||||||
|
def test_dry_run_does_not_start_progress(tmp_path):
|
||||||
|
progress = RecordingProgress()
|
||||||
|
run(tmp_path, FakeClient(), dry_run=True, progress=progress)
|
||||||
|
assert progress.total is None
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
from datetime import date, datetime, timezone
|
||||||
|
|
||||||
|
import vobject
|
||||||
|
|
||||||
|
from ldap2nextcloud.model import Contact, Email, Phone, contact_uid
|
||||||
|
from ldap2nextcloud.vcard import read_sync_hash, render_vcard
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 17, 8, 30, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
FULL = Contact(
|
||||||
|
key="omalmare",
|
||||||
|
given_name="Oscar",
|
||||||
|
family_name="MALMARE",
|
||||||
|
full_name="MALMARE Oscar",
|
||||||
|
organization="Exemple",
|
||||||
|
title="Ingénieur",
|
||||||
|
emails=(Email("o.malmare@example.org", "work", True),),
|
||||||
|
phones=(Phone("+33123459052", "work"),),
|
||||||
|
category="Direction des systèmes d'information",
|
||||||
|
birthday=date(1968, 6, 15),
|
||||||
|
photo=b"source",
|
||||||
|
)
|
||||||
|
|
||||||
|
MINIMAL = Contact(
|
||||||
|
key="x", given_name="A", family_name="B", full_name="A B", organization=None,
|
||||||
|
title=None, emails=(), phones=(), category=None, birthday=None, photo=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
LEGACY = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Ancien\r\nN:Ancien;;;;\r\nEND:VCARD\r\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_contains_expected_properties():
|
||||||
|
card = vobject.readOne(render_vcard(FULL, b"\xff\xd8jpeg", "abc", NOW))
|
||||||
|
assert card.version.value == "3.0"
|
||||||
|
assert card.uid.value == contact_uid("omalmare")
|
||||||
|
assert card.n.value.family == "MALMARE" and card.n.value.given == "Oscar"
|
||||||
|
assert card.fn.value == "MALMARE Oscar"
|
||||||
|
assert card.org.value == ["Exemple"]
|
||||||
|
assert card.title.value == "Ingénieur"
|
||||||
|
assert card.tel.value == "+33123459052"
|
||||||
|
assert {t.upper() for t in card.tel.params["TYPE"]} == {"VOICE", "WORK"}
|
||||||
|
assert card.email.value == "o.malmare@example.org"
|
||||||
|
assert {t.upper() for t in card.email.params["TYPE"]} == {"INTERNET", "WORK", "PREF"}
|
||||||
|
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"
|
||||||
|
assert card.rev.value == "20261117T083000Z"
|
||||||
|
assert card.prodid.value == "-//ldap2nextcloud//FR"
|
||||||
|
|
||||||
|
|
||||||
|
def test_optional_fields_omitted():
|
||||||
|
text = render_vcard(MINIMAL, None, "abc", NOW)
|
||||||
|
for prop in ("TITLE", "TEL", "EMAIL", "CATEGORIES", "BDAY", "PHOTO", "ORG"):
|
||||||
|
assert f"\r\n{prop}" not in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_legacy_properties():
|
||||||
|
text = render_vcard(FULL, 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():
|
||||||
|
long_name = "Élodie-Françoise " * 8
|
||||||
|
contact = Contact(**{**FULL.__dict__, "full_name": long_name.strip()})
|
||||||
|
text = render_vcard(contact, None, "abc", NOW)
|
||||||
|
assert vobject.readOne(text).fn.value == long_name.strip()
|
||||||
|
assert all(len(line.encode("utf-8")) <= 75 for line in text.split("\r\n"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_crlf_line_endings():
|
||||||
|
text = render_vcard(FULL, b"\xff\xd8jpeg", "abc", NOW)
|
||||||
|
assert "\r\n" in text
|
||||||
|
assert "\n" not in text.replace("\r\n", "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_category_with_comma_stays_single_group():
|
||||||
|
contact = Contact(**{**FULL.__dict__, "category": "Recherche, Innovation"})
|
||||||
|
card = vobject.readOne(render_vcard(contact, None, "abc", NOW))
|
||||||
|
assert card.categories.value == ["Recherche, Innovation"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_sync_hash_roundtrip():
|
||||||
|
assert read_sync_hash(render_vcard(FULL, None, "abc", NOW)) == "abc"
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_sync_hash_absent():
|
||||||
|
assert read_sync_hash(LEGACY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_sync_hash_unreadable():
|
||||||
|
assert read_sync_hash("pas une vcard") is None
|
||||||
Reference in new issue
Block a user