T13.7: dry run for the Okta sync, OKTA_SYNC_DRY_RUN (D22)
This commit is contained in:
@@ -415,6 +415,21 @@ status SUSPENDED or DEPROVISIONED. A password expiry, a lockout, or a recovery
|
||||
in progress does not disable anyone. With no token set, the sync is off and the
|
||||
startup log says `Okta sync DISABLED`.
|
||||
|
||||
**First deploy: use the dry run.** Set `OKTA_SYNC_DRY_RUN=true` in `.env` (or the
|
||||
Portainer stack environment) with the token, then run `docker compose up -d --build api`.
|
||||
The sync runs as normal but changes no account and writes no audit row. Read the
|
||||
result:
|
||||
|
||||
docker compose logs api | grep "Okta sync"
|
||||
|
||||
The summary line shows how many Okta users and active local accounts it checked,
|
||||
how many matched, and how many it would disable. A line `DRY RUN would disable ...`
|
||||
names each account. If the match count is close to your number of real users and
|
||||
the list holds only people who have left, remove `OKTA_SYNC_DRY_RUN` (or set it
|
||||
to `false`) and run `docker compose up -d api` again to go live. If the match
|
||||
count is low, the Okta attribute is wrong. Set `OKTA_SYNC_PROFILE_ATTRIBUTE`
|
||||
and run the dry run again.
|
||||
|
||||
The sync only ever disables. **It never re-enables an account.** A person comes
|
||||
back only when an admin enables the account by hand.
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ services:
|
||||
OKTA_ORG_URL: ${OKTA_ORG_URL:-}
|
||||
OKTA_SYNC_PROFILE_ATTRIBUTE: ${OKTA_SYNC_PROFILE_ATTRIBUTE:-}
|
||||
OKTA_SYNC_INTERVAL_SECONDS: ${OKTA_SYNC_INTERVAL_SECONDS:-}
|
||||
OKTA_SYNC_DRY_RUN: ${OKTA_SYNC_DRY_RUN:-}
|
||||
# Optional — SMTP password for WP-assignment emails. Email is off by
|
||||
# default and enabled from the Admin console; this is the only email
|
||||
# secret and it is never stored in the DB. Leave unset until configured.
|
||||
|
||||
31
docs/waves/decisions-2026-10-16.md
Normal file
31
docs/waves/decisions-2026-10-16.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Decisions: October 16, 2026
|
||||
|
||||
## D22: dry run for the Okta deprovisioning sync
|
||||
|
||||
**Asked by:** Matt Mabrey, 2026-10-16. **Extends:** D18 (wave 13). **Task:** T13.7.
|
||||
|
||||
**Why:** The sync disables a local account when Okta does not list the person.
|
||||
If the Okta profile attribute is wrong for some accounts, the first live run can
|
||||
disable people who have not left (see BL-069). The attribute `profile.login` is
|
||||
the default for `preferred_username`. It is not confirmed against the tenant, and
|
||||
the person who deploys has no access to the Okta admin console.
|
||||
|
||||
**Decision:** Add the environment variable `OKTA_SYNC_DRY_RUN`.
|
||||
|
||||
- Values `1`, `true`, `yes`, `on` (any case) turn it on. Any other value, or no
|
||||
value, leaves the sync live. It is off by default, so a deploy that does not set
|
||||
it behaves as before.
|
||||
- In a dry run the sync does every step of a live run: the fetch, the match, the
|
||||
zero-match guard and the fail-closed rules. It then changes no account and writes
|
||||
no audit row.
|
||||
- It logs one line for each account it would disable, and one summary line with the
|
||||
number of Okta users, active local accounts, matches, and accounts that would be
|
||||
disabled. Read them with `docker compose logs api | grep "Okta sync"`.
|
||||
- The startup line shows the mode.
|
||||
|
||||
**Not decided here:** a limit on accounts disabled in one run, and a rule to keep the
|
||||
last active admin (BL-069). The dry run lets a person see the result before the
|
||||
first live run. It does not stop a bad live run.
|
||||
|
||||
**Rules from D18 that stay:** fail closed, only disable, one audit row for each
|
||||
change, actor `system:okta_sync`.
|
||||
@@ -333,3 +333,19 @@ T13.6 result (2026-10-16, merged release tree, Edge on the PC): 47 test scripts,
|
||||
The two failures are not regressions. `token_check.py` exits 2 (CLI usage detail).
|
||||
`generalinfo_check.py` finds an old color-literal gap in `wp-creation-styles.css`.
|
||||
Alembic upgrade, downgrade, upgrade passed. Import check passed.
|
||||
|
||||
## T13.7: D22 dry run for the Okta sync
|
||||
|
||||
**Item:** D22 (`docs/waves/decisions-2026-10-16.md`). Extends T13.3 and T13.4.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] `OKTA_SYNC_DRY_RUN` on: the sync fetches and matches, logs the accounts it would disable, and changes no account and writes no audit row (`tests/okta_sync_dry_run_check.py`)
|
||||
- [x] both guards (zero match, fail closed) still apply in a dry run
|
||||
- [x] flag off or unset: behavior is unchanged (`okta_sync_job_check.py` still passes)
|
||||
- [x] the startup line names the mode
|
||||
- [x] `.env.example`, `docker-compose.yml` and `DEPLOYMENT.md` describe the flag and the first-deploy steps
|
||||
- [x] mutation check: if the dry-run guard is removed, the new test fails
|
||||
|
||||
Result 2026-10-16: all Okta sync tests and `security_check.py` pass in the sandbox.
|
||||
This task changes no frontend file.
|
||||
|
||||
@@ -84,6 +84,12 @@ OKTA_REDIRECT_URI=CHANGE_ME
|
||||
# once a minute and one of them wins each cycle, so raising the worker count does
|
||||
# not raise the call rate to Okta.
|
||||
# OKTA_SYNC_INTERVAL_SECONDS=900
|
||||
#
|
||||
# Dry run (D22). Set to true for the first deploy. The sync then does everything
|
||||
# except the change: it logs who it WOULD disable and writes nothing, and it writes
|
||||
# no audit rows. Read the result with: docker compose logs api | grep "Okta sync"
|
||||
# Remove it (or set it to false) to go live. Off by default.
|
||||
# OKTA_SYNC_DRY_RUN=true
|
||||
|
||||
# ── Email notifications (optional) ─────────────────────────────────────────────
|
||||
# WP-assignment emails are OFF by default and are turned on from the Admin
|
||||
|
||||
@@ -148,7 +148,16 @@ def describe() -> str:
|
||||
return "Okta sync DISABLED - no OKTA_ORG_URL and OKTA_ISSUER has no host. Deprovisioning is not detected."
|
||||
if not base.startswith("https://"):
|
||||
return f"Okta sync DISABLED - org URL {base!r} is not https. The token is never sent over http."
|
||||
return f"Okta sync configured - org {base}, identity claim {okta_auth.IDENTITY_CLAIM!r}"
|
||||
mode = "DRY RUN, no account is changed" if dry_run() else "live"
|
||||
return f"Okta sync configured ({mode}) - org {base}, identity claim {okta_auth.IDENTITY_CLAIM!r}"
|
||||
|
||||
|
||||
def dry_run() -> bool:
|
||||
"""OKTA_SYNC_DRY_RUN (D22). When it is 1, true, yes or on, the sync does its whole
|
||||
job except the change: it logs who it WOULD disable and writes nothing. Off by
|
||||
default, so a deploy that does not set it behaves as before. Read at each run,
|
||||
so the value in force is the one the worker started with."""
|
||||
return os.getenv("OKTA_SYNC_DRY_RUN", "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _profile_attribute() -> str:
|
||||
@@ -269,6 +278,8 @@ class SyncResult:
|
||||
okta_users: int = 0 # size of the Okta list
|
||||
checked: int = 0 # active local accounts looked at
|
||||
disabled: "list[str]" = field(default_factory=list) # usernames disabled this run
|
||||
# (in a dry run: the ones it WOULD disable)
|
||||
dry_run: bool = False # True = nothing was changed on purpose (D22)
|
||||
|
||||
|
||||
def _gen_id(prefix: str) -> str:
|
||||
@@ -277,7 +288,8 @@ def _gen_id(prefix: str) -> str:
|
||||
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None) -> SyncResult:
|
||||
def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None,
|
||||
dry: Optional[bool] = None) -> SyncResult:
|
||||
"""Compare the Okta user list to local accounts and disable the ones Okta no
|
||||
longer vouches for.
|
||||
|
||||
@@ -307,9 +319,16 @@ def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None
|
||||
identity twice with different statuses, the account is disabled only when
|
||||
every one of them is a disabling status.
|
||||
|
||||
`fetch` is for tests. In production it is None and fetch_users() is used.
|
||||
DRY RUN (D22, OKTA_SYNC_DRY_RUN): every step above runs, including the fetch and
|
||||
both guards, but the account changes and the audit rows are skipped. The run logs
|
||||
who it would disable. Use it for the first deploy, to see the match count and the
|
||||
list before any account is touched.
|
||||
|
||||
`fetch` and `dry` are for tests. In production fetch is None and fetch_users() is
|
||||
used, and dry is None so the environment decides.
|
||||
"""
|
||||
fetch = fetch or fetch_users
|
||||
dry = dry_run() if dry is None else dry
|
||||
|
||||
# 1. The fetch. Nothing below runs unless it returned a list.
|
||||
try:
|
||||
@@ -353,20 +372,29 @@ def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None
|
||||
|
||||
planned = [(local.username, status) for local, status in plan]
|
||||
checked = len(locals_)
|
||||
for local, status in plan:
|
||||
local.is_active = False
|
||||
db.add(models.AuditLog(
|
||||
id=_gen_id("ev"), actor=SYNC_ACTOR, action=SYNC_ACTION,
|
||||
entity_type="user", entity_id=local.id, project_id=None,
|
||||
summary=local.username[:400],
|
||||
detail={"okta_status": status, "via": "okta_sync"},
|
||||
))
|
||||
db.commit()
|
||||
if not dry:
|
||||
for local, status in plan:
|
||||
local.is_active = False
|
||||
db.add(models.AuditLog(
|
||||
id=_gen_id("ev"), actor=SYNC_ACTOR, action=SYNC_ACTION,
|
||||
entity_type="user", entity_id=local.id, project_id=None,
|
||||
summary=local.username[:400],
|
||||
detail={"okta_status": status, "via": "okta_sync"},
|
||||
))
|
||||
db.commit()
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
log.error("Okta sync FAILED, nothing was kept: unexpected %s", type(exc).__name__)
|
||||
return SyncResult(ok=False, error=f"unexpected {type(exc).__name__}")
|
||||
|
||||
if dry:
|
||||
for name, status in planned:
|
||||
log.warning("Okta sync DRY RUN would disable %r (Okta status: %s)", name, status)
|
||||
log.info("Okta sync DRY RUN done, no account was changed: %d Okta user(s), %d active "
|
||||
"local account(s) checked, %d matched, %d would be disabled",
|
||||
len(okta_users), checked, matched, len(planned))
|
||||
return SyncResult(ok=True, okta_users=len(okta_users), checked=checked,
|
||||
disabled=[name for name, _ in planned], dry_run=True)
|
||||
for name, status in planned:
|
||||
log.warning("Okta sync disabled %r (Okta status: %s)", name, status)
|
||||
log.info("Okta sync done: %d Okta user(s), %d active local account(s) checked, %d disabled",
|
||||
|
||||
134
tests/okta_sync_dry_run_check.py
Normal file
134
tests/okta_sync_dry_run_check.py
Normal file
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Does the Okta sync dry run change nothing? - D22 / T13.7.
|
||||
|
||||
With OKTA_SYNC_DRY_RUN on, the sync must fetch, match and apply both guards exactly
|
||||
as in a live run, report who it WOULD disable, and change no account and write no
|
||||
audit row. With it off (the default) behavior is as before.
|
||||
|
||||
Self-contained: in-memory SQLite, no server, no network, no browser.
|
||||
Exit 0 all passed, 1 a failure.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from sqlalchemy import create_engine, select # noqa: E402
|
||||
from sqlalchemy.orm import sessionmaker # noqa: E402
|
||||
from sqlalchemy.pool import StaticPool # noqa: E402
|
||||
|
||||
from server import models, okta_sync # noqa: E402
|
||||
from server.okta_sync import OktaSyncError, OktaUser, run_sync # noqa: E402
|
||||
|
||||
fails = 0
|
||||
|
||||
|
||||
def chk(label, ok, extra=""):
|
||||
global fails
|
||||
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
|
||||
if not ok:
|
||||
fails += 1
|
||||
|
||||
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
models.Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine, autoflush=False, future=True)
|
||||
|
||||
|
||||
def seed(names):
|
||||
with Session() as db:
|
||||
db.query(models.AuditLog).delete()
|
||||
db.query(models.User).delete()
|
||||
for n in names:
|
||||
db.add(models.User(id="u_" + n, username=n, is_active=True, email=""))
|
||||
db.commit()
|
||||
|
||||
|
||||
def state():
|
||||
with Session() as db:
|
||||
return ({u.username: u.is_active for u in db.scalars(select(models.User))},
|
||||
db.query(models.AuditLog).count())
|
||||
|
||||
|
||||
def okta(*pairs):
|
||||
return lambda: [OktaUser(identity=i, status=s) for i, s in pairs]
|
||||
|
||||
|
||||
class Capture(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.lines = []
|
||||
|
||||
def emit(self, r):
|
||||
self.lines.append(r.getMessage())
|
||||
|
||||
|
||||
cap = Capture()
|
||||
logging.getLogger("wpsuite.okta_sync").addHandler(cap)
|
||||
|
||||
# 1. Flag parsing
|
||||
for v, want in [("", False), ("false", False), ("0", False), ("true", True), ("TRUE", True),
|
||||
("1", True), ("yes", True), ("on", True), (" on ", True), ("maybe", False)]:
|
||||
os.environ["OKTA_SYNC_DRY_RUN"] = v
|
||||
chk(f"OKTA_SYNC_DRY_RUN={v!r} -> {want}", okta_sync.dry_run() is want)
|
||||
os.environ.pop("OKTA_SYNC_DRY_RUN")
|
||||
chk("unset -> live", okta_sync.dry_run() is False)
|
||||
|
||||
# 2. Dry run reports the plan and changes nothing
|
||||
seed(["alice", "bob", "carol", "dan"])
|
||||
before = state()
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=okta(("alice", "ACTIVE"), ("bob", "SUSPENDED"), ("carol", "DEPROVISIONED")), dry=True)
|
||||
after = state()
|
||||
chk("dry run ok", res.ok and res.dry_run)
|
||||
chk("dry run lists bob, carol and dan (missing)", sorted(res.disabled) == ["bob", "carol", "dan"], str(res.disabled))
|
||||
chk("dry run changed no account", before == after, f"{before} {after}")
|
||||
chk("dry run wrote no audit row", after[1] == 0)
|
||||
chk("log says DRY RUN would disable", any("DRY RUN would disable 'bob'" in l for l in cap.lines))
|
||||
chk("summary line says no account was changed and counts 3 matched, 3 would be disabled",
|
||||
any("DRY RUN done, no account was changed" in l and "3 matched" in l and "3 would be disabled" in l
|
||||
for l in cap.lines))
|
||||
|
||||
# 3. The environment decides when no argument is given
|
||||
os.environ["OKTA_SYNC_DRY_RUN"] = "true"
|
||||
seed(["alice", "bob"])
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=okta(("alice", "ACTIVE"), ("bob", "SUSPENDED")))
|
||||
chk("env on -> dry run", res.dry_run and state()[0]["bob"] is True and state()[1] == 0)
|
||||
|
||||
# 4. Guards still apply in a dry run
|
||||
seed(["alice", "bob"])
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=okta(("zed", "ACTIVE")))
|
||||
chk("zero-match guard still refuses in a dry run", (not res.ok) and "probably wrong" in res.error)
|
||||
|
||||
|
||||
def boom():
|
||||
raise OktaSyncError("down")
|
||||
|
||||
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=boom)
|
||||
chk("fetch failure still fails closed in a dry run", (not res.ok) and state() == ({"alice": True, "bob": True}, 0))
|
||||
|
||||
# 5. Live run (flag off) is unchanged
|
||||
os.environ.pop("OKTA_SYNC_DRY_RUN")
|
||||
seed(["alice", "bob"])
|
||||
with Session() as db:
|
||||
res = run_sync(db, fetch=okta(("alice", "ACTIVE"), ("bob", "SUSPENDED")))
|
||||
st = state()
|
||||
chk("live run disables and logs one audit row", (not res.dry_run) and st[0]["bob"] is False and st[1] == 1)
|
||||
|
||||
# 6. Startup line names the mode
|
||||
os.environ["OKTA_API_TOKEN"] = "tok-secret-9f3a"
|
||||
os.environ["OKTA_ORG_URL"] = "https://example.okta.com"
|
||||
os.environ["OKTA_SYNC_DRY_RUN"] = "true"
|
||||
chk("startup line says DRY RUN", "DRY RUN" in okta_sync.describe())
|
||||
os.environ.pop("OKTA_SYNC_DRY_RUN")
|
||||
chk("startup line says live", "(live)" in okta_sync.describe())
|
||||
chk("startup line never holds the token", "tok-secret-9f3a" not in okta_sync.describe())
|
||||
|
||||
print("\nDONE" if fails == 0 else f"\n{fails} FAILED")
|
||||
sys.exit(1 if fails else 0)
|
||||
Reference in New Issue
Block a user