Skip to content

Commit ddf5612

Browse files
committed
fix: AD username normalization, LDAP filter escaping, and auth error handling
1 parent 391f383 commit ddf5612

6 files changed

Lines changed: 117 additions & 9 deletions

File tree

‎fastapi_ldap/auth.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,8 @@ async def protected_route(user: LDAPUser = Depends(get_current_user)):
188188

189189
return user
190190

191+
except HTTPException:
192+
raise
191193
except LDAPConnectionError as e:
192194
logger.error("LDAP connection error", exc_info=True)
193195
raise HTTPException(

‎fastapi_ldap/client.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
Tls,
1111
)
1212
from ldap3.core.exceptions import LDAPException, LDAPSocketOpenError # type: ignore[import-untyped]
13+
from ldap3.utils.conv import escape_filter_chars # type: ignore[import-untyped]
1314

1415
from fastapi_ldap.config import LDAPSettings
1516
from fastapi_ldap.exceptions import (
@@ -20,6 +21,15 @@
2021
logger = logging.getLogger(__name__)
2122

2223

24+
def _normalize_username(username: str) -> str:
25+
"""Strip UPN or NetBIOS prefix for sAMAccountName-style searches."""
26+
if "@" in username:
27+
return username.split("@", 1)[0]
28+
if "\\" in username:
29+
return username.split("\\", 1)[-1]
30+
return username
31+
32+
2333
class LDAPClient:
2434
"""Async LDAP client with connection pooling and retry logic.
2535
@@ -248,12 +258,14 @@ async def authenticate(
248258
if not username or not password:
249259
return None
250260

261+
sam = _normalize_username(username)
262+
251263
try:
252264
async with self.connection() as conn:
253265
loop = asyncio.get_event_loop()
254266

255267
search_filter = self.settings.user_search_filter.format(
256-
username=username
268+
username=escape_filter_chars(sam)
257269
)
258270
search_base = self.settings.user_search_base or self.settings.ldap_base_dn
259271

@@ -287,7 +299,7 @@ async def authenticate(
287299
}
288300

289301
except LDAPException:
290-
logger.debug(f"Authentication failed for user: {username}")
302+
logger.info(f"Authentication failed for user: {username}")
291303
return None
292304

293305
except Exception as e:
@@ -309,10 +321,11 @@ async def get_user_groups(self, user_dn: str, username: str = "") -> list[str]:
309321
if not username:
310322
username = user_dn.split(",")[0].split("=")[-1]
311323

312-
# Format search filter with both user_dn and username
324+
group_username = _normalize_username(username) if username else username
325+
313326
search_filter = self.settings.group_search_filter.format(
314-
user_dn=user_dn,
315-
username=username
327+
user_dn=escape_filter_chars(user_dn),
328+
username=escape_filter_chars(group_username),
316329
)
317330
search_base = (
318331
self.settings.group_search_base or self.settings.ldap_base_dn

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "fastapi-ldap"
7-
version = "0.1.0"
7+
version = "0.1.1"
88
description = "Production-ready LDAP authentication and authorization for FastAPI"
99
readme = "README.md"
1010
requires-python = ">=3.10"

‎tests/test_auth.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from unittest.mock import AsyncMock, Mock, patch
23

34
import pytest
@@ -167,6 +168,26 @@ async def test_get_current_user_authentication_failed(self, ldap_settings):
167168

168169
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
169170

171+
@pytest.mark.asyncio
172+
async def test_get_current_user_401_not_logged_as_unexpected(
173+
self, ldap_settings, caplog
174+
):
175+
credentials = HTTPBasicCredentials(username="testuser", password="wrongpass")
176+
177+
mock_client = AsyncMock(spec=LDAPClient)
178+
mock_client.authenticate = AsyncMock(return_value=None)
179+
180+
caplog.set_level(logging.ERROR)
181+
182+
with patch("fastapi_ldap.auth._client", mock_client), patch(
183+
"fastapi_ldap.auth._cache", None
184+
), patch("fastapi_ldap.auth._settings", ldap_settings):
185+
with pytest.raises(HTTPException) as exc_info:
186+
await get_current_user(credentials)
187+
188+
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
189+
assert "Unexpected authentication error" not in caplog.text
190+
170191
@pytest.mark.asyncio
171192
async def test_get_current_user_client_not_initialized(self, ldap_settings):
172193
credentials = HTTPBasicCredentials(username="testuser", password="password")

‎tests/test_client.py‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from ldap3 import Connection, Server
66
from ldap3.core.exceptions import LDAPException, LDAPSocketOpenError
77

8-
from fastapi_ldap.client import LDAPClient
8+
from fastapi_ldap.client import LDAPClient, _normalize_username
99
from fastapi_ldap.config import LDAPSettings
1010
from fastapi_ldap.exceptions import LDAPConnectionError, LDAPError
1111

@@ -183,6 +183,68 @@ async def test_authenticate_empty_credentials(self, ldap_settings):
183183
result = await client.authenticate("", "pass")
184184
assert result is None
185185

186+
def test_normalize_username(self):
187+
assert _normalize_username("jsmith@example.com") == "jsmith"
188+
assert _normalize_username("EXAMPLE\\jsmith") == "jsmith"
189+
assert _normalize_username("jsmith") == "jsmith"
190+
191+
@pytest.mark.asyncio
192+
async def test_authenticate_normalizes_upn_for_search(self, ldap_settings):
193+
ldap_settings.user_search_filter = "(sAMAccountName={username})"
194+
client = LDAPClient(ldap_settings)
195+
mock_conn = Mock(spec=Connection)
196+
mock_conn.bound = True
197+
mock_conn.closed = False
198+
mock_conn.entries = []
199+
mock_conn.search = Mock(return_value=True)
200+
201+
with patch.object(client, "connection") as mock_ctx:
202+
mock_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_conn)
203+
mock_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
204+
205+
await client.authenticate("jsmith@example.com", "password")
206+
207+
search_filter = mock_conn.search.call_args[0][1]
208+
assert search_filter == "(sAMAccountName=jsmith)"
209+
210+
@pytest.mark.asyncio
211+
async def test_authenticate_normalizes_netbios_for_search(self, ldap_settings):
212+
ldap_settings.user_search_filter = "(sAMAccountName={username})"
213+
client = LDAPClient(ldap_settings)
214+
mock_conn = Mock(spec=Connection)
215+
mock_conn.bound = True
216+
mock_conn.closed = False
217+
mock_conn.entries = []
218+
mock_conn.search = Mock(return_value=True)
219+
220+
with patch.object(client, "connection") as mock_ctx:
221+
mock_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_conn)
222+
mock_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
223+
224+
await client.authenticate("EXAMPLE\\jsmith", "password")
225+
226+
search_filter = mock_conn.search.call_args[0][1]
227+
assert search_filter == "(sAMAccountName=jsmith)"
228+
229+
@pytest.mark.asyncio
230+
async def test_authenticate_escapes_filter_special_chars(self, ldap_settings):
231+
ldap_settings.user_search_filter = "(sAMAccountName={username})"
232+
client = LDAPClient(ldap_settings)
233+
mock_conn = Mock(spec=Connection)
234+
mock_conn.bound = True
235+
mock_conn.closed = False
236+
mock_conn.entries = []
237+
mock_conn.search = Mock(return_value=True)
238+
239+
with patch.object(client, "connection") as mock_ctx:
240+
mock_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_conn)
241+
mock_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
242+
243+
await client.authenticate("user*@example.com", "password")
244+
245+
search_filter = mock_conn.search.call_args[0][1]
246+
assert search_filter == "(sAMAccountName=user\\2a)"
247+
186248
@pytest.mark.asyncio
187249
async def test_get_user_groups_success(self, ldap_settings):
188250
client = LDAPClient(ldap_settings)

‎tests/test_config.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,24 +26,34 @@ def test_defaults(self):
2626
assert settings.pool_size == 10
2727
assert settings.cache_enabled is False
2828

29-
def test_anonymous_bind(self):
29+
def test_anonymous_bind(self, monkeypatch):
30+
monkeypatch.delenv("LDAP_BIND_DN", raising=False)
31+
monkeypatch.delenv("LDAP_BIND_PASSWORD", raising=False)
32+
3033
settings = LDAPSettings(
3134
ldap_url="ldaps://ldap.example.com:636",
3235
ldap_base_dn="dc=example,dc=com",
3336
allow_anonymous=True,
37+
bind_dn=None,
38+
bind_password=None,
39+
_env_file="",
3440
)
3541
assert settings.allow_anonymous is True
3642
assert settings.bind_dn is None
3743
assert settings.bind_password is None
3844

39-
def test_require_bind_credentials(self):
45+
def test_require_bind_credentials(self, monkeypatch):
46+
monkeypatch.delenv("LDAP_BIND_DN", raising=False)
47+
monkeypatch.delenv("LDAP_BIND_PASSWORD", raising=False)
48+
4049
with pytest.raises(ValueError, match="bind_dn and bind_password are required"):
4150
LDAPSettings(
4251
ldap_url="ldaps://ldap.example.com:636",
4352
ldap_base_dn="dc=example,dc=com",
4453
allow_anonymous=False,
4554
bind_dn=None,
4655
bind_password=None,
56+
_env_file="",
4757
)
4858

4959
def test_ldaps_url(self):

0 commit comments

Comments
 (0)