Compare commits
8 Commits
feat/wave-
...
feat/wave-
| Author | SHA1 | Date | |
|---|---|---|---|
| b2b3774dea | |||
| cfecdca3f7 | |||
| be3157baf2 | |||
| 0157b4b325 | |||
| c0b736e503 | |||
| f4d74879cc | |||
| d962ab2381 | |||
| 8dd0afaba4 |
Binary file not shown.
|
Before Width: | Height: | Size: 128 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 112 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 78 KiB |
@@ -316,17 +316,6 @@ python tests/critical_reopen_check.py # BL-021 - on-hold mail reaches PM + CM
|
||||
python tests/console_dialogs_check.py # BL-024 - consoles/launcher: 21 natives -> 0 17 checks
|
||||
```
|
||||
|
||||
Wave 12 (CR-020, bulk user editing) adds these:
|
||||
|
||||
```bash
|
||||
python tests/bulk_users_check.py # CR-020 - bulk routes, guards, audit, CSV; NO browser 61 checks
|
||||
python tests/bulk_users_ui_check.py # CR-020 - selection, toolbar, CSV, typed delete at 1440/390px
|
||||
```
|
||||
|
||||
`console_dialogs_check.py` gained section 4 (the bulk delete prompt). `tests/cdp.py`
|
||||
passes `--do-not-de-elevate` on Windows so the probes start from an Administrator
|
||||
shell (same change as wave 16, T16.4).
|
||||
|
||||
**Three probes were re-pointed at `T7.1`.** `sections_check.py` 5b drove the live
|
||||
cross-frame toggle hand-off, which no longer exists; it now pins the surviving path and
|
||||
the fact that an UNSAVED toggle correctly does not travel - a behaviour change, recorded
|
||||
|
||||
@@ -662,37 +662,3 @@ deliberately deferred.
|
||||
worth confirming rather than assuming).
|
||||
- **Suggested wave or follow-up:** next housekeeping pass — needs Nick on
|
||||
whether to delete, archive, or rewrite it as historical record.
|
||||
|
||||
### BL-060 — A super user is told they can change access the server then refuses
|
||||
|
||||
- **Found during:** T12.6 (CR-020 verification, the CSV path)
|
||||
- **Where:** `server/app.py` `manage_user_problem` (the reason text), `get_user_projects` / `set_user_projects` (the rule)
|
||||
- **What:** for an account that is also on a project the super user does not
|
||||
administer, the refusal reason ends "You can still change their access and
|
||||
role on your own projects." Neither the project-access dialog's routes nor
|
||||
the CR-020 bulk project route allow that: all of them call
|
||||
`require_manage_user`, which refuses the account. The bulk route mirrors the
|
||||
single route on purpose (CR-020: same rules), so the words promise something
|
||||
neither path does. Either the text or the rule is wrong; which one is a
|
||||
product call.
|
||||
- **Why not now:** changing either is out of CR-020's scope (the wave must
|
||||
not widen what a super user can do), and it needs a decision.
|
||||
- **Suggested wave or follow-up:** needs Nick: should a super user be able to
|
||||
add or remove a shared account on their own projects? Then fix the text or
|
||||
the rule, not both.
|
||||
|
||||
### BL-061 — The sync badge covers controls while it shows
|
||||
|
||||
- **Found during:** T12.6 (the wave 12 screenshots)
|
||||
- **Where:** `html/project-data.js` `renderSyncBadge` (fixed bottom-right, `z-index:9998`)
|
||||
- **What:** for about 2 seconds after each sync the "Everything sent to the
|
||||
project" badge sits over whatever is in the bottom-right corner: a Delete
|
||||
button on the User Directory at 1440px, the bulk bar's "Set permissions" at
|
||||
390px. It is `pointer-events:none`, so clicks pass through, but the control is
|
||||
hidden while it shows, and on the console pages there is no outbox work to
|
||||
report at all.
|
||||
- **Why not now:** `project-data.js` is shared by every page and owned by the
|
||||
outbox work in wave 14 (T14.1 to T14.3 change this badge's states anyway).
|
||||
- **Suggested wave or follow-up:** wave 14, alongside T14.1's badge changes:
|
||||
do not show the badge on pages with nothing to sync, and keep it clear of
|
||||
page controls.
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
# Decisions — September 17, 2026
|
||||
|
||||
Three items. Like `D11`, `D15`, `D16` and `D17`, these are new scope raised after
|
||||
R2 closed out (see `docs/reference/completion.md`, T9.7), not a reopening of
|
||||
anything already decided there.
|
||||
|
||||
`CR-019` and `CR-020` get `CR` ids because they are field/product-facing feature
|
||||
requests — the same kind of thing `CR-001`-`CR-018` were — not internal
|
||||
engineering calls made mid-build. `D18` gets a `D` id because it is exactly that:
|
||||
an internal security/architecture call, the same category as `D15` (Okta vs.
|
||||
LDAPS), not a feature a user asked for.
|
||||
|
||||
Requested/raised by Matt Mabrey, 2026-09-17.
|
||||
|
||||
---
|
||||
|
||||
## CR-019 — Usage and activity metrics (admin console)
|
||||
|
||||
- **Area:** Admin Console / Monitoring
|
||||
- **Priority:** proposed High — the current admin console has no reliable way to
|
||||
answer "who is using this and how much," which is the same visibility gap the
|
||||
original UX review found in `B4` (numbers that look authoritative but are not).
|
||||
- **Source:** Matt Mabrey, 2026-09-17.
|
||||
|
||||
### Why this is not already built
|
||||
|
||||
`D5`/`T7.10` already shipped a usage-analytics feature — `html/wp-usage.js`, with
|
||||
a report at `admin.js:666-699` — but it reads `localStorage`, which is scoped to
|
||||
one browser. The report's own empty state says exactly this: *"No usage recorded
|
||||
in this browser yet."* It cannot show who across the team is active or what they
|
||||
use, because each person's activity exists only on their own machine. This is the
|
||||
same class of defect `B4` named for the pipeline strip — a number that looks
|
||||
authoritative but is not — just never generalized to this feature. `CR-019` is
|
||||
therefore new server-side work, not a UI addition on top of what exists.
|
||||
|
||||
Two things already in the schema are relevant and reused rather than duplicated:
|
||||
`User.last_login_at` (one timestamp, no history) and `AuditLog` (append-only,
|
||||
already records business mutations — WP created, status changed, role changed —
|
||||
per user, with a timestamp). Neither captures navigation or feature-open events,
|
||||
which is the actual gap.
|
||||
|
||||
### Intent
|
||||
|
||||
Give admins a real, server-backed picture of who is using the suite, what parts
|
||||
of it they use, and how active they are — replacing the per-browser report as
|
||||
the thing anyone actually looks at.
|
||||
|
||||
### Decisions, made 2026-09-17
|
||||
|
||||
1. **Retention: indefinite.** No automatic purge of usage-event data. (Separate
|
||||
from `AuditLog`'s own retention, which this does not change.)
|
||||
2. **Scope: suite-wide, filterable.** Not per-project by default; the console
|
||||
provides filters (date range, project, user, tool/page) rather than scoping
|
||||
the data itself.
|
||||
3. **Export: raw view shows real identities; export supports sanitization.**
|
||||
The admin console's own tables and the CSV export both default to real
|
||||
usernames — this is an internal audit tool, not a public one. But the export
|
||||
also offers a "sanitize" toggle that replaces the actor with a **stable
|
||||
pseudonymous id** (a per-user hash, consistent across rows and across
|
||||
export runs) rather than dropping the identity field outright — so an
|
||||
external system (Power BI or similar) can still group and trend "by user"
|
||||
without ever receiving a real name. Flagged here as the recommended
|
||||
approach rather than the only one Matt confirmed in so many words: if a
|
||||
fully-anonymous (no stable id at all) export turns out to be what's
|
||||
actually wanted, that is a one-line change to the same feature, raise it
|
||||
in the PR rather than treating it as blocking.
|
||||
4. **The old per-browser report is retired**, not kept alongside the new one.
|
||||
Once `CR-019` ships, `admin.js`'s existing `usage-admin` panel (reading
|
||||
`WPUsage.load(...)` per browser) is removed rather than left next to the
|
||||
real report, where it would show a smaller, misleading number for whoever
|
||||
happens to have it open. `html/wp-usage.js` and its two call sites
|
||||
(`html/work-package-suite-app.js`'s wizard dwell-tracking, and the
|
||||
creator's equivalent) are a separate question — the *recording* code can
|
||||
stay or go independent of the *admin report* being retired, since dwell
|
||||
events were never reliably tied to a real identity anyway. Default to
|
||||
removing both unless a task finds a reason to keep the recorder; log that
|
||||
reason rather than deciding it here.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
- A new admin-only tab in `admin.html` (same role gate as the User Directory)
|
||||
shows: active users over a selectable date range (day/week/month), each
|
||||
user's last-active timestamp, and a breakdown of which tools/pages get
|
||||
opened and how often.
|
||||
- Server-side event capture, keyed to the authenticated session (real identity,
|
||||
not a browser-local guess) — a new table, not an extension of `AuditLog`,
|
||||
since page-open/navigation events are not business mutations and mixing them
|
||||
in would make `AuditLog` noisy for its existing, narrower purpose.
|
||||
- The console's filters cover date range, project, user, and tool/page, and
|
||||
combine (e.g., "user X, last 30 days, field view only").
|
||||
- CSV export from the console, in both raw (real usernames) and sanitized
|
||||
(stable pseudonymous id per user) modes.
|
||||
- Retention is indefinite; nothing in this item purges data.
|
||||
- View-only, refresh-on-load. No alerting — matches how the rest of the admin
|
||||
console works today; if that changes later it is new scope, not a rider on
|
||||
this item.
|
||||
- The old per-browser "Usage" report and its admin-console panel are removed
|
||||
in the same wave, not left running alongside the new one.
|
||||
- Accessible per `CLAUDE.md`'s standing `C1` rules (this is a new component,
|
||||
not a legacy one — it ships accessible or it is not done, same as
|
||||
everything else built since wave 7).
|
||||
|
||||
### Frontend/backend boundary
|
||||
|
||||
This needs server work, the same way `CR-004`/`CR-018`/`B4` did: a real table,
|
||||
a capture endpoint, an aggregation endpoint, and an export endpoint. If a task
|
||||
under this item is being built by writing to `localStorage`, it is rebuilding
|
||||
the exact defect this item exists to replace — stop and say so, per
|
||||
`CLAUDE.md`.
|
||||
|
||||
### Scheduling
|
||||
|
||||
New wave. Wave 10 (Okta) is merged, so this does not wait on anything.
|
||||
Task breakdown: `docs/waves/wave-11.md`.
|
||||
|
||||
---
|
||||
|
||||
## CR-020 — Bulk editing of users in the admin console
|
||||
|
||||
- **Area:** Admin Console / User Directory
|
||||
- **Priority:** proposed High — three of the four actions below touch access
|
||||
control (role, project assignment, active/disabled) and the fourth is a hard
|
||||
delete; getting the guardrails right matters more than getting it built fast.
|
||||
- **Source:** Matt Mabrey, 2026-09-17.
|
||||
|
||||
### Why this is not already built
|
||||
|
||||
Every user-editing action in `html/users.js` today is one row, one action:
|
||||
a role `<select>` per row, an activate/disable button per row, a
|
||||
per-user project-membership checklist opened one user at a time, and a
|
||||
per-row delete. There is no row selection in the User Directory table at all.
|
||||
Server-side, every corresponding endpoint
|
||||
(`/api/auth/users/{id}/active`, `/role`, `/project-role`, `/projects`, and
|
||||
`DELETE /api/auth/users/{id}`) takes exactly one `user_id`. Bulk editing is new
|
||||
UI (selection) and, for most actions, either a loop over the existing
|
||||
single-user endpoints or new endpoints that accept a list — the task decides
|
||||
which, per user count and transaction-safety needs.
|
||||
|
||||
**Deletion is already a hard delete today** (`delete_user`, `server/app.py:1121`
|
||||
— `db.delete(u)`, not a deactivate). Bulk delete inherits that: it is not this
|
||||
item's job to invent a soft-delete pattern that does not exist for the single
|
||||
case, but the confirmation step around it has to be sized for the fact that a
|
||||
bad multi-select now removes more than one account at once, permanently.
|
||||
|
||||
### Decisions, made 2026-09-17
|
||||
|
||||
1. **All four bulk actions are in scope:** role change, activate/disable,
|
||||
project assignment (add to / remove from a project, including the
|
||||
project-role), and delete.
|
||||
2. **Selection works two ways:** checkboxes (select-all and individual) in the
|
||||
existing User Directory table, respecting whatever filter is already
|
||||
applied (role, active/disabled, project) — and a CSV upload, for a one-off
|
||||
bulk operation against an external list (e.g., an offboarding list that
|
||||
didn't originate in this app). Both are in scope, not a choice between them.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
- The User Directory table gains row checkboxes and a select-all that respects
|
||||
the current filter; a bulk-action toolbar appears once at least one row is
|
||||
selected.
|
||||
- CSV upload as an alternative to checkbox selection: a list of usernames plus
|
||||
the action to apply. Validates every row, reports rejected ones by row (bad
|
||||
username, user not found, actor lacks permission over that user) rather than
|
||||
silently skipping them — the same validate-and-report pattern `CR-005`
|
||||
established for list uploads.
|
||||
- Every existing single-user guardrail carries forward unchanged: an actor
|
||||
cannot include their own account in a bulk action that would disable, demote,
|
||||
or delete it; a super user's bulk action is scoped to only the users and
|
||||
projects `require_see_user`/`require_manage_user` already let them touch
|
||||
today (a super user cannot use a bulk action to reach a user or project
|
||||
outside what they manage, even via CSV); `grantable_roles` still gates which
|
||||
roles an actor may assign in bulk, the same as one at a time.
|
||||
- Every affected row is written to `AuditLog` individually, exactly as the
|
||||
single-user endpoints do today (one `role_changed` / `user_deleted` / etc.
|
||||
row per user) — a bulk action is many audited changes, not one opaque batch
|
||||
entry, so per-user history stays intact and readable in isolation.
|
||||
- Confirmation before applying, using the `wp-dialog` kit (`T7.9`), not a
|
||||
native `confirm()`. The dialog names exactly how many users are affected and,
|
||||
for delete specifically, lists the affected usernames before committing.
|
||||
- Partial failure is reported, not hidden: if some rows in a batch fail (scope,
|
||||
already-deleted, bad CSV row), the action applies to what it can and states
|
||||
exactly which rows failed and why. It never reports success on a batch that
|
||||
partly failed.
|
||||
- Accessible per `C1`: real controls, keyboard-operable selection and bulk-
|
||||
action toolbar, `aria-live` announcing the result.
|
||||
|
||||
### Recommended, not yet confirmed — raise in the PR if this is wrong
|
||||
|
||||
- **Bulk delete gets an extra confirmation step beyond naming the count** —
|
||||
proposed as typing a confirmation phrase (e.g. the word `DELETE`) regardless
|
||||
of how many rows are selected, since one bad multi-select now removes more
|
||||
than one account, permanently, with no soft-delete to fall back on. This is
|
||||
a recommendation, not a confirmed requirement — Matt has not signed off on
|
||||
the exact mechanism.
|
||||
- **Project assignment is add/remove, not replace-the-whole-list** — a bulk
|
||||
"add these users to project X" or "remove these users from project X"
|
||||
action, rather than a bulk action that overwrites a user's entire project
|
||||
list. Proposed because add/remove is less likely to clobber project
|
||||
memberships the actor didn't intend to touch; a replace-the-whole-list
|
||||
version is a materially different (and riskier) feature if that turns out to
|
||||
be what's actually wanted.
|
||||
|
||||
### Confirmed 2026-10-06 (Matt Mabrey, at the start of wave 12)
|
||||
|
||||
Both recommendations above are confirmed as written, and the two details
|
||||
`wave-12.md` left to the build are decided:
|
||||
|
||||
1. **Bulk delete:** the dialog lists the affected usernames and the request is
|
||||
not sent until the word `DELETE` is typed, whatever the count.
|
||||
2. **Project assignment is add/remove** to or from one project at a time, with
|
||||
the per-project permissions role (`ProjectMember.role`) set on add. It never
|
||||
replaces a user's whole project list.
|
||||
3. **Changing the table filter clears the selection** (T12.2), and the toolbar
|
||||
says so, so no row hidden by the filter stays selected.
|
||||
4. **The CSV holds usernames only** (T12.4). The action and its settings are
|
||||
chosen in the toolbar and apply to every valid row of the file.
|
||||
|
||||
### Frontend/backend boundary
|
||||
|
||||
Selection state (which rows are checked) is fine as client-side UI state — it
|
||||
is not persisted data. Everything the bulk action actually does (role,
|
||||
active/disabled, project membership, delete) already requires server work
|
||||
today for the single-user case, and bulk does not change that: no new
|
||||
localStorage-derived state, no client-side aggregation of what changed.
|
||||
|
||||
### Scheduling
|
||||
|
||||
New wave. Independent of wave 11 (`CR-019`) — the two do not touch the same
|
||||
code and can build in either order or in parallel. Task breakdown:
|
||||
`docs/waves/wave-12.md`.
|
||||
|
||||
---
|
||||
|
||||
## D18 — Detecting and acting on Okta/AD deprovisioning
|
||||
|
||||
- **Raised by:** Matt Mabrey, 2026-09-17, in response to a direct question about
|
||||
what happens when someone's AD account is removed and Okta subsequently drops
|
||||
them.
|
||||
- **Amends:** nothing decided, closes a gap `D15`/`D16` left unaddressed. Those
|
||||
items designed how identity flows *into* this app (Okta authenticates, this
|
||||
app JIT-provisions and owns roles); neither addressed what happens when an
|
||||
identity is withdrawn. This app has never had any deprovisioning signal —
|
||||
push or pull — since Okta went live.
|
||||
|
||||
### What was found
|
||||
|
||||
Traced through `server/auth.py` and `server/okta_auth.py`: this app has no
|
||||
connection back to Okta after initial sign-in. Consequences, confirmed against
|
||||
the actual code:
|
||||
|
||||
1. A local `users` row is never touched by anything Okta-side. `is_active`
|
||||
stays `True` indefinitely unless an admin manually disables or deletes the
|
||||
account through the User Directory. There is no flag distinguishing a
|
||||
terminated employee's account from a current one.
|
||||
2. `get_current_user` (`server/auth.py:237`) re-checks `is_active` and
|
||||
`token_version` on **every request** — so a manual disable takes effect
|
||||
immediately, on the very next request. The gap is not enforcement, it's
|
||||
detection: nothing tells an admin to go flip that switch.
|
||||
3. A session already live when someone is deprovisioned keeps working, fully,
|
||||
for up to `AUTH_SESSION_HOURS` (12 hours today, `server/auth.py:63`),
|
||||
because validity is checked against this app's own JWT and DB state only,
|
||||
never against Okta.
|
||||
4. A NEW session can't be established once Okta drops the account —
|
||||
`okta_login`/`okta_callback` requires completing Okta's own sign-in, which
|
||||
Okta itself refuses. The front door closes on its own; the back door (an
|
||||
already-open session, and the stale local record) does not.
|
||||
|
||||
### Decisions, made 2026-09-17
|
||||
|
||||
1. **Build a scheduled sync against Okta's Management API**, not an Event Hook.
|
||||
This app has, since `D15`, only ever reached out to Okta — never received
|
||||
anything from it — and a polling design keeps that shape rather than
|
||||
introducing a new inbound, internet-reachable endpoint with its own
|
||||
signature-verification surface. Traded deliberately: this is
|
||||
poll-interval-late rather than real-time, which is judged acceptable for an
|
||||
HR/offboarding-driven event, not a to-the-second requirement.
|
||||
2. **Revised 2026-09-23, in response to Matt's question about idle time
|
||||
instead of a flat session length: sessions now slide on activity, with a
|
||||
hard ceiling underneath.** A flat `AUTH_SESSION_HOURS` forces a re-check
|
||||
with Okta on a fixed schedule regardless of activity; a pure idle timer
|
||||
with no ceiling does the opposite — a continuously-active session would
|
||||
never force a fresh Okta check on its own, which is a worse fit for the
|
||||
exact threat this item exists to address (someone still clicking around
|
||||
after being deprovisioned). Decided: **both**.
|
||||
- `AUTH_IDLE_MINUTES` (new, default **30**): a session with no request
|
||||
for this long stops being valid. Implemented as a sliding JWT expiry —
|
||||
the token is reissued with a fresh `exp` on activity, throttled so the
|
||||
cookie isn't rewritten on literally every request.
|
||||
- `AUTH_SESSION_HOURS` (existing var, meaning changes to an **absolute
|
||||
ceiling**): no session survives past this many hours from the original
|
||||
sign-in, no matter how continuously active it is. Default changing from
|
||||
12 to a proposed **8** — flagged as a recommendation, not confirmed.
|
||||
- Both defaults, and the mechanism itself, should be sanity-checked
|
||||
against the tenant's actual Okta SSO session policy — if Okta's own
|
||||
session silently outlives either number, re-authentication here is
|
||||
likely a fast redirect, not a real re-login screen, so these numbers
|
||||
cost less than they look like they do. Confirm before treating either
|
||||
as final.
|
||||
3. **The sync only ever disables an account — it never re-enables one.** A
|
||||
rehire showing active in Okta again does not automatically restore access;
|
||||
an admin re-enabling the account is a deliberate act, consistent with
|
||||
`D16`'s posture that this app never auto-grants access on its own initiative.
|
||||
4. **Fail closed on the side of INACTION, not disablement.** This is the
|
||||
opposite failure direction from `D16`'s login-time posture ("if Okta is
|
||||
unreachable, the app is unreachable for everyone"). Here, an Okta API
|
||||
error, timeout, empty response, or anything the sync can't confidently
|
||||
parse must result in **no change to any account** that cycle, plus a
|
||||
logged failure. A sync job that treats "couldn't reach Okta" as "nobody is
|
||||
active" is a far worse outcome than a missed cycle — it would lock out the
|
||||
entire org on an Okta API hiccup. This is the single most important
|
||||
acceptance criterion in this item.
|
||||
5. **Every auto-disable is audited individually**, same as every other
|
||||
account-state change in this app: an `AuditLog` row per user, with an actor
|
||||
value that's clearly the sync job and not a person (e.g.
|
||||
`system:okta_sync`), so it reads correctly in the User Directory's history
|
||||
and is never confused with an admin's own action.
|
||||
6. **New credential required:** a read-scoped Okta API token (or an Okta
|
||||
service-app OAuth2 client), separate from the `OKTA_CLIENT_ID`/
|
||||
`OKTA_CLIENT_SECRET` pair used for sign-in. This needs provisioning by
|
||||
whoever administers the Okta tenant — the same dependency that gated the
|
||||
original OIDC rollout (D15's "security scoping reply").
|
||||
|
||||
### Recommended, not yet confirmed — raise in the PR if this is wrong
|
||||
|
||||
- **Sync interval:** proposed every 15 minutes. Frequent enough that the
|
||||
detection gap is small, infrequent enough not to hammer Okta's API or need
|
||||
special rate-limit handling. Not confirmed with IT/security.
|
||||
- **Where the job runs:** proposed as an in-process background task inside the
|
||||
existing `api` container (it already has `outbound` network access to reach
|
||||
Okta, and already holds the Okta client config) rather than a new sidecar
|
||||
container. The `backup` container (`docker-compose.yml`) is the existing
|
||||
precedent for a scheduled-interval container in this stack, if isolation
|
||||
from the `api` process is preferred instead — a reasonable alternative, not
|
||||
the recommendation.
|
||||
- **Admin visibility:** at minimum, an auto-disable is a normal, readable
|
||||
`AuditLog` entry (visible whever admin already reviews audit history, and
|
||||
naturally covered once `CR-019`'s activity view exists). Whether it should
|
||||
also trigger an email/notification to admins is a genuine open question —
|
||||
proposed as a fast-follow rather than blocking this item, since `D10`
|
||||
already established the pattern for admin-controlled email toggles this
|
||||
could reuse.
|
||||
|
||||
### Frontend/backend boundary
|
||||
|
||||
Entirely server-side and infrastructure. No new `localStorage` state, no
|
||||
frontend surface beyond what already reads `is_active` and `AuditLog` today
|
||||
(the User Directory, and eventually `CR-019`'s activity view).
|
||||
|
||||
### Scheduling
|
||||
|
||||
New wave, independent of wave 11 and wave 12 in the sense that nothing here is
|
||||
blocked by them — but note it touches the same `is_active`/account-state
|
||||
surface `CR-020`'s bulk actions touch in `server/app.py`. Not a hard
|
||||
dependency; sequence commits to avoid an avoidable merge conflict, per
|
||||
`CLAUDE.md`'s "one task per PR" spirit. Task breakdown: `docs/waves/wave-13.md`.
|
||||
84
docs/waves/decisions-2026-10-02.md
Normal file
84
docs/waves/decisions-2026-10-02.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Decisions — October 2, 2026
|
||||
|
||||
Three items, from the security review of 2026-10-01
|
||||
(`docs/reference/security-review-2026-10-01.md`). They get `D` ids because they
|
||||
are internal security calls made mid-build, the same category as `D15` and
|
||||
`D18`, not features a user asked for.
|
||||
|
||||
Decided by Matt Mabrey, 2026-10-02.
|
||||
|
||||
| Item | Title | Review finding | Task |
|
||||
|---|---|---|---|
|
||||
| `D19` | Uploaded files download safely | SEC-01, SEC-15e (BL-035, BL-036) | T16.2 |
|
||||
| `D20` | One SOP per project | SEC-02 (BL-048) | T16.3 |
|
||||
| `D21` | Session decode fails closed; PyJWT upgraded | SEC-07 (BL-052) | T16.1 |
|
||||
|
||||
**Schedule:** wave 16. It is **independent of waves 12 to 15**: it touches
|
||||
`server/` only, and no file in it is changed by a task in those waves except
|
||||
`server/app.py`, in functions they do not touch (`get_wp_file`, `upsert_sop`,
|
||||
the SOP baseline readers). Wave 16 may merge before wave 12.
|
||||
|
||||
**Out of this round, by decision:** SEC-06 (session revocation) waits for the
|
||||
AWS work. All other SEC findings stay as backlog drafts in
|
||||
`docs/reference/security-review/backlog-drafts.md`.
|
||||
|
||||
---
|
||||
|
||||
## D19 — Uploaded files download safely
|
||||
|
||||
- **Problem:** an SVG drawing can carry a script. The server sends it back
|
||||
`inline` with its own content type, on the app's origin, so the script runs
|
||||
as whoever opens it (SEC-01). Separately, a file name that is not Latin-1
|
||||
(for example `Plan é.pdf`) makes the download fail with 500, and CR/LF in a
|
||||
name reaches the response header (SEC-15e).
|
||||
- **Decision:** SVG uploads stay **accepted**, but every file that is not a
|
||||
PDF or a raster image downloads as an **attachment** inside a **sandbox**:
|
||||
`Content-Disposition: attachment` and
|
||||
`Content-Security-Policy: sandbox; default-src 'none'`. PDF and raster images
|
||||
(PNG, JPEG, GIF, WebP, BMP, AVIF) keep opening inline. Every file name goes
|
||||
out in the RFC 6266 / RFC 5987 form (ASCII fallback plus `filename*`).
|
||||
- **Why accept SVG instead of refusing it:** no change for the person who
|
||||
uploads, and no migration for SVGs already stored. The protection is on the
|
||||
way out, which also covers any SVG already in the database.
|
||||
- **Must not change:** inline preview of PDF and images (CR-007), the
|
||||
`Cache-Control` the offline drawing cache relies on, the D8 limits, and the
|
||||
upload API.
|
||||
|
||||
## D20 — One SOP per project
|
||||
|
||||
- **Problem:** the rule "changing a completed SOP is a Project Admin action"
|
||||
checks only the SOP row being posted. A `project_user` can post a NEW SOP id
|
||||
with `complete: true`. Every reader picks "the latest complete SOP", so that
|
||||
row becomes the baseline every page loads and the source of PM, CM and QA
|
||||
mail routing (SEC-02, probe S3).
|
||||
- **Decision:**
|
||||
1. A project has one SOP, with the id `sop__<project_id>`. The browser has
|
||||
always written that id (`pushSOP` in `project-data.js`). A request with no
|
||||
id gets it. A request that would CREATE a SOP with any other id on a
|
||||
project is refused with 400.
|
||||
2. Existing SOP rows with other ids (for example rows `seed_demo.py` made)
|
||||
stay. They can still be updated under the old rules. Nothing is deleted.
|
||||
3. While a project has a complete SOP, writing any SOP on that project with
|
||||
`complete: true`, and changing a complete SOP, needs Project Admin on the
|
||||
project.
|
||||
4. The readers prefer the canonical row: `project_sop_team`,
|
||||
`project_qa_group`, `project_summary` and `GET /api/sops/latest` with
|
||||
`complete=true&project_id=` read `sop__<project_id>` when it is complete,
|
||||
and fall back to "latest complete" only when it is not. So a rogue row
|
||||
made before this fix cannot stay the baseline.
|
||||
- **Must not change:** a project member drafting the SOP and completing it the
|
||||
first time (allowed today, allowed after); admin access to project-less
|
||||
SOPs; the response shape of every SOP route.
|
||||
|
||||
## D21 — Session decode fails closed; PyJWT upgraded
|
||||
|
||||
- **Problem:** a crafted 1.6 KB cookie makes PyJWT 2.13.0 raise an error that
|
||||
`decode_token` does not catch, so an unauthenticated request gets a 500 and
|
||||
a stack trace in the log (SEC-07, probe S12). `pip-audit` lists 13
|
||||
advisories for 2.13.0.
|
||||
- **Decision:** pin **PyJWT 2.15.1** (`pip-audit`: no known vulnerabilities on
|
||||
2026-10-02). `decode_token` treats ANY decode failure, and any cookie longer
|
||||
than 4096 characters, as "not signed in" (401). It also requires the `exp`
|
||||
and `sub` claims, which every token this app issues carries.
|
||||
- **Must not change:** every valid session, the D18 sliding refresh and
|
||||
ceiling, and the fake Okta test seam.
|
||||
@@ -1,263 +0,0 @@
|
||||
# Wave 12 — Bulk editing of users
|
||||
|
||||
**Items:** `CR-020`
|
||||
**Depends on:** wave 10 merged (it is). Independent of wave 11 (`CR-019`) — no
|
||||
shared files, may build in either order or in parallel.
|
||||
**Decision record:** `docs/waves/decisions-2026-09-17.md` (open details
|
||||
confirmed 2026-10-06, see "Confirmed 2026-10-06" in the CR-020 section)
|
||||
|
||||
**Branch (decided 2026-10-06):** `feat/wave-12-bulk-users`, cut from `main`
|
||||
(`df20b8f`, production). Only this file and the decision record come across
|
||||
from `feat/waves-11-13`, so the PR into `main` is wave 12 alone: no wave 11
|
||||
code and no T13.1, which must not reach `main` before T14.1. Wave 16 is not
|
||||
merged yet; it touches different functions, and whichever lands second rebases.
|
||||
|
||||
Six tasks, in build order.
|
||||
|
||||
---
|
||||
|
||||
### T12.1 — CR-020: bulk endpoints
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** nothing (first task)
|
||||
- **Blocks:** T12.2, T12.4
|
||||
- **Surface:** `server/`
|
||||
- **Files:** `server/app.py`
|
||||
|
||||
**Do:** Add bulk variants of the four existing single-user actions — role
|
||||
change, active/disabled, project assignment (add/remove + project-role), and
|
||||
delete. Each takes a list of `user_id`s plus the action's parameters and
|
||||
applies `require_see_user`/`require_manage_user`/`grantable_roles` **per row**,
|
||||
exactly as the single-user endpoint does today — a super user's bulk request
|
||||
cannot reach further than their existing single-user requests can. Do not skip
|
||||
the self-action guard: an actor's own account is rejected out of any batch
|
||||
that would disable, demote, or delete it, same as today.
|
||||
|
||||
Each successful row writes its own `AuditLog` entry via `log_event`, same
|
||||
action names the single endpoints already use. A row that fails is reported in
|
||||
the response (user id, reason) and does not stop the rest of the batch from
|
||||
being attempted.
|
||||
|
||||
**Do not:** invent a single opaque "bulk_action" audit entry in place of the
|
||||
per-row entries. Do not build a soft-delete path for bulk delete that doesn't
|
||||
exist for the single case — bulk delete stays a hard delete, matching
|
||||
`delete_user` today.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] each of the four bulk actions is callable with a list of user ids and a
|
||||
single set of parameters
|
||||
- [x] a batch containing the actor's own account rejects only that row, not
|
||||
the whole batch — verified for disable, demote, and delete
|
||||
- [x] a super user's batch that includes a user/project outside what they
|
||||
manage rejects only that row, with a stated reason
|
||||
- [x] every successful row produces its own `AuditLog` entry, identical in
|
||||
shape to what the single-user endpoint would have written
|
||||
- [x] a batch with some failing rows still applies to the rows that succeed,
|
||||
and the response lists exactly which rows failed and why
|
||||
|
||||
---
|
||||
|
||||
### T12.2 — CR-020: row selection in the User Directory table
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** T12.1
|
||||
- **Blocks:** T12.3
|
||||
- **Surface:** `html/`
|
||||
- **Files:** `html/users.js`, `html/users.html`
|
||||
|
||||
**Do:** Add a checkbox per row and a select-all control, respecting whatever
|
||||
filter (`role`, `active`/`disabled`, project) is currently applied — select-all
|
||||
selects the filtered set, not every user in the system regardless of what's
|
||||
shown. A bulk-action toolbar appears once at least one row is checked and
|
||||
disappears at zero.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] select-all selects exactly the rows currently visible under the active
|
||||
filter, not the full unfiltered table
|
||||
- [x] changing the filter while rows are selected does something sane and
|
||||
visible (either clears the selection or keeps it explicit which rows are
|
||||
still selected) — pick one and state it, don't leave it undefined
|
||||
- [x] the toolbar is keyboard-reachable and only present when >=1 row is
|
||||
selected
|
||||
|
||||
---
|
||||
|
||||
### T12.3 — CR-020: bulk-action toolbar
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** T12.2
|
||||
- **Blocks:** T12.5
|
||||
- **Surface:** `html/`
|
||||
- **Files:** `html/users.js`
|
||||
|
||||
**Do:** Wire the toolbar to T12.1's endpoints for role change, activate/
|
||||
disable, and project assignment (add to / remove from a project + project-
|
||||
role). Confirmation before applying uses the `wp-dialog` kit (`T7.9`) —
|
||||
`wpConfirmDialog`, not a native `confirm()` — naming exactly how many users are
|
||||
affected. On completion, report per-row results if anything failed (T12.1
|
||||
already returns this) rather than a single success/failure toast that hides a
|
||||
partial failure.
|
||||
|
||||
**Delete is built separately, in T12.5** — do not wire delete here.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] role change, activate/disable, and project assignment each work end to
|
||||
end against a multi-row selection
|
||||
- [x] the confirmation dialog names the exact affected count before anything is
|
||||
sent
|
||||
- [x] a batch with a partial failure shows which rows failed, not just an
|
||||
undifferentiated error
|
||||
- [x] `aria-live` announces the outcome
|
||||
|
||||
---
|
||||
|
||||
### T12.4 — CR-020: CSV upload path
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** T12.1
|
||||
- **Blocks:** T12.6
|
||||
- **Surface:** `html/` + `server/`
|
||||
- **Files:** `html/users.js`, `server/app.py`
|
||||
|
||||
**Do:** An upload accepting a list of usernames plus the action to apply,
|
||||
following the validate-and-report pattern `CR-005` established: reject and
|
||||
report bad rows (username not found, actor lacks permission over that user)
|
||||
rather than silently dropping them. This is a second entry point onto the same
|
||||
T12.1 endpoints, not a third implementation of the bulk logic.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] a CSV with a mix of valid and invalid usernames applies to the valid
|
||||
rows and reports the invalid ones by row, with a reason
|
||||
- [x] the same permission/self-action guards from T12.1 apply here — a CSV
|
||||
cannot reach a user a checkbox-driven batch couldn't
|
||||
- [x] duplicate usernames in one CSV are handled without double-applying or
|
||||
erroring confusingly
|
||||
|
||||
---
|
||||
|
||||
### T12.5 — CR-020: bulk delete confirmation
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** T12.3
|
||||
- **Blocks:** T12.6
|
||||
- **Surface:** `html/`
|
||||
- **Files:** `html/users.js`
|
||||
|
||||
**Do:** Wire delete into the toolbar with a heavier confirmation than the other
|
||||
three actions, per the decision record's recommendation: list the affected
|
||||
usernames and require typing a confirmation phrase (e.g. `DELETE`) before the
|
||||
request is sent, regardless of how many rows are selected. This is flagged in
|
||||
the decision record as a recommendation Matt has not explicitly signed off on
|
||||
— if the PR reviewer wants a lighter or heavier mechanism, that's the moment to
|
||||
change it, not a reason to skip building a real confirmation now.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] the affected usernames are listed in the confirmation dialog before
|
||||
delete is sent
|
||||
- [x] the request is not sent until the confirmation phrase is typed correctly
|
||||
- [x] the actor's own account, if somehow selected, is rejected with a clear
|
||||
reason rather than silently included or silently dropped
|
||||
|
||||
---
|
||||
|
||||
### T12.6 — CR-020: verification
|
||||
|
||||
- **Items:** `CR-020`
|
||||
- **Depends on:** T12.4, T12.5
|
||||
- **Blocks:** nothing
|
||||
- **Surface:** `html/` + `server/`
|
||||
- **Files:** as touched above
|
||||
|
||||
**Do:** Full verification per `CLAUDE.md`: run locally, exercise bulk role
|
||||
change, activate/disable, project assignment, CSV upload, and bulk delete at
|
||||
390px and 1440px, before/after screenshots, smoke test, `seed_demo.py`, full
|
||||
suite.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] all `CR-020` acceptance criteria in `decisions-2026-09-17.md` are met or
|
||||
a failure is stated with a reason
|
||||
- [x] screenshots committed
|
||||
- [x] smoke test and `seed_demo.py` both still pass
|
||||
- [x] full test suite passes
|
||||
|
||||
---
|
||||
|
||||
## Wave 12 exit criteria
|
||||
|
||||
- [x] all four bulk actions work against both a checkbox selection and a CSV
|
||||
upload
|
||||
- [x] every existing single-user guardrail (self-action, scope, grantable
|
||||
roles) holds under bulk use
|
||||
- [x] bulk delete requires typed confirmation and lists affected usernames
|
||||
- [x] partial failures are always reported, never hidden behind a blanket
|
||||
success
|
||||
- [x] `CR-020` fully accounted for, no open acceptance criteria
|
||||
|
||||
## Verification record
|
||||
|
||||
Built 2026-10-06 on `feat/wave-12-bulk-users`
|
||||
(from `main`, `df20b8f`), one commit per task. Run in the build sandbox (Linux,
|
||||
Python 3.10, no browser).
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `tests/bulk_users_check.py` (new, no browser) | **61/61**: all four actions, own-row refusals, super-user scope, per-row audit in the single route's shape, partial failure, project add/remove keeping other projects and roles, CSV resolve, 403/401/422 gates |
|
||||
| Same check against `main` | 7/18: the 7 single-route checks pass; every bulk check fails, because the routes do not exist there |
|
||||
| Single-user routes before/after (16 calls: 200/400/403/404, as admin and super user) | **Identical** responses, audit rows and memberships against `main`. The routes now call the same `apply_*` functions as the bulk routes |
|
||||
| Page logic, DOM harness (jsdom, the real `users.html` and scripts, mocked API) | **48/48**: selection, select-all over the filtered rows, filter clears selection, toolbar, confirm counts, per-row report, CSV, typed DELETE |
|
||||
| Same flows, jsdom against a real server seeded by `browser_check.seed()` | **13/13**, including the CSV report texts the browser probe expects |
|
||||
| `server/smoketest.py` | **27/27** |
|
||||
| `server/seed_demo.py` | Seeds the demo project |
|
||||
|
||||
**Decisions applied (confirmed 2026-10-06):** typed `DELETE`; project assignment
|
||||
is add/remove per project, with the per-project role (`ProjectMember.role`) set
|
||||
on add; filter or search change clears the selection; CSV holds usernames only.
|
||||
A row already in the requested state reports `unchanged` and writes no audit
|
||||
row (nothing changed). An email address in the CSV resolves only when exactly
|
||||
one account has it.
|
||||
|
||||
**Found and logged, not fixed:** BL-060, a super user's refusal reason promises
|
||||
a project-access change that neither the dialog nor the bulk route allows.
|
||||
|
||||
**Browser probes, run 2026-10-06 on Matt's machine (Windows, Chrome 153 / Edge 154,
|
||||
`.venv`), one at a time:**
|
||||
|
||||
| Probe | Result |
|
||||
|---|---|
|
||||
| `tests/bulk_users_ui_check.py` (new) | **19/19**: selection, Space on a row box, role change, super-user CSV (another job / not found / herself / duplicate, each by line), add-to-project with a role, typed DELETE, 390px bar fit, no JS errors |
|
||||
| `tests/console_dialogs_check.py` | **16/16**, including the new section 4 (bulk delete prompt, natives poisoned) |
|
||||
| `tests/mobile_check.py` | **24/24**, users page included |
|
||||
| `tests/a11y_check.py` | **22/22**: users page 66 focusable elements, all with a visible ring; helper text 5.02:1 at worst |
|
||||
| `tests/browser_check.py` | **67/71**, then re-pointed (below); **rerun after the re-point: all passed** (reported by Matt, 2026-10-06) |
|
||||
|
||||
**`browser_check.py` re-pointed (T12.6).** Its four failures were assertions
|
||||
written against column POSITIONS: the manager table had 9 columns, and the
|
||||
own-row checks read `r.cells[3]` (Permissions) and `r.cells[4]` (Project role).
|
||||
CR-020's selection column is first, so the table has 10 and those indexes
|
||||
landed on Username and Email. Not an app defect. The probe now expects 10
|
||||
columns with the selection column first, finds the two cells by their header
|
||||
name rather than their position (so the next column cannot break it the same
|
||||
way), and adds one check: your own row has no selection box. Verified against
|
||||
the real page in the DOM harness, then rerun in the browser: all passed.
|
||||
|
||||
**Screenshots** (after; the before-shots are `baseline/users-1440.png` and
|
||||
`baseline/after-wave9/users-390.png`): `baseline/wave-12/users-1440.png`,
|
||||
`users-1440-selected.png`, `users-390.png`, `users-390-selected.png`. Reviewed:
|
||||
the bar, its four groups and the selected-row marking render as designed at
|
||||
both widths; nothing scrolls sideways at 390px.
|
||||
|
||||
**Seen in the screenshots, not caused by wave 12, logged as BL-061:** the
|
||||
pre-existing sync badge ("Everything sent to the project", `project-data.js`)
|
||||
is drawn over a row's Delete button at 1440px and over "Set permissions" at
|
||||
390px for about 2 seconds after a load. It is `pointer-events:none`, so it never
|
||||
blocks a click, but it hides a control while it shows.
|
||||
|
||||
**Wave 12 closed 2026-10-06.** Every task done-when and every exit criterion
|
||||
above is checked. Pushed as `feat/wave-12-bulk-users`; PR into `main` open.
|
||||
Merge after wave 16 (`feat/wave-16-on-main`); both orders tested conflict-free.
|
||||
155
docs/waves/wave-16.md
Normal file
155
docs/waves/wave-16.md
Normal file
@@ -0,0 +1,155 @@
|
||||
# Wave 16 — Urgent security fixes
|
||||
|
||||
**Items:** `D19`, `D20`, `D21`
|
||||
**Depends on:** nothing. Independent of waves 12 to 15 (see the decision record).
|
||||
**Decision record:** `docs/waves/decisions-2026-10-02.md`
|
||||
**Background:** `docs/reference/security-review-2026-10-01.md`
|
||||
|
||||
Four tasks, in build order. All server-side. No page markup or stylesheet
|
||||
changes, so the 390px / 1440px screenshot rule does not apply; the
|
||||
browser probes that read files and SOPs are still listed for a run on a
|
||||
machine with Edge.
|
||||
|
||||
New check for this wave: `tests/security_check.py`. It is self-contained (its
|
||||
own SQLite database, in-process, no browser), so it runs anywhere.
|
||||
|
||||
---
|
||||
|
||||
### T16.1 — D21: session decode fails closed; PyJWT 2.15.1
|
||||
|
||||
- **Items:** `D21`
|
||||
- **Depends on:** nothing (first task)
|
||||
- **Blocks:** T16.4
|
||||
- **Surface:** `server/`
|
||||
- **Files:** `server/requirements.txt`, `server/auth.py` (`decode_token`), `tests/security_check.py` (new)
|
||||
|
||||
**Do:** pin `PyJWT==2.15.1`. In `decode_token`, return `None` for an empty or
|
||||
over-long token (over 4096 characters) and for any exception from
|
||||
`jwt.decode`. Require the `exp` and `sub` claims.
|
||||
|
||||
**Do not:** change token contents, the cookie, or the D18 refresh.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] the crafted-cookie request returns 401, not 500
|
||||
- [x] a valid session still works, and the D18 refresh still reissues
|
||||
- [x] `pip-audit -r server/requirements.txt` reports no PyJWT advisory
|
||||
- [x] smoke test 27/27
|
||||
|
||||
---
|
||||
|
||||
### T16.2 — D19: uploaded files download safely
|
||||
|
||||
- **Items:** `D19`
|
||||
- **Depends on:** nothing
|
||||
- **Blocks:** T16.4
|
||||
- **Surface:** `server/`
|
||||
- **Files:** `server/files_http.py` (new), `server/app.py` (`get_wp_file`), `tests/security_check.py`
|
||||
|
||||
**Do:** serve PDF and raster images inline as today. Serve every other type,
|
||||
SVG included, as an attachment with `Content-Security-Policy: sandbox;
|
||||
default-src 'none'`. Send `X-Content-Type-Options: nosniff` from the API too
|
||||
(NGINX already does; the dev server does not). Build `Content-Disposition`
|
||||
with an ASCII fallback and an RFC 5987 `filename*`. Reference code:
|
||||
`docs/reference/architecture-review/proposals/server/files_http.py` (P-6).
|
||||
|
||||
**Do not:** refuse SVG uploads (decided: accept, download only). Do not change
|
||||
`Cache-Control`.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] an SVG downloads as an attachment with the sandbox header
|
||||
- [x] PNG, JPEG and PDF still open inline
|
||||
- [x] `Plan é.pdf` downloads (was 500)
|
||||
- [x] a name with CR/LF produces a valid header
|
||||
- [x] `tests/files_check.py` passes on a machine with Edge (CR-007 offline drawings)
|
||||
|
||||
---
|
||||
|
||||
### T16.3 — D20: one SOP per project
|
||||
|
||||
- **Items:** `D20`
|
||||
- **Depends on:** nothing
|
||||
- **Blocks:** T16.4
|
||||
- **Surface:** `server/`
|
||||
- **Files:** `server/app.py` (`upsert_sop`, `latest_sop`, `project_summary`, `project_sop_team`, `project_qa_group`), `tests/security_check.py`
|
||||
|
||||
**Do:** the four rules in D20. One helper picks the project's baseline SOP
|
||||
(canonical row if complete, else latest complete) and every baseline reader
|
||||
uses it.
|
||||
|
||||
**Do not:** delete or rename existing SOP rows. Do not change any response shape.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] a `project_user` cannot create a second SOP on a project (400) or post
|
||||
`complete: true` while a complete SOP exists (403)
|
||||
- [x] a `project_user` can still draft and complete the first SOP of a project
|
||||
- [x] a Project Admin can still change the completed SOP
|
||||
- [x] POST without an id lands on `sop__<project_id>`
|
||||
- [x] a rogue complete SOP made before the fix no longer drives the baseline
|
||||
or the QA and PM/CM recipients
|
||||
- [x] `tests/sample_check.py` and `tests/critical_reopen_check.py` pass on a
|
||||
machine with Edge
|
||||
|
||||
---
|
||||
|
||||
### T16.4 — D19, D20, D21: verification
|
||||
|
||||
- **Items:** `D19`, `D20`, `D21`
|
||||
- **Depends on:** T16.1 to T16.3
|
||||
- **Surface:** verification
|
||||
- **Files:** this file (verification record)
|
||||
|
||||
**Done when:**
|
||||
|
||||
- [x] `tests/security_check.py` passes
|
||||
- [x] `docs/reference/security-review/sec_probe.py`: S3 and S12 change as
|
||||
expected; every other line is unchanged
|
||||
- [x] the architecture review `equivalence_check.py` (current branch vs wave
|
||||
16) is IDENTICAL: the scenario does not use these paths, so it proves the
|
||||
rest of the work-package flow did not move
|
||||
- [x] smoke test 27/27
|
||||
- [x] the browser probes named in T16.2 and T16.3 are listed for a run on a
|
||||
machine with Edge (not available in the build sandbox)
|
||||
|
||||
## Verification record
|
||||
|
||||
Run 2026-10-02 in the build sandbox (Linux, Python 3.10, no browser), on branch
|
||||
`feat/wave-16-security` at T16.3.
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `tests/security_check.py` | **36/36** (D21 6, D19 14, D20 16) |
|
||||
| Same check against `da1325c` with PyJWT 2.13.0 | 20/36. The 16 failures are the findings (D21 3, D19 6, D20 7). The 20 passes are the "still works" checks plus three that already held (over-long cookie 401, non-member 404, SOP move refused by the existing completed-SOP rule) |
|
||||
| `docs/reference/security-review/sec_probe.py`, before vs after | Exactly 4 of 27 lines change: S3 (new complete SOP 200 -> **400**; baseline `sop_rogue` -> **`sop__proj_a`**; QA group attacker -> **real group**) and S12 (crafted cookie 500 -> **401**). All other lines identical |
|
||||
| `equivalence_check.py` (architecture review), `da1325c` vs wave 16 | **IDENTICAL**: 78 HTTP results, 89 audit rows, 24 notifications. The scenario's SOP id was changed from `sop_eq` to the canonical `sop__proj_eq` on both sides, because D20 refuses a non-canonical id on purpose |
|
||||
| `server/smoketest.py` | **27/27** after each of T16.1, T16.2, T16.3 |
|
||||
| `server/seed_demo.py` | Seeds the demo project; its SOP lands on the canonical id |
|
||||
| `pip-audit -r server/requirements.txt` | No known vulnerabilities |
|
||||
|
||||
**Browser probes, run 2026-10-02 on Matt's machine (Windows, Edge 154,
|
||||
Python 3.12.10, `.venv`), one at a time:**
|
||||
|
||||
| Probe | Task | Result |
|
||||
|---|---|---|
|
||||
| `tests/files_check.py` | T16.2 | **36/36**, including the 1440px creator, 390px Field View, and the offline drawing cache with the server gone |
|
||||
| `tests/sample_check.py` | T16.3 | **10/10** |
|
||||
| `tests/critical_reopen_check.py` | T16.3 | **11/11**, PM + CM + assignee mail, sink-verified |
|
||||
|
||||
T16.2 and T16.3 are done.
|
||||
|
||||
**Production data check for D20, 2026-10-02.** On the production database
|
||||
(`wp_db`, psql): projects with more than one complete SOP: **0 rows**. D20 has
|
||||
no legacy duplicates to handle on deploy.
|
||||
|
||||
**Harness fix needed to get there (`tests/cdp.py`, committed with this record).**
|
||||
Every probe failed first with "browser would not start ... exited rc=0
|
||||
without binding the port". Cause: the PowerShell session was elevated, and
|
||||
Edge and Chrome de-elevate by relaunching themselves through Explorer as a
|
||||
normal user; the relaunch drops `--remote-debugging-port`. Edge's log said so
|
||||
(`Edge is running elevated: 1`). No browser policy was involved (all hives
|
||||
checked). Two changes, both inert on a normal shell and on Linux/macOS:
|
||||
`--do-not-de-elevate` on Windows, and a 15-second grace for the port when the
|
||||
launched process exits rc=0. Probe results are unchanged by it; it only lets
|
||||
the browser start.
|
||||
@@ -24,10 +24,7 @@
|
||||
The directory is one wide table, so the column exceptions live here: email is
|
||||
the one cell long enough to stretch a row, and the two role dropdowns need
|
||||
room for "Assistant Project Manager" without pushing Actions off screen. */
|
||||
/* The email cell, by its class: CR-020's selection column moved it from third to
|
||||
fourth on the managers' table, and a position-based rule would have followed
|
||||
the wrong column. */
|
||||
#users-table table td.ell{ max-width:230px; overflow:hidden; text-overflow:ellipsis; }
|
||||
#users-table table td:nth-child(3){ max-width:230px; overflow:hidden; text-overflow:ellipsis; }
|
||||
#users-banner:not(:empty), #scope-banner:not(:empty){ margin-bottom:var(--s3); }
|
||||
#nu-projects{ margin-top:var(--s2); }
|
||||
#nu-projects .pickrow{ padding:var(--s1) var(--s1); }
|
||||
@@ -36,45 +33,6 @@
|
||||
#nu-project-list{ max-height:200px; overflow:auto; border:1px solid var(--border); }
|
||||
.whoami-chip{ font-size:12px; color:var(--muted); }
|
||||
.whoami-chip strong{ color:var(--text); }
|
||||
|
||||
/* CR-020: row selection and the bulk bar. Tokens only (the token rule). */
|
||||
#sel-banner:not(:empty), #bulk-banner:not(:empty), #csv-banner:not(:empty){ margin-bottom:var(--s3); }
|
||||
#bulk-banner ul, #csv-banner ul{ margin:var(--s1) 0 0; padding-left:var(--s5); font-weight:400;
|
||||
max-height:220px; overflow:auto; }
|
||||
#csv-btn[hidden]{ display:none; }
|
||||
table.grid th.selcell, table.grid td.selcell{ width:1%; padding:0 var(--s1); text-align:center; }
|
||||
/* The label is the hit area: the 16px box alone is under the 24px floor. */
|
||||
.selhit{ display:inline-flex; align-items:center; justify-content:center;
|
||||
min-width:28px; min-height:28px; cursor:pointer; }
|
||||
.selhit input{ width:16px; height:16px; margin:0; accent-color:var(--accent); cursor:pointer; }
|
||||
.selhit input:focus-visible{ outline:2px solid var(--accent); outline-offset:2px; }
|
||||
.selhit input:disabled{ cursor:default; }
|
||||
/* Not --accent-soft: that is the admin pill's own fill (console.css, hover note). */
|
||||
table.grid tbody tr.is-selected td{ background:var(--cds-layer-selected); }
|
||||
table.grid tbody tr.is-selected td.selcell{ box-shadow:inset 3px 0 0 var(--accent); }
|
||||
.bulkbar{ border:1px solid var(--accent); border-left:3px solid var(--accent);
|
||||
background:var(--surface); padding:var(--s2) var(--s3); margin:0 0 var(--s3); }
|
||||
.bulkbar[hidden]{ display:none; }
|
||||
.bulkhead{ display:flex; align-items:center; justify-content:space-between; gap:var(--s2);
|
||||
flex-wrap:wrap; margin-bottom:var(--s2); }
|
||||
.bulkgroup{ display:flex; flex-wrap:wrap; align-items:center; gap:var(--s2);
|
||||
padding:var(--s2) 0; border-top:1px solid var(--border); }
|
||||
.bulkgroup > .bulklabel{ font-size:12px; font-weight:600; color:var(--muted); min-width:110px; }
|
||||
.bulkgroup select{ height:var(--ctl); padding:0 var(--s1) 0 var(--s2); font:inherit; font-size:13px;
|
||||
border:1px solid var(--border-strong); border-radius:0; background:var(--surface); color:var(--text);
|
||||
max-width:100%; }
|
||||
.bulkgroup select:focus-visible{ outline:2px solid var(--accent); outline-offset:-2px; }
|
||||
/* The bulk delete dialog lists every affected username; a long list scrolls
|
||||
inside the dialog instead of pushing its buttons off the screen. */
|
||||
#wp-dlg-msg{ max-height:50vh; overflow:auto; }
|
||||
@media (max-width:620px){
|
||||
.bulkgroup > .bulklabel{ min-width:0; flex:1 1 100%; }
|
||||
.bulkgroup select, .bulkgroup button{ flex:1 1 100%; }
|
||||
}
|
||||
@media (pointer:coarse){
|
||||
.selhit{ min-width:44px; min-height:44px; }
|
||||
.bulkbar button, .bulkgroup select{ min-height:44px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -105,33 +63,15 @@
|
||||
<div class="sub" id="people-sub"></div>
|
||||
<div class="toolbar">
|
||||
<button onclick="loadUsers()">Refresh</button>
|
||||
<input id="user-search" placeholder="Search name / username / email / job function…" oninput="filterChanged()"
|
||||
aria-label="Search the directory">
|
||||
<select id="user-filter" onchange="filterChanged()" aria-label="Show">
|
||||
<input id="user-search" placeholder="Search name / username / email / job function…" oninput="renderUsers()">
|
||||
<select id="user-filter" onchange="renderUsers()">
|
||||
<option value="">Everyone</option>
|
||||
<option value="active">Active only</option>
|
||||
<option value="disabled">Disabled only</option>
|
||||
<option value="mine">Accounts I manage</option>
|
||||
</select>
|
||||
<!-- CR-020 (T12.4): a list of usernames from a file becomes the selection.
|
||||
Managers only; users.js shows it. -->
|
||||
<button type="button" id="csv-btn" onclick="pickCsv()" hidden
|
||||
title="A CSV with one username (or email) per line, first column. The action is chosen in the bulk bar.">Select from CSV…</button>
|
||||
<input type="file" id="csv-file" accept=".csv,.txt,text/csv,text/plain" hidden>
|
||||
</div>
|
||||
<div id="users-banner"></div>
|
||||
<div id="csv-banner"></div>
|
||||
<!-- CR-020: bulk actions on the selected rows. Present only while at least one
|
||||
row is selected (the hidden attribute also takes it out of the tab order). -->
|
||||
<div id="bulk-bar" class="bulkbar" role="region" aria-label="Bulk actions on the selected users" hidden>
|
||||
<div class="bulkhead">
|
||||
<strong id="bulk-count">0 selected</strong>
|
||||
<button type="button" onclick="clearSelection(true)">Clear selection</button>
|
||||
</div>
|
||||
<div id="bulk-actions"></div>
|
||||
</div>
|
||||
<div id="sel-banner"></div>
|
||||
<div id="bulk-banner"></div>
|
||||
<div id="users-table"><div class="note">Loading…</div></div>
|
||||
</div>
|
||||
|
||||
|
||||
316
html/users.js
316
html/users.js
@@ -23,10 +23,6 @@
|
||||
let _users = []; // the directory as the server scoped it
|
||||
let _scope = null; // GET /api/auth/user-scope
|
||||
let _meId = null;
|
||||
// CR-020: the rows checked for a bulk action. Client-side UI state only - every
|
||||
// bulk action is decided and audited by the server, row by row (T12.1).
|
||||
let _selected = new Set();
|
||||
let _shownSelectable = []; // ids the current filter shows AND this caller may select
|
||||
|
||||
// ── boot ──────────────────────────────────────────────────────────────────────
|
||||
async function boot(){
|
||||
@@ -44,7 +40,6 @@ async function boot(){
|
||||
renderScope();
|
||||
}
|
||||
renderCreateForm();
|
||||
renderBulkActions();
|
||||
loadUsers();
|
||||
}
|
||||
|
||||
@@ -95,309 +90,11 @@ async function loadUsers(){
|
||||
}
|
||||
banner('users-banner','', '');
|
||||
_users = json;
|
||||
// Fresh data: any earlier selection may name accounts that changed or are gone.
|
||||
clearSelection(false);
|
||||
renderUsers();
|
||||
}
|
||||
|
||||
function manages(){ return !!(_scope && _scope.can_manage_users); }
|
||||
|
||||
// ── selection (CR-020, T12.2) ─────────────────────────────────────────────────
|
||||
// A row is selectable when this caller may change the account. Your own row is
|
||||
// not: every bulk action that could touch it (disable, demote, delete) is refused
|
||||
// for your own account, so offering it would only produce a guaranteed failure.
|
||||
function selectable(u){ return manages() && !!u.manageable && u.id !== _meId; }
|
||||
|
||||
// The search box and the filter both decide which rows are shown. Changing either
|
||||
// clears the selection (decided 2026-10-06), so no row hidden by the filter can
|
||||
// stay selected and be acted on without being seen.
|
||||
function filterChanged(){
|
||||
const had = _selected.size;
|
||||
clearSelection(false);
|
||||
renderUsers();
|
||||
banner('sel-banner', '', had ? 'Selection cleared: the filter changed. Select the rows again.' : '');
|
||||
}
|
||||
|
||||
function clearSelection(announce){
|
||||
const had = _selected.size;
|
||||
_selected = new Set();
|
||||
updateSelectionUI();
|
||||
banner('sel-banner', '', (announce && had) ? 'Selection cleared.' : '');
|
||||
}
|
||||
|
||||
function setRowSelected(id, on){
|
||||
if(on) _selected.add(id); else _selected.delete(id);
|
||||
}
|
||||
|
||||
// Select-all acts on the rows the filter shows, never on the whole directory.
|
||||
function toggleSelectAll(on){
|
||||
_shownSelectable.forEach(id => setRowSelected(id, on));
|
||||
banner('sel-banner', '', '');
|
||||
updateSelectionUI();
|
||||
}
|
||||
|
||||
// Reflect _selected into the page without re-rendering the table, so keyboard
|
||||
// focus stays on the checkbox that was just used.
|
||||
function updateSelectionUI(){
|
||||
const wrap = document.getElementById('users-table');
|
||||
if(wrap){
|
||||
wrap.querySelectorAll('input.selbox').forEach(cb => {
|
||||
const on = _selected.has(cb.dataset.id);
|
||||
cb.checked = on;
|
||||
const tr = cb.closest('tr');
|
||||
if(tr) tr.classList.toggle('is-selected', on);
|
||||
});
|
||||
const all = document.getElementById('sel-all');
|
||||
if(all){
|
||||
const n = _shownSelectable.filter(id => _selected.has(id)).length;
|
||||
all.checked = n > 0 && n === _shownSelectable.length;
|
||||
all.indeterminate = n > 0 && n < _shownSelectable.length;
|
||||
all.disabled = !_shownSelectable.length;
|
||||
}
|
||||
}
|
||||
const bar = document.getElementById('bulk-bar');
|
||||
if(bar){
|
||||
const n = _selected.size;
|
||||
bar.hidden = n === 0;
|
||||
const c = document.getElementById('bulk-count');
|
||||
if(c) c.textContent = n + ' selected';
|
||||
}
|
||||
}
|
||||
|
||||
// One listener for every checkbox in the table (event delegation): no ids are
|
||||
// bound into inline handlers, so there is nothing to escape.
|
||||
document.addEventListener('change', e => {
|
||||
const t = e.target;
|
||||
if(!(t instanceof HTMLInputElement)) return;
|
||||
if(t.id === 'sel-all'){ toggleSelectAll(t.checked); return; }
|
||||
if(t.classList.contains('selbox')){
|
||||
setRowSelected(t.dataset.id, t.checked);
|
||||
banner('sel-banner', '', '');
|
||||
updateSelectionUI();
|
||||
}
|
||||
});
|
||||
|
||||
// ── bulk actions (CR-020, T12.3) ──────────────────────────────────────────────
|
||||
// The toolbar offers only what this caller may do: the roles they may grant, the
|
||||
// projects they administer, the per-project roles they may hand out. The server
|
||||
// re-checks every row anyway (T12.1); this is so nobody is offered a choice that
|
||||
// can only fail.
|
||||
function renderBulkActions(){
|
||||
const box = document.getElementById('bulk-actions');
|
||||
const csvBtn = document.getElementById('csv-btn');
|
||||
if(csvBtn) csvBtn.hidden = !manages();
|
||||
if(!box || !manages()) return;
|
||||
const grantable = PERM_ROLES.filter(r => (_scope.grantable_roles || []).indexOf(r) >= 0);
|
||||
const projects = (_scope.managed_projects || []).slice()
|
||||
.sort((a,b) => (a.archived?1:0) - (b.archived?1:0));
|
||||
const projRoles = PROJECT_SCOPED_ROLES.filter(r => (_scope.grantable_project_roles || []).indexOf(r) >= 0);
|
||||
const group = (label, inner) => '<div class="bulkgroup" role="group" aria-label="'+uesc(label)+'">'+
|
||||
'<span class="bulklabel">'+uesc(label)+'</span>'+inner+'</div>';
|
||||
box.innerHTML =
|
||||
group('Permissions',
|
||||
'<select id="bulk-role" aria-label="New permissions role">'+
|
||||
grantable.map(r => '<option value="'+r+'"'+(r==='project_user'?' selected':'')+'>'+uesc(PERM_LABELS[r])+'</option>').join('')+
|
||||
'</select>'+
|
||||
'<button type="button" onclick="bulkRole()">Set permissions</button>') +
|
||||
group('Sign-in',
|
||||
'<button type="button" onclick="bulkActive(true)">Enable</button>'+
|
||||
'<button type="button" onclick="bulkActive(false)">Disable</button>') +
|
||||
(projects.length ? group('Project access',
|
||||
'<select id="bulk-project" aria-label="Project">'+
|
||||
projects.map(p => '<option value="'+uesc(p.id)+'">'+uesc((p.name||'(unnamed)')+(p.number?' '+p.number:'')+
|
||||
(p.archived?' (archived)':''))+'</option>').join('')+
|
||||
'</select>'+
|
||||
'<select id="bulk-project-role" aria-label="Role on that project, for Add">'+
|
||||
'<option value="">Role: same as account</option>'+
|
||||
projRoles.map(r => '<option value="'+r+'">Role: '+uesc(PERM_LABELS[r])+' here</option>').join('')+
|
||||
'</select>'+
|
||||
'<button type="button" onclick="bulkProject(\'add\')">Add to project</button>'+
|
||||
'<button type="button" onclick="bulkProject(\'remove\')">Remove from project</button>') : '') +
|
||||
group('Delete',
|
||||
'<button type="button" class="danger" onclick="bulkDelete()">Delete selected…</button>');
|
||||
}
|
||||
|
||||
function selectedIds(){ return _users.filter(u => _selected.has(u.id)).map(u => u.id); }
|
||||
function people(n){ return n + ' user' + (n === 1 ? '' : 's'); }
|
||||
function selVal(id){ return (document.getElementById(id) || {}).value || ''; }
|
||||
function selText(id){
|
||||
const s = document.getElementById(id);
|
||||
return (s && s.selectedIndex >= 0) ? s.options[s.selectedIndex].text : '';
|
||||
}
|
||||
|
||||
// One path for every bulk action: confirm through the dialog kit with the exact
|
||||
// count, send, report row by row, reload. A reload clears the selection, which is
|
||||
// right: the rows may have changed underneath it.
|
||||
async function runBulk(path, body, ask){
|
||||
const ids = selectedIds();
|
||||
if(!ids.length) return;
|
||||
if(!(await wpConfirmDialog({title: ask.title, okLabel: ask.ok, message: ask.message(ids.length)}))) return;
|
||||
return sendBulk(path, body, ask.title, ids);
|
||||
}
|
||||
|
||||
async function sendBulk(path, body, title, ids){
|
||||
bannerHtml('bulk-banner', '', uesc(title)+': working on '+uesc(people(ids.length))+'…');
|
||||
const { status, json } = await api('POST', path, Object.assign({ user_ids: ids }, body));
|
||||
if(status !== 200 || !json || !Array.isArray(json.results)){
|
||||
bannerHtml('bulk-banner', 'bad', '✕ '+uesc(apiError(status, json, title+' failed'))+' Nothing was changed.');
|
||||
return;
|
||||
}
|
||||
showBulkResult(json, title);
|
||||
loadUsers();
|
||||
}
|
||||
|
||||
// T12.5: delete is permanent (a hard delete, as for one account) and one bad
|
||||
// multi-select now removes many, so it asks more than the other actions do:
|
||||
// every affected username is listed, and nothing is sent until the word DELETE
|
||||
// is typed, whatever the count (confirmed 2026-10-06). Your own account cannot
|
||||
// be selected; if it ever reached the request, the server refuses that row and
|
||||
// the report names it.
|
||||
async function bulkDelete(){
|
||||
const chosen = _users.filter(u => _selected.has(u.id));
|
||||
if(!chosen.length) return;
|
||||
const n = chosen.length;
|
||||
const typed = await wpPromptDialog({
|
||||
title: 'Delete '+people(n),
|
||||
message: 'Delete '+(n === 1 ? 'this account' : 'these '+n+' accounts')+'? Each one, and every project '+
|
||||
'assignment it has, is removed. This cannot be undone. Disable them instead if you only want to '+
|
||||
'block sign-in.\n\n'+chosen.map(u => '• '+u.username+(u.full_name ? ' ('+u.full_name+')' : '')).join('\n'),
|
||||
label: 'Type DELETE to confirm',
|
||||
value: '',
|
||||
okLabel: 'Delete '+people(n),
|
||||
validate: v => v === 'DELETE' ? '' : 'Type DELETE, in capital letters, to confirm.',
|
||||
});
|
||||
if(typed !== 'DELETE') return;
|
||||
return sendBulk('/api/auth/bulk-users/delete', {}, 'Delete accounts', chosen.map(u => u.id));
|
||||
}
|
||||
|
||||
// Every row is accounted for: changed, already so, or failed with the server's
|
||||
// reason. A batch that partly failed never reads as a success (CR-020).
|
||||
function showBulkResult(json, title){
|
||||
const failed = json.results.filter(r => r.status === 'failed');
|
||||
const parts = [json.ok+' changed'];
|
||||
if(json.unchanged) parts.push(json.unchanged+' already set');
|
||||
if(failed.length) parts.push(failed.length+' failed');
|
||||
const kind = !failed.length ? 'ok' : (json.ok + json.unchanged ? 'warn' : 'bad');
|
||||
const lead = (failed.length ? (kind === 'bad' ? '✕ ' : '⚠ ') : '✓ ')+uesc(title)+': '+parts.join(', ')+'.';
|
||||
const list = failed.length
|
||||
? '<ul>'+failed.map(r => '<li><strong>'+uesc(r.username || r.user_id)+'</strong>: '+uesc(r.reason)+'</li>').join('')+'</ul>'
|
||||
: '';
|
||||
bannerHtml('bulk-banner', kind, lead + list);
|
||||
}
|
||||
|
||||
function bannerHtml(id, kind, html){
|
||||
const el = document.getElementById(id);
|
||||
if(!el) return;
|
||||
el.className = 'banner' + (kind ? ' '+kind : '');
|
||||
el.innerHTML = html;
|
||||
}
|
||||
|
||||
function bulkRole(){
|
||||
const role = selVal('bulk-role');
|
||||
if(!role) return;
|
||||
return runBulk('/api/auth/bulk-users/role', { role }, {
|
||||
title: 'Set permissions', ok: 'Change permissions',
|
||||
message: n => 'Set permissions to '+(PERM_LABELS[role] || role)+' for '+people(n)+'?\n\n'+
|
||||
'Each account is checked on its own. Any that cannot be changed are listed afterwards.'});
|
||||
}
|
||||
|
||||
function bulkActive(on){
|
||||
return runBulk('/api/auth/bulk-users/active', { is_active: !!on }, {
|
||||
title: on ? 'Enable accounts' : 'Disable accounts', ok: on ? 'Enable' : 'Disable',
|
||||
message: n => (on ? 'Enable sign-in for ' : 'Disable sign-in for ')+people(n)+'?'+
|
||||
(on ? '' : '\n\nA disabled account cannot sign in. Nothing else about it changes.')});
|
||||
}
|
||||
|
||||
function bulkProject(op){
|
||||
const pid = selVal('bulk-project');
|
||||
if(!pid) return;
|
||||
const role = op === 'add' ? selVal('bulk-project-role') : '';
|
||||
const pname = selText('bulk-project');
|
||||
return runBulk('/api/auth/bulk-users/projects', { project_id: pid, op, role }, {
|
||||
title: op === 'add' ? 'Add to project' : 'Remove from project',
|
||||
ok: op === 'add' ? 'Add' : 'Remove',
|
||||
message: n => op === 'add'
|
||||
? 'Add '+people(n)+' to '+pname+' with '+(role ? PERM_LABELS[role]+' on that project' : 'their account role')+'?\n\n'+
|
||||
'Their other projects, and their roles there, stay as they are.'
|
||||
: 'Remove '+people(n)+' from '+pname+'?\n\nTheir other projects stay as they are.'});
|
||||
}
|
||||
|
||||
// ── CSV upload (CR-020, T12.4) ────────────────────────────────────────────────
|
||||
// The file holds usernames only (decided 2026-10-06). The server reads it and
|
||||
// answers line by line; the accepted accounts become the ordinary selection, so
|
||||
// the action, its confirmation and its row-by-row report are the same ones the
|
||||
// checkboxes use. A CSV cannot reach an account a checkbox could not: the bulk
|
||||
// route re-checks every row.
|
||||
const CSV_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
// Blob.text() where the browser has it, FileReader where it does not (older
|
||||
// tablet browsers).
|
||||
function readFileText(file){
|
||||
if(typeof file.text === 'function') return file.text();
|
||||
return new Promise((resolve, reject) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => resolve(String(r.result || ''));
|
||||
r.onerror = () => reject(r.error);
|
||||
r.readAsText(file);
|
||||
});
|
||||
}
|
||||
|
||||
function pickCsv(){
|
||||
const f = document.getElementById('csv-file');
|
||||
if(f){ f.value = ''; f.click(); }
|
||||
}
|
||||
|
||||
document.addEventListener('change', e => {
|
||||
if(e.target && e.target.id === 'csv-file' && e.target.files && e.target.files[0]) loadCsv(e.target.files[0]);
|
||||
});
|
||||
|
||||
async function loadCsv(file){
|
||||
if(file.size > CSV_MAX_BYTES){
|
||||
bannerHtml('csv-banner', 'bad', '✕ '+uesc(file.name)+' is larger than 1 MB. Split it and load the parts one at a time.');
|
||||
return;
|
||||
}
|
||||
let text = '';
|
||||
try { text = await readFileText(file); }
|
||||
catch(_){ bannerHtml('csv-banner', 'bad', '✕ Could not read '+uesc(file.name)+'.'); return; }
|
||||
bannerHtml('csv-banner', '', 'Reading '+uesc(file.name)+'…');
|
||||
const { status, json } = await api('POST', '/api/auth/bulk-users/resolve', { text });
|
||||
if(status !== 200 || !json || !Array.isArray(json.rows)){
|
||||
bannerHtml('csv-banner', 'bad', '✕ '+uesc(apiError(status, json, 'Could not read the list')));
|
||||
return;
|
||||
}
|
||||
// Show everyone, so every accepted account is a visible, checked row: a
|
||||
// selection must never include a row the filter hides.
|
||||
const s = document.getElementById('user-search'), f = document.getElementById('user-filter');
|
||||
if(s) s.value = '';
|
||||
if(f) f.value = '';
|
||||
await loadUsers();
|
||||
const want = new Set(json.user_ids || []);
|
||||
_shownSelectable.forEach(id => { if(want.has(id)) _selected.add(id); });
|
||||
updateSelectionUI();
|
||||
const missed = [...want].filter(id => !_selected.has(id)).length;
|
||||
const rejected = json.rows.filter(r => r.status !== 'ok');
|
||||
const lead = (rejected.length || missed ? '⚠ ' : '✓ ')+uesc(file.name)+': '+json.read+' line'+(json.read===1?'':'s')+' read, '+
|
||||
_selected.size+' selected'+(rejected.length ? ', '+rejected.length+' rejected' : '')+'.'+
|
||||
(missed ? ' '+missed+' accepted account'+(missed===1?' is':'s are')+' no longer in the directory; reload and try again.' : '')+
|
||||
(_selected.size ? ' Pick an action in the bulk bar to apply it to the selected accounts.' : '');
|
||||
const list = rejected.length
|
||||
? '<ul>'+rejected.map(r => '<li>Line '+r.line+' ('+uesc(r.text)+'): '+uesc(r.reason)+'</li>').join('')+'</ul>'
|
||||
: '';
|
||||
bannerHtml('csv-banner', (rejected.length || missed) ? 'warn' : 'ok', lead + list);
|
||||
}
|
||||
|
||||
function selCell(u){
|
||||
if(!selectable(u)){
|
||||
const why = u.id === _meId ? 'Your own account: change it one setting at a time'
|
||||
: (u.manage_blocked_reason || 'You cannot change this account');
|
||||
return '<td class="selcell"><span class="selhit" title="'+uesc(why)+'">'+
|
||||
'<input type="checkbox" disabled aria-label="'+uesc('Cannot select '+u.username+': '+why)+'"></span></td>';
|
||||
}
|
||||
return '<td class="selcell"><label class="selhit">'+
|
||||
'<input type="checkbox" class="selbox" data-id="'+uesc(u.id)+'"'+(_selected.has(u.id)?' checked':'')+
|
||||
' aria-label="'+uesc('Select '+u.username)+'"></label></td>';
|
||||
}
|
||||
|
||||
function renderUsers(){
|
||||
const wrap = document.getElementById('users-table');
|
||||
const q = ((document.getElementById('user-search')||{}).value||'').trim().toLowerCase();
|
||||
@@ -419,8 +116,7 @@ function renderUsers(){
|
||||
(u.project_role||'')+' '+roleLabel(u.role)).toLowerCase().indexOf(q) >= 0;
|
||||
});
|
||||
const count = '<div class="note">'+list.length+' of '+total+' '+(total===1?'person':'people')+'</div>';
|
||||
_shownSelectable = list.filter(selectable).map(u => u.id);
|
||||
if(!list.length){ wrap.innerHTML = count+'<div class="note">Nothing matches.</div>'; updateSelectionUI(); return; }
|
||||
if(!list.length){ wrap.innerHTML = count+'<div class="note">Nothing matches.</div>'; return; }
|
||||
|
||||
const head = manages()
|
||||
? ['Username','Name','Email',
|
||||
@@ -434,16 +130,9 @@ function renderUsers(){
|
||||
'Status'];
|
||||
const ths = head.map(h => Array.isArray(h)
|
||||
? '<th title="'+uesc(h[1])+'">'+uesc(h[0])+'</th>' : '<th>'+uesc(h)+'</th>').join('');
|
||||
// CR-020: a selection column for anyone who manages accounts. Select-all names
|
||||
// how many rows it covers, because it covers only what the filter shows.
|
||||
const selTh = manages()
|
||||
? '<th class="selcell"><label class="selhit"><input type="checkbox" id="sel-all" aria-label="'+
|
||||
uesc('Select all '+_shownSelectable.length+' shown that you can change')+'"></label></th>'
|
||||
: '';
|
||||
const rows = list.map(manages() ? managerRow : readonlyRow).join('');
|
||||
wrap.innerHTML = count+'<div class="tscroll"><table class="grid"><thead><tr>'+selTh+ths+
|
||||
wrap.innerHTML = count+'<div class="tscroll"><table class="grid"><thead><tr>'+ths+
|
||||
'</tr></thead><tbody>'+rows+'</tbody></table></div>'+legend();
|
||||
updateSelectionUI();
|
||||
}
|
||||
|
||||
function legend(){
|
||||
@@ -500,7 +189,6 @@ function managerRow(u){
|
||||
if(!can && !me) actions.push('<span class="note" style="margin:0" title="'+uesc(why)+'">read-only</span>');
|
||||
|
||||
return '<tr'+(can||me ? '' : ' class="is-locked"')+'>'+
|
||||
selCell(u)+
|
||||
'<td><strong>'+uesc(u.username)+'</strong>'+(me?'<span class="me-tag">you</span>':'')+'</td>'+
|
||||
'<td>'+uesc(u.full_name||'')+'</td>'+
|
||||
// The address is truncated with the full value on the title: a long one used to
|
||||
|
||||
467
server/app.py
467
server/app.py
@@ -27,7 +27,7 @@ from sqlalchemy.orm import Session
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from .db import Base, engine, get_db
|
||||
from . import models, auth, notify, assets_db, okta_auth, okta_fake
|
||||
from . import models, auth, notify, assets_db, okta_auth, okta_fake, files_http
|
||||
|
||||
log = logging.getLogger("wpsuite.app")
|
||||
|
||||
@@ -1013,100 +1013,16 @@ def create_user(body: NewUserIn, actor: models.User = Depends(require_user_manag
|
||||
return directory_entry(db, u, actor)
|
||||
|
||||
|
||||
# ── One account-level change, used by the single-user routes AND the bulk routes ──
|
||||
# CR-020 (T12.1): a bulk action is the single-user action, once per row. So each
|
||||
# rule lives in exactly one function below, and both kinds of route call it: a
|
||||
# bulk request cannot reach further than a one-at-a-time request, because there
|
||||
# is no second copy of the rules for it to reach through. Every function checks
|
||||
# all of its guards BEFORE it changes anything, so a row that is refused leaves
|
||||
# nothing half-written, and writes its AuditLog row the way the single route
|
||||
# always has. None of them commits; the route owns the transaction.
|
||||
def guard_target(db: Session, actor: "models.User", u: "models.User") -> None:
|
||||
"""The two checks every account change starts with: may the caller see this
|
||||
account (404 if not, so existence does not leak), and may they change it."""
|
||||
require_see_user(db, actor, u)
|
||||
require_manage_user(db, actor, u)
|
||||
|
||||
|
||||
def apply_user_active(db: Session, actor: "models.User", u: "models.User", is_active: bool) -> None:
|
||||
if u.id == actor.id and not is_active:
|
||||
raise HTTPException(status_code=400, detail="You cannot disable your own account")
|
||||
u.is_active = is_active
|
||||
log_event(db, actor, "user_enabled" if is_active else "user_disabled", "user", u.id,
|
||||
summary=u.username, detail={"is_active": bool(is_active)})
|
||||
|
||||
|
||||
def apply_user_role(db: Session, actor: "models.User", u: "models.User", role: str) -> None:
|
||||
"""The role guards: never your own role, never the last active admin. The
|
||||
grantable-roles check is the caller's, made once per request before this."""
|
||||
if u.id == actor.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot change your own role")
|
||||
if auth.is_admin(u) and role != auth.ROLE_ADMIN:
|
||||
other_admins = db.scalars(
|
||||
select(models.User.id).where(
|
||||
(models.User.role == auth.ROLE_ADMIN)
|
||||
& (models.User.id != u.id)
|
||||
& (models.User.is_active.is_(True))
|
||||
)
|
||||
).all()
|
||||
if not other_admins:
|
||||
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
|
||||
old_role = u.role
|
||||
u.role = role
|
||||
detail = {"from": old_role, "to": role}
|
||||
# Promoting someone to admin retires their default-member flag: an admin already
|
||||
# reaches every project, so the flag would do nothing except sit there invisibly
|
||||
# (the console shows admins no controls) and come back to life the day they are
|
||||
# demoted. Same reasoning as clearing the role in set_user_auto_add.
|
||||
if role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
|
||||
u.auto_add_projects = False
|
||||
u.auto_add_role = ""
|
||||
detail["auto_add_cleared"] = True
|
||||
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
|
||||
|
||||
|
||||
def apply_user_delete(db: Session, actor: "models.User", u: "models.User") -> None:
|
||||
if u.id == actor.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot delete your own account")
|
||||
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
|
||||
db.delete(u)
|
||||
|
||||
|
||||
def apply_user_projects(db: Session, actor: "models.User", u: "models.User",
|
||||
managed: Optional[set], valid: set, roles: dict) -> None:
|
||||
"""Replace the caller's slice of `u`'s memberships with `valid`, each carrying
|
||||
its role from `roles` ('' = inherit). `valid` must already be checked to exist
|
||||
and to sit inside `managed`."""
|
||||
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
|
||||
# "leave other jobs alone" guarantee — get it wrong and a super user's save
|
||||
# silently revokes access everywhere else.
|
||||
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == u.id)
|
||||
if managed is not None:
|
||||
# in_() on an empty set is a valid always-false predicate, so a caller who
|
||||
# administers nothing deletes nothing (require_manage_user already refused them).
|
||||
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
|
||||
db.execute(doomed)
|
||||
for pid in valid:
|
||||
db.add(models.ProjectMember(id=gen_id("pm"), user_id=u.id, project_id=pid,
|
||||
role=roles.get(pid, "")))
|
||||
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
|
||||
detail={"projects": len(valid),
|
||||
"scope": "all" if managed is None else "managed",
|
||||
"overrides": {p: r for p, r in roles.items() if p in valid}})
|
||||
|
||||
|
||||
def project_scoped_grantable(actor: "models.User") -> tuple:
|
||||
"""Per-project roles `actor` may hand out. Only an app admin can make someone a
|
||||
super user on a project. user_scope and get_user_projects still spell the same
|
||||
rule inline for the console; left as they are to keep this diff to CR-020."""
|
||||
return auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
|
||||
|
||||
|
||||
@app.post("/api/auth/users/{user_id}/active")
|
||||
def set_user_active(user_id: str, body: ActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
u = load_target_user(db, user_id)
|
||||
guard_target(db, actor, u)
|
||||
apply_user_active(db, actor, u, body.is_active)
|
||||
require_see_user(db, actor, u)
|
||||
require_manage_user(db, actor, u)
|
||||
if u.id == actor.id and not body.is_active:
|
||||
raise HTTPException(status_code=400, detail="You cannot disable your own account")
|
||||
u.is_active = body.is_active
|
||||
log_event(db, actor, "user_enabled" if body.is_active else "user_disabled", "user", u.id,
|
||||
summary=u.username, detail={"is_active": bool(body.is_active)})
|
||||
db.commit()
|
||||
return directory_entry(db, u, actor)
|
||||
|
||||
@@ -1123,8 +1039,32 @@ def set_user_role(user_id: str, body: RoleIn, actor: models.User = Depends(requi
|
||||
if body.role not in allowed:
|
||||
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
|
||||
u = load_target_user(db, user_id)
|
||||
guard_target(db, actor, u)
|
||||
apply_user_role(db, actor, u, body.role)
|
||||
require_see_user(db, actor, u)
|
||||
require_manage_user(db, actor, u)
|
||||
if u.id == actor.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot change your own role")
|
||||
if auth.is_admin(u) and body.role != auth.ROLE_ADMIN:
|
||||
other_admins = db.scalars(
|
||||
select(models.User.id).where(
|
||||
(models.User.role == auth.ROLE_ADMIN)
|
||||
& (models.User.id != u.id)
|
||||
& (models.User.is_active.is_(True))
|
||||
)
|
||||
).all()
|
||||
if not other_admins:
|
||||
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
|
||||
old_role = u.role
|
||||
u.role = body.role
|
||||
detail = {"from": old_role, "to": body.role}
|
||||
# Promoting someone to admin retires their default-member flag: an admin already
|
||||
# reaches every project, so the flag would do nothing except sit there invisibly
|
||||
# (the console shows admins no controls) and come back to life the day they are
|
||||
# demoted. Same reasoning as clearing the role in set_user_auto_add.
|
||||
if body.role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
|
||||
u.auto_add_projects = False
|
||||
u.auto_add_role = ""
|
||||
detail["auto_add_cleared"] = True
|
||||
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
|
||||
db.commit()
|
||||
db.refresh(u)
|
||||
return directory_entry(db, u, actor)
|
||||
@@ -1181,8 +1121,12 @@ def set_user_auto_add(user_id: str, body: AutoAddIn, admin: models.User = Depend
|
||||
@app.delete("/api/auth/users/{user_id}")
|
||||
def delete_user(user_id: str, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
u = load_target_user(db, user_id)
|
||||
guard_target(db, actor, u)
|
||||
apply_user_delete(db, actor, u)
|
||||
require_see_user(db, actor, u)
|
||||
require_manage_user(db, actor, u)
|
||||
if u.id == actor.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot delete your own account")
|
||||
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
|
||||
db.delete(u)
|
||||
db.commit()
|
||||
return {"deleted": user_id}
|
||||
|
||||
@@ -1235,7 +1179,8 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
|
||||
exactly as they were, because a payload that simply omits them would otherwise cut
|
||||
someone off from a job the caller can't even see."""
|
||||
u = load_target_user(db, user_id)
|
||||
guard_target(db, actor, u)
|
||||
require_see_user(db, actor, u)
|
||||
require_manage_user(db, actor, u)
|
||||
requested = [p for p in dict.fromkeys(body.project_ids) if p]
|
||||
for pid in requested:
|
||||
check_id(pid)
|
||||
@@ -1248,227 +1193,28 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
|
||||
# A super user may hand out the project-scoped roles below their own; only an app
|
||||
# admin can make someone a super user on a project. Anything unrecognised falls
|
||||
# back to inheriting the account's own role.
|
||||
allowed = project_scoped_grantable(actor)
|
||||
allowed = auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
|
||||
roles = {pid: r for pid, r in (body.roles or {}).items() if r in allowed}
|
||||
apply_user_projects(db, actor, u, managed, valid, roles)
|
||||
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
|
||||
# "leave other jobs alone" guarantee — get it wrong and a super user's save
|
||||
# silently revokes access everywhere else.
|
||||
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == user_id)
|
||||
if managed is not None:
|
||||
# in_() on an empty set is a valid always-false predicate, so a caller who
|
||||
# administers nothing deletes nothing (require_manage_user already refused them).
|
||||
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
|
||||
db.execute(doomed)
|
||||
for pid in valid:
|
||||
db.add(models.ProjectMember(id=gen_id("pm"), user_id=user_id, project_id=pid,
|
||||
role=roles.get(pid, "")))
|
||||
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
|
||||
detail={"projects": len(valid),
|
||||
"scope": "all" if managed is None else "managed",
|
||||
"overrides": {p: r for p, r in roles.items() if p in valid}})
|
||||
db.commit()
|
||||
return {"assigned": sorted(valid), "roles": {p: roles.get(p, "") for p in sorted(valid)}}
|
||||
|
||||
|
||||
# ── Bulk user administration — CR-020 (T12.1) ─────────────────────────────────
|
||||
# Four actions over a list of accounts: activate/disable, permissions role,
|
||||
# project add/remove (with the per-project role), delete. Each row runs exactly
|
||||
# the guards and the audit of the single-user route, through the same apply_*
|
||||
# function above. Rules, decided 2026-09-17 and confirmed 2026-10-06:
|
||||
# * a row that is refused is reported with its reason and the rest still run;
|
||||
# a batch is never reported as a success when part of it failed;
|
||||
# * one AuditLog row per changed account, the same as the single route writes -
|
||||
# never one opaque "bulk" entry;
|
||||
# * the caller's own account is refused only on its own row (disable, demote,
|
||||
# delete), never by failing the whole batch;
|
||||
# * project assignment adds to or removes from ONE project; it never replaces a
|
||||
# user's whole project list.
|
||||
# A row already in the requested state is reported "unchanged" and writes no
|
||||
# audit row: nothing changed, so there is nothing to audit.
|
||||
#
|
||||
# The routes live under /api/auth/bulk-users/ rather than /api/auth/users/bulk/,
|
||||
# because POST /api/auth/users/{user_id}/active would otherwise match "bulk" as
|
||||
# a user id.
|
||||
BULK_MAX_USERS = 500
|
||||
|
||||
|
||||
class BulkUsersIn(BaseModel):
|
||||
user_ids: list[str] = Field(default_factory=list, max_length=BULK_MAX_USERS)
|
||||
|
||||
|
||||
class BulkActiveIn(BulkUsersIn):
|
||||
is_active: bool
|
||||
|
||||
|
||||
class BulkRoleIn(BulkUsersIn):
|
||||
role: str
|
||||
|
||||
|
||||
class BulkProjectIn(BulkUsersIn):
|
||||
project_id: str
|
||||
op: str # "add" | "remove"
|
||||
role: str = "" # per-project role on add; '' = inherit the account's own
|
||||
|
||||
|
||||
def run_bulk(db: Session, actor: "models.User", user_ids: list[str], action: str, apply) -> dict:
|
||||
"""Run `apply(u)` once per distinct id, in the order given. `apply` returns
|
||||
"ok" or "unchanged", or raises HTTPException with the reason the single-user
|
||||
route would have given. The flush after every row matters: the session does
|
||||
not autoflush, and a later row's guard (the last-admin count, for one) has to
|
||||
see what an earlier row already changed."""
|
||||
results = []
|
||||
for uid in dict.fromkeys(i for i in user_ids if i):
|
||||
row = {"user_id": uid, "username": "", "status": "", "reason": ""}
|
||||
try:
|
||||
check_id(uid)
|
||||
u = load_target_user(db, uid)
|
||||
row["username"] = u.username
|
||||
guard_target(db, actor, u)
|
||||
row["status"] = apply(u)
|
||||
db.flush()
|
||||
except HTTPException as exc:
|
||||
row["status"] = "failed"
|
||||
row["reason"] = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
|
||||
results.append(row)
|
||||
db.commit()
|
||||
counts = {s: sum(1 for r in results if r["status"] == s) for s in ("ok", "unchanged", "failed")}
|
||||
return {"action": action, "requested": len(results), **counts, "results": results}
|
||||
|
||||
|
||||
@app.post("/api/auth/bulk-users/active")
|
||||
def bulk_set_active(body: BulkActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
def apply(u):
|
||||
if bool(u.is_active) == bool(body.is_active):
|
||||
return "unchanged"
|
||||
apply_user_active(db, actor, u, body.is_active)
|
||||
return "ok"
|
||||
return run_bulk(db, actor, body.user_ids, "enable" if body.is_active else "disable", apply)
|
||||
|
||||
|
||||
@app.post("/api/auth/bulk-users/role")
|
||||
def bulk_set_role(body: BulkRoleIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
allowed = grantable_roles(actor)
|
||||
if body.role not in allowed:
|
||||
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
|
||||
|
||||
def apply(u):
|
||||
# Compared as stored: a legacy 'user' row moved to 'project_user' is a real
|
||||
# change of the stored value, so it is applied and audited, as one at a time.
|
||||
if u.role == body.role:
|
||||
return "unchanged"
|
||||
apply_user_role(db, actor, u, body.role)
|
||||
return "ok"
|
||||
return run_bulk(db, actor, body.user_ids, "role", apply)
|
||||
|
||||
|
||||
@app.post("/api/auth/bulk-users/projects")
|
||||
def bulk_set_project(body: BulkProjectIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
"""Add every listed account to one project (with a per-project role), or remove
|
||||
them from it. Implemented as the single route's replace of the caller's slice,
|
||||
computed per user, so the audit row is the same shape the dialog writes."""
|
||||
if body.op not in ("add", "remove"):
|
||||
raise HTTPException(status_code=400, detail="op must be 'add' or 'remove'")
|
||||
check_id(body.project_id)
|
||||
if not db.get(models.Project, body.project_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
managed = managed_project_ids(db, actor)
|
||||
if managed is not None and body.project_id not in managed:
|
||||
raise HTTPException(status_code=403, detail="You don't administer the users of that project")
|
||||
role = (body.role or "").strip()
|
||||
if body.op == "add" and role and role not in project_scoped_grantable(actor):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"role must be '' (inherit) or one of {', '.join(project_scoped_grantable(actor))}")
|
||||
pid = body.project_id
|
||||
|
||||
def apply(u):
|
||||
mine = [m for m in db.scalars(select(models.ProjectMember)
|
||||
.where(models.ProjectMember.user_id == u.id)).all()
|
||||
if managed is None or m.project_id in managed]
|
||||
current = {m.project_id: (m.role or "") for m in mine}
|
||||
if body.op == "add":
|
||||
if current.get(pid) == role:
|
||||
return "unchanged"
|
||||
current[pid] = role
|
||||
else:
|
||||
if pid not in current:
|
||||
return "unchanged"
|
||||
current.pop(pid)
|
||||
# Roles on the caller's OTHER projects are carried over exactly as stored -
|
||||
# adding someone to one job must never reset their role on another.
|
||||
apply_user_projects(db, actor, u, managed, set(current),
|
||||
{p: r for p, r in current.items() if r})
|
||||
return "ok"
|
||||
return run_bulk(db, actor, body.user_ids, "project_" + body.op, apply)
|
||||
|
||||
|
||||
class BulkResolveIn(BaseModel):
|
||||
text: str = Field(default="", max_length=200_000)
|
||||
|
||||
|
||||
_CSV_HEADER_WORDS = ("username", "user", "login", "email", "user name")
|
||||
|
||||
|
||||
@app.post("/api/auth/bulk-users/resolve")
|
||||
def bulk_resolve(body: BulkResolveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
"""CR-020 (T12.4): turn an uploaded list of usernames into the account ids a
|
||||
bulk action will run on - a second way IN to the same four bulk routes, not a
|
||||
third copy of their rules. The CSV holds usernames only (decided 2026-10-06);
|
||||
the action is chosen in the console and applies to every accepted row.
|
||||
|
||||
Validate and report, the CR-005 pattern: every line is either accepted or
|
||||
rejected WITH ITS LINE NUMBER and a reason - never silently skipped. A line is
|
||||
rejected when it names nobody this caller can see (the same 'not found' a
|
||||
hidden account gets everywhere else), an account they may not change (with
|
||||
the same reason the single route would give), their own account, or a
|
||||
username already listed on an earlier line. Nothing is changed here; the
|
||||
bulk route the console calls next re-checks every row anyway."""
|
||||
rows = []
|
||||
seen: dict[str, int] = {}
|
||||
visible = visible_user_ids(db, actor)
|
||||
cache: dict = {}
|
||||
for line_no, raw in enumerate((body.text or "").splitlines(), start=1):
|
||||
line = raw.strip().lstrip("")
|
||||
if not line:
|
||||
continue
|
||||
cell = re.split(r"[,;\t]", line, maxsplit=1)[0].strip().strip('"').strip()
|
||||
if not cell:
|
||||
rows.append({"line": line_no, "text": line[:120], "status": "rejected",
|
||||
"reason": "no username in the first column"})
|
||||
continue
|
||||
if line_no == 1 and cell.lower() in _CSV_HEADER_WORDS:
|
||||
continue # header row
|
||||
row = {"line": line_no, "text": cell[:120], "status": "rejected", "reason": "",
|
||||
"user_id": None, "username": ""}
|
||||
if any(ord(ch) < 32 for ch in cell) or len(cell) > 120:
|
||||
row["reason"] = "not a valid username"
|
||||
rows.append(row)
|
||||
continue
|
||||
key = cell.lower()
|
||||
if key in seen:
|
||||
row["reason"] = f"duplicate of line {seen[key]}"
|
||||
rows.append(row)
|
||||
continue
|
||||
seen[key] = line_no
|
||||
u = db.scalars(select(models.User).where(func.lower(models.User.username) == key)).first()
|
||||
if u is None:
|
||||
# An offboarding list usually carries email addresses. Accepted only
|
||||
# when exactly one account has that address, so a shared or reused
|
||||
# address can never pick the wrong person.
|
||||
by_mail = db.scalars(select(models.User).where(func.lower(models.User.email) == key)).all()
|
||||
u = by_mail[0] if len(by_mail) == 1 else None
|
||||
if u is None or (visible is not None and u.id not in visible):
|
||||
row["reason"] = "User not found"
|
||||
elif u.id == actor.id:
|
||||
row["reason"] = "your own account - change it one setting at a time"
|
||||
else:
|
||||
problem = manage_user_problem(db, actor, u, cache)
|
||||
if problem:
|
||||
row["reason"] = problem
|
||||
else:
|
||||
row.update(status="ok", user_id=u.id, username=u.username)
|
||||
rows.append(row)
|
||||
accepted = [r for r in rows if r["status"] == "ok"]
|
||||
return {"read": len(rows), "accepted": len(accepted), "rejected": len(rows) - len(accepted),
|
||||
"user_ids": [r["user_id"] for r in accepted], "rows": rows}
|
||||
|
||||
|
||||
@app.post("/api/auth/bulk-users/delete")
|
||||
def bulk_delete(body: BulkUsersIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
|
||||
"""Hard delete, the same as DELETE /api/auth/users/{id} (decided 2026-09-17:
|
||||
no soft delete invented for the bulk case). The console asks for the typed
|
||||
word DELETE first; the server's guard is the per-row rules, as for one."""
|
||||
def apply(u):
|
||||
apply_user_delete(db, actor, u)
|
||||
return "ok"
|
||||
return run_bulk(db, actor, body.user_ids, "delete", apply)
|
||||
|
||||
|
||||
# ── Projects ─────────────────────────────────────────────────────────────────
|
||||
@app.post("/api/projects")
|
||||
def upsert_project(body: ProjectIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
|
||||
@@ -1585,6 +1331,32 @@ def archive_project(project_id: str, body: ArchiveIn, user: models.User = Depend
|
||||
|
||||
|
||||
# ── SOPs ─────────────────────────────────────────────────────────────────────
|
||||
def canonical_sop_id(project_id: Optional[str]) -> Optional[str]:
|
||||
"""D20: the one id a project's SOP lives at - the id pushSOP has always used."""
|
||||
return f"sop__{project_id}" if project_id else None
|
||||
|
||||
|
||||
def project_baseline_sop(db: Session, project_id: Optional[str]) -> Optional["models.Sop"]:
|
||||
"""D20: THE completed SOP of a project, for every reader that treats it as the
|
||||
baseline (page load, PM/CM mail, QA mail, the launcher summary).
|
||||
|
||||
The canonical row wins when it is complete. "Most recent complete" is only the
|
||||
fallback, for projects whose SOP predates the fixed id (seed data, API
|
||||
clients). Before D20 "most recent" was the whole rule, which is what let a
|
||||
second complete SOP take the baseline over (security review SEC-02)."""
|
||||
if not project_id:
|
||||
return None
|
||||
row = db.get(models.Sop, canonical_sop_id(project_id))
|
||||
if row is not None and row.complete and row.project_id == project_id:
|
||||
return row
|
||||
return db.scalars(
|
||||
select(models.Sop)
|
||||
.where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True)))
|
||||
.order_by(models.Sop.updated_at.desc())
|
||||
.limit(1)
|
||||
).first()
|
||||
|
||||
|
||||
@app.post("/api/sops")
|
||||
def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
|
||||
check_id(body.id)
|
||||
@@ -1593,6 +1365,11 @@ def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user),
|
||||
# one it currently sits on below — so an archived job can be neither edited nor
|
||||
# used as a source to move a SOP out of.
|
||||
require_project_writable(db, user, body.project_id, "Saving a SOP")
|
||||
# D20: one SOP per project, at a fixed id. The browser has always written
|
||||
# `sop__<project_id>` (pushSOP); a request with no id now gets it too.
|
||||
canonical = canonical_sop_id(body.project_id)
|
||||
if not body.id and canonical:
|
||||
body.id = canonical
|
||||
sop = db.get(models.Sop, body.id) if body.id else None
|
||||
if sop is not None:
|
||||
require_project_access(db, user, sop.project_id)
|
||||
@@ -1602,6 +1379,28 @@ def upsert_sop(body: SopIn, user: models.User = Depends(auth.get_current_user),
|
||||
# project member, including marking it complete the first time.
|
||||
if sop.complete:
|
||||
require_project_admin(db, user, sop.project_id, "Changing a completed SOP")
|
||||
# D20 (security review SEC-02): the rule above checked only the row being
|
||||
# posted, so a project_user could post a NEW id with complete=true and every
|
||||
# "latest complete SOP" reader - the page baseline and the PM/CM/QA mail
|
||||
# routing - followed it. A project gets no second SOP row (creating one, or
|
||||
# moving one in, under any id but the canonical one is refused), and while
|
||||
# it has a complete SOP, writing another complete one is a Project Admin act.
|
||||
# Rows made before D20 under other ids stay and keep their old rules.
|
||||
if canonical and body.id != canonical and (sop is None or sop.project_id != body.project_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"A project has one SOP. Save it as {canonical}.",
|
||||
)
|
||||
if body.project_id and body.complete:
|
||||
other_complete = db.scalar(
|
||||
select(models.Sop.id).where(
|
||||
(models.Sop.project_id == body.project_id)
|
||||
& (models.Sop.complete.is_(True))
|
||||
& (models.Sop.id != body.id)
|
||||
).limit(1)
|
||||
)
|
||||
if other_complete:
|
||||
require_project_admin(db, user, body.project_id, "Changing a completed SOP")
|
||||
is_new = sop is None
|
||||
if sop is None:
|
||||
sop = models.Sop(id=body.id or gen_id("sop"))
|
||||
@@ -1634,6 +1433,15 @@ def list_sops(project_id: Optional[str] = Query(None), full: bool = Query(False)
|
||||
|
||||
@app.get("/api/sops/latest")
|
||||
def latest_sop(complete: Optional[bool] = None, project_id: Optional[str] = Query(None), user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
|
||||
# D20: "the project's completed SOP" is what pullProject() asks for on every
|
||||
# page load, so it is answered by the baseline rule, not by "most recent".
|
||||
# Same 404 as before for a project the caller cannot reach.
|
||||
if complete is True and project_id:
|
||||
ids = accessible_project_ids(db, user)
|
||||
sop = project_baseline_sop(db, project_id) if (ids is None or project_id in ids) else None
|
||||
if not sop:
|
||||
raise HTTPException(status_code=404, detail="No SOP found")
|
||||
return sop.to_dict()
|
||||
stmt = select(models.Sop)
|
||||
if complete is not None:
|
||||
stmt = stmt.where(models.Sop.complete == complete)
|
||||
@@ -1814,15 +1622,10 @@ def reopened_critical(old_data: Optional[dict], new_data: Optional[dict]) -> lis
|
||||
|
||||
|
||||
def project_sop_team(db: Session, project_id: Optional[str]) -> list[str]:
|
||||
"""PM + CM user ids from the project's most recent complete SOP."""
|
||||
"""PM + CM user ids from the project's baseline SOP (D20: project_baseline_sop)."""
|
||||
if not project_id:
|
||||
return []
|
||||
sop = db.scalars(
|
||||
select(models.Sop)
|
||||
.where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True)))
|
||||
.order_by(models.Sop.updated_at.desc())
|
||||
.limit(1)
|
||||
).first()
|
||||
sop = project_baseline_sop(db, project_id)
|
||||
if not sop:
|
||||
return []
|
||||
data = sop.data or {}
|
||||
@@ -1840,15 +1643,11 @@ def project_qa_group(db: Session, project_id: Optional[str]) -> list["models.Use
|
||||
"""D2: the QA group named on the project's latest complete SOP. pushSOP writes
|
||||
the row as data={sop, state}, so the project block is data['sop']['project'] -
|
||||
project_sop_team above read the flat shape until BL-021 was fixed
|
||||
(2026-08-20); both now read nested-first, exactly alike."""
|
||||
(2026-08-20); both now read nested-first, exactly alike. D20: both also read
|
||||
the same row, project_baseline_sop."""
|
||||
if not project_id:
|
||||
return []
|
||||
sop = db.scalars(
|
||||
select(models.Sop)
|
||||
.where((models.Sop.project_id == project_id) & (models.Sop.complete.is_(True)))
|
||||
.order_by(models.Sop.updated_at.desc())
|
||||
.limit(1)
|
||||
).first()
|
||||
sop = project_baseline_sop(db, project_id)
|
||||
if not sop:
|
||||
return []
|
||||
data = sop.data or {}
|
||||
@@ -2915,12 +2714,7 @@ def project_summary(project_id: str, user: models.User = Depends(auth.get_curren
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
require_project_access(db, user, project_id)
|
||||
|
||||
sop = db.scalars(
|
||||
select(models.Sop)
|
||||
.where(models.Sop.project_id == project_id, models.Sop.complete.is_(True))
|
||||
.order_by(models.Sop.updated_at.desc())
|
||||
.limit(1)
|
||||
).first()
|
||||
sop = project_baseline_sop(db, project_id) # D20: the same row every page loads
|
||||
|
||||
wp_total = db.scalar(
|
||||
select(func.count()).select_from(models.WorkPackage).where(
|
||||
@@ -3164,10 +2958,9 @@ def get_wp_file(file_id: str, user: models.User = Depends(auth.get_current_user)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
require_project_access(db, user, row.project_id)
|
||||
return Response(content=row.data, media_type=row.mime or "application/octet-stream",
|
||||
headers={"Content-Disposition":
|
||||
f'inline; filename="{(row.name or "file").replace(chr(34), "")}"',
|
||||
"Cache-Control": "private, max-age=86400"})
|
||||
# D19: PDF and raster images inline as before; anything else (SVG included)
|
||||
# downloads as a sandboxed attachment, and every name is a valid header.
|
||||
return files_http.file_response(row)
|
||||
|
||||
|
||||
@app.patch("/api/files/{file_id}")
|
||||
|
||||
@@ -173,12 +173,29 @@ def create_token(user: "models.User") -> str:
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=JWT_ALG)
|
||||
|
||||
|
||||
# D21: a real session token is about 300 characters. Anything far larger is not
|
||||
# one of ours, and refusing it before parsing keeps a crafted cookie from making
|
||||
# the parser do work on our behalf.
|
||||
_MAX_TOKEN_CHARS = 4096
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[dict]:
|
||||
"""Return the token claims if the signature and expiry are valid, else None.
|
||||
Session cookies only — a token of any other type is rejected."""
|
||||
Session cookies only — a token of any other type is rejected.
|
||||
|
||||
D21: fails CLOSED on any error. This used to catch jwt.PyJWTError only, and
|
||||
PyJWT 2.13.0 let a RecursionError out of header parsing, so a 1.6 KB cookie
|
||||
from someone with no account produced a 500 and a stack trace instead of a
|
||||
401 (security review SEC-07). Whatever goes wrong inside the decoder, the
|
||||
answer is the same: not signed in."""
|
||||
if not token or len(token) > _MAX_TOKEN_CHARS:
|
||||
return None
|
||||
try:
|
||||
claims = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALG])
|
||||
except jwt.PyJWTError:
|
||||
# Every token this app issues carries exp and sub (create_token,
|
||||
# maybe_refresh_token); one without them is not ours.
|
||||
claims = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALG],
|
||||
options={"require": ["exp", "sub"]})
|
||||
except Exception: # noqa: BLE001 — see docstring: every failure is "not signed in"
|
||||
return None
|
||||
# No route issues a `typ`-carrying token anymore (that was the password-reset
|
||||
# token, removed in T10.4), but a session token still must never validate as
|
||||
|
||||
66
server/files_http.py
Normal file
66
server/files_http.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""Safe HTTP responses for uploaded drawings — D19 (T16.2).
|
||||
|
||||
Security review 2026-10-01, SEC-01 and SEC-15e.
|
||||
|
||||
WHY THIS EXISTS
|
||||
Uploads accept `image/*`, which includes `image/svg+xml`. An SVG is a
|
||||
document, not a picture: it can carry <script>. GET /api/files/{id} used to
|
||||
return every file `inline` with the uploader's content type, on the app's own
|
||||
origin, so a script inside an SVG ran as whoever opened the drawing - with
|
||||
their session, and with an admin's power if an admin opened it.
|
||||
|
||||
The download name was built by hand with only `"` removed. A name outside
|
||||
Latin-1 (`Plan é.pdf`) made the header unencodable, so the download failed
|
||||
with 500; CR/LF in a name went into the header as typed.
|
||||
|
||||
THE RULE (D19, decided 2026-10-02)
|
||||
* PDF and raster images open INLINE, exactly as before. That is what the
|
||||
creator's drawing list, the printed package and Field View link to
|
||||
(CR-007), and the offline drawing cache in sw.js stores.
|
||||
* Every other type, SVG included, is an ATTACHMENT inside a sandbox: the
|
||||
browser saves it instead of rendering it on our origin, and
|
||||
`Content-Security-Policy: sandbox` strips script and same-origin access
|
||||
even if someone opens the saved response directly.
|
||||
* SVG UPLOADS STAY ACCEPTED (decided: accept, download only). The fix is on
|
||||
the way out, so SVGs already in the database are covered too.
|
||||
* `Cache-Control` is unchanged - the offline drawing cache depends on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi.responses import Response
|
||||
|
||||
# Formats a browser shows as inert pixels, or in its own PDF viewer.
|
||||
INLINE_SAFE_MIME = frozenset({
|
||||
"application/pdf",
|
||||
"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/avif",
|
||||
})
|
||||
|
||||
# Control characters, and the characters that end or escape a quoted
|
||||
# header parameter. Replaced, never passed through.
|
||||
_UNSAFE_NAME = re.compile(r'[\x00-\x1f\x7f"\\;]')
|
||||
|
||||
|
||||
def content_disposition(disposition: str, name: str) -> str:
|
||||
"""A header value that is valid for ANY user-supplied file name: an ASCII
|
||||
fallback for old clients plus RFC 5987 `filename*` with the real name."""
|
||||
name = _UNSAFE_NAME.sub("_", name or "file").strip() or "file"
|
||||
ascii_name = name.encode("ascii", "replace").decode("ascii").replace("?", "_")
|
||||
return f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name, safe='')}"
|
||||
|
||||
|
||||
def file_response(row) -> Response:
|
||||
"""The response for GET /api/files/{id}. `row` is a models.WpFile."""
|
||||
mime = (row.mime or "application/octet-stream").lower()
|
||||
headers = {
|
||||
"Cache-Control": "private, max-age=86400", # unchanged: sw.js caches drawings offline
|
||||
"X-Content-Type-Options": "nosniff", # NGINX adds it too; the dev server did not
|
||||
}
|
||||
if mime in INLINE_SAFE_MIME:
|
||||
headers["Content-Disposition"] = content_disposition("inline", row.name)
|
||||
else:
|
||||
headers["Content-Disposition"] = content_disposition("attachment", row.name)
|
||||
headers["Content-Security-Policy"] = "sandbox; default-src 'none'"
|
||||
return Response(content=row.data, media_type=mime, headers=headers)
|
||||
@@ -17,7 +17,9 @@ pymssql==2.3.13 # read-only lookups against the Micron asset DB (SQL
|
||||
# MICRON_DB_URL to mssql+pyodbc://…?driver=ODBC+Driver+18+for+SQL+Server
|
||||
pydantic==2.13.4
|
||||
python-dotenv==1.2.2
|
||||
PyJWT==2.13.0 # signed session tokens
|
||||
PyJWT==2.15.1 # signed session tokens. D21 (2026-10-02): was 2.13.0, which
|
||||
# pip-audit lists 13 advisories for (GHSA-8wjv-2p76-3863 let a
|
||||
# crafted cookie raise past decode_token). 2.15.1: none known.
|
||||
starlette==1.3.1 # pinned transitive (cookie / CORS handling — security-relevant)
|
||||
Authlib==1.7.2 # Okta OIDC authorization-code flow (T10.1, wave 10 / D15)
|
||||
httpx==0.28.1 # Authlib's OIDC client needs an HTTP client; explicit, not transitive
|
||||
|
||||
@@ -207,12 +207,9 @@ def run(page, base, tok):
|
||||
chk("auth resolved to the admin account", page.eval("(window.WP_USER||{}).role") == "admin")
|
||||
chk("the directory is visible",
|
||||
page.eval("getComputedStyle(document.getElementById('users-main')).display") != "none")
|
||||
# 10 since CR-020 (T12.2): the 9 data columns plus the row-selection column.
|
||||
chk("manager table renders 10 columns (9 + row selection)",
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length") == 10,
|
||||
chk("manager table renders 9 columns",
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length") == 9,
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length"))
|
||||
chk("...the first is the selection column",
|
||||
page.eval("!!document.querySelector('#users-table thead th.selcell #sel-all')"))
|
||||
chk("an admin sees every account in the fixture (7)",
|
||||
page.eval("document.querySelectorAll('#users-table tbody tr').length") == 7,
|
||||
page.eval("document.querySelectorAll('#users-table tbody tr').length"))
|
||||
@@ -240,22 +237,15 @@ def run(page, base, tok):
|
||||
|
||||
# Your own row: permissions locked so you cannot demote yourself, job function
|
||||
# still editable. Asserted on the two cells, not "no select in the row".
|
||||
# The cells are found by their HEADER, not by position: CR-020's selection
|
||||
# column moved every column one to the right and these asserted r.cells[3]
|
||||
# and [4], which then read the username and the email (T12.6).
|
||||
ROW = ("const r=[...document.querySelectorAll('#users-table tbody tr')]"
|
||||
".find(r=>r.querySelector('.me-tag'));"
|
||||
"const col=n=>[...document.querySelectorAll('#users-table thead th')]"
|
||||
".findIndex(h=>h.textContent.trim().toLowerCase()===n);")
|
||||
".find(r=>r.querySelector('.me-tag'));")
|
||||
def own(q):
|
||||
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[col('permissions')];return " + q + "})()"
|
||||
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[3];return " + q + "})()"
|
||||
chk("your own permissions cell is locked, not a dropdown",
|
||||
page.eval(own("!c.querySelector('select') && !!c.querySelector('.tag')")))
|
||||
chk("...and wears the Administrator pill", page.eval(own("!!c.querySelector('.tag.admin')")))
|
||||
chk("...while your job function stays editable",
|
||||
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[col('project role')].querySelector('select')})()"))
|
||||
chk("...and your own row cannot be ticked for a bulk action",
|
||||
page.eval("(()=>{" + ROW + "return !!r && !r.querySelector('input.selbox')})()"))
|
||||
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[4].querySelector('select')})()"))
|
||||
|
||||
page.eval("[...document.querySelectorAll('#users-table tbody button')]"
|
||||
".find(b=>/project/i.test(b.textContent)).click()")
|
||||
|
||||
@@ -1,326 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CR-020 (wave 12): bulk user administration, server side.
|
||||
|
||||
python tests/bulk_users_check.py
|
||||
|
||||
Self-contained and needs NO browser: a throwaway SQLite database in a temp
|
||||
folder, the API driven in-process with FastAPI's TestClient, everything deleted
|
||||
afterward. Your real wpsuite.db is never touched.
|
||||
|
||||
What it proves is the wave's own exit criteria, measured on the server, where
|
||||
they are enforced:
|
||||
- every bulk action works on a list, row by row, with the single-user rules;
|
||||
- the caller's own account is refused on its own row, never the whole batch;
|
||||
- a super user's batch cannot reach an account or project outside their scope;
|
||||
- one AuditLog row per changed account, the same shape the single route writes;
|
||||
- a partial failure is reported row by row, never as a clean success;
|
||||
- project add/remove never touches the user's other projects or their roles;
|
||||
- the single-user routes, now built on the same functions, behave as before.
|
||||
|
||||
Exit codes: 0 all passed, 1 a check failed, 2 the run could not start.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TMP = tempfile.mkdtemp(prefix="wp-bulk-users-check-")
|
||||
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "bulk.db").replace("\\", "/")
|
||||
os.environ["AUTH_SECRET_KEY"] = "bulk-users-check-key-bulk-users-check-0000"
|
||||
os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None)
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
try:
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import select
|
||||
from server import app as A, auth, models
|
||||
from server.db import SessionLocal
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("could not start:", exc)
|
||||
sys.exit(2)
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append(bool(ok))
|
||||
print(f" {'PASS' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail and not ok else ""))
|
||||
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
|
||||
def account(uid, role="project_user"):
|
||||
u = models.User(id=uid, username=uid[5:], role=role, email=uid[5:] + "@example.test")
|
||||
db.add(u)
|
||||
db.commit()
|
||||
return u
|
||||
|
||||
|
||||
def member(uid, pid, role=""):
|
||||
db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role))
|
||||
db.commit()
|
||||
|
||||
|
||||
def client(user):
|
||||
c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
||||
c.cookies.set(auth.COOKIE_NAME, auth.create_token(user))
|
||||
return c
|
||||
|
||||
|
||||
def fresh():
|
||||
s = SessionLocal()
|
||||
s.expire_all()
|
||||
return s
|
||||
|
||||
|
||||
def audit(action, entity_id=None):
|
||||
s = fresh()
|
||||
q = select(models.AuditLog).where(models.AuditLog.action == action)
|
||||
if entity_id:
|
||||
q = q.where(models.AuditLog.entity_id == entity_id)
|
||||
return s.scalars(q.order_by(models.AuditLog.at)).all()
|
||||
|
||||
|
||||
def roles_of(uid):
|
||||
s = fresh()
|
||||
return {m.project_id: (m.role or "") for m in
|
||||
s.scalars(select(models.ProjectMember).where(models.ProjectMember.user_id == uid))}
|
||||
|
||||
|
||||
def by_user(resp):
|
||||
return {r["user_id"]: r for r in resp.json().get("results", [])}
|
||||
|
||||
|
||||
# ── fixture ──────────────────────────────────────────────────────────────────
|
||||
admin = account("user_admin", "admin")
|
||||
admin2 = account("user_admin2", "admin")
|
||||
superu = account("user_super") # super user on proj1 and proj4 by membership
|
||||
pu = account("user_pu") # plain project user: manages nobody
|
||||
for n in range(1, 10):
|
||||
account(f"user_u{n}")
|
||||
for pid in ("proj1", "proj2", "proj3", "proj4"):
|
||||
db.add(models.Project(id=pid, name=pid))
|
||||
db.commit()
|
||||
member("user_super", "proj1", "project_super_user")
|
||||
member("user_super", "proj4", "project_super_user")
|
||||
member("user_pu", "proj1")
|
||||
for n in (1, 2, 3, 4, 5):
|
||||
member(f"user_u{n}", "proj1")
|
||||
member("user_u6", "proj1"); member("user_u6", "proj2", "project_admin") # partly outside super's scope
|
||||
member("user_u7", "proj2") # wholly outside it
|
||||
member("user_u8", "proj1"); member("user_u8", "proj4", "project_super_user") # a role super may not grant
|
||||
ca, cs, cp = client(admin), client(superu), client(pu)
|
||||
|
||||
|
||||
def single_routes():
|
||||
print("\n0. the single-user routes still behave as before (now on the shared functions)")
|
||||
r = ca.post("/api/auth/users/user_admin/role", json={"role": "project_user"})
|
||||
check("changing your own role: 400, same words", r.status_code == 400 and "own role" in r.json()["detail"])
|
||||
r = ca.post("/api/auth/users/user_admin/active", json={"is_active": False})
|
||||
check("disabling yourself: 400, same words", r.status_code == 400 and "disable your own" in r.json()["detail"])
|
||||
r = ca.delete("/api/auth/users/user_admin")
|
||||
check("deleting yourself: 400, same words", r.status_code == 400 and "delete your own" in r.json()["detail"])
|
||||
r = cs.post("/api/auth/users/user_u6/role", json={"role": "project_admin"})
|
||||
check("a super user changing an account outside their scope: 403", r.status_code == 403)
|
||||
r = cs.put("/api/auth/users/user_u3/projects", json={"project_ids": ["proj1", "proj2"]})
|
||||
check("a super user assigning a project they don't run: 403", r.status_code == 403)
|
||||
r = ca.post("/api/auth/users/user_u9/role", json={"role": "project_admin"})
|
||||
check("a single role change still works and returns the directory row",
|
||||
r.status_code == 200 and r.json().get("role") == "project_admin")
|
||||
one = audit("role_changed", "user_u9")
|
||||
check("...and writes one role_changed row", len(one) == 1 and one[0].detail == {"from": "project_user", "to": "project_admin"},
|
||||
str([e.detail for e in one]))
|
||||
ca.post("/api/auth/users/user_u9/role", json={"role": "project_user"})
|
||||
|
||||
|
||||
def bulk_role():
|
||||
print("\n1. bulk permissions role")
|
||||
r = ca.post("/api/auth/bulk-users/role", json={
|
||||
"user_ids": ["user_u1", "user_u2", "user_admin", "user_nobody", "user_u1", "bad id!"],
|
||||
"role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("200 even though some rows fail (a partial failure is a result, not an error)", r.status_code == 200)
|
||||
check("u1 and u2 changed", res["user_u1"]["status"] == "ok" and res["user_u2"]["status"] == "ok")
|
||||
check("your own row is refused with its reason; the rest still ran",
|
||||
res["user_admin"]["status"] == "failed" and "own role" in res["user_admin"]["reason"])
|
||||
check("an unknown account is refused as 'User not found'",
|
||||
res["user_nobody"]["status"] == "failed" and res["user_nobody"]["reason"] == "User not found")
|
||||
check("a malformed id is refused, not crashed on", res["bad id!"]["status"] == "failed")
|
||||
check("a duplicated id is applied once", r.json()["requested"] == 5)
|
||||
check("counts match the rows", (r.json()["ok"], r.json()["failed"]) == (2, 3), str(r.json()))
|
||||
rows = audit("role_changed", "user_u1")
|
||||
check("one role_changed audit row per changed account, same shape as the single route",
|
||||
len(rows) == 1 and rows[0].detail == {"from": "project_user", "to": "project_admin"}
|
||||
and rows[0].actor == "admin" and rows[0].entity_type == "user", str([e.detail for e in rows]))
|
||||
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u1"], "role": "project_admin"})
|
||||
check("a row already in that role is 'unchanged' and writes no audit row",
|
||||
by_user(r)["user_u1"]["status"] == "unchanged" and len(audit("role_changed", "user_u1")) == 1)
|
||||
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3"], "role": "admin"})
|
||||
check("a super user cannot grant admin in bulk either (grantable_roles, whole request 400)",
|
||||
r.status_code == 400)
|
||||
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3", "user_u6", "user_u7"],
|
||||
"role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("super user: an account wholly inside their projects changes", res["user_u3"]["status"] == "ok")
|
||||
check("super user: an account also on a project they don't run is refused, with the reason",
|
||||
res["user_u6"]["status"] == "failed" and "don't administer" in res["user_u6"]["reason"],
|
||||
res["user_u6"]["reason"])
|
||||
check("super user: an account they cannot see is 'User not found' (no existence leak)",
|
||||
res["user_u7"]["status"] == "failed" and res["user_u7"]["reason"] == "User not found")
|
||||
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_admin2"], "role": "project_user"})
|
||||
check("demoting another admin works while one active admin remains (the caller)",
|
||||
by_user(r)["user_admin2"]["status"] == "ok")
|
||||
|
||||
|
||||
def bulk_active():
|
||||
print("\n2. bulk activate / disable")
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_admin", "user_u5"],
|
||||
"is_active": False})
|
||||
res = by_user(r)
|
||||
check("u4 and u5 disabled", res["user_u4"]["status"] == "ok" and res["user_u5"]["status"] == "ok"
|
||||
and not fresh().get(models.User, "user_u4").is_active)
|
||||
check("your own account is refused on its own row",
|
||||
res["user_admin"]["status"] == "failed" and "disable your own" in res["user_admin"]["reason"])
|
||||
check("one user_disabled audit row each, same shape as the single route",
|
||||
[e.detail for e in audit("user_disabled", "user_u4")] == [{"is_active": False}])
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_u2"], "is_active": True})
|
||||
res = by_user(r)
|
||||
check("re-enable: u4 ok, u2 (already active) unchanged",
|
||||
res["user_u4"]["status"] == "ok" and res["user_u2"]["status"] == "unchanged")
|
||||
|
||||
|
||||
def bulk_projects():
|
||||
print("\n3. bulk project add / remove")
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1", "user_u2", "user_u8"],
|
||||
"project_id": "proj1", "op": "add", "role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("add with a per-project role: every row ok", all(res[u]["status"] == "ok" for u in ("user_u1", "user_u2", "user_u8")),
|
||||
str(res))
|
||||
check("the role landed on that project", roles_of("user_u1").get("proj1") == "project_admin")
|
||||
check("the user's OTHER project and its role are untouched - even a role the caller could not grant",
|
||||
roles_of("user_u8").get("proj4") == "project_super_user", str(roles_of("user_u8")))
|
||||
rows = audit("project_access_changed", "user_u1")
|
||||
check("one project_access_changed row per account, in the single route's shape",
|
||||
len(rows) == 1 and set(rows[0].detail) == {"projects", "scope", "overrides"}
|
||||
and rows[0].detail["scope"] == "managed", str([e.detail for e in rows]))
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj2", "op": "add"})
|
||||
check("a super user cannot add anyone to a project they don't run (403)", r.status_code == 403)
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1",
|
||||
"op": "add", "role": "project_super_user"})
|
||||
check("a super user cannot hand out super user on a project (400)", r.status_code == 400)
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u6"], "project_id": "proj3", "op": "add"})
|
||||
check("admin adds u6 to proj3; proj1 and proj2 memberships and roles stay",
|
||||
by_user(r)["user_u6"]["status"] == "ok"
|
||||
and roles_of("user_u6") == {"proj1": "", "proj2": "project_admin", "proj3": ""}, str(roles_of("user_u6")))
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u2", "user_u9"], "project_id": "proj1", "op": "remove"})
|
||||
res = by_user(r)
|
||||
check("remove: u2 taken off proj1", res["user_u2"]["status"] == "ok" and "proj1" not in roles_of("user_u2"))
|
||||
check("remove: someone not on it is 'User not found' to a super user who cannot see them",
|
||||
res["user_u9"]["status"] == "failed")
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u9"], "project_id": "proj1", "op": "remove"})
|
||||
check("remove: an admin removing someone not on the project gets 'unchanged'",
|
||||
by_user(r)["user_u9"]["status"] == "unchanged")
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1", "op": "replace"})
|
||||
check("only add and remove exist: no replace-the-whole-list (400)", r.status_code == 400)
|
||||
|
||||
|
||||
def bulk_delete():
|
||||
print("\n4. bulk delete")
|
||||
r = ca.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u5", "user_admin", "user_gone"]})
|
||||
res = by_user(r)
|
||||
check("u5 deleted", res["user_u5"]["status"] == "ok" and fresh().get(models.User, "user_u5") is None)
|
||||
check("your own account is refused on its own row, the others still ran",
|
||||
res["user_admin"]["status"] == "failed" and "delete your own" in res["user_admin"]["reason"])
|
||||
check("an account that no longer exists is reported, not hidden",
|
||||
res["user_gone"]["status"] == "failed" and res["user_gone"]["reason"] == "User not found")
|
||||
check("one user_deleted audit row, same shape as the single route",
|
||||
[e.detail for e in audit("user_deleted", "user_u5")] == [{"role": "project_user"}])
|
||||
check("the deleted account's memberships went with it", roles_of("user_u5") == {})
|
||||
|
||||
|
||||
def csv_resolve():
|
||||
print("\n6. CSV upload: usernames in, a line-by-line report out (T12.4)")
|
||||
text = ("username\n" # header, skipped
|
||||
"u3\n"
|
||||
"U3\n" # same person, different case: a duplicate
|
||||
"nobody\n"
|
||||
"\n" # blank lines are not rows
|
||||
"u6\n" # visible to the super user, but also on a project they don't run
|
||||
"u7\n" # not visible to the super user at all
|
||||
"super\n" # the caller themself
|
||||
"u8@example.test,extra column\n" # an email address, matched to exactly one account
|
||||
",\n") # an empty first column
|
||||
r = cs.post("/api/auth/bulk-users/resolve", json={"text": text})
|
||||
j = r.json()
|
||||
rows = {x["line"]: x for x in j["rows"]}
|
||||
check("200 with a row for every non-blank line after the header",
|
||||
r.status_code == 200 and sorted(rows) == [2, 3, 4, 6, 7, 8, 9, 10], sorted(rows))
|
||||
check("a valid username is accepted", rows[2]["status"] == "ok" and rows[2]["user_id"] == "user_u3")
|
||||
check("a repeated username is rejected as a duplicate of its first line, not applied twice",
|
||||
rows[3]["status"] == "rejected" and rows[3]["reason"] == "duplicate of line 2")
|
||||
check("an unknown username: 'User not found', with its line number", rows[4]["reason"] == "User not found")
|
||||
check("an account the caller may not change: rejected with the single route's own reason",
|
||||
rows[6]["status"] == "rejected" and "don't administer" in rows[6]["reason"], rows[6]["reason"])
|
||||
check("an account the caller cannot see: 'User not found' (a CSV leaks no more than the table)",
|
||||
rows[7]["reason"] == "User not found")
|
||||
check("the caller's own account is rejected with a clear reason", "your own account" in rows[8]["reason"])
|
||||
check("an email address resolves when exactly one account has it",
|
||||
rows[9]["status"] == "ok" and rows[9]["user_id"] == "user_u8")
|
||||
check("an empty first column is rejected, not skipped", rows[10]["reason"] == "no username in the first column")
|
||||
check("the ids handed back are exactly the accepted rows",
|
||||
j["user_ids"] == ["user_u3", "user_u8"] and (j["accepted"], j["rejected"]) == (2, 6), str(j["user_ids"]))
|
||||
r = cs.post("/api/auth/bulk-users/active", json={"user_ids": j["user_ids"] + ["user_u7"], "is_active": False})
|
||||
res = by_user(r)
|
||||
check("the CSV's ids go through the same bulk route and the same guards: an id slipped in by hand "
|
||||
"is still refused", res["user_u7"]["status"] == "failed" and res["user_u3"]["status"] == "ok")
|
||||
ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u3", "user_u8"], "is_active": True})
|
||||
r = cp.post("/api/auth/bulk-users/resolve", json={"text": "u3"})
|
||||
check("a plain project user cannot resolve a list (403)", r.status_code == 403)
|
||||
r = cs.post("/api/auth/bulk-users/resolve", json={"text": "x" * 200_001})
|
||||
check("an oversized upload is refused (422)", r.status_code == 422)
|
||||
s = fresh()
|
||||
s.add(models.User(id="user_twin1", username="twin1", email="shared@example.test"))
|
||||
s.add(models.User(id="user_twin2", username="twin2", email="shared@example.test"))
|
||||
s.commit()
|
||||
r = ca.post("/api/auth/bulk-users/resolve", json={"text": "shared@example.test"})
|
||||
check("an email shared by two accounts matches neither", r.json()["rows"][0]["reason"] == "User not found")
|
||||
|
||||
|
||||
def gates():
|
||||
print("\n7. who may call, and how much")
|
||||
for path, body in (("role", {"role": "project_user"}), ("active", {"is_active": False}),
|
||||
("projects", {"project_id": "proj1", "op": "add"}), ("delete", {})):
|
||||
r = cp.post(f"/api/auth/bulk-users/{path}", json={"user_ids": ["user_u3"], **body})
|
||||
check(f"a plain project user is refused /bulk-users/{path} (403)", r.status_code == 403, str(r.status_code))
|
||||
anon = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
||||
check("no session: 401", anon.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u3"]}).status_code == 401)
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": [f"user_x{i}" for i in range(501)], "is_active": False})
|
||||
check("more than 500 ids in one request is refused (422)", r.status_code == 422, str(r.status_code))
|
||||
|
||||
|
||||
SECTIONS = [single_routes, bulk_role, bulk_active, bulk_projects, bulk_delete, csv_resolve, gates]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("Wave 12 bulk user administration - server checks")
|
||||
try:
|
||||
for section in SECTIONS:
|
||||
try:
|
||||
section()
|
||||
except Exception as exc: # noqa: BLE001 - a missing route must read as FAIL, not a traceback
|
||||
check(f"section {section.__name__} ran to the end", False, f"{type(exc).__name__}: {exc}")
|
||||
finally:
|
||||
db.close()
|
||||
A.engine.dispose()
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
passed = sum(RESULTS)
|
||||
print(f"\n{passed}/{len(RESULTS)} checks passed.")
|
||||
return 0 if passed == len(RESULTS) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,197 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CR-020 (wave 12): bulk user administration in the browser, at 1440px and 390px.
|
||||
|
||||
python tests/bulk_users_ui_check.py
|
||||
|
||||
Self-contained like the other probes: a throwaway SQLite database seeded by
|
||||
browser_check.seed(), its own uvicorn, headless Edge or Chrome over CDP. Your
|
||||
real wpsuite.db is never touched. Run it alone, not back to back with another
|
||||
probe (file-map.md: chained runs exhaust the browser's ports).
|
||||
|
||||
The server rules are proven in tests/bulk_users_check.py without a browser.
|
||||
This file proves the page: selection, the toolbar, the CSV path and the typed
|
||||
delete, end to end against the real server, operable by keyboard, and holding
|
||||
together at 390px. It writes the after-screenshots CLAUDE.md asks for to
|
||||
docs/reference/baseline/wave-12/; the before-shots are the existing
|
||||
users-1440.png and after-wave9/users-390.png.
|
||||
|
||||
Exit 0 all passed, 1 a failure, 2 could not run.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import cdp # noqa: E402
|
||||
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SHOTS = os.path.join(ROOT, "docs", "reference", "baseline", "wave-12")
|
||||
READY = "!!document.querySelector('#users-table table')"
|
||||
|
||||
|
||||
def api(base, path, token):
|
||||
req = urllib.request.Request(base + path, headers={"Cookie": "wp_session=" + token})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
def user(base, token, username):
|
||||
return next((u for u in api(base, "/api/auth/users", token) if u["username"] == username), None)
|
||||
|
||||
|
||||
def press(page, key, code, vk):
|
||||
"""A REAL key event (Input.dispatchKeyEvent), not a synthetic KeyboardEvent:
|
||||
only a real one triggers a checkbox's native Space toggle - the lesson
|
||||
launcher_check.py records."""
|
||||
for t in ("keyDown", "keyUp"):
|
||||
page.ws.call("Input.dispatchKeyEvent", {"type": t, "key": key, "code": code,
|
||||
"windowsVirtualKeyCode": vk, "text": " " if t == "keyDown" else ""})
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def answer(page, ok=True, typed=None):
|
||||
time.sleep(0.4)
|
||||
if typed is not None:
|
||||
page.eval("document.getElementById('wp-dlg-input').value=%s" % json.dumps(typed))
|
||||
page.eval("document.getElementById('%s').click()" % ("wp-dlg-ok" if ok else "wp-dlg-cancel"))
|
||||
time.sleep(1.2)
|
||||
|
||||
|
||||
def tick(page, username):
|
||||
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
|
||||
".find(x => x.dataset.id==='user_%s'); if(b) b.click(); })()" % username)
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
BAR_390 = """(function(){
|
||||
var bar=document.getElementById('bulk-bar'); var out={sw:document.documentElement.scrollWidth,under:[],clipped:[],n:0};
|
||||
bar.querySelectorAll('button, select').forEach(function(el){
|
||||
var r=el.getBoundingClientRect(); if(!r.width||!r.height) return; out.n++;
|
||||
var id=el.tagName+' '+(el.textContent||el.id).trim().slice(0,20)+' '+Math.round(r.width)+'x'+Math.round(r.height);
|
||||
if(Math.min(r.width,r.height)<24) out.under.push(id);
|
||||
if(r.left<-2||r.right>392) out.clipped.push(id);
|
||||
});
|
||||
return JSON.stringify(out);
|
||||
})()"""
|
||||
|
||||
|
||||
def main():
|
||||
exe = cdp.find_browser()
|
||||
if not exe:
|
||||
print("no headless-capable browser found; set WP_BROWSER.")
|
||||
return 2
|
||||
tmpdir = tempfile.mkdtemp(prefix="wpsuite-bulkui-")
|
||||
db_path = os.path.join(tmpdir, "check.db")
|
||||
server = browser = None
|
||||
try:
|
||||
tok = seed(db_path)
|
||||
port = cdp.free_port()
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
server = start_server(port, db_path)
|
||||
if server is None:
|
||||
print("server would not start")
|
||||
return 2
|
||||
browser = cdp.Browser(exe)
|
||||
page = browser.page()
|
||||
|
||||
def visit(who, width, mobile=False):
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok[who])
|
||||
page.viewport(width, 900 if width > 500 else 844, mobile=mobile)
|
||||
page.goto(base + "/users.html", wait_for=READY)
|
||||
time.sleep(0.6)
|
||||
|
||||
print("\n1. the admin at 1440px")
|
||||
visit("root", 1440)
|
||||
page.screenshot(os.path.join(SHOTS, "users-1440.png"))
|
||||
chk("a selection column with select-all", page.eval("!!document.getElementById('sel-all')"))
|
||||
chk("no bulk bar until a row is selected", page.eval("document.getElementById('bulk-bar').hidden"))
|
||||
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').focus()")
|
||||
press(page, " ", "Space", 32)
|
||||
chk("Space on a focused row checkbox selects it (keyboard operable)",
|
||||
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').checked"))
|
||||
chk("the bar appears, reachable by keyboard",
|
||||
page.eval("!document.getElementById('bulk-bar').hidden && document.querySelector('#bulk-bar button').tabIndex >= 0"))
|
||||
tick(page, "legacy")
|
||||
chk("the bar counts the selection", page.eval("document.getElementById('bulk-count').textContent") == "2 selected")
|
||||
page.screenshot(os.path.join(SHOTS, "users-1440-selected.png"))
|
||||
page.eval("document.getElementById('bulk-role').value='project_admin';"
|
||||
"document.querySelector('[onclick=\"bulkRole()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the confirm names the count", "for 2 users" in (page.eval("document.getElementById('wp-dlg-msg').textContent") or ""))
|
||||
answer(page)
|
||||
chk("both accounts changed on the server",
|
||||
user(base, tok["root"], "pat")["role"] == "project_admin" and user(base, tok["root"], "legacy")["role"] == "project_admin")
|
||||
chk("the result is announced", "2 changed" in page.eval("document.getElementById('bulk-banner').textContent")
|
||||
and page.eval("document.getElementById('bulk-banner').getAttribute('role')") in ("status", "alert"))
|
||||
tick(page, "pat")
|
||||
page.eval("const f=document.getElementById('user-filter'); f.value='active'; f.dispatchEvent(new Event('change'))")
|
||||
time.sleep(0.3)
|
||||
chk("changing the filter clears the selection, and says so",
|
||||
page.eval("document.getElementById('bulk-bar').hidden") and
|
||||
"filter changed" in page.eval("document.getElementById('sel-banner').textContent"))
|
||||
|
||||
print("\n2. the super user, a CSV with good and bad lines")
|
||||
visit("sue", 1440)
|
||||
page.eval("loadCsv(new File(['username\\npat\\nmix\\nbob\\nsue\\npat\\n'], 'list.csv', {type:'text/csv'}))")
|
||||
time.sleep(1.5)
|
||||
rep = page.eval("document.getElementById('csv-banner').textContent") or ""
|
||||
chk("only the account she may change is selected", page.eval("document.getElementById('bulk-count').textContent") == "1 selected", rep)
|
||||
chk("every bad line is reported by number and reason: another job, not found, herself, a duplicate",
|
||||
all(s in rep for s in ("Line 3 (mix)", "Line 4 (bob): User not found", "Line 5 (sue)", "Line 6 (pat): duplicate of line 2")), rep)
|
||||
page.eval("document.getElementById('bulk-project-role').value='project_admin';"
|
||||
"document.querySelector('[onclick=\"bulkProject(\\'add\\')\"]').click()")
|
||||
answer(page)
|
||||
roles = api(base, "/api/auth/users/user_pat/projects", tok["root"])["roles"]
|
||||
chk("add to project with a role landed on the server", roles.get("projA") == "project_admin", roles)
|
||||
|
||||
print("\n3. bulk delete needs the typed word")
|
||||
visit("root", 1440)
|
||||
tick(page, "bob")
|
||||
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the dialog lists the username", "bob" in page.eval("document.getElementById('wp-dlg-msg').textContent"))
|
||||
page.eval("document.getElementById('wp-dlg-input').value='delete'; document.getElementById('wp-dlg-ok').click()")
|
||||
time.sleep(0.4)
|
||||
chk("a wrong word sends nothing", user(base, tok["root"], "bob") is not None
|
||||
and page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"))
|
||||
answer(page, typed="DELETE")
|
||||
chk("DELETE deletes, and the report says so", user(base, tok["root"], "bob") is None
|
||||
and "1 changed" in page.eval("document.getElementById('bulk-banner').textContent"))
|
||||
|
||||
print("\n4. the gloved-hands width: 390px")
|
||||
visit("root", 390, mobile=True)
|
||||
page.screenshot(os.path.join(SHOTS, "users-390.png"))
|
||||
tick(page, "pat")
|
||||
m = json.loads(page.eval(BAR_390))
|
||||
page.screenshot(os.path.join(SHOTS, "users-390-selected.png"))
|
||||
chk("390px with the bar open: no sideways scrolling", m["sw"] <= 392, m["sw"])
|
||||
chk("390px: no bar control clipped past the screen", not m["clipped"], m["clipped"])
|
||||
chk("390px: every bar control meets the 24px floor", m["n"] > 0 and not m["under"], m["under"])
|
||||
|
||||
errs = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors in the whole run", not errs, errs[:3])
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
if server is not None:
|
||||
server.terminate()
|
||||
|
||||
print("\n" + "-" * 54)
|
||||
print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL)))
|
||||
for f in _FAIL:
|
||||
print(" - " + f)
|
||||
return 1 if _FAIL else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -112,33 +112,6 @@ def main():
|
||||
chk("cancel means no: bob is still an account",
|
||||
st == 200 and any(u.get("username") == "bob" for u in (users or [])),
|
||||
ascii_([u.get("username") for u in (users or [])]))
|
||||
# CR-020 / T12.5: the bulk delete is a PROMPT-style dialog (typed DELETE),
|
||||
# the kind this file's docstring says belongs back here.
|
||||
print("\n4. bulk delete needs the typed word")
|
||||
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
|
||||
".find(x => x.dataset.id==='user_bob'); b.click(); })()")
|
||||
time.sleep(0.3)
|
||||
chk("ticking a row shows the bulk bar",
|
||||
page.eval("!document.getElementById('bulk-bar').hidden"))
|
||||
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the bulk delete asks through the kit's prompt, listing the username",
|
||||
page.eval("(() => { const o=document.getElementById('wp-dlg-overlay');"
|
||||
" return o.classList.contains('open')"
|
||||
" && document.getElementById('wp-dlg-input-wrap').style.display !== 'none'"
|
||||
" && /bob/.test(document.getElementById('wp-dlg-msg').textContent); })()"))
|
||||
page.eval("document.getElementById('wp-dlg-input').value='delete';"
|
||||
"document.getElementById('wp-dlg-ok').click()")
|
||||
time.sleep(0.3)
|
||||
chk("the wrong word keeps it open and names what to type",
|
||||
page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"
|
||||
" && /DELETE/.test(document.getElementById('wp-dlg-err').textContent)"))
|
||||
page.eval("document.getElementById('wp-dlg-cancel').click()")
|
||||
time.sleep(0.6)
|
||||
st, users = api(base, "/api/auth/users", tok["root"])
|
||||
chk("cancel means no: bob is still an account after the bulk prompt",
|
||||
st == 200 and any(u.get("username") == "bob" for u in (users or [])))
|
||||
|
||||
errs = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors, and no path reached a native dialog (they throw here)",
|
||||
not errs, ascii_(errs[:3]))
|
||||
|
||||
270
tests/security_check.py
Normal file
270
tests/security_check.py
Normal file
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wave 16 security checks: D19, D20, D21.
|
||||
|
||||
python tests/security_check.py
|
||||
|
||||
Self-contained, like the other probes, but needs NO browser: it builds its own
|
||||
throwaway SQLite database in a temp folder, drives the API in-process with
|
||||
FastAPI's TestClient, and deletes everything afterward. Your real wpsuite.db is
|
||||
never touched, and no network traffic leaves the process.
|
||||
|
||||
Each check tests what was BROKEN, measured by the security review of
|
||||
2026-10-01 (docs/reference/security-review-2026-10-01.md), not only what is
|
||||
easy to assert. Every check that tests a fix FAILED against da1325c, the
|
||||
commit before wave 16; the checks that say "still works" passed there too,
|
||||
and are what proves the fix broke nothing.
|
||||
|
||||
Exit codes: 0 all passed, 1 a check failed, 2 the run could not start.
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TMP = tempfile.mkdtemp(prefix="wp-security-check-")
|
||||
# db.py reads DATABASE_URL at import, so the environment is set first.
|
||||
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "security.db").replace("\\", "/")
|
||||
os.environ["AUTH_SECRET_KEY"] = "security-check-key-security-check-key-0000"
|
||||
os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None)
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
try:
|
||||
from fastapi.testclient import TestClient
|
||||
from server import app as A, auth, models
|
||||
from server.db import SessionLocal
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("could not start:", exc)
|
||||
sys.exit(2)
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(item, name, ok, detail=""):
|
||||
RESULTS.append(bool(ok))
|
||||
print(f" {'PASS' if ok else 'FAIL'} {item:<4} {name}" + (f" ({detail})" if detail and not ok else ""))
|
||||
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
|
||||
def account(uid, role="project_user"):
|
||||
u = models.User(id=uid, username=uid[5:], role=role, email=uid[5:] + "@example.test")
|
||||
db.add(u)
|
||||
db.commit()
|
||||
return u
|
||||
|
||||
|
||||
def client(user=None, token=None):
|
||||
c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
||||
if user is not None:
|
||||
c.cookies.set(auth.COOKIE_NAME, auth.create_token(user))
|
||||
if token is not None:
|
||||
c.cookies.set(auth.COOKIE_NAME, token)
|
||||
return c
|
||||
|
||||
|
||||
admin = account("user_admin", "admin")
|
||||
member = account("user_member") # project_user on proj_a
|
||||
padmin = account("user_padmin") # project_admin on proj_a
|
||||
as_admin, as_member, as_padmin = client(admin), client(member), client(padmin)
|
||||
for pid in ("proj_a", "proj_b", "proj_c"):
|
||||
as_admin.post("/api/projects", json={"id": pid, "name": pid})
|
||||
for uid, role in (("user_member", ""), ("user_padmin", "project_admin")):
|
||||
for pid in ("proj_a", "proj_b"):
|
||||
db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role))
|
||||
db.commit()
|
||||
|
||||
|
||||
def b64url(raw: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
|
||||
# ── D21: session decode fails closed ─────────────────────────────────────────
|
||||
def d21():
|
||||
print("\nD21 session decode fails closed")
|
||||
crafted = b64url(b"[" * 1200) + "." + b64url(b"{}") + ".x"
|
||||
r = client(token=crafted).get("/api/projects")
|
||||
check("D21", "a crafted 1.6 KB cookie with no account gets 401, not 500",
|
||||
r.status_code == 401, f"status {r.status_code}")
|
||||
r = client(token="x" * 5000).get("/api/projects")
|
||||
check("D21", "an over-long cookie gets 401", r.status_code == 401, f"status {r.status_code}")
|
||||
no_exp = __import__("jwt").encode({"sub": member.id, "ver": 0}, auth.SECRET_KEY, algorithm="HS256")
|
||||
r = client(token=no_exp).get("/api/projects")
|
||||
check("D21", "a correctly signed token with no exp is refused", r.status_code == 401,
|
||||
f"status {r.status_code}")
|
||||
r = as_member.get("/api/auth/me")
|
||||
check("D21", "a real session still works", r.status_code == 200 and r.json()["user"]["id"] == member.id,
|
||||
f"status {r.status_code}")
|
||||
# D18 sliding refresh must survive the stricter decode: a token near its idle
|
||||
# edge, used now, comes back with a fresh cookie.
|
||||
from datetime import datetime, timedelta, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
near = __import__("jwt").encode({"sub": member.id, "username": member.username, "role": member.role,
|
||||
"ver": 0, "iat": now - timedelta(minutes=25),
|
||||
"login_at": (now - timedelta(minutes=25)).timestamp(),
|
||||
"exp": now + timedelta(minutes=5)}, auth.SECRET_KEY, algorithm="HS256")
|
||||
r = client(token=near).get("/api/projects")
|
||||
if hasattr(auth, "maybe_refresh_token"):
|
||||
check("D21", "the D18 sliding refresh still reissues the session",
|
||||
r.status_code == 200 and auth.COOKIE_NAME in (r.headers.get("set-cookie") or ""),
|
||||
f"status {r.status_code}")
|
||||
else:
|
||||
# D18 (T13.1) is not on this branch (wave 16 built on main, 2026-10-06):
|
||||
# there is no refresh to keep working, so prove the stricter decode still
|
||||
# accepts a valid token about to expire.
|
||||
check("D21", "a valid token close to its expiry is still accepted (no D18 on this branch)",
|
||||
r.status_code == 200, f"status {r.status_code}")
|
||||
import re
|
||||
pin = re.search(r"(?im)^pyjwt==([0-9.]+)", open(os.path.join(ROOT, "server", "requirements.txt")).read())
|
||||
pinned = tuple(int(x) for x in pin.group(1).split(".")) if pin else (0,)
|
||||
check("D21", "server/requirements.txt pins PyJWT 2.15.1 or later", pinned >= (2, 15, 1),
|
||||
pin.group(1) if pin else "no pin")
|
||||
|
||||
|
||||
# ── D19: uploaded files download safely ──────────────────────────────────────
|
||||
def d19():
|
||||
print("\nD19 uploaded files download safely")
|
||||
r = as_member.post("/api/wps", json={"id": "wp_files", "project_id": "proj_a", "number": "F1"})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
def upload(name, mime, data):
|
||||
r = as_member.post("/api/wps/wp_files/files", json={
|
||||
"name": name, "mime": mime, "data_base64": base64.b64encode(data).decode()})
|
||||
return r.status_code, (r.json().get("file") or {}).get("id")
|
||||
|
||||
code, svg = upload("route.svg", "image/svg+xml",
|
||||
b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
|
||||
check("D19", "an SVG upload is still accepted (decided: accept, download only)", code == 200, f"status {code}")
|
||||
r = as_member.get(f"/api/files/{svg}")
|
||||
disp, csp = r.headers.get("content-disposition", ""), r.headers.get("content-security-policy", "")
|
||||
check("D19", "an SVG downloads as an attachment, never inline", disp.startswith("attachment"), disp)
|
||||
check("D19", "an SVG download carries a sandbox CSP", "sandbox" in csp, csp or "no CSP")
|
||||
check("D19", "file responses carry nosniff", r.headers.get("x-content-type-options") == "nosniff")
|
||||
|
||||
for name, mime, data in (("plan.png", "image/png", b"\x89PNG\r\n\x1a\n"),
|
||||
("photo.jpg", "image/jpeg", b"\xff\xd8\xff"),
|
||||
("sheet.pdf", "application/pdf", b"%PDF-1.4")):
|
||||
_, fid = upload(name, mime, data)
|
||||
r = as_member.get(f"/api/files/{fid}")
|
||||
check("D19", f"{mime} still opens inline, no sandbox",
|
||||
r.status_code == 200 and r.headers.get("content-disposition", "").startswith("inline")
|
||||
and "content-security-policy" not in r.headers, r.headers.get("content-disposition", ""))
|
||||
check("D19", f"{mime} keeps the offline cache header",
|
||||
r.headers.get("cache-control") == "private, max-age=86400", r.headers.get("cache-control", ""))
|
||||
|
||||
_, fid = upload("Plan é – Nivel 2.pdf", "application/pdf", b"%PDF-1.4")
|
||||
r = as_member.get(f"/api/files/{fid}")
|
||||
check("D19", "a drawing with a non-Latin-1 name downloads (was 500)", r.status_code == 200,
|
||||
f"status {r.status_code}")
|
||||
check("D19", "the real name rides in filename*",
|
||||
"filename*=UTF-8''Plan%20%C3%A9" in r.headers.get("content-disposition", ""),
|
||||
r.headers.get("content-disposition", ""))
|
||||
|
||||
_, fid = upload('a\r\nSet-Cookie: x=1;".pdf', "application/pdf", b"%PDF-1.4")
|
||||
r = as_member.get(f"/api/files/{fid}")
|
||||
disp = r.headers.get("content-disposition", "")
|
||||
check("D19", "CR/LF and quotes in a name cannot reach the header",
|
||||
r.status_code == 200 and "\r" not in disp and "\n" not in disp and "set-cookie" not in r.headers,
|
||||
repr(disp))
|
||||
r = client(account("user_outsider")).get(f"/api/files/{svg}")
|
||||
check("D19", "a non-member still gets 403 (access check unchanged)", r.status_code == 403,
|
||||
f"status {r.status_code}")
|
||||
|
||||
|
||||
# ── D20: one SOP per project ─────────────────────────────────────────────────
|
||||
def d20():
|
||||
print("\nD20 one SOP per project")
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
def sop(c, **body):
|
||||
body.setdefault("project_id", "proj_a")
|
||||
return c.post("/api/sops", json=body)
|
||||
|
||||
def team(qa):
|
||||
return {"sop": {"project": {"pmId": qa, "cmId": qa, "qaGroupIds": [qa]}}, "state": {}}
|
||||
|
||||
r = sop(as_member, name="draft", complete=False, data=team("user_padmin"))
|
||||
check("D20", "a SOP posted with no id lands on sop__<project_id>",
|
||||
r.status_code == 200 and r.json().get("id") == "sop__proj_a", f"{r.status_code} {r.json().get('id')}")
|
||||
r = sop(as_member, id="sop__proj_a", name="done", complete=True, data=team("user_padmin"))
|
||||
check("D20", "a project_user still completes the first SOP of a project", r.status_code == 200,
|
||||
f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop_rogue", name="mine", complete=True, data=team("user_member"))
|
||||
check("D20", "a project_user cannot create a second SOP (the SEC-02 attack)", r.status_code == 400,
|
||||
f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop__proj_a", name="edit", complete=True, data=team("user_member"))
|
||||
check("D20", "a project_user still cannot change the completed SOP", r.status_code == 403,
|
||||
f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop__proj_a", name="undo", complete=False, data=team("user_member"))
|
||||
check("D20", "a project_user cannot un-complete it either", r.status_code == 403, f"status {r.status_code}")
|
||||
r = sop(as_padmin, id="sop__proj_a", name="revised", complete=True, data=team("user_padmin"))
|
||||
check("D20", "a Project Admin can still change the completed SOP", r.status_code == 200,
|
||||
f"status {r.status_code}")
|
||||
qa = [u.id for u in A.project_qa_group(SessionLocal(), "proj_a")]
|
||||
check("D20", "QA mail still goes to the group the real SOP names", qa == ["user_padmin"], str(qa))
|
||||
|
||||
# A rogue complete SOP made BEFORE D20 (written straight to the table, newer
|
||||
# than the real one) must not stay the baseline.
|
||||
s = SessionLocal()
|
||||
old, new = datetime.now(timezone.utc) - timedelta(days=2), datetime.now(timezone.utc)
|
||||
s.add(models.Sop(id="sop__proj_b", project_id="proj_b", name="real", complete=True,
|
||||
data=team("user_padmin"), updated_at=old))
|
||||
s.add(models.Sop(id="sop_rogue_b", project_id="proj_b", name="rogue", complete=True,
|
||||
data=team("user_member"), updated_at=new))
|
||||
s.commit()
|
||||
r = as_member.get("/api/sops/latest?complete=true&project_id=proj_b")
|
||||
check("D20", "the page-load baseline is the canonical SOP, not a newer rogue row",
|
||||
r.status_code == 200 and r.json().get("id") == "sop__proj_b", f"{r.status_code} {r.json().get('id')}")
|
||||
qa = [u.id for u in A.project_qa_group(SessionLocal(), "proj_b")]
|
||||
team_ids = A.project_sop_team(SessionLocal(), "proj_b")
|
||||
check("D20", "QA and PM/CM mail follow the canonical SOP", qa == ["user_padmin"] and team_ids == ["user_padmin", "user_padmin"],
|
||||
f"qa={qa} team={team_ids}")
|
||||
r = as_member.get("/api/projects/proj_b/summary")
|
||||
check("D20", "the launcher summary reports the canonical SOP", r.json().get("sop_id") == "sop__proj_b",
|
||||
str(r.json().get("sop_id")))
|
||||
|
||||
# Rows made before D20 under other ids keep working under the old rules.
|
||||
s.add(models.Sop(id="sop_legacy", project_id="proj_c", name="legacy", complete=False, data={}))
|
||||
db.add(models.ProjectMember(id="pm_member_c", user_id="user_member", project_id="proj_c", role=""))
|
||||
db.commit(); s.commit()
|
||||
r = sop(as_member, id="sop_legacy", project_id="proj_c", name="legacy edited", complete=False)
|
||||
check("D20", "an existing non-canonical SOP can still be edited", r.status_code == 200,
|
||||
f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop_legacy", project_id="proj_c", name="legacy done", complete=True)
|
||||
check("D20", "...and completed the first time", r.status_code == 200, f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop__proj_c", project_id="proj_c", name="second", complete=True)
|
||||
check("D20", "while a project has a complete SOP, another complete one needs Project Admin",
|
||||
r.status_code == 403, f"status {r.status_code}")
|
||||
r = sop(as_member, id="sop_legacy", project_id="proj_a", name="moved", complete=False)
|
||||
check("D20", "a SOP cannot be moved into another project under a non-canonical id",
|
||||
r.status_code in (400, 403), f"status {r.status_code}")
|
||||
r = client(account("user_stranger")).get("/api/sops/latest?complete=true&project_id=proj_a")
|
||||
check("D20", "a non-member still gets 404 for the baseline", r.status_code == 404, f"status {r.status_code}")
|
||||
r = as_admin.post("/api/sops", json={"project_id": "proj_c", "name": "x", "complete": False})
|
||||
check("D20", "an id-less write (smoke test, seed_demo, admin diagnostics) targets the canonical row",
|
||||
r.status_code == 200 and r.json().get("id") == "sop__proj_c", f"{r.status_code} {r.json().get('id')}")
|
||||
|
||||
|
||||
SECTIONS = [d21, d19, d20]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("Wave 16 security checks")
|
||||
try:
|
||||
for section in SECTIONS:
|
||||
section()
|
||||
finally:
|
||||
db.close()
|
||||
A.engine.dispose()
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
passed = sum(RESULTS)
|
||||
print(f"\n{passed}/{len(RESULTS)} checks passed.")
|
||||
return 0 if passed == len(RESULTS) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user