Files
Project-SDE-WP-Suite/server/ldap_fake.py
Cody Schaefer c47b2ae210 T10.7 D13 - the suite runs without a domain controller
Far smaller than estimated, because the premise was wrong. I had said four
checks sign in and would each need a fake directory. They do not: seed() mints
a session token with auth.create_token() and sets the cookie directly -
browser_check's own docstring says so - and the only breakage was a leftover
password_hash= kwarg on a model that no longer has the column. Deleting that one
line in browser_check.seed() unblocked 39 files that import seed/start_server
from it. launcher_check needed the same.

console_dialogs_check's password-reset half is deleted rather than ported. Its
docstring now records what went and where the prompt kit is still covered
(wpPromptDialog has five callers left in wp-creation-app.js; creator_dialogs_check
exercises them, validation included - verified, 20/20). Nothing was left skipped
in place of the removed section.

Exactly one check genuinely needed a seam: url_state_check drives the real login
form to prove a deep link's ?next= survives authentication. That cannot be faked
by minting a cookie, because the login round trip is the thing under test.

The seam is env-driven because it has to be: start_server launches the app as a
SUBPROCESS, so a monkeypatch in the test process would never reach the code doing
the authenticating. server/ldap_fake.py reads WP_LDAP_FAKE_DIRECTORY and
ldap_auth dispatches to it AFTER the empty-input guard, so the anonymous-bind
guard covers the fake path too - a fake that reimplemented it would let the real
one rot unnoticed.

The production guard is the point of that module. An env var that makes any
password work is exactly the kind of thing that escapes into production, and D13
left no other way in. is_active() refuses whenever a non-SQLite DATABASE_URL is
configured - the same test auth._load_secret uses - and describe() shouts in
capitals so a fake run can never be mistaken for a real one in the startup log.

Two things found on the way, neither of them the app's fault:

- url_state_check's "signing in continues to the requested page" asserted
  `"wp-creation-index.html" in location.href`. That string is in the ?next=
  parameter too, so it passed while sitting on login.html with the sign-in
  rejected. It would have passed with login entirely broken. Tightened to assert
  we actually left the login page.
- Two assertions in my own new ldap_auth_check read the WRONG database:
  server/db.py binds its engine from DATABASE_URL at import, so setting the env
  var afterwards keeps reading whichever file was configured first. users_in()
  now opens the file it is asked about with sqlite3. The CERT_NONE check also had
  to become an AST walk - the module docstring names validate=ssl.CERT_NONE in
  order to explain why it is banned, and a text search cannot tell that apart
  from a real call.

tests/ldap_auth_check.py is new coverage rather than repair: the anonymous-bind
guard, CERT_REQUIRED by AST, the nested matching rule in the filter, the
production refusal, a refused sign-in creating no account, and an existing admin
still being an admin with their locally-set name intact. 20/20.

Run so far, all green: browser_check 71/71, launcher_check 58/58,
console_dialogs 12/12, url_state 23/23, qa_gate 41/41, critical_reopen 11/11,
creator_dialogs 20/20, a11y 22/22, kitting_notify 17/17, ldap_auth 20/20.
A full sweep of the remaining ~30 is running; its box stays unticked until it
reports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 09:18:05 -05:00

96 lines
3.9 KiB
Python

"""A fake directory, for tests only — D13 / T10.7.
`server/ldap_auth.py` normally opens an LDAPS connection to a domain controller.
Tests cannot: CI has no domain, and the browser checks launch the app as a
SUBPROCESS (`start_server` in tests/browser_check.py), so a monkeypatch in the
test process would never reach the code doing the authenticating. The seam has to
be configurable from the ENVIRONMENT, which is what this module is.
Set `WP_LDAP_FAKE_DIRECTORY` to a JSON object and `ldap_auth.verify()` answers
from it instead of touching the network:
{"root": {"password": "", "mail": "root@example.test",
"full_name": "Root", "groups": ["WP-Suite-Users"]}}
`groups` is a flat list of names the account is "in". Nested groups do not exist
here — the real `member_of` resolves a DN and uses AD's LDAP_MATCHING_RULE_IN_CHAIN,
and faking that faithfully would mean reimplementing AD. A test that cares about
nesting has to run against a real directory; this one is honest about being a
string comparison.
THE PRODUCTION GUARD IS THE POINT OF THIS FILE.
An environment variable that makes any password work is exactly the kind of thing
that escapes into production, and D13 removed every other way in — there is no
local password to fall back on and no break-glass, so a fake directory silently
active in production would be a total authentication bypass with nothing behind it.
So `is_active()` refuses whenever a real database is configured, using the same
test `auth._load_secret` uses to refuse an ephemeral signing key: a non-SQLite
`DATABASE_URL` means production, full stop. `ldap_auth.describe()` also shouts
when the fake is live, so the startup line can never be mistaken for a real one.
"""
import json
import logging
import os
from typing import Optional
log = logging.getLogger("wpsuite.ldap.fake")
ENV_VAR = "WP_LDAP_FAKE_DIRECTORY"
def _raw() -> str:
return os.getenv(ENV_VAR, "").strip()
def is_active() -> bool:
"""Whether the fake should answer. False in anything resembling production."""
if not _raw():
return False
# Imported lazily: server.db reads DATABASE_URL at import, and this module is
# imported from ldap_auth, which must stay importable on its own.
from .db import DATABASE_URL
if not str(DATABASE_URL).startswith("sqlite"):
log.error(
"%s is set but a non-SQLite DATABASE_URL is configured. REFUSING to use "
"the fake directory — this looks like production, and D13 leaves no "
"other way in, so honouring it would be an authentication bypass. "
"Unset %s.", ENV_VAR, ENV_VAR)
return False
return True
def directory() -> dict:
try:
data = json.loads(_raw())
if not isinstance(data, dict):
raise ValueError("top level must be an object")
return data
except Exception as exc: # noqa: BLE001 — a malformed fake must not look like a bad password
log.error("%s is not valid JSON (%s); the fake directory is empty", ENV_VAR, exc)
return {}
def lookup(username: str, password: str, required_group: Optional[str]) -> tuple:
"""Return (ok, reason, attrs). Mirrors what ldap_auth.verify() needs.
Deliberately does NOT re-check for an empty password: `verify()` guards that
before it ever gets here, and duplicating the check in the fake would let the
real guard rot without any test noticing.
"""
people = directory()
who = people.get(username) or people.get(username.lower())
if not isinstance(who, dict) or password != who.get("password"):
return (False, "bad_credentials", {})
if required_group:
groups = who.get("groups") or []
if required_group not in groups:
return (False, "not_in_group", {})
return (True, "ok", {
"sam": who.get("sam") or username,
"mail": who.get("mail", ""),
"full_name": who.get("full_name", ""),
"upn": who.get("upn", ""),
})