test_auth_api.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. """Integration tests for Authentication API endpoints.
  2. Tests the full request/response cycle for /api/v1/auth/ and /api/v1/users/ endpoints.
  3. """
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestAuthStatusAPI:
  7. """Integration tests for /api/v1/auth/status endpoint."""
  8. @pytest.mark.asyncio
  9. @pytest.mark.integration
  10. async def test_get_auth_status_disabled(self, async_client: AsyncClient):
  11. """Verify auth status returns disabled when not configured."""
  12. response = await async_client.get("/api/v1/auth/status")
  13. assert response.status_code == 200
  14. result = response.json()
  15. assert "auth_enabled" in result
  16. assert result["auth_enabled"] is False
  17. assert result["requires_setup"] is True
  18. class TestAuthSetupAPI:
  19. """Integration tests for /api/v1/auth/setup endpoint."""
  20. @pytest.mark.asyncio
  21. @pytest.mark.integration
  22. async def test_setup_auth_disabled(self, async_client: AsyncClient):
  23. """Verify auth can be set up with auth disabled (no password required)."""
  24. response = await async_client.post(
  25. "/api/v1/auth/setup",
  26. json={"auth_enabled": False},
  27. )
  28. assert response.status_code == 200
  29. result = response.json()
  30. assert result["auth_enabled"] is False
  31. assert result["admin_created"] is False
  32. @pytest.mark.asyncio
  33. @pytest.mark.integration
  34. async def test_setup_auth_enabled_requires_credentials(self, async_client: AsyncClient):
  35. """Verify enabling auth requires admin username and password."""
  36. response = await async_client.post(
  37. "/api/v1/auth/setup",
  38. json={"auth_enabled": True},
  39. )
  40. assert response.status_code == 400
  41. assert "Admin username and password are required" in response.json()["detail"]
  42. @pytest.mark.asyncio
  43. @pytest.mark.integration
  44. async def test_setup_auth_enabled_with_credentials(self, async_client: AsyncClient):
  45. """Verify auth can be enabled with admin credentials."""
  46. response = await async_client.post(
  47. "/api/v1/auth/setup",
  48. json={
  49. "auth_enabled": True,
  50. "admin_username": "testadmin",
  51. "admin_password": "TestPass1!",
  52. },
  53. )
  54. assert response.status_code == 200
  55. result = response.json()
  56. assert result["auth_enabled"] is True
  57. assert result["admin_created"] is True
  58. @pytest.mark.asyncio
  59. @pytest.mark.integration
  60. async def test_setup_weak_password_rejected_when_creating_new_admin(self, async_client: AsyncClient):
  61. """Complexity is enforced only when a new admin is being created."""
  62. response = await async_client.post(
  63. "/api/v1/auth/setup",
  64. json={
  65. "auth_enabled": True,
  66. "admin_username": "weakpw_admin",
  67. "admin_password": "NoSpecial1",
  68. },
  69. )
  70. assert response.status_code == 400
  71. assert "special character" in response.json()["detail"].lower()
  72. @pytest.mark.asyncio
  73. @pytest.mark.integration
  74. async def test_setup_reenable_with_existing_admin_ignores_password(self, async_client: AsyncClient, db_session):
  75. """Re-enabling auth when an admin already exists must not reject the placeholder
  76. password the frontend still sends. Regression for the LDAP re-enable flow that
  77. previously 422'd because the Pydantic schema enforced complexity unconditionally.
  78. """
  79. from backend.app.core.auth import get_password_hash
  80. from backend.app.models.user import User
  81. existing = User(
  82. username="existing_admin",
  83. # pragma: allowlist secret — test fixture only, not a real credential
  84. password_hash=get_password_hash("DoesNotMatter1!"), # noqa: S106
  85. role="admin",
  86. is_active=True,
  87. )
  88. db_session.add(existing)
  89. await db_session.commit()
  90. response = await async_client.post(
  91. "/api/v1/auth/setup",
  92. json={
  93. "auth_enabled": True,
  94. "admin_username": "irrelevant",
  95. "admin_password": "NoSpecial1",
  96. },
  97. )
  98. assert response.status_code == 200
  99. result = response.json()
  100. assert result["auth_enabled"] is True
  101. assert result["admin_created"] is False
  102. class TestAuthLoginAPI:
  103. """Integration tests for /api/v1/auth/login endpoint."""
  104. @pytest.mark.asyncio
  105. @pytest.mark.integration
  106. async def test_login_auth_disabled(self, async_client: AsyncClient):
  107. """Verify login fails when auth is not enabled."""
  108. response = await async_client.post(
  109. "/api/v1/auth/login",
  110. json={"username": "admin", "password": "password"},
  111. )
  112. assert response.status_code == 400
  113. assert "Authentication is not enabled" in response.json()["detail"]
  114. @pytest.mark.asyncio
  115. @pytest.mark.integration
  116. async def test_login_success(self, async_client: AsyncClient):
  117. """Verify login succeeds with valid credentials after setup."""
  118. # First enable auth
  119. await async_client.post(
  120. "/api/v1/auth/setup",
  121. json={
  122. "auth_enabled": True,
  123. "admin_username": "logintest",
  124. "admin_password": "LoginPass1!",
  125. },
  126. )
  127. # Now login
  128. response = await async_client.post(
  129. "/api/v1/auth/login",
  130. json={"username": "logintest", "password": "LoginPass1!"},
  131. )
  132. assert response.status_code == 200
  133. result = response.json()
  134. assert "access_token" in result
  135. assert result["token_type"] == "bearer"
  136. assert result["user"]["username"] == "logintest"
  137. assert result["user"]["role"] == "admin"
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_login_invalid_credentials(self, async_client: AsyncClient):
  141. """Verify login fails with invalid credentials."""
  142. # First enable auth
  143. await async_client.post(
  144. "/api/v1/auth/setup",
  145. json={
  146. "auth_enabled": True,
  147. "admin_username": "invalidtest",
  148. "admin_password": "CorrectPass1!",
  149. },
  150. )
  151. # Try login with wrong password
  152. response = await async_client.post(
  153. "/api/v1/auth/login",
  154. json={"username": "invalidtest", "password": "wrongpassword"},
  155. )
  156. assert response.status_code == 401
  157. assert "Incorrect username or password" in response.json()["detail"]
  158. class TestAuthMeAPI:
  159. """Integration tests for /api/v1/auth/me endpoint."""
  160. @pytest.mark.asyncio
  161. @pytest.mark.integration
  162. async def test_me_without_token(self, async_client: AsyncClient):
  163. """Verify /me fails without authentication token."""
  164. response = await async_client.get("/api/v1/auth/me")
  165. assert response.status_code == 401
  166. @pytest.mark.asyncio
  167. @pytest.mark.integration
  168. async def test_me_with_valid_token(self, async_client: AsyncClient):
  169. """Verify /me returns user info with valid token."""
  170. # Setup and login
  171. await async_client.post(
  172. "/api/v1/auth/setup",
  173. json={
  174. "auth_enabled": True,
  175. "admin_username": "metest",
  176. "admin_password": "MePass1!",
  177. },
  178. )
  179. login_response = await async_client.post(
  180. "/api/v1/auth/login",
  181. json={"username": "metest", "password": "MePass1!"},
  182. )
  183. token = login_response.json()["access_token"]
  184. # Get current user
  185. response = await async_client.get(
  186. "/api/v1/auth/me",
  187. headers={"Authorization": f"Bearer {token}"},
  188. )
  189. assert response.status_code == 200
  190. result = response.json()
  191. assert result["username"] == "metest"
  192. assert result["role"] == "admin"
  193. assert result["is_active"] is True
  194. @pytest.mark.asyncio
  195. @pytest.mark.integration
  196. async def test_me_with_api_key_bearer(self, async_client: AsyncClient, db_session):
  197. """Verify /me returns synthetic admin user when using API key via Bearer token."""
  198. from backend.app.core.auth import generate_api_key
  199. from backend.app.models.api_key import APIKey
  200. # Create an API key directly in the database
  201. full_key, key_hash, key_prefix = generate_api_key()
  202. api_key = APIKey(name="test-kiosk", key_hash=key_hash, key_prefix=key_prefix, enabled=True)
  203. db_session.add(api_key)
  204. await db_session.commit()
  205. # Call /me with the API key as Bearer token
  206. response = await async_client.get(
  207. "/api/v1/auth/me",
  208. headers={"Authorization": f"Bearer {full_key}"},
  209. )
  210. assert response.status_code == 200
  211. result = response.json()
  212. assert result["id"] == 0
  213. assert result["username"].startswith("api-key:")
  214. assert result["role"] == "admin"
  215. assert result["is_admin"] is True
  216. assert result["is_active"] is True
  217. assert len(result["permissions"]) > 0
  218. @pytest.mark.asyncio
  219. @pytest.mark.integration
  220. async def test_me_with_api_key_header(self, async_client: AsyncClient, db_session):
  221. """Verify /me returns synthetic admin user when using X-API-Key header."""
  222. from backend.app.core.auth import generate_api_key
  223. from backend.app.models.api_key import APIKey
  224. full_key, key_hash, key_prefix = generate_api_key()
  225. api_key = APIKey(name="test-kiosk-header", key_hash=key_hash, key_prefix=key_prefix, enabled=True)
  226. db_session.add(api_key)
  227. await db_session.commit()
  228. response = await async_client.get(
  229. "/api/v1/auth/me",
  230. headers={"X-API-Key": full_key},
  231. )
  232. assert response.status_code == 200
  233. result = response.json()
  234. assert result["id"] == 0
  235. assert result["username"].startswith("api-key:")
  236. assert result["is_admin"] is True
  237. @pytest.mark.asyncio
  238. @pytest.mark.integration
  239. async def test_me_with_invalid_api_key(self, async_client: AsyncClient):
  240. """Verify /me rejects invalid API key."""
  241. response = await async_client.get(
  242. "/api/v1/auth/me",
  243. headers={"Authorization": "Bearer bb_invalid_key_value"},
  244. )
  245. assert response.status_code == 401
  246. class TestUsersAPI:
  247. """Integration tests for /api/v1/users/ endpoints."""
  248. @pytest.fixture
  249. async def auth_token(self, async_client: AsyncClient):
  250. """Setup auth and return admin token."""
  251. await async_client.post(
  252. "/api/v1/auth/setup",
  253. json={
  254. "auth_enabled": True,
  255. "admin_username": "usersadmin",
  256. "admin_password": "AdminPass1!",
  257. },
  258. )
  259. login_response = await async_client.post(
  260. "/api/v1/auth/login",
  261. json={"username": "usersadmin", "password": "AdminPass1!"},
  262. )
  263. return login_response.json()["access_token"]
  264. @pytest.mark.asyncio
  265. @pytest.mark.integration
  266. async def test_list_users_requires_auth(self, async_client: AsyncClient):
  267. """Verify listing users requires authentication when auth is enabled."""
  268. # First enable auth
  269. await async_client.post(
  270. "/api/v1/auth/setup",
  271. json={
  272. "auth_enabled": True,
  273. "admin_username": "authreqadmin",
  274. "admin_password": "AdminPass1!",
  275. },
  276. )
  277. # Now try to list users without a token
  278. response = await async_client.get("/api/v1/users/")
  279. assert response.status_code == 401
  280. @pytest.mark.asyncio
  281. @pytest.mark.integration
  282. async def test_list_users_as_admin(self, async_client: AsyncClient, auth_token: str):
  283. """Verify admin can list users."""
  284. response = await async_client.get(
  285. "/api/v1/users/",
  286. headers={"Authorization": f"Bearer {auth_token}"},
  287. )
  288. assert response.status_code == 200
  289. result = response.json()
  290. assert isinstance(result, list)
  291. assert len(result) >= 1 # At least the admin user
  292. @pytest.mark.asyncio
  293. @pytest.mark.integration
  294. async def test_create_user(self, async_client: AsyncClient, auth_token: str):
  295. """Verify admin can create a new user."""
  296. response = await async_client.post(
  297. "/api/v1/users/",
  298. headers={"Authorization": f"Bearer {auth_token}"},
  299. json={
  300. "username": "newuser",
  301. "password": "Newuserpass1!",
  302. "role": "user",
  303. },
  304. )
  305. assert response.status_code == 201
  306. result = response.json()
  307. assert result["username"] == "newuser"
  308. assert result["role"] == "user"
  309. assert result["is_active"] is True
  310. @pytest.mark.asyncio
  311. @pytest.mark.integration
  312. async def test_create_user_duplicate_username(self, async_client: AsyncClient, auth_token: str):
  313. """Verify creating user with duplicate username fails."""
  314. # Create first user
  315. await async_client.post(
  316. "/api/v1/users/",
  317. headers={"Authorization": f"Bearer {auth_token}"},
  318. json={
  319. "username": "duplicateuser",
  320. "password": "Password123!",
  321. "role": "user",
  322. },
  323. )
  324. # Try to create duplicate
  325. response = await async_client.post(
  326. "/api/v1/users/",
  327. headers={"Authorization": f"Bearer {auth_token}"},
  328. json={
  329. "username": "duplicateuser",
  330. "password": "Password456!",
  331. "role": "user",
  332. },
  333. )
  334. assert response.status_code == 400
  335. assert "Username already exists" in response.json()["detail"]
  336. @pytest.mark.asyncio
  337. @pytest.mark.integration
  338. async def test_update_user(self, async_client: AsyncClient, auth_token: str):
  339. """Verify admin can update a user."""
  340. # Create user
  341. create_response = await async_client.post(
  342. "/api/v1/users/",
  343. headers={"Authorization": f"Bearer {auth_token}"},
  344. json={
  345. "username": "updateuser",
  346. "password": "Password123!",
  347. "role": "user",
  348. },
  349. )
  350. user_id = create_response.json()["id"]
  351. # Update user
  352. response = await async_client.patch(
  353. f"/api/v1/users/{user_id}",
  354. headers={"Authorization": f"Bearer {auth_token}"},
  355. json={"role": "admin"},
  356. )
  357. assert response.status_code == 200
  358. assert response.json()["role"] == "admin"
  359. @pytest.mark.asyncio
  360. @pytest.mark.integration
  361. async def test_delete_user(self, async_client: AsyncClient, auth_token: str, db_session):
  362. """Verify admin can delete a user and that all auth-table side effects cascade.
  363. The auth-cleanup side effects matter on SQLite (FK enforcement off by default):
  364. without explicit DELETEs in the endpoint, deleting a user leaves orphan rows
  365. in user_oidc_links / user_totp / user_otp_codes / api_keys — which would
  366. block SSO re-login and leak MFA secrets (#1285).
  367. """
  368. from sqlalchemy import select
  369. from backend.app.models.api_key import APIKey
  370. from backend.app.models.long_lived_token import LongLivedToken
  371. from backend.app.models.oidc_provider import UserOIDCLink
  372. from backend.app.models.user import User
  373. from backend.app.models.user_otp_code import UserOTPCode
  374. from backend.app.models.user_totp import UserTOTP
  375. # Create user
  376. create_response = await async_client.post(
  377. "/api/v1/users/",
  378. headers={"Authorization": f"Bearer {auth_token}"},
  379. json={
  380. "username": "deleteuser",
  381. "password": "Password123!",
  382. "role": "user",
  383. },
  384. )
  385. user_id = create_response.json()["id"]
  386. # Delete user
  387. response = await async_client.delete(
  388. f"/api/v1/users/{user_id}",
  389. headers={"Authorization": f"Bearer {auth_token}"},
  390. )
  391. assert response.status_code == 204
  392. # All auth-related rows for this user must be gone — see #1285.
  393. await db_session.commit()
  394. user_row = await db_session.execute(select(User).where(User.id == user_id))
  395. assert user_row.scalar_one_or_none() is None, "User row not deleted"
  396. for model in (UserOIDCLink, UserTOTP, UserOTPCode, APIKey, LongLivedToken):
  397. rows = await db_session.execute(select(model).where(model.user_id == user_id))
  398. assert rows.scalars().all() == [], f"Orphan {model.__name__} rows left after user delete"
  399. class TestAuthDisableAPI:
  400. """Integration tests for /api/v1/auth/disable endpoint."""
  401. @pytest.mark.asyncio
  402. @pytest.mark.integration
  403. async def test_disable_auth(self, async_client: AsyncClient):
  404. """Verify admin can disable authentication."""
  405. # Setup auth
  406. await async_client.post(
  407. "/api/v1/auth/setup",
  408. json={
  409. "auth_enabled": True,
  410. "admin_username": "disableadmin",
  411. "admin_password": "AdminPass1!",
  412. },
  413. )
  414. # Login to get token
  415. login_response = await async_client.post(
  416. "/api/v1/auth/login",
  417. json={"username": "disableadmin", "password": "AdminPass1!"},
  418. )
  419. token = login_response.json()["access_token"]
  420. # Disable auth
  421. response = await async_client.post(
  422. "/api/v1/auth/disable",
  423. headers={"Authorization": f"Bearer {token}"},
  424. )
  425. assert response.status_code == 200
  426. assert response.json()["auth_enabled"] is False
  427. # Verify auth is now disabled
  428. status_response = await async_client.get("/api/v1/auth/status")
  429. assert status_response.json()["auth_enabled"] is False
  430. class TestGroupsAPI:
  431. """Integration tests for /api/v1/groups/ endpoints."""
  432. @pytest.fixture
  433. async def auth_token(self, async_client: AsyncClient):
  434. """Setup auth and return admin token."""
  435. await async_client.post(
  436. "/api/v1/auth/setup",
  437. json={
  438. "auth_enabled": True,
  439. "admin_username": "groupsadmin",
  440. "admin_password": "AdminPass1!",
  441. },
  442. )
  443. login_response = await async_client.post(
  444. "/api/v1/auth/login",
  445. json={"username": "groupsadmin", "password": "AdminPass1!"},
  446. )
  447. return login_response.json()["access_token"]
  448. @pytest.mark.asyncio
  449. @pytest.mark.integration
  450. async def test_list_groups(self, async_client: AsyncClient, auth_token: str):
  451. """Verify listing groups returns default groups."""
  452. response = await async_client.get(
  453. "/api/v1/groups/",
  454. headers={"Authorization": f"Bearer {auth_token}"},
  455. )
  456. assert response.status_code == 200
  457. groups = response.json()
  458. assert isinstance(groups, list)
  459. # Should have default groups: Administrators, Operators, Viewers
  460. group_names = [g["name"] for g in groups]
  461. assert "Administrators" in group_names
  462. assert "Operators" in group_names
  463. assert "Viewers" in group_names
  464. @pytest.mark.asyncio
  465. @pytest.mark.integration
  466. async def test_get_permissions(self, async_client: AsyncClient, auth_token: str):
  467. """Verify getting available permissions."""
  468. response = await async_client.get(
  469. "/api/v1/groups/permissions",
  470. headers={"Authorization": f"Bearer {auth_token}"},
  471. )
  472. assert response.status_code == 200
  473. permissions = response.json()
  474. assert isinstance(permissions, dict)
  475. # Should have permission categories
  476. assert "Printers" in permissions or len(permissions) > 0
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_create_group(self, async_client: AsyncClient, auth_token: str):
  480. """Verify creating a new group."""
  481. response = await async_client.post(
  482. "/api/v1/groups/",
  483. headers={"Authorization": f"Bearer {auth_token}"},
  484. json={
  485. "name": "Custom Group",
  486. "description": "A custom test group",
  487. "permissions": ["printers:read", "archives:read"],
  488. },
  489. )
  490. assert response.status_code == 201
  491. group = response.json()
  492. assert group["name"] == "Custom Group"
  493. assert group["description"] == "A custom test group"
  494. assert "printers:read" in group["permissions"]
  495. assert group["is_system"] is False
  496. @pytest.mark.asyncio
  497. @pytest.mark.integration
  498. async def test_update_group(self, async_client: AsyncClient, auth_token: str):
  499. """Verify updating a group."""
  500. # Create a group first
  501. create_response = await async_client.post(
  502. "/api/v1/groups/",
  503. headers={"Authorization": f"Bearer {auth_token}"},
  504. json={
  505. "name": "Update Test Group",
  506. "permissions": ["printers:read"],
  507. },
  508. )
  509. group_id = create_response.json()["id"]
  510. # Update the group
  511. response = await async_client.patch(
  512. f"/api/v1/groups/{group_id}",
  513. headers={"Authorization": f"Bearer {auth_token}"},
  514. json={
  515. "description": "Updated description",
  516. "permissions": ["printers:read", "printers:control"],
  517. },
  518. )
  519. assert response.status_code == 200
  520. group = response.json()
  521. assert group["description"] == "Updated description"
  522. assert "printers:control" in group["permissions"]
  523. @pytest.mark.asyncio
  524. @pytest.mark.integration
  525. async def test_cannot_delete_system_group(self, async_client: AsyncClient, auth_token: str):
  526. """Verify system groups cannot be deleted."""
  527. # Get the Administrators group
  528. list_response = await async_client.get(
  529. "/api/v1/groups/",
  530. headers={"Authorization": f"Bearer {auth_token}"},
  531. )
  532. admin_group = next(g for g in list_response.json() if g["name"] == "Administrators")
  533. # Try to delete it
  534. response = await async_client.delete(
  535. f"/api/v1/groups/{admin_group['id']}",
  536. headers={"Authorization": f"Bearer {auth_token}"},
  537. )
  538. assert response.status_code == 400
  539. assert "system group" in response.json()["detail"].lower()
  540. @pytest.mark.asyncio
  541. @pytest.mark.integration
  542. async def test_delete_custom_group(self, async_client: AsyncClient, auth_token: str):
  543. """Verify custom groups can be deleted."""
  544. # Create a group
  545. create_response = await async_client.post(
  546. "/api/v1/groups/",
  547. headers={"Authorization": f"Bearer {auth_token}"},
  548. json={"name": "Delete Test Group"},
  549. )
  550. group_id = create_response.json()["id"]
  551. # Delete it
  552. response = await async_client.delete(
  553. f"/api/v1/groups/{group_id}",
  554. headers={"Authorization": f"Bearer {auth_token}"},
  555. )
  556. assert response.status_code == 204
  557. class TestUserGroupsAPI:
  558. """Integration tests for user-group assignments."""
  559. @pytest.fixture
  560. async def auth_token(self, async_client: AsyncClient):
  561. """Setup auth and return admin token."""
  562. await async_client.post(
  563. "/api/v1/auth/setup",
  564. json={
  565. "auth_enabled": True,
  566. "admin_username": "usergroupadmin",
  567. "admin_password": "AdminPass1!",
  568. },
  569. )
  570. login_response = await async_client.post(
  571. "/api/v1/auth/login",
  572. json={"username": "usergroupadmin", "password": "AdminPass1!"},
  573. )
  574. return login_response.json()["access_token"]
  575. @pytest.mark.asyncio
  576. @pytest.mark.integration
  577. async def test_create_user_with_groups(self, async_client: AsyncClient, auth_token: str):
  578. """Verify creating a user with group assignments."""
  579. # Get Operators group ID
  580. groups_response = await async_client.get(
  581. "/api/v1/groups/",
  582. headers={"Authorization": f"Bearer {auth_token}"},
  583. )
  584. operators_group = next(g for g in groups_response.json() if g["name"] == "Operators")
  585. # Create user with group
  586. response = await async_client.post(
  587. "/api/v1/users/",
  588. headers={"Authorization": f"Bearer {auth_token}"},
  589. json={
  590. "username": "groupuser",
  591. "password": "Password123!",
  592. "group_ids": [operators_group["id"]],
  593. },
  594. )
  595. assert response.status_code == 201
  596. user = response.json()
  597. assert any(g["name"] == "Operators" for g in user["groups"])
  598. @pytest.mark.asyncio
  599. @pytest.mark.integration
  600. async def test_add_user_to_group(self, async_client: AsyncClient, auth_token: str):
  601. """Verify adding a user to a group."""
  602. # Create a user
  603. user_response = await async_client.post(
  604. "/api/v1/users/",
  605. headers={"Authorization": f"Bearer {auth_token}"},
  606. json={"username": "addtogroup", "password": "Password123!"},
  607. )
  608. user_id = user_response.json()["id"]
  609. # Get Viewers group
  610. groups_response = await async_client.get(
  611. "/api/v1/groups/",
  612. headers={"Authorization": f"Bearer {auth_token}"},
  613. )
  614. viewers_group = next(g for g in groups_response.json() if g["name"] == "Viewers")
  615. # Add user to group
  616. response = await async_client.post(
  617. f"/api/v1/groups/{viewers_group['id']}/users/{user_id}",
  618. headers={"Authorization": f"Bearer {auth_token}"},
  619. )
  620. assert response.status_code == 204
  621. # Verify user is in group
  622. user_check = await async_client.get(
  623. f"/api/v1/users/{user_id}",
  624. headers={"Authorization": f"Bearer {auth_token}"},
  625. )
  626. assert any(g["name"] == "Viewers" for g in user_check.json()["groups"])
  627. class TestChangePasswordAPI:
  628. """Integration tests for /api/v1/users/me/change-password endpoint."""
  629. @pytest.fixture
  630. async def user_token(self, async_client: AsyncClient):
  631. """Setup auth and return regular user token."""
  632. # Enable auth with admin
  633. await async_client.post(
  634. "/api/v1/auth/setup",
  635. json={
  636. "auth_enabled": True,
  637. "admin_username": "pwchangeadmin",
  638. "admin_password": "AdminPass1!",
  639. },
  640. )
  641. admin_login = await async_client.post(
  642. "/api/v1/auth/login",
  643. json={"username": "pwchangeadmin", "password": "AdminPass1!"},
  644. )
  645. admin_token = admin_login.json()["access_token"]
  646. # Create a regular user
  647. await async_client.post(
  648. "/api/v1/users/",
  649. headers={"Authorization": f"Bearer {admin_token}"},
  650. json={"username": "pwchangeuser", "password": "Oldpassword123!"},
  651. )
  652. # Login as regular user
  653. user_login = await async_client.post(
  654. "/api/v1/auth/login",
  655. json={"username": "pwchangeuser", "password": "Oldpassword123!"},
  656. )
  657. return user_login.json()["access_token"]
  658. @pytest.mark.asyncio
  659. @pytest.mark.integration
  660. async def test_change_password_success(self, async_client: AsyncClient, user_token: str):
  661. """Verify user can change their own password."""
  662. response = await async_client.post(
  663. "/api/v1/users/me/change-password",
  664. headers={"Authorization": f"Bearer {user_token}"},
  665. json={
  666. "current_password": "Oldpassword123!",
  667. "new_password": "Newpassword456!",
  668. },
  669. )
  670. assert response.status_code == 200
  671. assert "success" in response.json()["message"].lower()
  672. # Verify can login with new password
  673. login_response = await async_client.post(
  674. "/api/v1/auth/login",
  675. json={"username": "pwchangeuser", "password": "Newpassword456!"},
  676. )
  677. assert login_response.status_code == 200
  678. @pytest.mark.asyncio
  679. @pytest.mark.integration
  680. async def test_change_password_wrong_current(self, async_client: AsyncClient, user_token: str):
  681. """Verify changing password fails with wrong current password."""
  682. response = await async_client.post(
  683. "/api/v1/users/me/change-password",
  684. headers={"Authorization": f"Bearer {user_token}"},
  685. json={
  686. "current_password": "wrongpassword",
  687. "new_password": "Newpassword456!",
  688. },
  689. )
  690. assert response.status_code == 400
  691. assert "incorrect" in response.json()["detail"].lower()
  692. @pytest.mark.asyncio
  693. @pytest.mark.integration
  694. async def test_change_password_requires_auth(self, async_client: AsyncClient):
  695. """Verify changing password requires authentication."""
  696. response = await async_client.post(
  697. "/api/v1/users/me/change-password",
  698. json={
  699. "current_password": "oldpassword",
  700. "new_password": "Strongpass456!",
  701. },
  702. )
  703. assert response.status_code == 401
  704. class TestAuthMiddlewarePublicRoutes:
  705. """Tests for auth middleware public route configuration.
  706. These routes must be accessible without authentication, even when auth is enabled,
  707. because browser elements like <img src> and <video src> don't send Authorization headers.
  708. """
  709. @pytest.fixture
  710. async def enabled_auth(self, async_client: AsyncClient):
  711. """Enable auth for testing middleware behavior."""
  712. await async_client.post(
  713. "/api/v1/auth/setup",
  714. json={
  715. "auth_enabled": True,
  716. "admin_username": "middlewareadmin",
  717. "admin_password": "AdminPass1!",
  718. },
  719. )
  720. @pytest.mark.asyncio
  721. @pytest.mark.integration
  722. async def test_auth_status_is_public(self, async_client: AsyncClient, enabled_auth):
  723. """Verify /api/v1/auth/status is accessible without auth."""
  724. response = await async_client.get("/api/v1/auth/status")
  725. assert response.status_code == 200
  726. assert "auth_enabled" in response.json()
  727. @pytest.mark.asyncio
  728. @pytest.mark.integration
  729. async def test_system_appliance_is_public(self, async_client: AsyncClient, enabled_auth):
  730. """Verify /api/v1/system/appliance is reachable without a JWT.
  731. The SPA's i18n bootstrap fetches this BEFORE login to seed locale,
  732. hostname, timezone, and NTP-gate state. The route handler has no
  733. auth dependency, but the global auth_middleware blocks every
  734. /api/ path not in PUBLIC_API_ROUTES — so without an explicit
  735. allowlist entry the user sees a 401 in the browser console on
  736. every page load.
  737. """
  738. response = await async_client.get("/api/v1/system/appliance")
  739. assert response.status_code == 200, response.text
  740. body = response.json()
  741. # Shape contract (no-auth surface):
  742. for key in ("hostname", "timezone", "locale", "time_synced"):
  743. assert key in body
  744. @pytest.mark.asyncio
  745. @pytest.mark.integration
  746. async def test_auth_login_is_public(self, async_client: AsyncClient, enabled_auth):
  747. """Verify /api/v1/auth/login is accessible without auth."""
  748. response = await async_client.post(
  749. "/api/v1/auth/login",
  750. json={"username": "middlewareadmin", "password": "AdminPass1!"},
  751. )
  752. # Should not return 401 (unauthorized) - it should either succeed or return
  753. # a different error (like 400 for wrong credentials)
  754. assert response.status_code != 401 or "token" in response.json()
  755. @pytest.mark.asyncio
  756. @pytest.mark.integration
  757. async def test_auth_setup_is_public(self, async_client: AsyncClient):
  758. """Verify /api/v1/auth/setup is accessible without auth (needed for setup/recovery)."""
  759. # Don't enable auth first - test that setup endpoint itself is accessible
  760. response = await async_client.post(
  761. "/api/v1/auth/setup",
  762. json={"auth_enabled": False},
  763. )
  764. # Should not be 401
  765. assert response.status_code != 401
  766. @pytest.mark.asyncio
  767. @pytest.mark.integration
  768. async def test_updates_version_is_public(self, async_client: AsyncClient, enabled_auth):
  769. """Verify /api/v1/updates/version is accessible without auth."""
  770. response = await async_client.get("/api/v1/updates/version")
  771. # Should not be 401
  772. assert response.status_code != 401
  773. @pytest.mark.asyncio
  774. @pytest.mark.integration
  775. async def test_protected_route_requires_auth(self, async_client: AsyncClient, enabled_auth):
  776. """Verify non-public routes return 401 without token."""
  777. response = await async_client.get("/api/v1/printers/")
  778. assert response.status_code == 401
  779. @pytest.mark.asyncio
  780. @pytest.mark.integration
  781. async def test_protected_route_works_with_token(self, async_client: AsyncClient, enabled_auth):
  782. """Verify non-public routes work with valid token."""
  783. # Login to get token
  784. login_response = await async_client.post(
  785. "/api/v1/auth/login",
  786. json={"username": "middlewareadmin", "password": "AdminPass1!"},
  787. )
  788. token = login_response.json()["access_token"]
  789. # Access protected route
  790. response = await async_client.get(
  791. "/api/v1/printers/",
  792. headers={"Authorization": f"Bearer {token}"},
  793. )
  794. assert response.status_code == 200
  795. @pytest.mark.asyncio
  796. @pytest.mark.integration
  797. async def test_advanced_auth_status_is_public(self, async_client: AsyncClient, enabled_auth):
  798. """Verify /api/v1/auth/advanced-auth/status is accessible without auth."""
  799. response = await async_client.get("/api/v1/auth/advanced-auth/status")
  800. # Should not be 401 (must be accessible for login page)
  801. assert response.status_code != 401
  802. # Should return valid response (200 with auth status)
  803. if response.status_code == 200:
  804. result = response.json()
  805. assert "advanced_auth_enabled" in result
  806. assert "smtp_configured" in result
  807. @pytest.mark.asyncio
  808. @pytest.mark.integration
  809. async def test_forgot_password_is_public(self, async_client: AsyncClient, enabled_auth):
  810. """Verify /api/v1/auth/forgot-password is accessible without auth."""
  811. response = await async_client.post(
  812. "/api/v1/auth/forgot-password",
  813. json={"email": "test@example.com"},
  814. )
  815. # Should not be 401 (must be accessible for password reset from login page)
  816. assert response.status_code != 401
  817. # Will likely be 400 (advanced auth not enabled) but that's okay -
  818. # the important thing is it's not blocked by auth middleware
  819. assert response.status_code in [200, 400]
  820. # ===========================================================================
  821. # H-1: Input length validation
  822. # ===========================================================================
  823. class TestInputLengthValidation:
  824. """LoginRequest and SetupRequest must reject oversized inputs (H-1)."""
  825. @pytest.mark.asyncio
  826. @pytest.mark.integration
  827. async def test_login_password_too_long_rejected(self, async_client: AsyncClient):
  828. """Password exceeding 256 characters must be rejected with 422."""
  829. response = await async_client.post(
  830. "/api/v1/auth/login",
  831. json={"username": "admin", "password": "x" * 257},
  832. )
  833. assert response.status_code == 422
  834. @pytest.mark.asyncio
  835. @pytest.mark.integration
  836. async def test_login_username_too_long_rejected(self, async_client: AsyncClient):
  837. """Username exceeding 150 characters must be rejected with 422."""
  838. response = await async_client.post(
  839. "/api/v1/auth/login",
  840. json={"username": "u" * 151, "password": "password"},
  841. )
  842. assert response.status_code == 422
  843. @pytest.mark.asyncio
  844. @pytest.mark.integration
  845. async def test_setup_password_too_long_rejected(self, async_client: AsyncClient):
  846. """SetupRequest admin_password exceeding 256 characters must be rejected with 422."""
  847. response = await async_client.post(
  848. "/api/v1/auth/setup",
  849. json={
  850. "auth_enabled": True,
  851. "admin_username": "admin",
  852. "admin_password": "x" * 257,
  853. },
  854. )
  855. assert response.status_code == 422
  856. @pytest.mark.asyncio
  857. @pytest.mark.integration
  858. async def test_login_password_at_limit_accepted(self, async_client: AsyncClient):
  859. """Password of exactly 256 characters must pass schema validation (may fail auth)."""
  860. response = await async_client.post(
  861. "/api/v1/auth/login",
  862. json={"username": "admin", "password": "x" * 256},
  863. )
  864. # Schema accepts it; auth may reject with 401 (auth disabled) or 400
  865. assert response.status_code != 422