🤖 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:
zeguiguiandClaude Opus 5.5 committed 2026-11-17 09:47:31 +01:00
commit f6a01b85e1
42 files changed
+5538

No files matched your search

View File
Whitespace-only changes.
+39
View File
@@ -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
+159
View File
@@ -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&#13;\nFN:A&#13;\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"
+127
View File
@@ -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)
+113
View File
@@ -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"
+96
View File
@@ -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
+113
View File
@@ -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))
+53
View File
@@ -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)
+56
View File
@@ -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
+83
View File
@@ -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)
+64
View File
@@ -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)
+43
View File
@@ -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()
+259
View 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
+92
View File
@@ -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