Grant a module to a person, and let a unit stay a shortcut
Atrium becomes the writer of `dredd.module_permission` -- the one table that decides who may use which module, and with what role. No row is no access; `user` may use; `moderator` may administer; a platform administrator needs no row anywhere. The administration pane grants and revokes per module, with a role, and `module_assignment` survives only as the record of WHY somebody holds a row: naming a unit is still how you grant a whole department at once, but it now writes the per-user rows, so the three modules read exactly one table and never have to reach into this schema to find out who may enter. The shortcut re-materialises on every change that can alter who is in a unit -- an assignment added or removed, availability changed, a module created, an access request approved, a unit grant given or taken away, a unit deleted, an account created, and every deploy through the seed. That is possible without a background job for one reason: the hub is the only writer of membership AND of permissions, so every input is a request this app served. Freezing it instead would have been a regression -- unit membership already resolved live -- and re-resolving on read would mean a GET that writes, in three deployments that hold SELECT and nothing else. Two rules keep the set-difference safe. Naming somebody on a roster pins a direct assignment for them, so an unrelated change to that module cannot sweep them away later -- a silent, delayed revocation. And a deactivated account takes no part in either direction, so switching somebody off and on again does not strip every module they moderated. Two gaps found by running it rather than reading it: - Existing modules have no permission rows, and nothing in the trigger list creates them -- so the first deploy of this would have let nobody into anything, including modules marked available to everyone. The seed now sweeps every module, which makes it a backstop as well as a backfill since it writes only differences. - A table created by the new revision carries no runtime grants: 0003 granted ON ALL TABLES at the time it ran. Invisible until the day the deployment joins a platform and every roster read is a permission error. The new revision re-runs the grants, as 0003's own docstring says every later revision adding a table must. The HTTP route keeps its name. `/admin/modules/<slug>/moderators` is quoted in three other repositories and scanned by a test in one of them; renaming it to match the table would be tidiness bought with four repos and a broken suite. Requires dredd-core v0.11.0. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+5
-4
@@ -72,13 +72,13 @@ SESSION_COOKIE_SECURE=
|
||||
|
||||
# ── one platform, one account ────────────────────────────────────────────────
|
||||
# Empty (the default) is the STANDALONE deployment: Atrium owns app_user, session and
|
||||
# module_moderator in its own schema, signs its own users in, and nothing below applies.
|
||||
# module_permission in its own schema, signs its own users in, and nothing below applies.
|
||||
#
|
||||
# Set IDENTITY_SCHEMA and those three tables live in a neutral schema that every module reads, so a
|
||||
# person has ONE account across the platform and signs in once, here. It is a name rather than a
|
||||
# flag because three things must agree on it: the revision that creates the tables there, the
|
||||
# start-up assertion that they really resolve there (a shadow copy in this app's own schema has no
|
||||
# other symptom), and the moderator tier, which is meaningless without a platform.
|
||||
# other symptom), and the per-module permissions, which are meaningless without a platform.
|
||||
#
|
||||
# The schema itself, its owner and the roles' search_path are PROVISIONING, not migration — a
|
||||
# migrator holds no CREATE on the database and cannot ALTER ROLE another role. See
|
||||
@@ -90,8 +90,9 @@ IDENTITY_SCHEMA=
|
||||
# owns the schema. Naming them here keeps the modules' names out of this app's source.
|
||||
IDENTITY_READER_ROLES=
|
||||
IDENTITY_MIGRATOR_ROLES=
|
||||
# This app's slug on the platform, and the hub's own: module_moderator(user, 'atrium') is refused,
|
||||
# because the hub has administrators and its administration is not delegable one module at a time.
|
||||
# This app's slug on the platform, and the hub's own: module_permission(user, 'atrium') is refused —
|
||||
# every account may open the launcher, so a 'user' row would say nothing, and the hub has
|
||||
# administrators whose job is not delegable one module at a time.
|
||||
MODULE_SLUG=atrium
|
||||
# One account means one cookie. At the cutover every app in the family is set to
|
||||
# SESSION_COOKIE_NAME=dredd_session, and because the family runs at ONE origin that is all there is
|
||||
|
||||
@@ -260,12 +260,17 @@ jobs:
|
||||
-- symptom -- the search_path reaches it first and everything keeps working, silently
|
||||
-- back to two rows per person. assert_identity_schema catches it at boot; this catches
|
||||
-- it here, before anything is deployed.
|
||||
-- `module_moderator` is listed as well as `module_permission`: it is the name the
|
||||
-- same table had before dredd-core v0.11.0, and a copy left behind under EITHER name is
|
||||
-- the same shadow. 0006 normalises the name in this app's own schema, and is guarded so
|
||||
-- that on a platform database it never creates one here at all.
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'atrium'
|
||||
AND tablename IN ('app_user', 'session', 'module_moderator')) THEN
|
||||
RAISE EXCEPTION 'an identity table is still in schema atrium after revision 0004';
|
||||
AND tablename IN ('app_user', 'session', 'module_permission',
|
||||
'module_moderator')) THEN
|
||||
RAISE EXCEPTION 'an identity table is still in schema atrium after revisions 0004-0006';
|
||||
END IF;
|
||||
IF (SELECT count(*) FROM pg_tables WHERE schemaname = 'dredd'
|
||||
AND tablename IN ('app_user', 'session', 'module_moderator')) <> 3 THEN
|
||||
AND tablename IN ('app_user', 'session', 'module_permission')) <> 3 THEN
|
||||
RAISE EXCEPTION 'the three shared identity tables are not in schema dredd';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
@@ -39,8 +39,8 @@ was inferred by an assistant, never chosen.
|
||||
|
||||
**Where the work actually stands.** The one origin and the four paths landed first. Atrium's half of
|
||||
the shared identity store has landed too: revision `0004_shared_identity` creates `app_user`,
|
||||
`session` and `module_moderator` in a neutral schema, moves Atrium's rows into it and grants every
|
||||
role its tier. The three modules move their own rows in their own repositories. Until each one does,
|
||||
`session` and `module_permission` in a neutral schema, moves Atrium's rows into it and grants
|
||||
every role its tier. The three modules move their own rows in their own repositories. Until each one does,
|
||||
that module still asks for a password — a migration in flight, not the design, so don't re-derive
|
||||
the old model from what one module does today.
|
||||
|
||||
@@ -59,24 +59,56 @@ platform admin can, via `db/managed/provision.sql` (`--identity-schema` / `--ide
|
||||
tiers. Neither half can move into the other, which is what makes a missed ordering a named error
|
||||
rather than a race — and `deploy/compose.yaml` makes every module's migration wait for Atrium's.
|
||||
|
||||
**Two words for administration, used verbatim everywhere** — table, API, guard names, audit actions
|
||||
and console copy — because two words for one idea is how a permission model rots:
|
||||
**Three words for what somebody may do, used verbatim everywhere** — table, API, guard names,
|
||||
audit actions and console copy — because two words for one idea is how a permission model rots:
|
||||
|
||||
- **administrator** — platform-wide: every module, plus the hub itself. `app_user.is_admin`,
|
||||
changed only through `services/accounts.py`.
|
||||
- **moderator** — exactly one module. A `module_moderator` row, granted only through
|
||||
`services/moderation.py`.
|
||||
changed only through `services/accounts.py`. Needs no row anywhere.
|
||||
- **moderator** — administers exactly one module. A `module_permission` row with
|
||||
`role = 'moderator'`, written only through `services/moderation.py`.
|
||||
- **user** — may USE exactly one module. The same row with `role = 'user'`.
|
||||
|
||||
The fourth answer is **no row at all**, and it is the default for everybody: no access to that
|
||||
module. That is what `module_permission` exists for — before it, anyone with an account could
|
||||
type `/galena` and be let in, saw an empty drive, and nothing had refused them.
|
||||
|
||||
An administrator is a moderator of everything; a moderator is nothing outside their own module.
|
||||
**Neither tier can be granted from inside a module**, and the thing that makes that true is the
|
||||
grant, not a missing menu item: a module's runtime role holds `SELECT` on `module_moderator`, a
|
||||
**No tier can be granted from inside a module**, and the thing that makes that true is the
|
||||
grant, not a missing menu item: a module's runtime role holds `SELECT` on `module_permission`, a
|
||||
seven-column `SELECT` on `app_user` and a three-column `UPDATE` on `session`, and nothing else. It
|
||||
cannot create an account, elevate one, or mint a credential. Atrium has administrators and **no
|
||||
moderators of its own** — `module_moderator(user, 'atrium')` is refused — which is why this app
|
||||
cannot admit anybody, promote anybody (least of all itself), create an account, elevate one, or
|
||||
mint a credential. Atrium has administrators and **no
|
||||
moderators of its own** — `module_permission(user, 'atrium')` is refused, and every account may
|
||||
open the launcher anyway — which is why this app
|
||||
defines `require_administrator` and deliberately no `require_moderator`, and why it never calls
|
||||
`authz.bind_moderation` (that binding projects a moderator onto a module's node tree as `manager`;
|
||||
Atrium's tree is the organisation chart, and a Galena moderator has no business managing it).
|
||||
|
||||
**An assignment is a shortcut, not a second permission model.** `module_permission` is the ONE
|
||||
table that decides access: no row, no entry, and every module reads it and nothing else.
|
||||
`module_assignment` survives only as this hub's convenience — a record of *why* somebody has a
|
||||
module, and in particular the one way to say "everybody in Legal" without naming twelve people. It
|
||||
is no longer consulted by anything making an access decision, and it is **materialised** into
|
||||
per-user rows by `services/marketplace.py`.
|
||||
|
||||
That shortcut is **re-materialised on every membership change**, so it cannot go stale in either
|
||||
direction: somebody who joins the department next week gets the module, and somebody who leaves
|
||||
loses it. `sync_module` reconciles one module against its assignments; `sync_members` reconciles
|
||||
one person against the whole catalogue; between them they are called from every hub write path that
|
||||
can change the answer — assignment added or removed, availability changed, module created, access
|
||||
request approved, unit grant given or taken away, unit deleted, account created. There is no third
|
||||
table and no background job, because the hub is the only writer of membership *and* of permissions,
|
||||
so every input is a request it served. Two rules keep the reconciliation safe and must not be
|
||||
"simplified" away: it is a full set-difference, so **every row it could delete has an assignment
|
||||
behind it** (naming somebody on a module's roster records a direct assignment for them, exactly as
|
||||
approving an access request already did); and **deactivated accounts take no part in it on either
|
||||
side**, or switching somebody off and on again would silently strip every module they moderated.
|
||||
|
||||
**The roster's HTTP path is still `/admin/modules/{slug}/moderators`**, although the table is
|
||||
`module_permission`. That is a deliberate exception to "one word per idea" and a **cross-repo
|
||||
contract**: Counsel Scorecard's suite asserts the address character for character, and Galena and
|
||||
Sygna quote it in their docs. Rename it in four repositories in one pass, or not at all.
|
||||
|
||||
**The last administrator cannot be demoted or deactivated** (`services/accounts.py`, counting only
|
||||
*active* ones). Atrium had no such guard at all, and once the tier is platform-wide a mis-click
|
||||
locked every module's administration out at once, with no second door back in.
|
||||
@@ -104,9 +136,9 @@ catches it after a restore.
|
||||
|
||||
```
|
||||
dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMixin · SafeInet · pg_enum
|
||||
AppUser · Session · ModuleModerator · AppSetting · AuditLog
|
||||
AppUser · Session · ModulePermission · AppSetting · AuditLog
|
||||
Node · PermissionGrant · Favorite
|
||||
SHARED_IDENTITY_TABLES (app_user, session, module_moderator) — the three
|
||||
SHARED_IDENTITY_TABLES (app_user, session, module_permission) — the three
|
||||
that move to the shared schema; everything else stays per app
|
||||
dredd_core.enums NodeRole PrincipalType ReviewPolicy EncryptionMode
|
||||
SessionKind TokenScope
|
||||
@@ -137,15 +169,17 @@ dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMi
|
||||
backend/app/
|
||||
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
|
||||
observability.py logging_config.py (db/errors/security/enums are shims)
|
||||
models/ __init__ (re-exports core's AppUser/Session/ModuleModerator/AppSetting/AuditLog/
|
||||
models/ __init__ (re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog/
|
||||
Node/PermissionGrant/Favorite next to this app's own models)
|
||||
marketplace Module · ModuleAssignment · AccessRequest (Text + CHECK vocabularies)
|
||||
services/ auth · authz · audit (shims over dredd_core)
|
||||
accounts the ADMINISTRATOR tier + the last-administrator guard, deactivate /
|
||||
reactivate, and minting an app token FOR A MODULE (<slug>_pat_)
|
||||
moderation the MODERATOR tier: the roster, grant, revoke, revoke_module
|
||||
marketplace (catalog, who is offered what, requests, probe) · settings (closed,
|
||||
typed) · audit_log (reader) · nodes (org units) · changes
|
||||
moderation module_permission: the roster, grant (an UPSERT, so it promotes and
|
||||
demotes), revoke, revoke_module. The only writer on the platform.
|
||||
marketplace (catalog, who may open what, requests, probe — and the reconciliation
|
||||
that materialises a unit assignment into per-user permission rows) · settings
|
||||
(closed, typed) · audit_log (reader) · nodes (org units) · changes
|
||||
integrations/ health (the outbound module probe — stdlib http.client on a socket it owns)
|
||||
routers/ health auth users admin admin_modules marketplace nodes
|
||||
backend/
|
||||
@@ -158,6 +192,15 @@ backend/
|
||||
its 14 foreign keys, drops the local copies, grants all eight roles their tier,
|
||||
forbids DELETE on an account. NOT downgradable on a platform — see the docstring,
|
||||
and deploy/RUNBOOK-one-account.md for the operator sequence)
|
||||
+ 0005_counsel_slug (the catalogue row the seed got wrong, and the permission rows
|
||||
addressed to it; the survivor of a duplicate keeps the HIGHER role)
|
||||
+ 0006_module_permission (dredd-core v0.11.0's rename, in THIS app's own schema —
|
||||
`0001` is stamped and can never reach a database that already exists, which is
|
||||
the `node_kind` mistake this family has made once. Decided by catalogue check:
|
||||
already renamed → nothing; `module_moderator` → RENAME + its constraints +
|
||||
`role` + every existing row set to moderator; in the shared schema or
|
||||
IDENTITY_SCHEMA set → nothing, because a local copy would be the shadow table;
|
||||
nowhere at all → built from the metadata)
|
||||
scripts/ license_gate (CI copyleft gate) · deploy_check (compose/Dockerfile/Caddyfile/.env)
|
||||
frontend/ index.html · app.css · app.js (no build step)
|
||||
Tabler icon path data vendored into app.js's ICN map (CREDITS.md)
|
||||
|
||||
@@ -115,7 +115,7 @@ Atrium shares that code with its siblings, and — where the platform is switche
|
||||
store with them too. What stays separate is the domain data: locally each app has its own database,
|
||||
and in the family's shared managed database its own schema and its own least-privilege roles, which
|
||||
no other app's role can read. **Database isolation is unchanged by single sign-on.** Exactly three
|
||||
tables are shared — `app_user`, `session` and `module_moderator`, which is
|
||||
tables are shared — `app_user`, `session` and `module_permission`, which is
|
||||
`dredd_core.identity.SHARED_IDENTITY_TABLES` — they live in a *neutral* schema rather than Atrium's
|
||||
(so a module's `USAGE` opens onto a list a person can read, not onto the whole marketplace), and
|
||||
they are the hub's to write. Everything else, `app_setting` and `audit_log` included, stays per app:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This is the revision the whole "one platform, one account, one admin pane" change turns on. Before
|
||||
it, four apps each kept their own `app_user` and four people called `admin@example.com` happened to
|
||||
share an email address. After it, Atrium's `app_user`, `session` and `module_moderator` live in a
|
||||
share an email address. After it, Atrium's `app_user`, `session` and `module_permission` live in a
|
||||
**neutral schema** that every module reads, a person has ONE account, and signing in at the hub
|
||||
signs them in everywhere — because the family runs at one origin, so one cookie and one `session`
|
||||
row is the entire mechanism. There is no handoff protocol here, and there must never be one.
|
||||
@@ -59,7 +59,13 @@ already granted, and drops what is already dropped.
|
||||
**When a module joins the platform later**, add its two roles to `IDENTITY_READER_ROLES` /
|
||||
`IDENTITY_MIGRATOR_ROLES` and add a new three-line revision that calls
|
||||
`shared_identity_grants_sql` again — the block is authoritative, not additive, so re-running it is
|
||||
how the matrix stays true. Do not edit this file; it has already run.
|
||||
how the matrix stays true.
|
||||
|
||||
**This file has still never run anywhere** (no environment sets `IDENTITY_SCHEMA`; the live box
|
||||
still has four separate `app_user` tables), which is the only reason the dredd-core v0.11.0 rename
|
||||
of `module_moderator` to `module_permission` could be made here rather than in a revision after it.
|
||||
`0001` HAS run everywhere, though, so the rename in the app's OWN schema needed a new revision all
|
||||
the same — that is `0006`, and what it and this file do are deliberately different halves.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -90,9 +96,20 @@ depends_on = None
|
||||
log = logging.getLogger("alembic.runtime.migration")
|
||||
|
||||
#: Local tables to drop once their rows are in the shared schema, children before parents.
|
||||
#: `module_moderator` is on `Base.metadata` from dredd-core v0.10.0, so a fresh `0001` creates a
|
||||
#: local one; a database migrated before the bump has none, which is why every drop is IF EXISTS.
|
||||
_LOCAL_TABLES = ("module_moderator", "session", "app_user")
|
||||
#:
|
||||
#: BOTH names of the roster table are listed, and every drop is `IF EXISTS`, because which one a
|
||||
#: database has depends only on when its `0001` ran: none at all before dredd-core v0.10.0,
|
||||
#: `module_moderator` from v0.10.0, `module_permission` from v0.11.0. All three are live shapes —
|
||||
#: the live box is the first, a developer database is the second, a fresh install is the third —
|
||||
#: and this runs before `0006`, which is what normalises the name in a schema that keeps it.
|
||||
_LOCAL_TABLES = ("module_permission", "module_moderator", "session", "app_user")
|
||||
|
||||
#: The columns of the pre-v0.11.0 `module_moderator`, in the order `0001` created them. Typed out
|
||||
#: rather than read from `Base.metadata`, because that table is no longer in the metadata at all —
|
||||
#: this is frozen history, and the only thing that can still be read off a database that has it.
|
||||
#: Every row in it meant "this person moderates this module", which is why the merge below inserts
|
||||
#: them with `role` set to `moderator` and not to the column's own default.
|
||||
_LEGACY_MODERATOR_COLUMNS = '"id", "user_id", "module_slug", "created_at", "created_by"'
|
||||
|
||||
|
||||
def _ident(value: str, what: str) -> str:
|
||||
@@ -200,7 +217,7 @@ BEGIN
|
||||
had_local boolean NOT NULL,
|
||||
accounts bigint NOT NULL,
|
||||
credentials bigint NOT NULL,
|
||||
moderators bigint NOT NULL
|
||||
permissions bigint NOT NULL
|
||||
) ON COMMIT DROP;
|
||||
|
||||
IF to_regclass(quote_ident(own) || '.app_user') IS NULL THEN
|
||||
@@ -239,12 +256,22 @@ BEGIN
|
||||
WHERE d.id = l.id OR d.token_hash = l.token_hash);
|
||||
GET DIAGNOSTICS creds = ROW_COUNT;
|
||||
|
||||
-- Only a database created AFTER the dredd-core v0.10.0 bump has a local one of these; on a live
|
||||
-- box migrated before it, there is nothing here to move.
|
||||
IF to_regclass(quote_ident(own) || '.module_moderator') IS NOT NULL THEN
|
||||
INSERT INTO {identity_schema}.module_moderator ({moderator_columns})
|
||||
SELECT {moderator_columns} FROM module_moderator l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM {identity_schema}.module_moderator d
|
||||
-- Which local roster table there is, if any, says only when this database was first migrated:
|
||||
-- none before dredd-core v0.10.0 (the live box), module_moderator from v0.10.0, and
|
||||
-- module_permission from v0.11.0. The shared store is always the new shape, so the old one is
|
||||
-- read column by column and every row it holds arrives as a moderator, which is the only thing
|
||||
-- a row in that table ever meant.
|
||||
IF to_regclass(quote_ident(own) || '.module_permission') IS NOT NULL THEN
|
||||
INSERT INTO {identity_schema}.module_permission ({permission_columns})
|
||||
SELECT {permission_columns} FROM module_permission l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM {identity_schema}.module_permission d
|
||||
WHERE d.id = l.id
|
||||
OR (d.user_id = l.user_id AND d.module_slug = l.module_slug));
|
||||
GET DIAGNOSTICS tiers = ROW_COUNT;
|
||||
ELSIF to_regclass(quote_ident(own) || '.module_moderator') IS NOT NULL THEN
|
||||
INSERT INTO {identity_schema}.module_permission ({legacy_columns}, "role")
|
||||
SELECT {legacy_columns}, 'moderator' FROM module_moderator l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM {identity_schema}.module_permission d
|
||||
WHERE d.id = l.id
|
||||
OR (d.user_id = l.user_id AND d.module_slug = l.module_slug));
|
||||
GET DIAGNOSTICS tiers = ROW_COUNT;
|
||||
@@ -269,7 +296,7 @@ $dredd_identity_merge$
|
||||
# included. Hence no schema name interpolated here either: it is a temporary table, and the schema
|
||||
# it reports is the one it recorded.
|
||||
_SUMMARY = """
|
||||
SELECT own_schema, had_local, accounts, credentials, moderators FROM dredd_identity_moved
|
||||
SELECT own_schema, had_local, accounts, credentials, permissions FROM dredd_identity_moved
|
||||
"""
|
||||
|
||||
# The last statement that can lose data, and the only one in this app that could damage the whole
|
||||
@@ -325,9 +352,9 @@ def _report(identity: str) -> None:
|
||||
log.info("shared identity: no local app_user in %s, nothing to move", row["own_schema"])
|
||||
return
|
||||
log.info(
|
||||
"shared identity: moved %s account(s), %s credential(s) and %s moderator row(s) from %s "
|
||||
"to %s", row["accounts"], row["credentials"], row["moderators"], row["own_schema"],
|
||||
identity)
|
||||
"shared identity: moved %s account(s), %s credential(s) and %s module permission row(s) "
|
||||
"from %s to %s", row["accounts"], row["credentials"], row["permissions"],
|
||||
row["own_schema"], identity)
|
||||
|
||||
|
||||
def _report_stale_grants(identity: str) -> None:
|
||||
@@ -387,7 +414,8 @@ def upgrade() -> None:
|
||||
identity_schema=identity,
|
||||
user_columns=_columns("app_user"),
|
||||
session_columns=_columns("session"),
|
||||
moderator_columns=_columns("module_moderator"),
|
||||
permission_columns=_columns("module_permission"),
|
||||
legacy_columns=_LEGACY_MODERATOR_COLUMNS,
|
||||
))
|
||||
_report(identity)
|
||||
|
||||
@@ -425,6 +453,13 @@ def upgrade() -> None:
|
||||
# non-secret columns of an account and write three columns of a session row; it may never
|
||||
# create an account or mint a credential, which is what "the modules are readers of identity
|
||||
# and the hub is its writer" means at the level that actually enforces it.
|
||||
#
|
||||
# `permission_table` is left at its default (`module_permission`), which is deliberate and
|
||||
# is the sharpest edge in this whole change: on that table the hub now also holds UPDATE,
|
||||
# because promoting or demoting somebody is an UPDATE of a row that stays — and **a module
|
||||
# holds SELECT and nothing else**. A module that could write its own permission rows could
|
||||
# admit anyone, promote anyone, and promote itself, which is the entire reason this table
|
||||
# lives in the hub's keeping rather than in each module's schema.
|
||||
op.execute(shared_identity_grants_sql(
|
||||
identity,
|
||||
owner_role=owner,
|
||||
|
||||
@@ -5,7 +5,7 @@ its path (`/counsel`), its schema, its two roles and its own `MODULE_SLUG` defau
|
||||
one module, and **nothing reported an error**, because a slug only the catalogue believes in fails
|
||||
silently on both paths that now cross the platform boundary:
|
||||
|
||||
* `POST /admin/modules/counsel-scorecard/moderators` wrote a `module_moderator` row and returned
|
||||
* `POST /admin/modules/counsel-scorecard/moderators` wrote a module-permission row and returned
|
||||
201. Counsel reads that table with its own slug, finds nothing, and the person stays
|
||||
`is_moderator = false`. An administrator delegated a module and nothing happened.
|
||||
* `POST /me/modules/counsel/tokens` was a 404 (no such module in the catalogue), and Counsel's own
|
||||
@@ -66,14 +66,20 @@ depends_on = None
|
||||
#: (`INFO [alembic.runtime.migration] …`). Not a logger of this app's: nothing configures one here.
|
||||
log = logging.getLogger("alembic.runtime.migration")
|
||||
|
||||
#: The catalogue row, and the moderator grants that were written against the wrong name.
|
||||
#: The catalogue row, and the module-permission rows that were written against the wrong name.
|
||||
#:
|
||||
#: `module_moderator` is left unqualified on purpose: standalone it is this app's own table, and on
|
||||
#: the platform the local copy is gone and the search_path resolves the shared one. Both are owned
|
||||
#: by the role running this migration, which is the only role that may UPDATE it at all — the eight
|
||||
#: app roles hold SELECT/INSERT/DELETE there and never UPDATE, because "moving" a moderator is
|
||||
#: normally a revoke plus a grant. This is not a move: the person was granted Counsel, and this is
|
||||
#: the only place that can write down which module that was.
|
||||
#: The roster table is resolved through `to_regclass` and named unqualified, on purpose: standalone
|
||||
#: it is this app's own table, and on the platform the local copy is gone and the search_path
|
||||
#: resolves the shared one. It is owned either way by the role running this migration, which is the
|
||||
#: only role that may rewrite a `module_slug` at all — the eight app roles never hold that, because
|
||||
#: no screen moves a permission from one module to another. This is not such a move: the person was
|
||||
#: granted Counsel, and this is the only place that can write down which module that was.
|
||||
#:
|
||||
#: WHICH table it finds says only when this database was first migrated: `module_permission` from
|
||||
#: dredd-core v0.11.0 (or after `0006` has renamed it), `module_moderator` from v0.10.0, and
|
||||
#: nothing at all before that — the live box. `0006` runs after this revision, so both names are
|
||||
#: still reachable here and the block asks the catalogue rather than assuming. The older shape has
|
||||
#: no `role` column, and on it every row means moderator.
|
||||
#:
|
||||
#: The counts leave the block through a TEMPORARY TABLE rather than a `RAISE NOTICE` — see the
|
||||
#: module docstring for why a notice here would reach the PostgreSQL log and nobody else.
|
||||
@@ -87,6 +93,10 @@ DECLARE
|
||||
wanted CONSTANT text := 'counsel';
|
||||
moved integer := 0;
|
||||
merged integer := 0;
|
||||
-- regclass, not oid: `oid::text` is the number, and the statements below need the NAME, already
|
||||
-- schema-qualified and quoted exactly as far as it has to be.
|
||||
roster regclass;
|
||||
rel text;
|
||||
BEGIN
|
||||
CREATE TEMPORARY TABLE counsel_slug_renamed (
|
||||
renamed boolean NOT NULL,
|
||||
@@ -107,18 +117,34 @@ BEGIN
|
||||
|
||||
UPDATE module SET slug = wanted, updated_at = now() WHERE slug = stale;
|
||||
|
||||
-- Moderator grants can only exist after the identity cutover, so on most boxes this is zero.
|
||||
-- Permission rows can only exist after the identity cutover, so on most boxes this is zero.
|
||||
-- Where they do exist they are exactly the grants that silently did nothing, and they are the
|
||||
-- reason this revision is worth writing at all. Both counts stay at their declared zero on a
|
||||
-- database with no `module_moderator` in reach at all — a standalone Atrium migrated before core
|
||||
-- grew that table — and that is the same report for the same reason: no such grant exists.
|
||||
IF to_regclass('module_moderator') IS NOT NULL THEN
|
||||
DELETE FROM module_moderator stale_row
|
||||
WHERE stale_row.module_slug = stale
|
||||
AND EXISTS (SELECT 1 FROM module_moderator kept
|
||||
WHERE kept.user_id = stale_row.user_id AND kept.module_slug = wanted);
|
||||
-- database with no roster table in reach at all — a standalone Atrium migrated before core grew
|
||||
-- one — and that is the same report for the same reason: no such grant exists.
|
||||
roster := COALESCE(to_regclass('module_permission'), to_regclass('module_moderator'));
|
||||
IF roster IS NOT NULL THEN
|
||||
rel := roster::text;
|
||||
-- A person granted BOTH slugs keeps one row, and it keeps the HIGHER of the two roles: the
|
||||
-- stale row was a real decision by an administrator, and dropping it silently in favour of a
|
||||
-- weaker one would quietly demote somebody. Only the newer shape has a role to compare; on the
|
||||
-- older one every row already means the same thing.
|
||||
IF EXISTS (SELECT 1 FROM pg_attribute
|
||||
WHERE attrelid = roster AND attname = 'role' AND NOT attisdropped) THEN
|
||||
EXECUTE 'UPDATE ' || rel || ' kept SET role = ''moderator'' FROM ' || rel || ' stale_row'
|
||||
|| ' WHERE kept.module_slug = ' || quote_literal(wanted)
|
||||
|| ' AND stale_row.module_slug = ' || quote_literal(stale)
|
||||
|| ' AND kept.user_id = stale_row.user_id'
|
||||
|| ' AND stale_row.role = ''moderator'' AND kept.role <> ''moderator''';
|
||||
END IF;
|
||||
EXECUTE 'DELETE FROM ' || rel || ' stale_row'
|
||||
|| ' WHERE stale_row.module_slug = ' || quote_literal(stale)
|
||||
|| ' AND EXISTS (SELECT 1 FROM ' || rel || ' kept'
|
||||
|| ' WHERE kept.user_id = stale_row.user_id'
|
||||
|| ' AND kept.module_slug = ' || quote_literal(wanted) || ')';
|
||||
GET DIAGNOSTICS merged = ROW_COUNT;
|
||||
UPDATE module_moderator SET module_slug = wanted WHERE module_slug = stale;
|
||||
EXECUTE 'UPDATE ' || rel || ' SET module_slug = ' || quote_literal(wanted)
|
||||
|| ' WHERE module_slug = ' || quote_literal(stale);
|
||||
GET DIAGNOSTICS moved = ROW_COUNT;
|
||||
END IF;
|
||||
|
||||
@@ -143,10 +169,10 @@ SELECT renamed, grants, dropped FROM counsel_slug_renamed
|
||||
def _report() -> None:
|
||||
"""Say what the rename did, including the thing the audit log deliberately will not.
|
||||
|
||||
The counts are nought on almost every box — a moderator grant can only exist after the identity
|
||||
cutover — and that is fine: what an operator needs from this line is that the rename happened,
|
||||
and that no `module.update` row was written for it on purpose. A second run says so too, which
|
||||
is the honest answer for an idempotent revision and not a failure.
|
||||
The counts are nought on almost every box — a module-permission row can only exist after the
|
||||
identity cutover — and that is fine: what an operator needs from this line is that the rename
|
||||
happened, and that no `module.update` row was written for it on purpose. A second run says so
|
||||
too, which is the honest answer for an idempotent revision and not a failure.
|
||||
|
||||
Online only. Under `alembic upgrade --sql` nothing connects, so there is no temporary table to
|
||||
read and nothing to say — the rendered SQL is the deliverable there, not a live correction.
|
||||
@@ -158,8 +184,8 @@ def _report() -> None:
|
||||
log.info("counsel slug: the catalogue already says counsel, nothing to rename")
|
||||
return
|
||||
log.info(
|
||||
"counsel slug: catalogue row renamed counsel-scorecard -> counsel, %s moderator grant(s) "
|
||||
"moved, %s duplicate(s) dropped. The audit log keeps the old name, on purpose.",
|
||||
"counsel slug: catalogue row renamed counsel-scorecard -> counsel, %s module permission "
|
||||
"row(s) moved, %s duplicate(s) dropped. The audit log keeps the old name, on purpose.",
|
||||
row["grants"], row["dropped"])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
"""`module_moderator` becomes `module_permission` in this app's OWN schema.
|
||||
|
||||
Why this revision has to exist at all
|
||||
-------------------------------------
|
||||
dredd-core v0.11.0 replaces `ModuleModerator` with `ModulePermission`: the same table plus a `role`
|
||||
column, so that "may use this module" and "administers this module" are one row with three answers
|
||||
instead of a roster of administrators and an open door for everybody else.
|
||||
|
||||
Renaming the model reaches a *fresh* database, because `0001` builds every table from
|
||||
`Base.metadata`. It reaches no database that already exists, because `0001` is stamped and never
|
||||
runs again. That is exactly the `node_kind` failure the family's CLAUDE.md warns about — *never
|
||||
change what `0001` creates without a follow-up revision for databases migrated before* — and its
|
||||
symptoms are all late and confusing: the backup sweep dies on `relation "module_permission" does not
|
||||
exist`, a restore dies the same way, and every read of the roster fails on a screen that used to
|
||||
work.
|
||||
|
||||
Editing the cutover (`0004`) was not enough on its own, and the difference is worth stating: `0004`
|
||||
is a **no-op** on a standalone box and is stamped there all the same. A standalone Atrium therefore
|
||||
records the cutover as applied while its own schema still holds a table by the old name — or, on a
|
||||
box first migrated before dredd-core v0.10.0, no such table at all.
|
||||
|
||||
What it does, decided by catalogue check rather than by settings
|
||||
----------------------------------------------------------------
|
||||
Three live shapes, and the right answer for each is read off `pg_class`:
|
||||
|
||||
1. this schema already has `module_permission` — nothing to do (a fresh install, or a second run);
|
||||
2. this schema has `module_moderator` — RENAME it, rename its constraints and indexes onto the
|
||||
`module_permission` names the metadata will expect, add `role`, add the CHECK, and set every
|
||||
existing row to `moderator`, because that is the only thing a row in that table ever meant;
|
||||
3. neither — either the table lives in the SHARED identity schema (the platform, after `0004`
|
||||
moved it there), in which case this app must not build a second one, or this database predates
|
||||
the table entirely and needs it created here.
|
||||
|
||||
Case 3 is the one with a trap in it. An unqualified `CREATE TABLE module_permission` would land in
|
||||
this app's own schema — first on the `search_path`, and it has to be — and on the platform that is
|
||||
a **shadow copy**: `assert_identity_schema` exists precisely because an unqualified `app_user` then
|
||||
resolves to the local one and everything keeps working, silently back to two rows per human. So the
|
||||
"create it" branch is guarded twice over: `IDENTITY_SCHEMA` being set rules it out outright, and
|
||||
even standalone it runs only when the search_path can find the table nowhere at all. Two guards
|
||||
because they fail differently — a platform box whose migrator's `search_path` does not carry the
|
||||
identity schema would see no table, and rebuild the shadow copy on every single deploy.
|
||||
|
||||
Every name here is resolved against `current_schema()` with `quote_ident`, never unqualified, for
|
||||
the same reason `0004`'s drops are: the moment a local table is gone, an unqualified name resolves
|
||||
to the shared schema's.
|
||||
|
||||
**No percent sign and no colon-name sequence appears in any string below, comments included.**
|
||||
`op.execute` wraps a string in `text()`, which scans the whole statement: a comment quoting that
|
||||
very rule has already killed a migration on its first live run elsewhere in this family.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
from sqlalchemy import CheckConstraint, text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.models import Base
|
||||
|
||||
revision = "0006"
|
||||
down_revision = "0005"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
#: Alembic's own logger, the one `0004` and `0005` report through, so this lands on stdout between
|
||||
#: the `Running upgrade 0005 -> 0006` lines. Not a logger of this app's: nothing configures one here.
|
||||
log = logging.getLogger("alembic.runtime.migration")
|
||||
|
||||
#: `0003`'s two lists, repeated rather than imported: `alembic/versions` is not a package and a
|
||||
#: module name beginning with a digit cannot be imported at all. Keep them in step with
|
||||
#: `0003_runtime_grants.py` — and with `python -m dredd_core.managed check --append-only`.
|
||||
APPEND_ONLY = ("audit_log",)
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
|
||||
# The rename, and the column that carries the whole point of the change.
|
||||
#
|
||||
# `ALTER ... RENAME` moves the table but leaves every constraint and index carrying the old name.
|
||||
# Those names are cosmetic to PostgreSQL and load-bearing to everything else: a later revision that
|
||||
# drops a constraint by the name the metadata gives it, and a developer reading `\d`, both need the
|
||||
# two to agree. Renaming them is `IF EXISTS`-shaped via the catalogue, because a database built by
|
||||
# an older `0001` may not have every one of them under the name this expects.
|
||||
#
|
||||
# The counts leave through a TEMPORARY TABLE rather than a notice, for the reason `0004` and `0005`
|
||||
# already document: pg8000 collects server notices on the connection and nothing ever prints them,
|
||||
# so a `RAISE NOTICE` here would reach the PostgreSQL log and no human running the migration.
|
||||
# `ON COMMIT DROP` ties it to the one transaction the whole upgrade runs in, and every branch
|
||||
# writes exactly one row — without that, "nothing to do" and "this block never ran" would be the
|
||||
# same empty result.
|
||||
_MIGRATE = """
|
||||
DO $dredd_module_permission$
|
||||
DECLARE
|
||||
own text := current_schema();
|
||||
old_rel oid := to_regclass(quote_ident(current_schema()) || '.module_moderator');
|
||||
new_rel oid := to_regclass(quote_ident(current_schema()) || '.module_permission');
|
||||
anywhere oid := to_regclass('module_permission');
|
||||
-- IDENTITY_SCHEMA is set: the roster belongs to the shared schema and this app only reads it.
|
||||
-- Belt as well as braces with the catalogue check below, because the two can fail differently:
|
||||
-- a search_path that does not carry the identity schema would make `anywhere` NULL on a platform
|
||||
-- box and this block would build the shadow copy on every deploy.
|
||||
platform CONSTANT boolean := {shares_identity};
|
||||
promoted bigint := 0;
|
||||
action text;
|
||||
pair text[];
|
||||
renames text[][] := ARRAY[
|
||||
ARRAY['pk_module_moderator', 'pk_module_permission'],
|
||||
ARRAY['module_moderator_pkey', 'pk_module_permission'],
|
||||
ARRAY['uq_module_moderator_user_module', 'uq_module_permission_user_module'],
|
||||
ARRAY['ix_module_moderator_module_slug', 'ix_module_permission_module_slug'],
|
||||
ARRAY['fk_module_moderator_user_id_app_user', 'fk_module_permission_user_id_app_user'],
|
||||
ARRAY['fk_module_moderator_created_by_app_user', 'fk_module_permission_created_by_app_user'],
|
||||
ARRAY['ck_module_moderator_slug', 'ck_module_permission_slug']
|
||||
];
|
||||
BEGIN
|
||||
CREATE TEMPORARY TABLE dredd_module_permission_done (
|
||||
own_schema text NOT NULL,
|
||||
action text NOT NULL,
|
||||
promoted bigint NOT NULL
|
||||
) ON COMMIT DROP;
|
||||
|
||||
IF new_rel IS NOT NULL THEN
|
||||
INSERT INTO dredd_module_permission_done VALUES (own, 'already', 0);
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
IF old_rel IS NULL THEN
|
||||
IF platform OR anywhere IS NOT NULL THEN
|
||||
-- The shared identity schema has it and this app only reads it. Building a local one here
|
||||
-- would be the shadow copy with no other symptom: the search_path reaches it first and
|
||||
-- everything keeps working, silently back to two rosters.
|
||||
INSERT INTO dredd_module_permission_done VALUES (own, 'shared', 0);
|
||||
ELSE
|
||||
INSERT INTO dredd_module_permission_done VALUES (own, 'create', 0);
|
||||
END IF;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_moderator RENAME TO module_permission';
|
||||
|
||||
FOREACH pair SLICE 1 IN ARRAY renames LOOP
|
||||
IF EXISTS (SELECT 1 FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
|
||||
WHERE n.nspname = own AND c.conname = pair[1]) THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission RENAME CONSTRAINT '
|
||||
|| quote_ident(pair[1]) || ' TO ' || quote_ident(pair[2]);
|
||||
ELSIF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = own AND c.relname = pair[1] AND c.relkind = 'i') THEN
|
||||
EXECUTE 'ALTER INDEX ' || quote_ident(own) || '.' || quote_ident(pair[1])
|
||||
|| ' RENAME TO ' || quote_ident(pair[2]);
|
||||
END IF;
|
||||
END LOOP;
|
||||
|
||||
-- The server default is the LESSER role, here as everywhere: an INSERT that forgets to name one
|
||||
-- admits a user and never a moderator.
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|
||||
|| 'ADD COLUMN role varchar(20) NOT NULL DEFAULT ''user''';
|
||||
|
||||
-- ... but every row that was ALREADY in this table was a moderator, because that is the only
|
||||
-- thing the old table could say. Setting them to the column default would silently demote every
|
||||
-- moderator on the instance, which is the one mistake this revision must not make.
|
||||
EXECUTE 'UPDATE ' || quote_ident(own) || '.module_permission SET role = ''moderator''';
|
||||
GET DIAGNOSTICS promoted = ROW_COUNT;
|
||||
|
||||
-- Text plus a CHECK, never a PostgreSQL enum: a new role is then an ALTER TABLE in the one
|
||||
-- schema that owns this table, not an ALTER TYPE four schemas' migrations have to agree on.
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
|
||||
WHERE n.nspname = own AND c.conname = 'ck_module_permission_role') THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|
||||
|| 'ADD CONSTRAINT ck_module_permission_role CHECK (role IN ({role_values}))';
|
||||
END IF;
|
||||
|
||||
-- The old table had no slug CHECK at all, so a rename alone would leave this database a
|
||||
-- different shape from one a fresh `0001` builds — which is the drift that makes the next
|
||||
-- revision behave differently on the live box than it did in a test. Existing rows all pass:
|
||||
-- every writer validated the slug, and `0005` runs before this one, so counsel-scorecard is
|
||||
-- already counsel by now.
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
|
||||
WHERE n.nspname = own AND c.conname = 'ck_module_permission_slug') THEN
|
||||
EXECUTE 'ALTER TABLE ' || quote_ident(own) || '.module_permission '
|
||||
|| 'ADD CONSTRAINT ck_module_permission_slug CHECK ({slug_check})';
|
||||
END IF;
|
||||
|
||||
INSERT INTO dredd_module_permission_done VALUES (own, 'renamed', promoted);
|
||||
END
|
||||
$dredd_module_permission$
|
||||
"""
|
||||
|
||||
#: Read back by `_report`. Through `text()` by hand, so the family's rule about a rendered template
|
||||
#: applies to it with nothing else to catch a slip — which is why this note is out here and not in
|
||||
#: the string. One row, always: the block creates the table before it can take any branch, so
|
||||
#: `.one()` is the difference between noticing that `_MIGRATE` never ran and reporting a rename
|
||||
#: that never happened as a quiet success.
|
||||
_SUMMARY = """
|
||||
SELECT own_schema, action, promoted FROM dredd_module_permission_done
|
||||
"""
|
||||
|
||||
_WORDS = {
|
||||
"already": "module_permission is already in %s, nothing to do",
|
||||
"shared": "module_permission lives in the shared identity schema; %s keeps no copy, as it must "
|
||||
"not",
|
||||
"create": "created module_permission in %s (this database predates the table)",
|
||||
}
|
||||
|
||||
|
||||
def _report() -> None:
|
||||
"""Say which of the four things happened, and how many people were kept as moderators.
|
||||
|
||||
Online only. Under `alembic upgrade --sql` nothing connects, so there is no temporary table to
|
||||
read and nothing to say — the rendered SQL is the deliverable there.
|
||||
"""
|
||||
if op.get_context().as_sql:
|
||||
return
|
||||
row = op.get_bind().execute(text(_SUMMARY)).mappings().one()
|
||||
if row["action"] == "renamed":
|
||||
log.info(
|
||||
"module permissions: renamed %s.module_moderator to module_permission and kept %s "
|
||||
"existing row(s) as moderator", row["own_schema"], row["promoted"])
|
||||
return
|
||||
log.info("module permissions: " + _WORDS[row["action"]], row["own_schema"])
|
||||
|
||||
|
||||
def _quoted(value: str) -> str:
|
||||
"""A fragment that will sit inside a PL/pgSQL string literal, so its own quotes are doubled.
|
||||
|
||||
Both CHECK constraints below are assembled in Python and then EXECUTEd, which means they are
|
||||
written INTO a quoted string. Leaving `'user'` as it stands would close that string early and
|
||||
turn the rest of the statement into a syntax error at the worst possible moment — on the one
|
||||
run that converts a live database.
|
||||
"""
|
||||
return value.replace("'", "''")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Both vocabularies come from core's own model, so Python, the DDL a fresh `0001` writes and
|
||||
# the CHECK this revision adds cannot drift apart. The role tuple and the slug pattern are the
|
||||
# very objects `ModulePermission.__table_args__` is built from.
|
||||
from dredd_core.identity import MODULE_ROLES
|
||||
|
||||
slug_check = next(
|
||||
str(c.sqltext) for c in Base.metadata.tables["module_permission"].constraints
|
||||
if isinstance(c, CheckConstraint) and "module_slug" in str(c.sqltext))
|
||||
op.execute(_MIGRATE.format(
|
||||
role_values=_quoted(", ".join(f"'{role}'" for role in MODULE_ROLES)),
|
||||
slug_check=_quoted(slug_check),
|
||||
shares_identity="true" if get_settings().shares_identity else "false",
|
||||
))
|
||||
_report()
|
||||
|
||||
# The "this database predates the table" branch, done in Python because building a table from
|
||||
# the metadata is what `0001` does and duplicating its DDL by hand is how the two drift. It is
|
||||
# reached only when the search_path finds `module_permission` nowhere at all, so it can neither
|
||||
# overwrite a local table nor shadow the shared one.
|
||||
if _wants_create():
|
||||
Base.metadata.tables["module_permission"].create(op.get_bind(), checkfirst=False)
|
||||
|
||||
# `0003`'s own docstring: "every later revision that adds a table should call it once more",
|
||||
# because `GRANT ... ON ALL TABLES` only covers the tables that exist when it runs. A table this
|
||||
# revision creates would otherwise be one the runtime role holds NOTHING on — invisible until
|
||||
# the day the deployment joins a platform and every read of the roster becomes "permission
|
||||
# denied for table module_permission". Run unconditionally: the block is authoritative rather
|
||||
# than additive, so re-granting what is already granted is the intended way to use it.
|
||||
op.execute(runtime_grants_sql(get_settings().db_app_role,
|
||||
append_only=APPEND_ONLY, no_delete=NO_DELETE))
|
||||
|
||||
|
||||
def _wants_create() -> bool:
|
||||
"""Did the block above decide this database needs the table built from the metadata?
|
||||
|
||||
Offline (`alembic upgrade --sql`) there is no connection to ask and no temporary table to read,
|
||||
so this answers no and the rendered script carries only the branches the DO block above can
|
||||
take by itself. Emitting the CREATE unconditionally there would hand an operator a script that
|
||||
fails on every database that already has the table — and `CREATE TABLE IF NOT EXISTS` would be
|
||||
worse: unqualified, it creates in this app's own schema, which on the platform is exactly the
|
||||
shadow copy `assert_identity_schema` exists to catch.
|
||||
"""
|
||||
if op.get_context().as_sql:
|
||||
return False
|
||||
return op.get_bind().execute(text(_SUMMARY)).mappings().one()["action"] == "create"
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Deliberately a no-op.
|
||||
|
||||
There is no information to restore. Going back would mean dropping `role` — and with it the
|
||||
distinction between a person who may use a module and a person who administers it, which is the
|
||||
only thing this revision adds. Renaming the table back would then leave every row looking like
|
||||
a moderator, including the ones that were never anything of the sort. Nothing before `0006`
|
||||
reads either name, so leaving the new shape in place downgrades cleanly.
|
||||
"""
|
||||
@@ -71,7 +71,7 @@ class Settings(BaseSettings):
|
||||
|
||||
# ── one platform, one account ────────────────────────────────────────────────
|
||||
# The shared identity schema. Empty (the default) is the STANDALONE deployment: Atrium owns
|
||||
# `app_user` / `session` / `module_moderator` in its own schema and nothing below changes. Set it
|
||||
# `app_user` / `session` / `module_permission` in its own schema and nothing below changes. Set it
|
||||
# (IDENTITY_SCHEMA=dredd) and those three tables live in a neutral schema every module reads, so
|
||||
# a person has ONE account across the whole platform and signs in once, here.
|
||||
#
|
||||
@@ -79,7 +79,7 @@ class Settings(BaseSettings):
|
||||
# a name is what each of them needs: revision 0004 creates the tables there and grants each
|
||||
# module's roles their tier; the lifespan asserts the tables really resolve there (a shadow copy
|
||||
# in Atrium's own schema has no other symptom); and `services/moderation.py` switches the
|
||||
# MODERATOR tier on, since a per-module moderator is meaningless without a platform.
|
||||
# per-module permissions on, since they are meaningless without a platform.
|
||||
#
|
||||
# The schema itself, its owner and the eight roles' search_path are PROVISIONING, not migration —
|
||||
# a migrator holds no CREATE on the database and cannot ALTER ROLE another role. See
|
||||
@@ -94,8 +94,9 @@ class Settings(BaseSettings):
|
||||
identity_reader_roles: str = ""
|
||||
identity_migrator_roles: str = ""
|
||||
# This app's slug on the platform. It is also the HUB's slug, which `services/moderation.py`
|
||||
# passes to core as `hub_slug`: `module_moderator(user, 'atrium')` is refused, because the hub has
|
||||
# administrators and its administration is not delegable one module at a time.
|
||||
# passes to core as `hub_slug`: `module_permission(user, 'atrium')` is refused — every account may
|
||||
# open the launcher, so a `user` row would say nothing, and the hub has administrators whose job
|
||||
# is not delegable one module at a time.
|
||||
module_slug: str = "atrium"
|
||||
|
||||
# Auth / sessions (cookie-based, DB-backed — one `session` row is the whole of single sign-on)
|
||||
|
||||
+1
-1
@@ -135,7 +135,7 @@ def require_administrator(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
"""The platform-wide tier, and the only one that guards a route in the HUB.
|
||||
|
||||
Two words, used exactly: an **administrator** is platform-wide (`app_user.is_admin`), a
|
||||
**moderator** administers exactly one module (`module_moderator`). Atrium has administrators and
|
||||
**moderator** administers exactly one module (`module_permission`). Atrium has administrators and
|
||||
no moderators of its own — granting and revoking both tiers happens here, so a hub route guarded
|
||||
by the narrower tier would let a Galena moderator promote themselves platform-wide. That is why
|
||||
there is no `require_moderator` in this app: `services/moderation.py` only ever *reads* and
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
The migration builds tables from `Base.metadata`, so a model that is never imported silently
|
||||
never gets a table — and the failure surfaces much later, as a missing relation at runtime.
|
||||
|
||||
The shared tables are not defined here: identity (`app_user`, `session`, `module_moderator`,
|
||||
The shared tables are not defined here: identity (`app_user`, `session`, `module_permission`,
|
||||
`app_setting`, `audit_log`) and the org tree (`node`, `permission_grant`, `favorite`) live in
|
||||
**dredd-core**, and importing `dredd_core` is what registers them on `Base.metadata`. This module
|
||||
re-exports them under the names the rest of the app already uses, so every call site stays
|
||||
`from ..models import AppUser, Node` regardless of where the class is declared.
|
||||
|
||||
Three of those — `app_user`, `session` and `module_moderator`, i.e.
|
||||
Three of those — `app_user`, `session` and `module_permission`, i.e.
|
||||
`dredd_core.identity.SHARED_IDENTITY_TABLES` — move OUT of this app's schema when the family runs
|
||||
as one platform: revision 0004 builds them in the shared identity schema and drops the local copies.
|
||||
They stay on `Base.metadata` either way, because the models are the same models and every query in
|
||||
@@ -24,7 +24,7 @@ from dredd_core import (
|
||||
AuditLog,
|
||||
Base,
|
||||
Favorite,
|
||||
ModuleModerator,
|
||||
ModulePermission,
|
||||
Node,
|
||||
PermissionGrant,
|
||||
SafeInet,
|
||||
@@ -38,7 +38,7 @@ from .marketplace import AccessRequest, Module, ModuleAssignment
|
||||
|
||||
__all__ = [
|
||||
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
|
||||
"AppUser", "Session", "ModuleModerator", "AppSetting", "AuditLog",
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"Node", "PermissionGrant", "Favorite",
|
||||
"Module", "ModuleAssignment", "AccessRequest",
|
||||
]
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
"""Administration of the catalog: modules, who they are offered to, who moderates them, health, and
|
||||
"""Administration of the catalog: modules, who may open them, who moderates them, health, and
|
||||
access requests.
|
||||
|
||||
Every route here is `require_administrator`, the moderator ones included — and that is not an
|
||||
Every route here is `require_administrator`, the roster ones included — and that is not an
|
||||
oversight to tidy up later. A moderator who could appoint moderators could appoint themselves out
|
||||
of the tier's one constraint, so granting stays with the platform-wide tier. Delegated
|
||||
administration of the catalogue (a unit manager assigning modules to their own unit) is deliberately
|
||||
not offered either: availability is an instance-wide decision.
|
||||
|
||||
Two things that look alike on this page and are not: an **assignment** decides whether a module is
|
||||
*offered* to someone (it lands on their launcher), a **moderator** grant decides whether they may
|
||||
*administer* it. Neither implies the other, and the pane says so — a moderator who was never
|
||||
assigned the module can still administer it, because authorization is not an offer.
|
||||
Two things on this page that look alike and are not the same:
|
||||
|
||||
* an **assignment** says *why* somebody has the module — this person, or everybody in that unit. It
|
||||
is the hub's shortcut, and its record of the decision.
|
||||
* the **roster** (`module_permission`) is what actually lets them in: one row per person, and it is
|
||||
what every module reads at its own door. No row means no entry.
|
||||
|
||||
The first is materialised into the second on every change to either
|
||||
(`services/marketplace.py`), so the two cannot drift. The roster also carries the `role`, which an
|
||||
assignment has no opinion about: a bulk shortcut admits people as `user` and never promotes anyone.
|
||||
|
||||
The roster's three routes are still spelled `/moderators`. See the comment above them: the address
|
||||
is quoted in three other repositories and asserted by another app's test suite, so it is a
|
||||
cross-repo contract rather than a name this file may tidy up on its own.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,9 +32,8 @@ from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import AssignmentIn, ModeratorIn, ModuleCreateIn, ModuleUpdateIn, NoteIn
|
||||
from ..schemas import AssignmentIn, ModuleCreateIn, ModuleUpdateIn, NoteIn, PermissionIn
|
||||
from ..services import marketplace as service
|
||||
from ..services import moderation
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin: marketplace"])
|
||||
|
||||
@@ -87,41 +96,52 @@ def remove_assignment(slug: str, assignment_id: uuid.UUID, request: Request,
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# The path stays `/moderators` although the table is now `module_permission`, and that is a
|
||||
# deliberate exception to this family's "one word per idea" rule. It is a CROSS-REPO contract: the
|
||||
# three module repos quote this address in their docs, and Counsel Scorecard's suite asserts it
|
||||
# character for character. Renaming it would break another app's tests and leave three sets of
|
||||
# documentation wrong — a bigger blast radius than the tidiness is worth. Rename it in all four
|
||||
# repos in one pass, or not at all.
|
||||
@router.get("/modules/{slug}/moderators")
|
||||
def list_moderators(slug: str, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
"""Who administers this module. Answerable only here, which is the point: the hub grants the
|
||||
tier, so the hub is where the roster lives. A module never shows its own."""
|
||||
service.get_module(db, slug) # 404 before reporting a roster for a slug that names nothing
|
||||
return moderation.list_moderators(db, slug)
|
||||
def list_permissions(slug: str, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
"""Who may open this module, and at what role. Answerable only here, which is the point: the
|
||||
hub writes the table, so the hub is where the roster lives. A module never shows its own."""
|
||||
return service.list_access(db, slug)
|
||||
|
||||
|
||||
@router.post("/modules/{slug}/moderators", status_code=201)
|
||||
def add_moderator(slug: str, body: ModeratorIn, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Make someone a MODERATOR of this module: they administer it, and nothing else.
|
||||
def grant_permission(slug: str, body: PermissionIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Give someone access to this module — as a USER, or as a MODERATOR who also administers it.
|
||||
|
||||
Core refuses the hub's own slug (Atrium has administrators, not moderators), an unknown account
|
||||
and a deactivated one. A repeat is idempotent, so a double-click is not an error.
|
||||
The same call promotes and demotes, because core's `grant` is an UPSERT: the row stays, so who
|
||||
admitted this person and when survives the change. Core refuses the hub's own slug (every
|
||||
account may open the launcher, and Atrium has administrators rather than moderators), an
|
||||
unknown account, a deactivated one and an unknown role. A repeat is idempotent, so a
|
||||
double-click is not an error.
|
||||
"""
|
||||
module = service.get_module(db, slug)
|
||||
out = moderation.grant(db, admin, module_slug=module.slug, user_id=body.user_id,
|
||||
ip=client_ip(request))
|
||||
out = service.grant_access(db, admin, slug, user_id=body.user_id, role=body.role,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.delete("/modules/{slug}/moderators/{user_id}")
|
||||
def remove_moderator(slug: str, user_id: uuid.UUID, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Revoke the tier. A hard DELETE, never a flag — `services/moderation.py` says why a soft one
|
||||
would fail OPEN in every module that forgot to filter it. It bites on that module's very next
|
||||
request: the only cached copy anywhere is a memo on the SQLAlchemy session, which dies with the
|
||||
request that opened it."""
|
||||
module = service.get_module(db, slug)
|
||||
out = moderation.revoke(db, admin, module_slug=module.slug, user_id=user_id,
|
||||
ip=client_ip(request))
|
||||
def revoke_permission(slug: str, user_id: uuid.UUID, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Take the access away. A hard DELETE, never a flag — `services/moderation.py` says why a soft
|
||||
one would fail OPEN in every module that forgot to filter it. It bites on that module's very
|
||||
next request: the only cached copy anywhere is a memo on the SQLAlchemy session, which dies
|
||||
with the request that opened it.
|
||||
|
||||
`still_a_member` in the reply is the one thing a screen cannot work out for itself: the person
|
||||
may also be reached by a unit assignment, in which case they keep ordinary access and only stop
|
||||
being a moderator. Saying so is better than a revocation the next re-render appears to undo.
|
||||
"""
|
||||
out = service.revoke_access(db, admin, slug, user_id=user_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@@ -63,11 +63,11 @@ def _clear_legacy_cookies(request: Request, response: Response) -> None:
|
||||
def _user_out(db: Session, user: AppUser) -> dict:
|
||||
return {"id": str(user.id), "email": user.email, "full_name": user.full_name,
|
||||
"is_admin": user.is_admin, "is_active": user.is_active,
|
||||
# Every module this person moderates, so the console can show someone their own
|
||||
# standing without a second request. Empty on a standalone Atrium, and empty for an
|
||||
# administrator who holds no per-module grant — an administrator is a moderator of
|
||||
# everything by definition, and inventing rows to say so would make the roster lie.
|
||||
"moderates": sorted(moderation.moderated_slugs(db, user.id))}
|
||||
# Every module this person may open, and at what role, so the console can show someone
|
||||
# their own standing without a second request. Empty on a standalone Atrium, and empty
|
||||
# for an administrator who holds no per-module row — an administrator reaches every
|
||||
# module by definition, and inventing rows to say so would make the roster lie.
|
||||
"modules": moderation.module_roles(db, user.id)}
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginOut)
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
Every handler asks `services/authz.py` first. In Atrium the tree is the organization — workspace,
|
||||
groups, folders — and membership in a unit is a permission grant on it.
|
||||
|
||||
**Every write here can change who may open a module**, because a module assigned to a unit is
|
||||
materialised into a `module_permission` row per member (see `services/marketplace.py`). So the
|
||||
three handlers that add, change or destroy a grant end in `marketplace.sync_members`: that is what
|
||||
makes "assign Galena to Legal" still mean what it said when somebody joins Legal a week later,
|
||||
instead of decaying into a one-time bulk grant nobody remembers making.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,7 +21,7 @@ from ..deps import client_ip, get_current_user
|
||||
from ..enums import NodeRole
|
||||
from ..models import AppUser, Node
|
||||
from ..schemas import GrantIn, NodeCreateIn, NodeOut
|
||||
from ..services import audit, authz, nodes as node_service
|
||||
from ..services import audit, authz, marketplace, nodes as node_service
|
||||
|
||||
router = APIRouter(tags=["nodes"])
|
||||
|
||||
@@ -53,9 +59,15 @@ def create(body: NodeCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
def delete(node_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
node = node_service.get(db, node_id)
|
||||
ip = client_ip(request)
|
||||
audit.record(db, action="node.delete", entity_type="node", entity_id=node.id,
|
||||
actor_id=user.id, detail=node.path, ip=client_ip(request))
|
||||
actor_id=user.id, detail=node.path, ip=ip)
|
||||
# Read the membership BEFORE the delete: `permission_grant.node_id` is ON DELETE CASCADE, so
|
||||
# after this line there is nothing left to say whose access to re-check.
|
||||
members = node_service.direct_member_ids(db, node)
|
||||
node_service.delete(db, user, node)
|
||||
db.flush()
|
||||
marketplace.sync_members(db, user, members, ip=ip)
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -75,9 +87,14 @@ def upsert_grant(node_id: uuid.UUID, body: GrantIn, request: Request, db: Sessio
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
node = node_service.get(db, node_id)
|
||||
authz.assert_role(db, user, node, NodeRole.manager)
|
||||
ip = client_ip(request)
|
||||
grant, target = authz.upsert_user_grant(db, node, body.user_id, NodeRole(body.role), user.id)
|
||||
audit.record(db, action="grant.upsert", entity_type="node", entity_id=node.id,
|
||||
actor_id=user.id, detail=f"{target.email}={body.role}", ip=client_ip(request))
|
||||
actor_id=user.id, detail=f"{target.email}={body.role}", ip=ip)
|
||||
db.flush()
|
||||
# Joining a unit is how somebody picks up the modules assigned to it — now, not the next time
|
||||
# an administrator happens to re-save the assignment.
|
||||
marketplace.sync_members(db, user, [target.id], ip=ip)
|
||||
db.commit()
|
||||
return {"status": "ok", "role": grant.role.value}
|
||||
|
||||
@@ -89,7 +106,11 @@ def remove_grant(node_id: uuid.UUID, user_id: uuid.UUID, request: Request, db: S
|
||||
authz.assert_role(db, user, node, NodeRole.manager)
|
||||
removed = authz.remove_user_grant(db, node.id, user_id)
|
||||
if removed:
|
||||
ip = client_ip(request)
|
||||
audit.record(db, action="grant.remove", entity_type="node", entity_id=node.id,
|
||||
actor_id=user.id, detail=user_id, ip=client_ip(request))
|
||||
actor_id=user.id, detail=user_id, ip=ip)
|
||||
db.flush()
|
||||
# And leaving one takes those modules away again, unless something else still reaches them.
|
||||
marketplace.sync_members(db, user, [user_id], ip=ip)
|
||||
db.commit()
|
||||
return {"status": "ok", "removed": removed}
|
||||
|
||||
@@ -5,11 +5,11 @@ deactivated and reactivated here, because the hub is the only writer of identity
|
||||
role holds a column-restricted `SELECT` on `app_user` and no `INSERT` or `UPDATE` at all. The
|
||||
enforcement is that grant, not the absence of a screen in the other three consoles.
|
||||
|
||||
Both tiers show up here and neither is written here alone. **Administrator** — platform-wide,
|
||||
Every tier shows up here and none of them is written here alone. **Administrator** — platform-wide,
|
||||
`app_user.is_admin` — is toggled below, through `services/accounts.py`, which carries the
|
||||
last-administrator guard. **Moderator** — exactly one module — is granted on that module's own page
|
||||
(`routers/admin_modules.py`); this file only *reports* which modules a person moderates, so the
|
||||
Users list can show the whole of someone's standing in one row.
|
||||
last-administrator guard. Access to one module, as **user** or **moderator**, is granted on that
|
||||
module's own page (`routers/admin_modules.py`); this file only *reports* it, so the Users list can
|
||||
show the whole of someone's standing in one row.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -40,13 +40,13 @@ from ..services import auth as auth_service
|
||||
router = APIRouter(tags=["users"])
|
||||
|
||||
|
||||
def _user_out(u: AppUser, moderates: list[str] | None = None) -> dict:
|
||||
def _user_out(u: AppUser, modules: dict[str, str] | None = None) -> dict:
|
||||
return {"id": str(u.id), "email": u.email, "full_name": u.full_name,
|
||||
"is_admin": u.is_admin, "is_active": u.is_active,
|
||||
# Always a list, never absent: a console that has to test for the field will one day
|
||||
# Always a mapping, never absent: a console that has to test for the field will one day
|
||||
# test wrong and render a moderator as an ordinary user. Empty on a standalone Atrium,
|
||||
# where there is no platform and therefore no such thing as a moderator.
|
||||
"moderates": moderates or []}
|
||||
# where there is one app and everybody with an account may use it.
|
||||
"modules": modules or {}}
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
@@ -56,8 +56,8 @@ def list_users(db: Session = Depends(get_db),
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
users = auth_service.list_users(db)
|
||||
# One query for the whole page, not one per row — see services/moderation.py.
|
||||
moderates = moderation.moderated_by_user(db, [u.id for u in users])
|
||||
return [_user_out(u, moderates.get(u.id)) for u in users]
|
||||
standing = moderation.module_roles_by_user(db, [u.id for u in users])
|
||||
return [_user_out(u, standing.get(u.id)) for u in users]
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserOut, status_code=201)
|
||||
@@ -68,13 +68,17 @@ def create_user(body: UserCreateIn, request: Request, db: Session = Depends(get_
|
||||
password=body.password, is_admin=body.is_admin)
|
||||
audit.record(db, action="user.create", entity_type="app_user", entity_id=user.id,
|
||||
actor_id=admin.id, detail=user.email, ip=ip)
|
||||
# Both tiers in one act, each still audited by its own service: an administrator filling in the
|
||||
# Every tier in one act, each still audited by its own service: an administrator filling in the
|
||||
# new-person form should not have to visit three module pages afterwards to finish the job.
|
||||
for slug in body.moderates:
|
||||
marketplace.get_module(db, slug) # 404 on a slug that names no module
|
||||
moderation.grant(db, admin, module_slug=slug, user_id=user.id, ip=ip)
|
||||
# `grant_access` (not `moderation.grant`) because a row with no assignment behind it would be
|
||||
# swept away by the next reconciliation of that module — see `services/marketplace.py`.
|
||||
for slug, role in body.modules.items():
|
||||
marketplace.grant_access(db, admin, slug, user_id=user.id, role=role, ip=ip)
|
||||
# And then the modules nobody had to name: `availability = everyone` means exactly that, and a
|
||||
# person who joined today has to have the rows to prove it.
|
||||
marketplace.sync_members(db, admin, [user.id], ip=ip)
|
||||
db.commit()
|
||||
return _user_out(user, sorted(body.moderates))
|
||||
return _user_out(user, moderation.module_roles(db, user.id))
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/deactivate", response_model=UserOut)
|
||||
@@ -82,7 +86,7 @@ def deactivate(user_id: uuid.UUID, request: Request, db: Session = Depends(get_d
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
user = accounts.deactivate(db, admin, user_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return _user_out(user, sorted(moderation.moderated_slugs(db, user.id)))
|
||||
return _user_out(user, moderation.module_roles(db, user.id))
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/reactivate", response_model=UserOut)
|
||||
@@ -92,7 +96,7 @@ def reactivate(user_id: uuid.UUID, request: Request, db: Session = Depends(get_d
|
||||
revoked, and signing in again is the cheap half of this."""
|
||||
user = accounts.reactivate(db, admin, user_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return _user_out(user, sorted(moderation.moderated_slugs(db, user.id)))
|
||||
return _user_out(user, moderation.module_roles(db, user.id))
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/administrator", response_model=UserOut)
|
||||
@@ -104,7 +108,7 @@ def set_administrator(user_id: uuid.UUID, body: AdministratorIn, request: Reques
|
||||
user = accounts.set_administrator(db, admin, user_id, is_admin=body.is_admin,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return _user_out(user, sorted(moderation.moderated_slugs(db, user.id)))
|
||||
return _user_out(user, moderation.module_roles(db, user.id))
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/password")
|
||||
@@ -142,7 +146,7 @@ def update_profile(user_id: uuid.UUID, body: UserProfileIn, request: Request,
|
||||
user = accounts.update_profile(db, admin, user_id, ip=client_ip(request),
|
||||
**body.model_dump(exclude_unset=True))
|
||||
db.commit()
|
||||
return _user_out(user, sorted(moderation.moderated_slugs(db, user.id)))
|
||||
return _user_out(user, moderation.module_roles(db, user.id))
|
||||
|
||||
|
||||
@router.post("/me/password")
|
||||
|
||||
+38
-9
@@ -10,6 +10,8 @@ import re
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dredd_core.identity import MODULE_ROLES
|
||||
from dredd_core.moderation import USER
|
||||
from pydantic import AfterValidator, BaseModel, Field
|
||||
|
||||
from .enums import NodeRole
|
||||
@@ -27,6 +29,18 @@ def _valid_email(v: str) -> str:
|
||||
Email = Annotated[str, AfterValidator(_valid_email)]
|
||||
|
||||
|
||||
def _valid_role(v: str) -> str:
|
||||
if v not in MODULE_ROLES:
|
||||
raise ValueError(f"A module role is one of: {', '.join(MODULE_ROLES)}.")
|
||||
return v
|
||||
|
||||
|
||||
#: What somebody may do in one module. Validated against core's `MODULE_ROLES` rather than spelled
|
||||
#: out here, so the API, the service, the database CHECK and the console all take the vocabulary
|
||||
#: from one place — a fifth copy is how a role that exists in three of them gets added.
|
||||
ModuleRole = Annotated[str, AfterValidator(_valid_role)]
|
||||
|
||||
|
||||
# ── auth ──────────────────────────────────────────────────────────────────────
|
||||
class LoginIn(BaseModel):
|
||||
email: Email
|
||||
@@ -34,19 +48,26 @@ class LoginIn(BaseModel):
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
"""A person and their standing on the platform — both tiers in one shape.
|
||||
"""A person and their standing on the platform — every tier in one shape.
|
||||
|
||||
`is_admin` is the **administrator**: platform-wide, every module plus the hub. `moderates` lists
|
||||
the modules they are a **moderator** of: each one administered, nothing outside it. An
|
||||
administrator is a moderator of everything by definition, so the two are not exclusive and the
|
||||
console shows whichever is the stronger claim.
|
||||
`is_admin` is the **administrator**: platform-wide, every module plus the hub, and no row
|
||||
anywhere. `modules` is the whole of the rest — slug → role, one entry per module they may open,
|
||||
`"user"` for using it and `"moderator"` for administering it as well. A module they have no
|
||||
entry for is one they cannot enter at all, which is the answer that did not exist before
|
||||
`module_permission`.
|
||||
|
||||
One field rather than two, because "may open it" and "administers it" are one question with
|
||||
three answers (the absent one included), and splitting them is how a console ends up rendering
|
||||
a moderator as somebody with no access. An administrator is a moderator of everything by
|
||||
definition, so `is_admin` and `modules` are not exclusive and the console shows whichever is
|
||||
the stronger claim.
|
||||
"""
|
||||
id: str
|
||||
email: str
|
||||
full_name: str
|
||||
is_admin: bool
|
||||
is_active: bool
|
||||
moderates: list[str] = []
|
||||
modules: dict[str, str] = {}
|
||||
|
||||
|
||||
class LoginOut(BaseModel):
|
||||
@@ -63,7 +84,9 @@ class UserCreateIn(BaseModel):
|
||||
# writes its own audit row — a new account that quietly arrived with power is the one shape this
|
||||
# model must never have.
|
||||
is_admin: bool = False
|
||||
moderates: list[str] = Field(default_factory=list, max_length=20)
|
||||
# slug → role, the same shape `UserOut.modules` reports back. An empty dict means an account
|
||||
# that can sign in and open nothing, which is the correct starting point for a new person.
|
||||
modules: dict[str, ModuleRole] = Field(default_factory=dict, max_length=20)
|
||||
|
||||
|
||||
class AdministratorIn(BaseModel):
|
||||
@@ -72,9 +95,15 @@ class AdministratorIn(BaseModel):
|
||||
is_admin: bool
|
||||
|
||||
|
||||
class ModeratorIn(BaseModel):
|
||||
"""Who to make a moderator. The module is the path segment; only the person is in the body."""
|
||||
class PermissionIn(BaseModel):
|
||||
"""Who to admit to a module, and as what. The module is the path segment; the body is the
|
||||
person and the role.
|
||||
|
||||
`role` defaults to the LESSER one on purpose, here as well as in the database and in core: a
|
||||
caller that forgets to name it admits a user and never a moderator.
|
||||
"""
|
||||
user_id: uuid.UUID
|
||||
role: ModuleRole = USER
|
||||
|
||||
|
||||
class PasswordChangeIn(BaseModel):
|
||||
|
||||
+18
-1
@@ -36,7 +36,7 @@ CATALOG_SEEDED = "_seed.catalog"
|
||||
#
|
||||
# **A slug here is the module's OWN slug, and nothing else may be spelled into it.** Since one
|
||||
# account, the slug is no longer just a URL segment in this app: `POST /admin/modules/{slug}/
|
||||
# moderators` writes `module_moderator.module_slug`, which the module itself reads back with its
|
||||
# moderators` writes `module_permission.module_slug`, which the module itself reads back with its
|
||||
# `MODULE_SLUG` — and `POST /me/modules/{slug}/tokens` builds a `<slug>_pat_` credential. A slug
|
||||
# only the catalogue believes in therefore fails **silently**: the grant is written, nobody holds
|
||||
# the tier, and no error is raised anywhere, because a module only ever SELECTs by its own name and
|
||||
@@ -127,6 +127,23 @@ def run(session_factory: sessionmaker | None = None) -> None:
|
||||
log.info("Seeded the module catalog (%d modules)", len(FAMILY))
|
||||
db.add(AppSetting(key=CATALOG_SEEDED, value="true", updated_by=None))
|
||||
|
||||
# Make `module_permission` say what the catalogue means — every module, every deploy.
|
||||
#
|
||||
# Not decoration and not a flag-guarded one-shot. `module_permission` is the table every
|
||||
# module now reads at its own door, and the hub's request paths keep it true from here on
|
||||
# (`services/marketplace.py`) — but they can only do that for changes made THROUGH them.
|
||||
# Every module that existed before this shipped has no rows at all, and on a platform that
|
||||
# is not "nobody is offered anything": it is nobody being let INTO anything, including the
|
||||
# modules whose availability has always been `everyone`. The one deploy step that already
|
||||
# runs after `alembic upgrade head` is the honest place to close that.
|
||||
#
|
||||
# It stays unguarded because it is idempotent and writes only differences, which makes it a
|
||||
# backstop as well as a backfill: if a write path is ever added that forgets to reconcile,
|
||||
# the next deploy repairs it rather than leaving somebody quietly shut out. Standalone it
|
||||
# does nothing at all — there is no table to read and no platform to be admitted to.
|
||||
for module in db.scalars(select(Module)).all():
|
||||
marketplace.sync_module(db, None, module)
|
||||
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
The hub is the only writer of identity. Three grants say so at the database level — a module holds
|
||||
`SELECT` on a few columns of `app_user`, `SELECT` plus a three-column `UPDATE` on `session`, and
|
||||
`SELECT` on `module_moderator` — and nothing else in the family may create an account, change one,
|
||||
`SELECT` on `module_permission` — and nothing else in the family may create an account, change one,
|
||||
or mint a credential. This file is where that authority is actually exercised, and it exists rather
|
||||
than living in the routers because `services/auth.py` is a **shim over dredd-core and must stay
|
||||
one**: core owns the mechanics (hashing, session rows, token expiry), and what belongs to Atrium is
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
Two questions, kept apart on purpose:
|
||||
|
||||
* **Status** (`live` / `beta` / `coming_soon`) is the catalog's claim about the product.
|
||||
* **Availability** (`everyone` / `selected` / `off`) is this instance's decision about who is
|
||||
offered it. `selected` means: the users assigned directly, plus the members of every assigned
|
||||
* **Availability** (`everyone` / `selected` / `off`) is this instance's decision about who may open
|
||||
it. `selected` means: the users assigned directly, plus the members of every assigned
|
||||
organizational unit *and of every unit below it* — assign Galena to Legal and Legal's teams get it
|
||||
too, the way turning a service on for an organizational unit works in Google Workspace.
|
||||
|
||||
@@ -15,11 +15,36 @@ down the tree to members of sub-units, where a read grant flows down to everythi
|
||||
Instance administrators are members of the units they hold grants on, like anyone else — the
|
||||
launcher shows an administrator what they are offered, not everything that exists.
|
||||
|
||||
**What this is not:** availability decides what Atrium *offers*. It is not an access control on the
|
||||
module. The family runs at one origin with one module per path, so a module's address is a guessable
|
||||
path and withholding it withholds nothing: what keeps someone out is the module's own permission
|
||||
grants, and an unassigned person who types the path reaches the module and finds it empty. Say that
|
||||
in the console copy; never present the tile as the lock.
|
||||
An assignment is a **shortcut, not a second permission model**
|
||||
--------------------------------------------------------------
|
||||
`module_permission` (dredd-core, the shared identity schema) is the ONE table that decides access:
|
||||
no row means no entry, and every module reads it and nothing else. `module_assignment` survives
|
||||
only as this hub's convenience — a record of *why* someone has a module, and in particular the one
|
||||
way to say "everybody in Legal" without naming twelve people. It is no longer consulted by anyone
|
||||
making an access decision.
|
||||
|
||||
So an assignment has to be **materialised** into per-user `module_permission` rows, and the whole
|
||||
question a bulk shortcut raises is what happens when the unit's membership changes a week later.
|
||||
The answer here is: **it is re-materialised on every membership change**, so the shortcut never goes
|
||||
stale in either direction. `sync_module` reconciles one module against its assignments and
|
||||
`sync_members` reconciles one person against the whole catalogue; between them they are called from
|
||||
every hub write path that can change the answer — an assignment added or removed, a module's
|
||||
availability changed, a module created, an access request approved, a unit grant given or taken
|
||||
away, a unit deleted, and an account created. There is no third table and no background job: the
|
||||
hub is the only writer of membership *and* of permissions, so every input is a request it served.
|
||||
`app/seed.py` sweeps every module once more on each deploy — a backfill for everything that
|
||||
existed before this shipped, and a backstop if a write path is ever added that forgets.
|
||||
|
||||
The reconciliation is a full set-difference, which is safe only because **every row it could delete
|
||||
has a `module_assignment` behind it**: granting someone access on a module's own page records a
|
||||
direct assignment for that person, exactly as approving an access request already did. Deactivated
|
||||
accounts are excluded from both sides — their rows are frozen until they come back, so switching
|
||||
somebody off and on again does not silently strip the modules they moderated.
|
||||
|
||||
**What this is not:** availability is now the access decision, but the tile still is not the lock.
|
||||
The family runs at one origin with one module per path, so a module's address is a guessable path;
|
||||
what keeps someone out is the missing `module_permission` row that the module itself checks at its
|
||||
own door, not the absence of a tile here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -31,13 +56,16 @@ from urllib.parse import urlsplit
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import AccessRequestStatus, Availability, ModuleStatus
|
||||
from ..config import get_settings
|
||||
from ..enums import AccessRequestStatus, Availability, ModuleStatus, PrincipalType
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..integrations import health
|
||||
from ..models import AccessRequest, AppUser, Module, ModuleAssignment, Node
|
||||
from ..models import AccessRequest, AppUser, Module, ModuleAssignment, Node, PermissionGrant
|
||||
from . import audit, authz, changes, moderation, settings
|
||||
from .nodes import CONTAINER_KINDS
|
||||
|
||||
app_settings = get_settings()
|
||||
|
||||
# The console draws these; keep them in step with the `.mi.h-<hue>` classes in frontend/app.css
|
||||
# and `HUES`/`GLYPH` in frontend/app.js (tests/test_marketplace_unit.py fails when they drift).
|
||||
HUES = ("grape", "violet", "indigo", "blue", "cyan", "teal", "green", "lime",
|
||||
@@ -124,8 +152,14 @@ def _covered_units(member_paths: list[str]) -> set[str]:
|
||||
return {a for p in member_paths for a in authz.ancestor_paths(p)}
|
||||
|
||||
|
||||
def accessible_ids(db: DbSession, user: AppUser, modules: list[Module]) -> set[uuid.UUID]:
|
||||
"""Which of `modules` are offered to `user`, in a fixed number of queries."""
|
||||
def assigned_ids(db: DbSession, user: AppUser, modules: list[Module]) -> set[uuid.UUID]:
|
||||
"""Which of `modules` the ASSIGNMENTS reach `user` through, in a fixed number of queries.
|
||||
|
||||
One of the two directions of one rule, and the direction a person is resolved in. The other is
|
||||
`_assigned_member_ids`, which resolves a module; `tests/test_marketplace_unit.py` checks they
|
||||
agree, because a materialisation that disagreed with the screen that caused it is the bug this
|
||||
whole design exists to avoid.
|
||||
"""
|
||||
ids = {m.id for m in modules if m.availability == Availability.everyone}
|
||||
selected = [m.id for m in modules if m.availability == Availability.selected]
|
||||
if not selected:
|
||||
@@ -152,6 +186,140 @@ def accessible_ids(db: DbSession, user: AppUser, modules: list[Module]) -> set[u
|
||||
return ids
|
||||
|
||||
|
||||
def accessible_ids(db: DbSession, user: AppUser, modules: list[Module]) -> set[uuid.UUID]:
|
||||
"""Which of `modules` this person may actually open.
|
||||
|
||||
On the platform that is read from `module_permission` — **the same table the module itself
|
||||
checks at its own door** — so the launcher can never show a tile that the module will refuse.
|
||||
One query for the whole page, whatever the assignments look like.
|
||||
|
||||
Standalone there is no such table to read (core answers `"user"` for everybody and `module_roles`
|
||||
returns nothing), so the offering is still resolved from the assignments, exactly as it always
|
||||
was. That is the one branch, and it is `settings.shares_identity` — the family's single switch —
|
||||
rather than a second access model.
|
||||
"""
|
||||
if not app_settings.shares_identity:
|
||||
return assigned_ids(db, user, modules)
|
||||
roles = moderation.module_roles(db, user.id)
|
||||
return {m.id for m in modules if m.slug in roles}
|
||||
|
||||
|
||||
# ── materialising the shortcut: assignments → per-user permissions ────────────
|
||||
def _assigned_member_ids(db: DbSession, m: Module) -> set[uuid.UUID]:
|
||||
"""Everyone this module's assignments reach — the module-shaped direction of `assigned_ids`.
|
||||
|
||||
A grant on an assigned unit **or on anything below it** makes you a member of it, which is the
|
||||
same rule `_covered_units` applies from the other end (membership flows UP the tree, so a grant
|
||||
on the workspace root does not make you a member of every department under it).
|
||||
|
||||
Overlays: Atrium registers none (see `services/authz.py`), so this is the same answer
|
||||
`readable_node_ids` gives the per-user direction. If one is ever registered, both directions
|
||||
have to honour it or the launcher and the materialised table will disagree.
|
||||
"""
|
||||
if m.availability == Availability.off:
|
||||
return set()
|
||||
if m.availability == Availability.everyone:
|
||||
return _active_ids(db)
|
||||
rows = db.execute(
|
||||
select(ModuleAssignment.user_id, Node.path)
|
||||
.outerjoin(Node, Node.id == ModuleAssignment.node_id)
|
||||
.where(ModuleAssignment.module_id == m.id)
|
||||
).all()
|
||||
ids = {user_id for user_id, _path in rows if user_id is not None}
|
||||
paths = [path for user_id, path in rows if user_id is None and path]
|
||||
if paths:
|
||||
ids |= set(db.scalars(
|
||||
select(PermissionGrant.principal_id)
|
||||
.join(Node, Node.id == PermissionGrant.node_id)
|
||||
.where(PermissionGrant.principal_type == PrincipalType.user,
|
||||
or_(*[or_(Node.path == p, Node.path.startswith(p + "/")) for p in paths]))
|
||||
).all())
|
||||
return ids
|
||||
|
||||
|
||||
def _active_ids(db: DbSession) -> set[uuid.UUID]:
|
||||
"""A deactivated account takes no part in the reconciliation, in EITHER direction.
|
||||
|
||||
Not an optimisation: core's `grant` refuses a deactivated person, so they cannot be added — and
|
||||
if they could be *removed* instead, switching somebody off and on again would silently strip
|
||||
every module they moderated. Their rows are frozen until they come back, and the thing that
|
||||
keeps them out meanwhile is that they cannot sign in at all.
|
||||
"""
|
||||
return set(db.scalars(select(AppUser.id).where(AppUser.is_active.is_(True))).all())
|
||||
|
||||
|
||||
def sync_module(db: DbSession, actor: AppUser | None, m: Module, *,
|
||||
ip: str | None = None) -> tuple[int, int]:
|
||||
"""Make `module_permission` say what ONE module's assignments mean. Returns (added, removed).
|
||||
|
||||
A full set-difference, which is only safe because every row it can delete has an assignment
|
||||
behind it — `grant_access` writes one, and so does approving an access request. Added rows come
|
||||
in as `user`: a bulk shortcut admits people, it never promotes them.
|
||||
|
||||
One audit row for the sweep rather than one per person. The *cause* is audited where it
|
||||
happened (`module.assign`, `module.update`, `grant.upsert`), and a hundred rows saying the same
|
||||
thing would bury it.
|
||||
"""
|
||||
if not app_settings.shares_identity or m.slug == app_settings.module_slug:
|
||||
return (0, 0)
|
||||
active = _active_ids(db)
|
||||
want = _assigned_member_ids(db, m) & active
|
||||
have = moderation.member_ids(db, m.slug) & active
|
||||
for user_id in want - have:
|
||||
moderation.grant(db, actor, module_slug=m.slug, user_id=user_id,
|
||||
role=moderation.USER, ip=ip, audited=False)
|
||||
for user_id in have - want:
|
||||
moderation.revoke(db, actor, module_slug=m.slug, user_id=user_id, ip=ip,
|
||||
audited=False, required=False)
|
||||
added, removed = len(want - have), len(have - want)
|
||||
if added or removed:
|
||||
audit.record(db, action="module_permission.sync", entity_type="module", entity_id=m.id,
|
||||
actor_id=actor.id if actor else None,
|
||||
detail=f"{m.slug} +{added} -{removed}", ip=ip)
|
||||
return added, removed
|
||||
|
||||
|
||||
def sync_members(db: DbSession, actor: AppUser | None, user_ids, *,
|
||||
ip: str | None = None) -> None:
|
||||
"""Re-materialise one or more PEOPLE against the whole catalogue.
|
||||
|
||||
The other half of "the shortcut never goes stale": somebody joins Legal a week after Galena was
|
||||
assigned to it, and their membership grant is what changes — not the assignment. Every hub path
|
||||
that writes a membership grant (and the one that deletes a unit, which cascades them away) ends
|
||||
here, and so does creating an account, which is how a new person picks up the `everyone`
|
||||
modules on their first day.
|
||||
|
||||
Deactivated accounts are skipped entirely; see `_active_ids`. Rows for a slug that has left the
|
||||
catalogue are left alone — `delete_module` owns those, and a person sweep must not decide the
|
||||
fate of a module it is not looking at.
|
||||
"""
|
||||
if not app_settings.shares_identity:
|
||||
return
|
||||
ids = {u for u in user_ids if u}
|
||||
if not ids:
|
||||
return
|
||||
modules = [m for m in _ordered(db) if m.slug != app_settings.module_slug]
|
||||
if not modules:
|
||||
return
|
||||
slug_of = {m.id: m.slug for m in modules}
|
||||
known = set(slug_of.values())
|
||||
for user in db.scalars(
|
||||
select(AppUser).where(AppUser.id.in_(ids), AppUser.is_active.is_(True))
|
||||
).all():
|
||||
want = {slug_of[module_id] for module_id in assigned_ids(db, user, modules)}
|
||||
have = {slug for slug in moderation.module_roles(db, user.id) if slug in known}
|
||||
for slug in want - have:
|
||||
moderation.grant(db, actor, module_slug=slug, user_id=user.id,
|
||||
role=moderation.USER, ip=ip, audited=False)
|
||||
for slug in have - want:
|
||||
moderation.revoke(db, actor, module_slug=slug, user_id=user.id, ip=ip,
|
||||
audited=False, required=False)
|
||||
if want != have:
|
||||
audit.record(db, action="module_permission.sync", entity_type="app_user",
|
||||
entity_id=user.id, actor_id=actor.id if actor else None,
|
||||
detail=f"{user.email} +{len(want - have)} -{len(have - want)}", ip=ip)
|
||||
|
||||
|
||||
def _visible(user: AppUser, m: Module) -> bool:
|
||||
"""A module switched off is invisible to everyone but administrators — including in a 404."""
|
||||
return user.is_admin or m.availability != Availability.off
|
||||
@@ -369,6 +537,9 @@ def create_module(db: DbSession, actor: AppUser | None, data: dict, *,
|
||||
audit.record(db, action="module.create", entity_type="module", entity_id=m.id,
|
||||
actor_id=actor.id if actor else None, detail=slug, ip=ip,
|
||||
diff={f: [None, v] for f, v in _snapshot(m).items()})
|
||||
# A module created as `everyone` reaches everyone from the moment it exists, and "reaches" is
|
||||
# now a row per person rather than a rule applied at read time.
|
||||
sync_module(db, actor, m, ip=ip)
|
||||
return _admin_out(m)
|
||||
|
||||
|
||||
@@ -390,6 +561,11 @@ def update_module(db: DbSession, actor: AppUser, slug: str, data: dict, *,
|
||||
if diff:
|
||||
audit.record(db, action="module.update", entity_type="module", entity_id=m.id,
|
||||
actor_id=actor.id, detail=m.slug, ip=ip, diff=diff)
|
||||
if "availability" in diff:
|
||||
# Availability IS the access decision now, so changing it has to rewrite the rows: `off`
|
||||
# empties the roster, `everyone` fills it, and `selected` puts it back to what the
|
||||
# assignments say. Nothing else in `EDITABLE` touches who may open the module.
|
||||
sync_module(db, actor, m, ip=ip)
|
||||
return admin_detail(db, slug)
|
||||
|
||||
|
||||
@@ -398,10 +574,10 @@ def delete_module(db: DbSession, actor: AppUser, slug: str, *, ip: str | None =
|
||||
audit.record(db, action="module.delete", entity_type="module", entity_id=m.id,
|
||||
actor_id=actor.id, detail=m.slug, ip=ip,
|
||||
diff={f: [v, None] for f, v in _snapshot(m).items()})
|
||||
# Its moderators, in the same transaction. `module_moderator.module_slug` is deliberately NOT a
|
||||
# foreign key to this table — the shared identity schema must not depend on the marketplace —
|
||||
# Its whole roster, in the same transaction. `module_permission.module_slug` is deliberately NOT
|
||||
# a foreign key to this table — the shared identity schema must not depend on the marketplace —
|
||||
# so nothing cascades, and without this line a slug that is deleted and recreated silently
|
||||
# resurrects its old moderators, including the ones revoked in between.
|
||||
# resurrects its old roster, including the people whose access was revoked in between.
|
||||
moderation.revoke_module(db, actor, module_slug=m.slug, ip=ip)
|
||||
db.delete(m) # assignments and requests go with it (ON DELETE CASCADE)
|
||||
db.flush()
|
||||
@@ -409,6 +585,13 @@ def delete_module(db: DbSession, actor: AppUser, slug: str, *, ip: str | None =
|
||||
|
||||
def add_assignment(db: DbSession, actor: AppUser, slug: str, *, node_id: uuid.UUID | None,
|
||||
user_id: uuid.UUID | None, ip: str | None = None) -> dict:
|
||||
"""Assign the module to one organizational unit or one person.
|
||||
|
||||
A unit assignment is a **shortcut that stays true**: it admits everybody in that unit and in
|
||||
every unit below it, as `user`, right now — and it is re-materialised whenever somebody joins
|
||||
or leaves, because the hub is the only writer of membership too. It is not a one-time bulk
|
||||
grant, and the console says so.
|
||||
"""
|
||||
if (node_id is None) == (user_id is None):
|
||||
raise ValidationError("Assign the module to one organizational unit or one user.")
|
||||
m = get_module(db, slug)
|
||||
@@ -431,6 +614,7 @@ def add_assignment(db: DbSession, actor: AppUser, slug: str, *, node_id: uuid.UU
|
||||
db.flush()
|
||||
audit.record(db, action="module.assign", entity_type="module", entity_id=m.id,
|
||||
actor_id=actor.id, detail=target, ip=ip)
|
||||
sync_module(db, actor, m, ip=ip)
|
||||
return _assignment_out(a, node, user)
|
||||
|
||||
|
||||
@@ -451,6 +635,67 @@ def remove_assignment(db: DbSession, actor: AppUser, slug: str, assignment_id: u
|
||||
actor_id=actor.id, detail=target, ip=ip)
|
||||
db.delete(a)
|
||||
db.flush()
|
||||
# Un-assigning takes the access with it — unless another assignment still reaches the same
|
||||
# people, which is exactly what the reconciliation works out rather than guessing.
|
||||
sync_module(db, actor, m, ip=ip)
|
||||
|
||||
|
||||
# ── administration: who may open the module, and who administers it ──────────
|
||||
def list_access(db: DbSession, slug: str) -> list[dict]:
|
||||
"""The roster of one module. 404 first, so a slug that names nothing gets no roster."""
|
||||
get_module(db, slug)
|
||||
return moderation.list_permissions(db, slug)
|
||||
|
||||
|
||||
def _pin_assignment(db: DbSession, actor: AppUser | None, m: Module,
|
||||
user_id: uuid.UUID) -> None:
|
||||
"""Record the direct assignment behind a roster grant — and it is load-bearing, not tidiness.
|
||||
|
||||
`sync_module` is a full set-difference: it deletes every row the assignments do not account
|
||||
for. A person admitted here with no assignment would therefore be swept away by the next
|
||||
unrelated change to this module, which is precisely the kind of silent, delayed revocation this
|
||||
design exists to prevent. So naming somebody on the roster and assigning the module to them are
|
||||
one act with one record, exactly as approving an access request already was.
|
||||
"""
|
||||
if db.scalar(select(ModuleAssignment.id).where(
|
||||
ModuleAssignment.module_id == m.id, ModuleAssignment.user_id == user_id)) is None:
|
||||
db.add(ModuleAssignment(module_id=m.id, user_id=user_id,
|
||||
created_by=actor.id if actor else None))
|
||||
db.flush()
|
||||
|
||||
|
||||
def grant_access(db: DbSession, actor: AppUser | None, slug: str, *, user_id: uuid.UUID,
|
||||
role: str = moderation.USER, ip: str | None = None) -> dict:
|
||||
"""Give one person access to one module, as `user` or `moderator`.
|
||||
|
||||
Idempotent, and the same call promotes and demotes (core's `grant` is an UPSERT), so a
|
||||
double-click is not an error. Core refuses the hub's own slug, an unknown account, a deactivated
|
||||
one and an unknown role.
|
||||
"""
|
||||
m = get_module(db, slug)
|
||||
out = moderation.grant(db, actor, module_slug=m.slug, user_id=user_id, role=role, ip=ip)
|
||||
_pin_assignment(db, actor, m, user_id)
|
||||
return out
|
||||
|
||||
|
||||
def revoke_access(db: DbSession, actor: AppUser, slug: str, *, user_id: uuid.UUID,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Take one person's access to one module away: the row, and the assignment behind it.
|
||||
|
||||
Then reconcile, because a person named on the roster may ALSO be reached by a unit assignment —
|
||||
and then they keep ordinary access and merely stop being a moderator. That is the honest
|
||||
outcome rather than a revocation that a re-render silently undoes, so it is reported
|
||||
(`still_a_member`) and the console says which of the two happened.
|
||||
"""
|
||||
m = get_module(db, slug)
|
||||
a = db.scalar(select(ModuleAssignment).where(
|
||||
ModuleAssignment.module_id == m.id, ModuleAssignment.user_id == user_id))
|
||||
if a is not None:
|
||||
db.delete(a)
|
||||
db.flush()
|
||||
moderation.revoke(db, actor, module_slug=m.slug, user_id=user_id, ip=ip)
|
||||
added, _removed = sync_module(db, actor, m, ip=ip)
|
||||
return {"status": "ok", "still_a_member": bool(added)}
|
||||
|
||||
|
||||
def probe_target(db: DbSession, slug: str) -> tuple[uuid.UUID, str | None]:
|
||||
@@ -511,6 +756,9 @@ def decide(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, approve: boo
|
||||
db.flush()
|
||||
audit.record(db, action=f"access_request.{req.status}", entity_type="access_request",
|
||||
entity_id=req.id, actor_id=actor.id, detail=f"{m.slug} {user.email}", ip=ip)
|
||||
if approve:
|
||||
# The assignment above is the record of the decision; the row that lets them in is this.
|
||||
sync_module(db, actor, m, ip=ip)
|
||||
return _request_out(req, m, user)
|
||||
|
||||
|
||||
|
||||
@@ -1,65 +1,78 @@
|
||||
"""The MODERATOR tier: who administers one module, granted and revoked only here.
|
||||
"""Who may open a module, and who administers it — granted and revoked only here.
|
||||
|
||||
Two words, used verbatim in the table, the API, the guard names and the console copy, because two
|
||||
words for one idea is how a permission model rots:
|
||||
Three answers, and the first of them is the absence of a row, which is the whole point of the table:
|
||||
|
||||
* **administrator** — platform-wide. Every module, plus the hub itself. `app_user.is_admin`.
|
||||
`services/accounts.py` owns it.
|
||||
* **moderator** — exactly one module. A `module_moderator` row in the shared identity schema.
|
||||
This file owns it.
|
||||
* **no row** — no access to that module at all. The default for everybody.
|
||||
* **user** — may use it. A `module_permission` row with `role = 'user'`.
|
||||
* **moderator** — may use it AND administer it. The same row with `role = 'moderator'`.
|
||||
* **administrator** — platform-wide: every module, plus the hub itself. `app_user.is_admin`, and it
|
||||
needs no row anywhere. `services/accounts.py` owns it.
|
||||
|
||||
Before `module_permission` a person with an account could type `/galena` and be let in: they saw an
|
||||
empty drive, but nothing had refused them, and "you can see nothing" is not an access decision. Now
|
||||
the absence of a row is one, and this file is the only place on the platform that writes those rows.
|
||||
|
||||
An administrator is a moderator of everything by definition; a moderator is nothing outside their
|
||||
own module. **Neither tier can be granted from inside a module** — and the thing that makes that
|
||||
true is not this file. It is the grant: a module's runtime role holds `SELECT` on
|
||||
`module_moderator` and nothing else, so a compromised module cannot promote anybody, cannot
|
||||
un-promote the person who would notice, and cannot hide the row from the hub. This file is the
|
||||
matching sentence at the edge, and the audit trail.
|
||||
own module. **No tier can be granted from inside a module** — and the thing that makes that true is
|
||||
not this file. It is the grant: a module's runtime role holds `SELECT` on `module_permission` and
|
||||
nothing else, so a compromised module cannot admit anybody, cannot promote anybody (least of all
|
||||
itself), cannot un-promote the person who would notice, and cannot hide the row from the hub. This
|
||||
file is the matching sentence at the edge, and the audit trail.
|
||||
|
||||
Why it is here and not in `services/marketplace.py`, where the screen lives: the catalogue answers
|
||||
"is this module *offered* to you", which is a different question from "may you administer it", and
|
||||
the first person to conflate them hands moderator to everybody the day they switch a module from
|
||||
`selected` to `everyone`. The one place the two genuinely meet is `delete_module`, which must call
|
||||
`revoke_module` — `module_moderator.module_slug` is deliberately not a foreign key, so nothing
|
||||
cascades and a slug that came back would otherwise resurrect its old moderators.
|
||||
Why it is here and not in `services/marketplace.py`, where the screen lives: this file owns the
|
||||
table and its audit rows, and nothing else may write them. What `marketplace.py` owns is the other
|
||||
half — *which* rows should exist, derived from the catalogue's assignments — and it calls the
|
||||
functions below to make that true. The one place they meet in the other direction is
|
||||
`delete_module`, which must call `revoke_module`: `module_permission.module_slug` is deliberately
|
||||
not a foreign key, so nothing cascades and a slug that came back would otherwise resurrect its old
|
||||
roster.
|
||||
|
||||
**Revocation is a hard DELETE, never a flag.** That inverts the family's usual posture
|
||||
(`app_user.is_active`, `session.revoked_at`) on purpose: a soft delete makes every reader
|
||||
responsible for remembering `WHERE revoked_at IS NULL`, and a module that forgets keeps a revoked
|
||||
moderator — a fail-*open* mistake in the one place this design cannot afford one. The permanent
|
||||
record is the audit row below, which the runtime role may insert and never rewrite.
|
||||
record is the audit row below, which the runtime role may insert and never rewrite. The `role`, by
|
||||
contrast, IS mutable: promoting or demoting is an UPDATE of a row that stays, so who admitted this
|
||||
person and when survives it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from dredd_core.moderation import ModerationPolicy, ModerationService
|
||||
from dredd_core.moderation import MODERATOR, USER, ModerationPolicy, ModerationService
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import ConflictError, NotFoundError
|
||||
from ..models import AppUser, ModuleModerator
|
||||
from ..models import AppUser, ModulePermission
|
||||
from . import audit
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
# Re-exported so no call site in this app spells a role as a bare string; the values are core's.
|
||||
__all__ = ["MODERATOR", "USER", "grant", "is_administrator", "list_permissions", "member_ids",
|
||||
"module_roles", "module_roles_by_user", "moderated_slugs", "revoke", "revoke_module"]
|
||||
|
||||
# Core reads no app config of its own, so the app supplies its slug and its mode as DATA — never a
|
||||
# predicate. Three knobs, and each one is load-bearing:
|
||||
#
|
||||
# * `module_slug` / `hub_slug` are both Atrium's own, which is what makes `grant()` refuse
|
||||
# `module_moderator(user, 'atrium')`: the hub has administrators, and its administration is not
|
||||
# delegable one module at a time. Revisit when there are two administrators, not before.
|
||||
# * `shared_moderators` follows `IDENTITY_SCHEMA`, because a per-module moderator is meaningless
|
||||
# without a platform: standalone, core short-circuits to `user.is_admin` and emits no SQL, so a
|
||||
# deployment with no modules pays nothing for a tier it does not have.
|
||||
# * `moderator_writes_enabled=True` is the half of the design that is *code*. Only the hub sets it;
|
||||
# `module_permission(user, 'atrium')`: every account may open the launcher, so a `user` row for
|
||||
# the hub would say nothing, and the hub has administrators — its administration is not delegable
|
||||
# one module at a time. Revisit when there are two administrators, not before.
|
||||
# * `shared_permissions` follows `IDENTITY_SCHEMA`, because per-module permissions are meaningless
|
||||
# without a platform: standalone, core short-circuits (`"user"` for everybody, `"moderator"` for an
|
||||
# administrator) and emits no SQL, so a deployment with no modules pays nothing for a table it has
|
||||
# no use for.
|
||||
# * `permission_writes_enabled=True` is the half of the design that is *code*. Only the hub sets it;
|
||||
# a module leaves it False and gets a clean 409 instead of a Postgres permission error surfacing
|
||||
# as a 500 on an ordinary screen.
|
||||
_service = ModerationService(ModerationPolicy(
|
||||
module_slug=settings.module_slug,
|
||||
hub_slug=settings.module_slug,
|
||||
shared_moderators=settings.shares_identity,
|
||||
moderator_writes_enabled=True,
|
||||
shared_permissions=settings.shares_identity,
|
||||
permission_writes_enabled=True,
|
||||
))
|
||||
|
||||
# Deliberately NOT `authz.bind_moderation(_service)`. That binding projects a moderator onto a
|
||||
@@ -69,17 +82,17 @@ _service = ModerationService(ModerationPolicy(
|
||||
|
||||
|
||||
def _assert_platform() -> None:
|
||||
"""A standalone Atrium has no modules sharing its accounts, so it has no moderators.
|
||||
"""A standalone Atrium has no modules sharing its accounts, so it has no per-module permissions.
|
||||
|
||||
Core is already inert there — `is_moderator` short-circuits to `user.is_admin` and emits no SQL,
|
||||
and `moderated_slugs` returns nothing — which means a grant written standalone would *succeed*
|
||||
and then be invisible forever: a row nobody reads, on a screen that says someone has a tier they
|
||||
do not have. Refusing at the edge, with a sentence, is the honest version of "inert".
|
||||
Core is already inert there — `module_role` short-circuits to `"user"` / `"moderator"` and emits
|
||||
no SQL, and `module_roles` returns nothing — which means a grant written standalone would
|
||||
*succeed* and then be invisible forever: a row nobody reads, on a screen that says someone has a
|
||||
tier they do not have. Refusing at the edge, with a sentence, is the honest version of "inert".
|
||||
"""
|
||||
if not settings.shares_identity:
|
||||
raise ConflictError(
|
||||
"This Atrium runs on its own, with no modules sharing its accounts, so there is no "
|
||||
"module to moderate. Administrators already have every permission here."
|
||||
"module to grant. Administrators already have every permission here."
|
||||
)
|
||||
|
||||
|
||||
@@ -89,39 +102,51 @@ def is_administrator(user: AppUser) -> bool:
|
||||
|
||||
|
||||
def moderated_slugs(db: DbSession, user_id: uuid.UUID) -> frozenset[str]:
|
||||
"""Every module this person moderates — the `moderates` field on a user row."""
|
||||
"""Every module this person MODERATES — the narrow half of `module_roles`."""
|
||||
return _service.moderated_slugs(db, user_id)
|
||||
|
||||
|
||||
def moderated_by_user(db: DbSession, user_ids: list[uuid.UUID]) -> dict[uuid.UUID, list[str]]:
|
||||
"""`moderated_slugs` for a whole page of people, in ONE query rather than one per row.
|
||||
def module_roles(db: DbSession, user_id: uuid.UUID) -> dict[str, str]:
|
||||
"""Every module this person has a row for, slug → role. The whole of someone's standing."""
|
||||
return _service.module_roles(db, user_id)
|
||||
|
||||
|
||||
def member_ids(db: DbSession, module_slug: str) -> set[uuid.UUID]:
|
||||
"""Everyone with a row for a module, whatever their role — the set `marketplace.py` reconciles
|
||||
its assignments against."""
|
||||
return _service.member_ids(db, module_slug=module_slug)
|
||||
|
||||
|
||||
def module_roles_by_user(db: DbSession,
|
||||
user_ids: list[uuid.UUID]) -> dict[uuid.UUID, dict[str, str]]:
|
||||
"""`module_roles` for a whole page of people, in ONE query rather than one per row.
|
||||
|
||||
The Users screen renders every account, and asking per row would be a query per person — the
|
||||
shape somebody eventually "optimises" by dropping the column that shows the tier. Core has no
|
||||
all-rows read (nothing but the hub has a reason to want one), so the query lives here, in a
|
||||
service, where the layering rule puts it.
|
||||
shape somebody eventually "optimises" by dropping the column that shows what people may open.
|
||||
Core has no all-rows read (nothing but the hub has a reason to want one), so the query lives
|
||||
here, in a service, where the layering rule puts it.
|
||||
"""
|
||||
if not user_ids or not settings.shares_identity:
|
||||
return {}
|
||||
wanted = set(user_ids)
|
||||
out: dict[uuid.UUID, list[str]] = {}
|
||||
for user_id, slug in db.execute(
|
||||
select(ModuleModerator.user_id, ModuleModerator.module_slug)
|
||||
.where(ModuleModerator.user_id.in_(wanted))
|
||||
.order_by(ModuleModerator.module_slug)
|
||||
out: dict[uuid.UUID, dict[str, str]] = {}
|
||||
for user_id, slug, role in db.execute(
|
||||
select(ModulePermission.user_id, ModulePermission.module_slug, ModulePermission.role)
|
||||
.where(ModulePermission.user_id.in_(wanted))
|
||||
.order_by(ModulePermission.module_slug)
|
||||
).all():
|
||||
out.setdefault(user_id, []).append(slug)
|
||||
out.setdefault(user_id, {})[slug] = role
|
||||
return out
|
||||
|
||||
|
||||
def list_moderators(db: DbSession, module_slug: str) -> list[dict]:
|
||||
def list_permissions(db: DbSession, module_slug: str) -> list[dict]:
|
||||
"""The roster of one module, oldest grant first, with the people resolved for display.
|
||||
|
||||
`is_active` and `is_admin` come along because the pane says something useful with each: a
|
||||
deactivated moderator is a row to clean up, and an administrator listed here is already a
|
||||
moderator of everything, so the grant is redundant rather than wrong.
|
||||
deactivated person is a row to clean up, and an administrator listed here already reaches every
|
||||
module, so the row is redundant rather than wrong.
|
||||
"""
|
||||
rows = _service.list_moderators(db, module_slug=module_slug)
|
||||
rows = _service.list_permissions(db, module_slug=module_slug)
|
||||
if not rows:
|
||||
return []
|
||||
ids = {r.user_id for r in rows} | {r.created_by for r in rows if r.created_by}
|
||||
@@ -135,6 +160,7 @@ def list_moderators(db: DbSession, module_slug: str) -> list[dict]:
|
||||
"email": person.email if person else "",
|
||||
# An em dash rather than a blank: the account is gone, which is worth seeing.
|
||||
"full_name": person.full_name if person else "—",
|
||||
"role": row.role,
|
||||
"is_active": bool(person.is_active) if person else False,
|
||||
"is_admin": bool(person.is_admin) if person else False,
|
||||
"created_at": row.created_at.isoformat() if row.created_at else None,
|
||||
@@ -143,46 +169,65 @@ def list_moderators(db: DbSession, module_slug: str) -> list[dict]:
|
||||
return out
|
||||
|
||||
|
||||
def grant(db: DbSession, actor: AppUser, *, module_slug: str, user_id: uuid.UUID,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Make someone a moderator of `module_slug`. Idempotent — a double-click is not an error.
|
||||
def grant(db: DbSession, actor: AppUser | None, *, module_slug: str, user_id: uuid.UUID,
|
||||
role: str = USER, ip: str | None = None, audited: bool = True) -> dict:
|
||||
"""Give someone access to `module_slug` as `role`, or change the role they already have.
|
||||
|
||||
Core refuses the hub's own slug, an unknown account and a deactivated one. What is added here is
|
||||
the audit row, which is the permanent record the table deliberately does not keep.
|
||||
Idempotent, and the same call promotes and demotes: core's `grant` is an UPSERT, so a
|
||||
double-click is not an error and "make them a moderator" is one operation rather than a revoke
|
||||
plus a grant. `role` defaults to the LESSER one, so a caller that forgets to name it admits a
|
||||
user and never a moderator.
|
||||
|
||||
Core refuses the hub's own slug, an unknown account, a deactivated one and an unknown role. What
|
||||
is added here is the audit row, which is the permanent record the table deliberately does not
|
||||
keep. `audited=False` is for `marketplace.py`'s bulk reconciliation, which writes ONE row for a
|
||||
whole sweep instead of one per person — the *cause* (an assignment, a membership change) is
|
||||
already audited where it happened.
|
||||
"""
|
||||
_assert_platform()
|
||||
row = _service.grant(db, user_id=user_id, module_slug=module_slug, created_by=actor.id)
|
||||
person = db.get(AppUser, user_id)
|
||||
audit.record(db, action="moderator.grant", entity_type="module_moderator", entity_id=row.id,
|
||||
actor_id=actor.id, detail=f"{module_slug} {person.email if person else user_id}",
|
||||
ip=ip)
|
||||
return {"module_slug": module_slug, "user_id": str(user_id)}
|
||||
row = _service.grant(db, user_id=user_id, module_slug=module_slug, role=role,
|
||||
created_by=actor.id if actor else None)
|
||||
if audited:
|
||||
person = db.get(AppUser, user_id)
|
||||
audit.record(db, action="module_permission.grant", entity_type="module_permission",
|
||||
entity_id=row.id, actor_id=actor.id if actor else None,
|
||||
detail=f"{module_slug} {person.email if person else user_id} {row.role}",
|
||||
ip=ip)
|
||||
return {"module_slug": module_slug, "user_id": str(user_id), "role": row.role}
|
||||
|
||||
|
||||
def revoke(db: DbSession, actor: AppUser, *, module_slug: str, user_id: uuid.UUID,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Remove the row. A 404 when there was none, so a stale screen says so rather than claiming
|
||||
success — the audit log should not record a revocation that revoked nothing."""
|
||||
def revoke(db: DbSession, actor: AppUser | None, *, module_slug: str, user_id: uuid.UUID,
|
||||
ip: str | None = None, audited: bool = True, required: bool = True) -> bool:
|
||||
"""Remove the row — all access to that module. A hard delete; see the module docstring.
|
||||
|
||||
`required` (the default) turns "there was no row" into a 404, so a stale screen says so rather
|
||||
than claiming success: the audit log should not record a revocation that revoked nothing. The
|
||||
reconciliation in `marketplace.py` passes False, because it is removing rows it has just
|
||||
computed are surplus and a race that removed one first is not an error.
|
||||
"""
|
||||
_assert_platform()
|
||||
person = db.get(AppUser, user_id)
|
||||
if not _service.revoke(db, user_id=user_id, module_slug=module_slug):
|
||||
raise NotFoundError("That person does not moderate this module.")
|
||||
audit.record(db, action="moderator.revoke", entity_type="module_moderator", entity_id=None,
|
||||
actor_id=actor.id, detail=f"{module_slug} {person.email if person else user_id}",
|
||||
ip=ip)
|
||||
return {"status": "ok"}
|
||||
if required:
|
||||
raise NotFoundError("That person does not have access to this module.")
|
||||
return False
|
||||
if audited:
|
||||
audit.record(db, action="module_permission.revoke", entity_type="module_permission",
|
||||
entity_id=None, actor_id=actor.id if actor else None,
|
||||
detail=f"{module_slug} {person.email if person else user_id}", ip=ip)
|
||||
return True
|
||||
|
||||
|
||||
def revoke_module(db: DbSession, actor: AppUser, *, module_slug: str,
|
||||
ip: str | None = None) -> int:
|
||||
"""Every moderator of a module, when the module leaves the catalogue. See the module docstring:
|
||||
there is no foreign key to cascade, so without this a recreated slug resurrects its old
|
||||
moderators — silently, and with the people who were revoked in between."""
|
||||
"""Everyone's access to a module, when the module leaves the catalogue. See the module
|
||||
docstring: there is no foreign key to cascade, so without this a recreated slug resurrects its
|
||||
old roster — silently, and with the people who were revoked in between."""
|
||||
if not settings.shares_identity:
|
||||
return 0 # nothing to clean up: the tier does not exist here (see _assert_platform)
|
||||
return 0 # nothing to clean up: the table is inert here (see _assert_platform)
|
||||
removed = _service.revoke_module(db, module_slug=module_slug)
|
||||
if removed:
|
||||
audit.record(db, action="moderator.revoke_all", entity_type="module_moderator",
|
||||
audit.record(db, action="module_permission.revoke_all", entity_type="module_permission",
|
||||
entity_id=None, actor_id=actor.id,
|
||||
detail=f"{module_slug} ({removed})", ip=ip)
|
||||
return removed
|
||||
|
||||
@@ -2,9 +2,15 @@
|
||||
|
||||
In Atrium the tree holds **organizational units only**: a workspace at the top (the organisation),
|
||||
groups and folders beneath it. Modules are catalog rows, not nodes, so there is no leaf kind here.
|
||||
Units matter to the marketplace in one way — a module assigned to a unit is offered to the members
|
||||
of that unit and of every unit below it (see `services/marketplace.py`) — which is why deleting a
|
||||
unit that still has modules assigned is refused.
|
||||
Units matter to the marketplace in one way — a module assigned to a unit admits the members of that
|
||||
unit and of every unit below it (see `services/marketplace.py`) — which is why deleting a unit that
|
||||
still has modules assigned is refused.
|
||||
|
||||
Since that assignment is **materialised** into per-user `module_permission` rows, membership in a
|
||||
unit is no longer only a display question: a grant given or taken away here changes who may open a
|
||||
module. Every caller that writes one therefore ends in `marketplace.sync_members`, and
|
||||
`direct_member_ids` below is what a delete needs in order to say whose membership it is about to
|
||||
cascade away.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,9 +21,9 @@ import uuid
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import NodeKind, NodeRole
|
||||
from ..enums import NodeKind, NodeRole, PrincipalType
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..models import AppUser, ModuleAssignment, Node
|
||||
from ..models import AppUser, ModuleAssignment, Node, PermissionGrant
|
||||
from . import authz
|
||||
|
||||
CONTAINER_KINDS = {NodeKind.workspace, NodeKind.group, NodeKind.folder}
|
||||
@@ -101,6 +107,21 @@ def children(db: DbSession, user: AppUser, parent: Node) -> list[Node]:
|
||||
return [n for n in rows if n.id in allowed]
|
||||
|
||||
|
||||
def direct_member_ids(db: DbSession, node: Node) -> set[uuid.UUID]:
|
||||
"""Who holds a grant ON this unit itself — the membership a delete is about to take with it.
|
||||
|
||||
Only the node's own grants, because `delete` refuses a unit that still has children: there is
|
||||
no sub-tree left to sweep. A grant on an ANCESTOR is untouched by the delete and makes nobody a
|
||||
member of this unit anyway (membership flows up the tree, not down — see
|
||||
`marketplace._covered_units`).
|
||||
"""
|
||||
return set(db.scalars(
|
||||
select(PermissionGrant.principal_id).where(
|
||||
PermissionGrant.node_id == node.id,
|
||||
PermissionGrant.principal_type == PrincipalType.user)
|
||||
).all())
|
||||
|
||||
|
||||
def delete(db: DbSession, user: AppUser, node: Node) -> None:
|
||||
"""Refuse to delete anything that still holds something.
|
||||
|
||||
|
||||
@@ -28,7 +28,28 @@
|
||||
# so as the platform admin the hub built the whole platform's accounts first — owned by that role, and
|
||||
# on a managed provider open to its auto-generated API — with nothing but Alembic's transaction undoing
|
||||
# it. This is the one revision in the family where that matters most. Required: `0001` imports it.
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.10.2
|
||||
#
|
||||
# v0.11.0 answers the second of the owner's three requests — "separate tables for permissions that
|
||||
# control what it can do on what modules". `ModuleModerator` becomes `ModulePermission`: the same
|
||||
# row plus a `role` (`MODULE_ROLES` = user | moderator), so the THIRD answer is the absence of a
|
||||
# row, and that answer is **no access to that module at all**. Before it, anybody with an account
|
||||
# could type `/galena` and be let in; they saw an empty drive, but nothing had refused them, and
|
||||
# "you can see nothing" is not an access decision.
|
||||
#
|
||||
# Renamed with it: `ModerationPolicy.shared_permissions` / `permission_writes_enabled`,
|
||||
# `list_permissions`, and `shared_identity_grants_sql(permission_table=…)`. New: `module_role`,
|
||||
# `may_use` / `assert_may_use` (the guard each MODULE puts in `get_current_user` — Atrium does not,
|
||||
# because every account may open the launcher), `module_roles`, `member_ids`, and a `grant` that
|
||||
# UPSERTs, so promoting and demoting are one call rather than a revoke plus a grant. On that table
|
||||
# the hub holds SELECT/INSERT/UPDATE/DELETE and a module holds SELECT and nothing else: a module
|
||||
# that could write its own permission rows could admit anyone, promote anyone, and promote itself.
|
||||
# Standalone still answers `"user"` for everybody and emits no SQL, so a lone Atrium is unchanged.
|
||||
#
|
||||
# Atrium is the only WRITER of that table. Two revisions carry the bump, and they are different
|
||||
# halves: `0004` (the cutover, which has still never run anywhere) moves it to the shared schema,
|
||||
# and `0006_module_permission.py` renames it in this app's OWN schema — which `0001` being stamped
|
||||
# could never have reached, and which is the `node_kind` mistake the family has made once already.
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.11.0
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
|
||||
@@ -6,7 +6,7 @@ and its own `MODULE_SLUG`. Nothing anywhere reported an error, and nothing could
|
||||
account, a slug crosses the platform boundary twice, and both crossings fail *silently* on a name
|
||||
only the hub believes in.
|
||||
|
||||
* `POST /admin/modules/{slug}/moderators` writes `module_moderator.module_slug` and returns 201.
|
||||
* `POST /admin/modules/{slug}/moderators` writes `module_permission.module_slug` and returns 201.
|
||||
The module reads that table with its own slug, finds nothing, and the person it was granted to
|
||||
has no tier. An administrator delegated a module and nothing happened.
|
||||
* `POST /me/modules/{slug}/tokens` 404s, because the catalogue is what validates the slug before a
|
||||
@@ -37,7 +37,7 @@ DEPLOY = ROOT / "deploy"
|
||||
|
||||
def _hub_slug() -> str:
|
||||
"""Atrium's own slug, read from the field's default rather than written out again here — the
|
||||
hub never appears in its own catalogue, and `module_moderator(user, 'atrium')` is refused."""
|
||||
hub never appears in its own catalogue, and `module_permission(user, 'atrium')` is refused."""
|
||||
from app.config import Settings
|
||||
|
||||
return Settings.model_fields["module_slug"].default
|
||||
@@ -126,7 +126,7 @@ def test_a_checked_out_module_answers_to_the_catalog_slug(slug):
|
||||
|
||||
|
||||
def test_the_hub_is_never_a_catalog_entry():
|
||||
"""Atrium has administrators and no moderators of its own — `module_moderator(user, 'atrium')`
|
||||
"""Atrium has administrators and no moderators of its own — `module_permission(user, 'atrium')`
|
||||
is refused in core — so a catalogue row for the hub would show a *Moderators* pane whose every
|
||||
grant is a 409."""
|
||||
assert _hub_slug() not in _catalog()
|
||||
@@ -152,8 +152,14 @@ class TestTheRowThatIsAlreadyWrong:
|
||||
def test_it_renames_the_catalogue_row_and_the_grants_written_against_it(self, revision):
|
||||
sql = revision._RENAME
|
||||
assert "UPDATE module SET slug = wanted" in sql
|
||||
# The moderator rows are the ones that silently did nothing, so they must move too.
|
||||
assert "UPDATE module_moderator SET module_slug = wanted" in sql
|
||||
# The permission rows are the ones that silently did nothing, so they must move too. The
|
||||
# table is resolved at run time, because which of its two names this database has says only
|
||||
# when it was first migrated — and `0006`, which normalises that, runs AFTER this revision.
|
||||
assert "COALESCE(to_regclass('module_permission'), to_regclass('module_moderator'))" in sql
|
||||
assert "'UPDATE ' || rel || ' SET module_slug = ' || quote_literal(wanted)" in sql
|
||||
# A person granted BOTH slugs keeps one row, at the higher of the two roles: dropping the
|
||||
# stale one in favour of a weaker kept one would quietly demote somebody.
|
||||
assert "SET role = ''moderator''" in sql
|
||||
# Unqualified on purpose: standalone it is this app's table, on the platform the
|
||||
# search_path resolves the shared one. A schema literal here would work in one shape only.
|
||||
assert "dredd" not in sql and "atrium." not in sql
|
||||
@@ -236,8 +242,9 @@ class TestTheRenameSaysSoWhereSomebodyCanReadIt:
|
||||
with caplog.at_level(logging.INFO, logger="alembic.runtime.migration"):
|
||||
revision._report()
|
||||
assert caplog.messages[-1] == (
|
||||
"counsel slug: catalogue row renamed counsel-scorecard -> counsel, 2 moderator "
|
||||
"grant(s) moved, 1 duplicate(s) dropped. The audit log keeps the old name, on purpose.")
|
||||
"counsel slug: catalogue row renamed counsel-scorecard -> counsel, 2 module "
|
||||
"permission row(s) moved, 1 duplicate(s) dropped. The audit log keeps the old name, "
|
||||
"on purpose.")
|
||||
|
||||
def test_it_says_so_when_there_was_nothing_to_rename(self, revision, monkeypatch, caplog):
|
||||
"""A fresh install and a second run both land here, and neither is a failure: the seed now
|
||||
|
||||
@@ -138,7 +138,7 @@ def emitted(revision, monkeypatch):
|
||||
monkeypatch.setattr(revision.op, "execute", lambda sql, *a, **k: statements.append(str(sql)))
|
||||
# create_identity_tables needs a live connection; it is covered by the managed-db job.
|
||||
monkeypatch.setattr(revision, "create_identity_tables",
|
||||
lambda *a, **k: ["app_user", "module_moderator", "session"])
|
||||
lambda *a, **k: ["app_user", "module_permission", "session"])
|
||||
monkeypatch.setattr(revision.op, "get_bind", lambda: None)
|
||||
# `_report` reads the merge's counts back off a live connection, and `op.get_context()` outside
|
||||
# a real migration raises. Offline rendering is the branch that genuinely has neither, so it is
|
||||
@@ -203,8 +203,9 @@ class TestTheRenderedSQL:
|
||||
# model these would be read by every authenticated request in every module.
|
||||
for secret in ("password_hash", "failed_login_count", "locked_until"):
|
||||
assert secret in grants
|
||||
# Revoking a moderator is a hard DELETE, so the hub needs it there and only there.
|
||||
assert "moderator escalation" in grants
|
||||
# Revoking access is a hard DELETE and promoting is an UPDATE, so the hub needs both
|
||||
# there and only there; a module holds SELECT and nothing else.
|
||||
assert "permission escalation" in grants
|
||||
|
||||
def test_deleting_an_account_is_forbidden_rather_than_merely_ungranted(self, emitted):
|
||||
"""Nobody is GRANTED delete, which covers the eight app roles but not the owner — and the
|
||||
@@ -284,14 +285,14 @@ class TestTheCutoverSummaryIsVisible:
|
||||
monkeypatch.setattr(revision.op, "get_context", lambda: types.SimpleNamespace(as_sql=False))
|
||||
monkeypatch.setattr(revision.op, "get_bind", lambda: _one_row(
|
||||
{"own_schema": "atrium", "had_local": True, "accounts": 1, "credentials": 7,
|
||||
"moderators": 0}))
|
||||
"permissions": 0}))
|
||||
with caplog.at_level(logging.INFO, logger="alembic.runtime.migration"):
|
||||
revision._report("dredd")
|
||||
# `caplog.messages` is already interpolated, which is the whole point: the line the operator
|
||||
# reads has to name both schemas and all three counts, not a format string and five values.
|
||||
assert caplog.messages[-1] == (
|
||||
"shared identity: moved 1 account(s), 7 credential(s) and 0 moderator row(s) "
|
||||
"from atrium to dredd")
|
||||
"shared identity: moved 1 account(s), 7 credential(s) and 0 module permission "
|
||||
"row(s) from atrium to dredd")
|
||||
|
||||
def test_it_says_so_when_there_was_nothing_to_move(self, revision, monkeypatch, caplog):
|
||||
"""A fresh install and a second run both land here, and neither is a failure — this
|
||||
@@ -299,7 +300,7 @@ class TestTheCutoverSummaryIsVisible:
|
||||
monkeypatch.setattr(revision.op, "get_context", lambda: types.SimpleNamespace(as_sql=False))
|
||||
monkeypatch.setattr(revision.op, "get_bind", lambda: _one_row(
|
||||
{"own_schema": "atrium", "had_local": False, "accounts": 0, "credentials": 0,
|
||||
"moderators": 0}))
|
||||
"permissions": 0}))
|
||||
with caplog.at_level(logging.INFO, logger="alembic.runtime.migration"):
|
||||
revision._report("dredd")
|
||||
assert "nothing to move" in caplog.messages[-1]
|
||||
@@ -380,19 +381,34 @@ class TestTheGrantsThatNameNobody:
|
||||
|
||||
|
||||
class TestTheTwoTiers:
|
||||
"""ADMINISTRATOR is platform-wide, MODERATOR is one module. Two words, used exactly."""
|
||||
"""ADMINISTRATOR is platform-wide, MODERATOR administers one module, USER may open one — and
|
||||
the fourth answer is no row at all, which is no access. Those words, used exactly."""
|
||||
|
||||
def test_the_api_returns_both_on_a_person(self):
|
||||
def test_the_api_returns_every_tier_on_a_person(self):
|
||||
from app.schemas import UserOut
|
||||
|
||||
out = UserOut(id="x", email="a@b.test", full_name="A", is_admin=False, is_active=True)
|
||||
assert out.moderates == [] # always a list, never absent
|
||||
assert out.modules == {} # always a mapping, never absent
|
||||
|
||||
def test_a_new_account_gets_neither_tier_by_default(self):
|
||||
def test_a_new_account_gets_no_tier_and_no_module_by_default(self):
|
||||
"""The default is an account that can sign in and open nothing. Before `module_permission`
|
||||
there was no way to express that: everybody could open everything."""
|
||||
from app.schemas import UserCreateIn
|
||||
|
||||
body = UserCreateIn(email="a@b.test", full_name="A", password="correct-horse-1")
|
||||
assert body.is_admin is False and body.moderates == []
|
||||
assert body.is_admin is False and body.modules == {}
|
||||
|
||||
def test_a_role_outside_cores_vocabulary_is_refused(self):
|
||||
"""The API, the service, the CHECK constraint and the console all take the roles from
|
||||
dredd-core's `MODULE_ROLES`; a fifth spelling is how a role that exists in three of them
|
||||
gets added."""
|
||||
import uuid
|
||||
|
||||
from app.schemas import PermissionIn
|
||||
|
||||
assert PermissionIn(user_id=uuid.uuid4()).role == "user" # the LESSER one by default
|
||||
with pytest.raises(PydanticValidationError):
|
||||
PermissionIn(user_id=uuid.uuid4(), role="administrator")
|
||||
|
||||
def test_the_hub_guards_its_routes_with_the_platform_wide_tier_only(self):
|
||||
"""A hub route guarded by the narrower tier would let a module's moderator promote
|
||||
@@ -402,15 +418,27 @@ class TestTheTwoTiers:
|
||||
assert hasattr(deps, "require_administrator")
|
||||
assert not hasattr(deps, "require_moderator")
|
||||
|
||||
def test_the_console_and_the_api_use_the_same_two_words(self):
|
||||
def test_the_console_and_the_api_use_the_same_words(self):
|
||||
js = (FRONTEND / "app.js").read_text(encoding="utf-8")
|
||||
assert "Administrator" in js and "Moderator" in js
|
||||
# The console reads the tier from the field the API actually sends.
|
||||
assert "moderates" in js
|
||||
assert "Administrator" in js and "Moderator" in js and "Użytkownik" in js
|
||||
# The console reads someone's standing from the field the API actually sends.
|
||||
assert "u.modules" in js
|
||||
# And it asks the server what shape this deployment is, rather than hard-coding the slug of
|
||||
# the one instance that can never be moderated.
|
||||
# the one instance that never appears in the table.
|
||||
assert "shares_identity" in js and "hub_slug" in js
|
||||
|
||||
def test_the_roster_route_is_still_the_one_three_other_repositories_quote(self):
|
||||
"""The table is `module_permission`; the HTTP path stays `/moderators`. It is a CROSS-REPO
|
||||
contract — Counsel Scorecard's suite asserts this address character for character and the
|
||||
other two quote it in their docs — so renaming it here alone breaks another app's tests and
|
||||
leaves three sets of documentation wrong. Rename it in four repositories at once, or not at
|
||||
all."""
|
||||
from app.main import app
|
||||
|
||||
paths = {r.path for r in app.routes if hasattr(r, "path")}
|
||||
assert "/api/v1/admin/modules/{slug}/moderators" in paths
|
||||
assert "/api/v1/admin/modules/{slug}/moderators/{user_id}" in paths
|
||||
|
||||
def test_the_console_never_promises_a_second_sign_in(self):
|
||||
"""The old launcher copy said each module asks you to sign in separately. It no longer
|
||||
does, and a line telling people to expect a password prompt is how a working single sign-on
|
||||
@@ -423,8 +451,9 @@ class TestTheTwoTiers:
|
||||
"""Atrium's source language is Polish; a standalone UI string with no I18N entry silently
|
||||
stays Polish for an English reader."""
|
||||
js = (FRONTEND / "app.js").read_text(encoding="utf-8")
|
||||
for phrase in ("Moderatorzy", "Moderowane moduły", "Uprawnienia", "Przywróć",
|
||||
"Brak moderatorów.", "Dodaj moderatora", "Rola"):
|
||||
for phrase in ("Dostęp", "Dostęp do modułów", "Uprawnienia", "Przywróć", "Użytkownik",
|
||||
"Nikt nie ma jeszcze dostępu.", "Nadaj dostęp",
|
||||
"Nie ma dostępu do żadnego modułu.", "Rola"):
|
||||
assert re.search(rf"^\s*'{re.escape(phrase)}':\s*'", js, re.M), phrase
|
||||
|
||||
|
||||
@@ -685,8 +714,8 @@ class TestTheRunbookOrdersTheCutover:
|
||||
assert "The audit log keeps the old name, on purpose." in five, (
|
||||
"the one thing no query can tell an operator afterwards")
|
||||
assert "SELECT slug, name FROM atrium.module" in five
|
||||
assert "dredd.module_moderator" in five, (
|
||||
"the half that fails silently is the moderator grant, so it has to be checked too")
|
||||
assert "dredd.module_permission" in five, (
|
||||
"the half that fails silently is the permission row, so it has to be checked too")
|
||||
|
||||
def test_the_modules_phase_names_the_slug_and_the_hub_address(self, book):
|
||||
"""The two settings a module cannot be correct without: the slug a moderator grant is
|
||||
@@ -997,3 +1026,98 @@ class TestTheRollbackPutsBackWhatItRestores:
|
||||
("sygna-migrate", "0002"),
|
||||
("counsel-migrate", "0003_user_role_admin_removed")):
|
||||
assert any(app in line and line.rstrip().endswith(version) for line in stamps), app
|
||||
|
||||
|
||||
class TestTheRenameZeroZeroOneCanNeverReach:
|
||||
"""`0006` exists because `0001` is STAMPED.
|
||||
|
||||
dredd-core v0.11.0 renamed `module_moderator` to `module_permission` and gave it a `role`.
|
||||
`0001` builds every table from `Base.metadata`, so a *fresh* database gets the new shape for
|
||||
free — and no database that already exists ever will, because `0001` will not run again. That
|
||||
is precisely the `node_kind` failure the family has made once already, and its symptoms are all
|
||||
late: a backup sweep, a restore and the cutover all die on `relation "module_permission" does
|
||||
not exist`.
|
||||
|
||||
Editing the cutover was not enough on its own either: `0004` is a no-op standalone and is
|
||||
stamped there all the same, so a standalone box records the cutover as applied while its own
|
||||
schema still holds the old name — or, migrated before dredd-core v0.10.0, no such table at all.
|
||||
"""
|
||||
|
||||
@pytest.fixture(scope="class")
|
||||
def revision(self):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0006", BACKEND / "alembic" / "versions" / "0006_module_permission.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
@pytest.fixture(scope="class")
|
||||
def sql(self, revision):
|
||||
from dredd_core.identity import MODULE_ROLES
|
||||
from sqlalchemy import CheckConstraint
|
||||
|
||||
check = next(str(c.sqltext)
|
||||
for c in revision.Base.metadata.tables["module_permission"].constraints
|
||||
if isinstance(c, CheckConstraint) and "module_slug" in str(c.sqltext))
|
||||
return revision._MIGRATE.format(
|
||||
role_values=revision._quoted(", ".join(f"'{r}'" for r in MODULE_ROLES)),
|
||||
slug_check=revision._quoted(check), shares_identity="false")
|
||||
|
||||
def test_it_follows_the_current_head(self, revision):
|
||||
assert (revision.revision, revision.down_revision) == ("0006", "0005")
|
||||
|
||||
def test_it_carries_no_sequence_a_driver_would_eat(self, revision, sql):
|
||||
"""The family's rule for a rendered template, and it applies to the COMMENTS too: `text()`
|
||||
scans the whole statement, and a comment quoting this very rule has already killed a
|
||||
migration on its first live run elsewhere in this family."""
|
||||
binds = re.compile(r"(?<![:\w$])(?::(?!:))([\w$]+)(?![:\w$])")
|
||||
for statement in (sql, revision._SUMMARY):
|
||||
assert not binds.findall(statement), statement[:120]
|
||||
assert "%" not in statement
|
||||
|
||||
def test_every_existing_row_becomes_a_moderator(self, sql):
|
||||
"""The old table could say only one thing, so setting the renamed rows to the column's own
|
||||
default would silently demote every moderator on the instance."""
|
||||
assert "SET role = ''moderator''" in sql
|
||||
assert "DEFAULT ''user''" in sql # ... but a NEW row is a user, never a moderator
|
||||
|
||||
def test_it_renames_the_constraints_and_indexes_too(self, revision):
|
||||
"""Cosmetic to PostgreSQL, load-bearing to everything else: a later revision that drops a
|
||||
constraint by the name the metadata gives it needs the two to agree."""
|
||||
for name in ("pk_module_permission", "uq_module_permission_user_module",
|
||||
"ix_module_permission_module_slug", "fk_module_permission_user_id_app_user",
|
||||
"fk_module_permission_created_by_app_user", "ck_module_permission_slug"):
|
||||
assert name in revision._MIGRATE, name
|
||||
|
||||
def test_the_role_vocabulary_comes_from_core(self, sql):
|
||||
"""Four places have to agree — the model, the CHECK, the API and the console — so the
|
||||
constraint is rendered from `MODULE_ROLES` rather than typed out again."""
|
||||
assert "CHECK (role IN (''user'', ''moderator''))" in sql
|
||||
|
||||
def test_it_never_builds_a_local_copy_on_a_platform(self, revision):
|
||||
"""The one trap in this revision. An unqualified CREATE lands in THIS app's schema, which is
|
||||
first on the search_path — and on the platform that is the shadow copy `assert_identity_schema`
|
||||
exists to catch. Guarded twice, because the two guards fail differently: a platform box whose
|
||||
migrator's search_path does not carry the identity schema would see no table at all."""
|
||||
platform = revision._MIGRATE.format(role_values="x", slug_check="y", shares_identity="true")
|
||||
assert "platform CONSTANT boolean := true" in platform
|
||||
assert "IF platform OR anywhere IS NOT NULL THEN" in platform
|
||||
|
||||
def test_offline_rendering_creates_nothing(self, revision, monkeypatch):
|
||||
"""`alembic upgrade --sql` connects to nothing, so the catalogue check cannot be made. An
|
||||
unconditional CREATE in that script would fail on every database that already has the
|
||||
table, and `IF NOT EXISTS` would be worse: unqualified, it builds the shadow copy."""
|
||||
monkeypatch.setattr(revision.op, "get_context",
|
||||
lambda: types.SimpleNamespace(as_sql=True))
|
||||
assert revision._wants_create() is False
|
||||
|
||||
def test_it_says_which_of_the_four_things_it_did(self, revision, monkeypatch, caplog):
|
||||
monkeypatch.setattr(revision.op, "get_context",
|
||||
lambda: types.SimpleNamespace(as_sql=False))
|
||||
monkeypatch.setattr(revision.op, "get_bind", lambda: _one_row(
|
||||
{"own_schema": "atrium", "action": "renamed", "promoted": 3}))
|
||||
with caplog.at_level(logging.INFO, logger="alembic.runtime.migration"):
|
||||
revision._report()
|
||||
assert caplog.messages[-1] == (
|
||||
"module permissions: renamed atrium.module_moderator to module_permission and kept 3 "
|
||||
"existing row(s) as moderator")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""DB-free tests for the marketplace's rules: addresses, settings, membership, console parity."""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
@@ -11,6 +12,7 @@ from app.errors import ValidationError
|
||||
from app.services import marketplace, settings
|
||||
|
||||
FRONTEND = pathlib.Path(__file__).resolve().parents[2] / "frontend"
|
||||
BACKEND = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class TestAddresses:
|
||||
@@ -296,3 +298,65 @@ class TestSlugify:
|
||||
from app.services.nodes import slugify
|
||||
|
||||
assert slugify(name) == slug
|
||||
|
||||
|
||||
class TestTheShortcutStaysTrue:
|
||||
"""Assigning a whole unit is a shortcut, and a shortcut that silently goes stale is worse than
|
||||
no shortcut.
|
||||
|
||||
`module_permission` is the one table that decides access, so an assignment has to be
|
||||
materialised into per-user rows — and the whole question that raises is what happens when
|
||||
somebody joins the department a week later. The answer is *re-materialise on every membership
|
||||
change*, which is only an answer if every hub write path that can change the outcome actually
|
||||
calls it. That is what these check: not that the rule is right (`TestMembership` above does
|
||||
that), but that nothing can change membership behind the reconciliation's back.
|
||||
"""
|
||||
|
||||
def _source(self, *names: str) -> str:
|
||||
return "\n".join(inspect.getsource(getattr(marketplace, n)) for n in names)
|
||||
|
||||
@pytest.mark.parametrize("fn", [
|
||||
"create_module", # a new `everyone` module reaches everyone from the moment it exists
|
||||
"update_module", # availability IS the access decision now
|
||||
"add_assignment",
|
||||
"remove_assignment",
|
||||
"decide", # approving an access request writes an assignment
|
||||
"revoke_access", # they may still be reached by a unit, and then they keep `user`
|
||||
])
|
||||
def test_every_catalogue_path_that_changes_who_may_enter_reconciles(self, fn):
|
||||
assert "sync_module(" in self._source(fn), fn
|
||||
|
||||
@pytest.mark.parametrize("path, fn", [
|
||||
("app/routers/nodes.py", "upsert_grant"), # joining a unit
|
||||
("app/routers/nodes.py", "remove_grant"), # leaving one
|
||||
("app/routers/nodes.py", "delete"), # a delete cascades the grants away
|
||||
("app/routers/users.py", "create_user"), # a new person picks up the `everyone` modules
|
||||
])
|
||||
def test_every_membership_path_reconciles_the_people_it_touched(self, path, fn):
|
||||
"""Membership is a permission grant on a unit, and the hub is its only writer — which is the
|
||||
whole reason re-materialising on change is possible at all without a background job."""
|
||||
source = (BACKEND / path).read_text(encoding="utf-8")
|
||||
body = re.search(rf"^def {fn}\(.*?(?=\n@|\n\ndef |\Z)", source, re.S | re.M)
|
||||
assert body, f"{path} no longer defines {fn}()"
|
||||
assert "sync_members(" in body.group(0), f"{path}:{fn} does not re-materialise"
|
||||
|
||||
def test_a_roster_grant_records_the_assignment_behind_it(self):
|
||||
"""The reconciliation is a full set-difference, so it deletes every row no assignment
|
||||
accounts for. Admitting somebody on a module's own page without one would therefore be
|
||||
undone by the next unrelated change to that module — a silent, delayed revocation, which is
|
||||
exactly what this design exists to prevent."""
|
||||
assert "_pin_assignment(" in self._source("grant_access")
|
||||
|
||||
def test_a_deactivated_account_is_out_of_the_reconciliation_on_both_sides(self):
|
||||
"""Not an optimisation: core refuses to grant a deactivated person, so they can never be
|
||||
added — and if they could be removed instead, switching somebody off and on again would
|
||||
silently strip every module they moderated."""
|
||||
source = self._source("sync_module")
|
||||
assert source.count("& active") == 2
|
||||
|
||||
def test_the_console_says_it_is_not_a_one_time_grant(self):
|
||||
"""The copy is the other half of the promise: an administrator assigning a department has
|
||||
to know whether it keeps up with the department."""
|
||||
js = (FRONTEND / "app.js").read_text(encoding="utf-8")
|
||||
assert "To nie jest jednorazowe nadanie" in js
|
||||
assert "This is not a one-time bulk grant" in js
|
||||
|
||||
@@ -79,7 +79,7 @@ python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
|
||||
```
|
||||
|
||||
- `--identity-schema` / `--identity-owner` are the **shared identity schema**: the neutral schema
|
||||
where `app_user`, `session` and `module_moderator` live so that a person has ONE account across
|
||||
where `app_user`, `session` and `module_permission` live so that a person has ONE account across
|
||||
the whole family. Atrium's migrator owns it, so **Atrium's run is the one that creates it**; each
|
||||
module's run then grants only its own two roles `USAGE` and never creates a schema for someone
|
||||
else, which is what keeps provisioning per-app and stops any script having to enumerate all eight
|
||||
|
||||
@@ -373,7 +373,7 @@ That runs `alembic upgrade head` and then the seed. Revision `0004` does, in one
|
||||
|
||||
1. **Refuses** unless `dredd` exists and `atrium_migrator` owns it. (If you skipped section 3 you
|
||||
get a named error here, not a half-migrated database.)
|
||||
2. Creates `app_user`, `session` and `module_moderator` **in `dredd`**, schema-qualified.
|
||||
2. Creates `app_user`, `session` and `module_permission` **in `dredd`**, schema-qualified.
|
||||
3. Copies every Atrium account and session across, keeping their UUIDs. Refuses if an account with
|
||||
the same email is already there under a *different* id.
|
||||
4. Counts `permission_grant` rows whose `principal_id` names nobody, and answers the two cases
|
||||
@@ -383,7 +383,8 @@ That runs `alembic upgrade head` and then the seed. Revision `0004` does, in one
|
||||
is what used to make a second attempt refuse for ever.
|
||||
5. Re-points all fourteen foreign keys at `dredd.app_user`. PostgreSQL validates each one as it is
|
||||
added, so a value that failed to move fails loudly here.
|
||||
6. Drops the local `app_user`, `session` and `module_moderator` — **after** proving every local
|
||||
6. Drops the local `app_user`, `session` and `module_permission` (and `module_moderator`, the
|
||||
name the table had before dredd-core v0.11.0) — **after** proving every local
|
||||
account is present in the shared store, and never unqualified.
|
||||
7. Grants each of the eight roles its tier, verifies the result, and raises if it did not take.
|
||||
8. Installs a trigger making `DELETE FROM dredd.app_user` raise.
|
||||
@@ -392,7 +393,7 @@ Expect, in the container's own output, one line between `Running upgrade 0003 ->
|
||||
revision:
|
||||
|
||||
```
|
||||
INFO [alembic.runtime.migration] shared identity: moved 1 account(s), N credential(s) and 0 moderator row(s) from atrium to dredd
|
||||
INFO [alembic.runtime.migration] shared identity: moved 1 account(s), N credential(s) and 0 module permission row(s) from atrium to dredd
|
||||
```
|
||||
|
||||
**That line is the cutover**, and it is worth knowing why it is a log line rather than a `NOTICE`
|
||||
@@ -449,10 +450,10 @@ indistinguishable from a count that was never taken — so they are captured whe
|
||||
and logged from Python. Expect a second line, after the one above:
|
||||
|
||||
```
|
||||
INFO [alembic.runtime.migration] counsel slug: catalogue row renamed counsel-scorecard -> counsel, 0 moderator grant(s) moved, 0 duplicate(s) dropped. The audit log keeps the old name, on purpose.
|
||||
INFO [alembic.runtime.migration] counsel slug: catalogue row renamed counsel-scorecard -> counsel, 0 module permission row(s) moved, 0 duplicate(s) dropped. The audit log keeps the old name, on purpose.
|
||||
```
|
||||
|
||||
Both counts are **nought on this box**, and that is correct: a moderator grant cannot exist until
|
||||
Both counts are **nought on this box**, and that is correct: a module permission cannot exist until
|
||||
the cutover you are running right now. The sentence on the end is the part worth reading — the
|
||||
rename writes no `module.update` audit row, deliberately, because that log is append-only and
|
||||
`module.create` under the old name is a true statement about the past. This line is the only place
|
||||
@@ -465,12 +466,12 @@ Then confirm the **outcome** as well, which a query can, once the migration has
|
||||
```bash
|
||||
docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
|
||||
SELECT slug, name FROM atrium.module ORDER BY slug;
|
||||
SELECT module_slug, count(*) FROM dredd.module_moderator GROUP BY 1 ORDER BY 1;
|
||||
SELECT module_slug, role, count(*) FROM dredd.module_permission GROUP BY 1, 2 ORDER BY 1, 2;
|
||||
SQL
|
||||
```
|
||||
|
||||
`counsel` must appear in the first and `counsel-scorecard` in neither. The second is empty on this
|
||||
box today — moderator grants can only exist after this cutover — and it is there because it is the
|
||||
box today — module permissions can only exist after this cutover — and it is there because it is the
|
||||
half that fails silently: a grant still addressed to `counsel-scorecard` gives its holder nothing,
|
||||
in a table Counsel reads under its own name.
|
||||
|
||||
@@ -884,7 +885,7 @@ Each module needs, in this order:
|
||||
that genuinely lives on another host, and a value set here would mean the derivation underneath
|
||||
it never runs in production — which is how a fix stops being a fix;
|
||||
3. `MODULE_SLUG` matching the slug in Atrium's catalogue — `galena`, `sygna`, `counsel`. It is the
|
||||
name a moderator grant is addressed by, and a module that answers to a different one reads an
|
||||
name a module permission is addressed by, and a module that answers to a different one reads an
|
||||
empty table and reports the person as having no tier, with no error on either side (that is
|
||||
exactly what `counsel-scorecard` did; see section 5). Each module's default is already its own
|
||||
slug, so this is a check, not an edit;
|
||||
@@ -1048,9 +1049,9 @@ possible message about the role the design trusts most. Each module is checked w
|
||||
A passing report names the allowlist explicitly, and that is the sentence worth reading:
|
||||
|
||||
```
|
||||
[OK] identity shadow: atrium holds no copy of app_user, module_moderator, session
|
||||
[OK] identity shadow: atrium holds no copy of app_user, module_permission, session
|
||||
[OK] identity atrium_app: in dredd: USAGE, no CREATE, owns nothing;
|
||||
app_user: SELECT, INSERT, UPDATE; module_moderator: SELECT, INSERT, DELETE;
|
||||
app_user: SELECT, INSERT, UPDATE; module_permission: SELECT, INSERT, UPDATE, DELETE;
|
||||
session: SELECT, INSERT, UPDATE; nothing else in dredd
|
||||
```
|
||||
|
||||
@@ -1059,7 +1060,7 @@ and after a module has moved, the other half of it:
|
||||
```
|
||||
[OK] identity galena_app: app_user: SELECT (id, created_at, updated_at, email, full_name, is_admin,
|
||||
is_active), nothing at all on password_hash/failed_login_count/locked_until;
|
||||
module_moderator: SELECT; session: SELECT, UPDATE (last_seen_at, expires_at, revoked_at)
|
||||
module_permission: SELECT; session: SELECT, UPDATE (last_seen_at, expires_at, revoked_at)
|
||||
```
|
||||
|
||||
That is the whole security argument in two lines: a module may read who exists and write three
|
||||
|
||||
Vendored
+2
-2
@@ -40,7 +40,7 @@ DB_MAX_OVERFLOW=10
|
||||
|
||||
# ── one platform, one account ───────────────────────────────────────────────────────────────────
|
||||
# The shared identity schema. Set it (IDENTITY_SCHEMA=dredd) and `app_user`, `session` and
|
||||
# `module_moderator` live in one neutral schema every module reads, so a person has ONE account
|
||||
# `module_permission` live in one neutral schema every module reads, so a person has ONE account
|
||||
# across the family and signs in once, here. Empty is the standalone deployment: Atrium keeps those
|
||||
# tables in its own schema and nothing else changes.
|
||||
#
|
||||
@@ -59,7 +59,7 @@ IDENTITY_SCHEMA=
|
||||
# IDENTITY_MIGRATOR_ROLES=galena_migrator,sygna_migrator,counsel_migrator
|
||||
IDENTITY_READER_ROLES=
|
||||
IDENTITY_MIGRATOR_ROLES=
|
||||
# This app's slug on the platform, which is also the HUB's slug: `module_moderator(user, 'atrium')`
|
||||
# This app's slug on the platform, which is also the HUB's slug: `module_permission(user, 'atrium')`
|
||||
# is refused, because the hub has administrators and its administration is not delegable one module
|
||||
# at a time.
|
||||
MODULE_SLUG=atrium
|
||||
|
||||
Vendored
+1
-1
@@ -46,7 +46,7 @@ CORS_ALLOW_ORIGINS=
|
||||
#
|
||||
# IDENTITY_SCHEMA names the neutral schema where the platform's accounts live. With it set, this
|
||||
# module READS identity and never writes it: its database role holds a column-restricted SELECT on
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_moderator. It cannot
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_permission. It cannot
|
||||
# create an account, elevate one, or mint a credential -- the enforcement is that grant, not a
|
||||
# missing screen. SESSION_COOKIE_NAME must match every other app's, because one origin plus one
|
||||
# cookie plus one session row IS the single sign-on; there is no handoff protocol to configure.
|
||||
|
||||
Vendored
+1
-1
@@ -51,7 +51,7 @@ PLUGINS_DIR=
|
||||
#
|
||||
# IDENTITY_SCHEMA names the neutral schema where the platform's accounts live. With it set, this
|
||||
# module READS identity and never writes it: its database role holds a column-restricted SELECT on
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_moderator. It cannot
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_permission. It cannot
|
||||
# create an account, elevate one, or mint a credential -- the enforcement is that grant, not a
|
||||
# missing screen. SESSION_COOKIE_NAME must match every other app's, because one origin plus one
|
||||
# cookie plus one session row IS the single sign-on; there is no handoff protocol to configure.
|
||||
|
||||
Vendored
+1
-1
@@ -49,7 +49,7 @@ SECRET_KEY=
|
||||
#
|
||||
# IDENTITY_SCHEMA names the neutral schema where the platform's accounts live. With it set, this
|
||||
# module READS identity and never writes it: its database role holds a column-restricted SELECT on
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_moderator. It cannot
|
||||
# app_user, SELECT plus a three-column UPDATE on session, and SELECT on module_permission. It cannot
|
||||
# create an account, elevate one, or mint a credential -- the enforcement is that grant, not a
|
||||
# missing screen. SESSION_COOKIE_NAME must match every other app's, because one origin plus one
|
||||
# cookie plus one session row IS the single sign-on; there is no handoff protocol to configure.
|
||||
|
||||
+117
-63
@@ -460,23 +460,29 @@ const I18N = {
|
||||
'Co najmniej 10 znaków. Zdarzenie trafia do dziennika wraz z tym, kto je wykonał.': 'At least 10 characters. The audit log records the reset and who made it.',
|
||||
'Hasło ustawione. Sesje tej osoby zostały zakończone.': 'Password set. That person’s sessions have ended.',
|
||||
'Jedno konto na osobę, wspólne dla wszystkich modułów. Logowanie odbywa się tutaj; moduły tylko odczytują tę samą sesję.': 'One account per person, shared by every module. Signing in happens here; the modules only read the same session.',
|
||||
// the two administration tiers. Administrator = platform-wide, Moderator = exactly one module.
|
||||
// The owner chose those two words, so they are used verbatim in both languages and in the API.
|
||||
// the three tiers. Administrator = platform-wide, Moderator = exactly one module, User = may
|
||||
// open exactly one module. The owner chose those words, so they are used verbatim in both
|
||||
// languages, in the API and in the table. The fourth answer is no row at all: no access.
|
||||
'Rola': 'Role',
|
||||
'Uprawnienia': 'Permissions',
|
||||
'Moderatorzy': 'Moderators',
|
||||
'Moderowane moduły': 'Moderated modules',
|
||||
'Dodaj moderatora': 'Add a moderator',
|
||||
'Brak moderatorów.': 'No moderators.',
|
||||
'Nie moderuje żadnego modułu.': 'Moderates no module.',
|
||||
'Użytkownik': 'User',
|
||||
'Dostęp': 'Access',
|
||||
'Dostęp do modułów': 'Module access',
|
||||
'Nadaj dostęp': 'Grant access',
|
||||
'Nikt nie ma jeszcze dostępu.': 'Nobody has access yet.',
|
||||
'Nie ma dostępu do żadnego modułu.': 'Has access to no module.',
|
||||
'Odbierz': 'Revoke',
|
||||
'Moderator zarządza tym modułem — jego ustawieniami, kopiami zapasowymi i dostępem wewnątrz niego. Nie ma żadnych uprawnień w pozostałych modułach.': 'A moderator administers this module: its settings, its backups and access inside it. They have no permissions in any other module.',
|
||||
'To co innego niż przypisanie: przypisanie decyduje o tym, czy moduł pojawi się na liście aplikacji, a nie o tym, kto nim zarządza.': 'That is not the same as an assignment: an assignment decides whether the module appears in someone’s apps, not who administers it.',
|
||||
'Moderator zarządza jednym modułem i nie ma uprawnień w pozostałych.': 'A moderator administers one module and has no permissions in the others.',
|
||||
'Administrator zarządza każdym modułem niezależnie od tej listy.': 'An administrator administers every module, whatever this list says.',
|
||||
'Bez wpisu na tej liście nie da się wejść do modułu. Użytkownik z niego korzysta; moderator dodatkowo nim zarządza — jego ustawieniami, kopiami zapasowymi i dostępem wewnątrz niego — i nie ma żadnych uprawnień w pozostałych modułach.': 'Without an entry on this list nobody can enter the module. A user works in it; a moderator also administers it — its settings, its backups and access inside it — and has no permissions in any other module.',
|
||||
'Przypisanie wyżej mówi, dlaczego ktoś ma ten moduł; ta lista mówi, kto go ma naprawdę. Administrator wchodzi wszędzie i nie potrzebuje wpisu.': 'The assignment above says why somebody has this module; this list says who really has it. An administrator reaches everything and needs no entry.',
|
||||
'Moduł przypisany do jednostki dostają jej członkowie i członkowie jednostek podrzędnych.': 'A module assigned to an organizational unit goes to its members and to the members of every unit below it.',
|
||||
'To nie jest jednorazowe nadanie: lista dostępu jest odświeżana przy każdej zmianie członkostwa, więc osoba, która dołączy do jednostki za tydzień, też dostanie moduł — a osoba, która odejdzie, straci go.': 'This is not a one-time bulk grant: the access list is re-made on every membership change, so somebody who joins the unit a week from now gets the module too — and somebody who leaves loses it.',
|
||||
'Dostęp cofnięty. Osoba nadal należy do jednostki, która ma ten moduł, więc zachowuje zwykły dostęp.': 'Access revoked. They are still in an organizational unit that has this module, so they keep ordinary access.',
|
||||
'Bez wpisu na tej liście osoba nie wejdzie do modułu. Moderator dodatkowo zarządza jednym modułem i nie ma uprawnień w pozostałych.': 'Without an entry on this list they cannot enter the module. A moderator also administers one module and has no permissions in the others.',
|
||||
'Administrator wchodzi do każdego modułu i zarządza nim niezależnie od tej listy.': 'An administrator enters and administers every module, whatever this list says.',
|
||||
'Pełne uprawnienia na całej platformie: wszystkie moduły i sam Atrium. Ostatniego administratora nie da się odebrać ani dezaktywować.': 'Full permissions across the whole platform: every module, and Atrium itself. The last administrator can be neither demoted nor deactivated.',
|
||||
'To twoje własne konto. Po odebraniu sobie roli nie przywrócisz jej samodzielnie.': 'This is your own account. Once you take the role off yourself you cannot put it back.',
|
||||
'Konto działa od razu we wszystkich modułach. Obie role są domyślnie wyłączone — nadaje się je świadomie.': 'The account works in every module straight away. Both roles are off by default: each is a deliberate act.',
|
||||
'Konto samo w sobie nie otwiera żadnego modułu — dostęp nadaje się poniżej albo później. Rola administratora jest domyślnie wyłączona.': 'An account on its own opens no module: access is granted below, or later. The administrator role is off by default.',
|
||||
'Jako użytkownik. Moderatora nadaje się na stronie danego modułu.': 'As a user. A moderator is appointed on that module’s own page.',
|
||||
'Rola jest domyślnie wyłączona — nadaje się ją świadomie.': 'The role is off by default: granting it is a deliberate act.',
|
||||
// admin settings
|
||||
'Nazwa instancji': 'Instance name',
|
||||
@@ -561,6 +567,10 @@ const REQ_LABEL = { pending: 'Oczekuje', approved: 'Zatwierdzony', declined: 'Od
|
||||
const KIND_LABEL = { workspace: 'Przestrzeń', group: 'Dział', folder: 'Zespół' };
|
||||
const ACCESS_LABEL = { viewer: 'podgląd', editor: 'edycja', approver: 'zatwierdzanie', manager: 'zarządzanie' };
|
||||
const ROLE_LABEL = { viewer: 'Członek', editor: 'Edytor', approver: 'Zatwierdzający', manager: 'Zarządca jednostki' };
|
||||
/* What somebody may do in ONE module — the `role` on their `module_permission` row. The third
|
||||
answer is the absence of a row, which is no entry at all, so it has no label here. Keep in step
|
||||
with dredd-core's MODULE_ROLES; the server validates against that tuple and so does a CHECK. */
|
||||
const MODULE_ROLE_LABEL = { user: 'Użytkownik', moderator: 'Moderator' };
|
||||
const PROBE_ERR = {
|
||||
timeout: 'przekroczono czas', unreachable: 'brak połączenia', redirect: 'przekierowanie (nie śledzone)',
|
||||
'http error': 'błąd HTTP', 'no health address': 'brak adresu stanu', 'unsupported address': 'nieobsługiwany adres',
|
||||
@@ -628,14 +638,15 @@ async function restore() {
|
||||
|
||||
const isAdmin = () => !!(state.user && state.user.is_admin);
|
||||
/* Deployment shape, from /config — not a setting anyone can change here. `sharesIdentity()` is false
|
||||
on a standalone Atrium, where there are no modules sharing its accounts and therefore no such
|
||||
thing as a moderator: the whole tier is hidden rather than offered and then refused. `hubSlug()`
|
||||
is this instance's own slug, which can never be moderated (the hub has administrators), so it
|
||||
comes out of every module picker. */
|
||||
on a standalone Atrium, where there are no modules sharing its accounts and therefore nothing to
|
||||
be admitted to: the whole per-module list is hidden rather than offered and then refused.
|
||||
`hubSlug()` is this instance's own slug, which never appears in the table at all — every account
|
||||
may open the launcher, and the hub has administrators rather than moderators — so it comes out
|
||||
of every module picker. */
|
||||
const sharesIdentity = () => !!state.config.shares_identity;
|
||||
const hubSlug = () => state.config.hub_slug || '';
|
||||
/* Modules someone can actually be made a moderator of: the catalogue minus the hub itself. */
|
||||
const moderatable = () => (state.modules || []).filter((m) => m.slug !== hubSlug());
|
||||
/* Modules somebody can actually be given access to: the catalogue minus the hub itself. */
|
||||
const grantable = () => (state.modules || []).filter((m) => m.slug !== hubSlug());
|
||||
|
||||
async function afterLogin() {
|
||||
showApp();
|
||||
@@ -651,7 +662,7 @@ async function afterLogin() {
|
||||
|
||||
async function refreshShared() {
|
||||
state.stale = false; // before the reads: a write that lands meanwhile marks it again
|
||||
// The catalogue is cached for the people pickers and the moderator chips; any write may have
|
||||
// The catalogue is cached for the people pickers and the access chips; any write may have
|
||||
// renamed or removed a module, so it is dropped here and read again on the next screen needing it.
|
||||
// `_catalogue` is the same list as an ordinary user may see it (see ensureCatalogue), and goes for
|
||||
// the same reason.
|
||||
@@ -1295,7 +1306,7 @@ function saveModuleNew() {
|
||||
}
|
||||
|
||||
async function viewAdminModule(C, slug) {
|
||||
const [m, units, mods] = await Promise.all([
|
||||
const [m, units, people] = await Promise.all([
|
||||
api('GET', '/admin/modules/' + enc(slug)), api('GET', '/tree/containers'),
|
||||
sharesIdentity() ? api('GET', `/admin/modules/${enc(slug)}/moderators`) : [], ensureUsers()]);
|
||||
setCrumb([{ label: 'Administracja' }, { label: 'Moduły', href: '#/admin/modules' }, { label: m.name, data: true }]);
|
||||
@@ -1306,15 +1317,17 @@ async function viewAdminModule(C, slug) {
|
||||
<td class="shrink"><button class="btn sm danger" onclick="removeAssignment('${esc(m.slug)}','${esc(a.id)}')" title="Usuń">${svg(ICN.x, 14)}</button></td>
|
||||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Brak przypisań.</div>';
|
||||
|
||||
/* The moderator roster, directly under Przypisania because that is where an administrator is
|
||||
already thinking about who this module is for. The two answer different questions, though, and
|
||||
the copy under the heading says so rather than letting the page imply they are one thing. */
|
||||
const moderators = mods.length ? `<div class="tablewrap"><table><tbody>${mods.map((x) => `<tr>
|
||||
/* Who may actually open this module, and at what role — the `module_permission` rows the module
|
||||
itself reads at its own door. Directly under Przypisania because that is where an administrator
|
||||
is already thinking about who the module is for, and the copy says how the two relate: an
|
||||
assignment is the reason, this list is the effect. */
|
||||
const roster = people.length ? `<div class="tablewrap"><table><tbody>${people.map((x) => `<tr>
|
||||
<td>${dat(x.full_name)}<div class="mono tiny faint">${dat(x.email)}</div>
|
||||
${x.is_admin ? '<span class="chip">Administrator</span>' : ''}${x.is_active ? '' : '<span class="chip err">nieaktywny</span>'}</td>
|
||||
<td class="shrink">${roleSelect(`pr-${esc(x.user_id)}`, x.role, `setPermission('${esc(m.slug)}','${esc(x.user_id)}', this.value)`)}</td>
|
||||
<td class="faint tiny">${esc(fmtDateTime(x.created_at))}</td>
|
||||
<td class="shrink"><button class="btn sm danger" onclick="removeModerator('${esc(m.slug)}','${esc(x.user_id)}')" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Brak moderatorów.</div>';
|
||||
<td class="shrink"><button class="btn sm danger" onclick="revokePermission('${esc(m.slug)}','${esc(x.user_id)}')" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Nikt nie ma jeszcze dostępu.</div>';
|
||||
|
||||
C.innerHTML = `<div class="card mhead">${moduleIcon(m, 64)}
|
||||
<div class="mhtxt"><h2>${dat(m.name)}</h2><div class="mono tiny faint">${esc(m.slug)}</div>
|
||||
@@ -1334,7 +1347,8 @@ async function viewAdminModule(C, slug) {
|
||||
</div>
|
||||
<div class="card"><h3>Przypisania<span class="n">${m.assignments.length}</span></h3>
|
||||
${m.availability !== 'selected' ? '<div class="banner warn">Przypisania działają tylko przy dostępności „Wybrani”.</div>' : ''}
|
||||
<div class="faint tiny" style="margin-bottom:10px">Moduł przypisany do jednostki trafia do jej członków i do członków jednostek podrzędnych.</div>
|
||||
<div class="faint tiny" style="margin-bottom:10px">Moduł przypisany do jednostki dostają jej członkowie i członkowie jednostek podrzędnych.</div>
|
||||
<div class="faint tiny" style="margin-bottom:10px">To nie jest jednorazowe nadanie: lista dostępu jest odświeżana przy każdej zmianie członkostwa, więc osoba, która dołączy do jednostki za tydzień, też dostanie moduł — a osoba, która odejdzie, straci go.</div>
|
||||
${assigned}
|
||||
<div class="assign">
|
||||
<div class="row"><select id="asUnit">${unitOptions(units)}</select>
|
||||
@@ -1343,13 +1357,14 @@ async function viewAdminModule(C, slug) {
|
||||
<button class="btn sm" onclick="addAssignment('${esc(m.slug)}','user')">Przypisz osobę</button></div>
|
||||
</div>
|
||||
</div>
|
||||
${!sharesIdentity() || m.slug === hubSlug() ? '' : `<div class="card"><h3>Moderatorzy<span class="n">${mods.length}</span></h3>
|
||||
<div class="faint tiny" style="margin-bottom:10px">Moderator zarządza tym modułem — jego ustawieniami, kopiami zapasowymi i dostępem wewnątrz niego. Nie ma żadnych uprawnień w pozostałych modułach.</div>
|
||||
<div class="faint tiny" style="margin-bottom:10px">To co innego niż przypisanie: przypisanie decyduje o tym, czy moduł pojawi się na liście aplikacji, a nie o tym, kto nim zarządza.</div>
|
||||
${moderators}
|
||||
${!sharesIdentity() || m.slug === hubSlug() ? '' : `<div class="card"><h3>Dostęp<span class="n">${people.length}</span></h3>
|
||||
<div class="faint tiny" style="margin-bottom:10px">Bez wpisu na tej liście nie da się wejść do modułu. Użytkownik z niego korzysta; moderator dodatkowo nim zarządza — jego ustawieniami, kopiami zapasowymi i dostępem wewnątrz niego — i nie ma żadnych uprawnień w pozostałych modułach.</div>
|
||||
<div class="faint tiny" style="margin-bottom:10px">Przypisanie wyżej mówi, dlaczego ktoś ma ten moduł; ta lista mówi, kto go ma naprawdę. Administrator wchodzi wszędzie i nie potrzebuje wpisu.</div>
|
||||
${roster}
|
||||
<div class="assign">
|
||||
<div class="row"><select id="mdUser">${userOptions()}</select>
|
||||
<button class="btn sm" onclick="addModerator('${esc(m.slug)}')">${svg(ICN.plus, 14)}<span>Dodaj moderatora</span></button></div>
|
||||
${roleSelect('mdRole', 'user')}
|
||||
<button class="btn sm" onclick="grantPermission('${esc(m.slug)}')">${svg(ICN.plus, 14)}<span>Nadaj dostęp</span></button></div>
|
||||
</div>
|
||||
</div>`}
|
||||
<div class="card"><h3>Stan</h3>
|
||||
@@ -1377,14 +1392,34 @@ function removeAssignment(slug, id) {
|
||||
mutate('DELETE', `/admin/modules/${enc(slug)}/assignments/${enc(id)}`);
|
||||
}
|
||||
|
||||
/* The MODERATOR tier: this module's own administration, and nothing outside it. Both writes go
|
||||
through mutate(), so they get the toast, the re-render and the one error path for free. */
|
||||
function addModerator(slug) {
|
||||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`, () => ({ user_id: $('mdUser').value }));
|
||||
/* Who may open one module, and at what role. Every write goes through mutate(), so they get the
|
||||
toast, the re-render and the one error path for free. */
|
||||
const roleSelect = (id, role, onchange) => `<select id="${esc(id)}"${onchange ? ` onchange="${onchange}"` : ''}>${
|
||||
Object.keys(MODULE_ROLE_LABEL).map((k) =>
|
||||
`<option value="${esc(k)}" ${k === role ? 'selected' : ''}>${esc(MODULE_ROLE_LABEL[k])}</option>`).join('')}</select>`;
|
||||
|
||||
function grantPermission(slug) {
|
||||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`,
|
||||
() => ({ user_id: $('mdUser').value, role: $('mdRole').value }));
|
||||
}
|
||||
|
||||
function removeModerator(slug, userId) {
|
||||
mutate('DELETE', `/admin/modules/${enc(slug)}/moderators/${enc(userId)}`);
|
||||
/* Promotion and demotion are the SAME call: the server's grant is an upsert, so the row stays and
|
||||
with it the record of who admitted this person and when. */
|
||||
function setPermission(slug, userId, role) {
|
||||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`, { user_id: userId, role });
|
||||
}
|
||||
|
||||
/* Revoking may not empty the row: if a unit assignment still reaches this person they keep
|
||||
ordinary access and merely stop being a moderator. Only the server knows which happened, so the
|
||||
toast says what it did rather than claiming a revocation the re-render appears to undo. */
|
||||
function revokePermission(slug, userId) {
|
||||
guard(async () => {
|
||||
const out = await api('DELETE', `/admin/modules/${enc(slug)}/moderators/${enc(userId)}`);
|
||||
toast(out.still_a_member
|
||||
? 'Dostęp cofnięty. Osoba nadal należy do jednostki, która ma ten moduł, więc zachowuje zwykły dostęp.'
|
||||
: 'Zapisano.');
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
function deleteModule(slug) {
|
||||
@@ -1515,12 +1550,15 @@ function removeMember(id, userId) {
|
||||
/* ── administration: users ──────────────────────────────────────────────── */
|
||||
/* ONE admin pane. Every account on the platform is made, elevated and switched off here, because
|
||||
the hub is the only writer of identity — a module's database role cannot create or change an
|
||||
account at all. Two tiers, two words, used exactly: ADMINISTRATOR is platform-wide, MODERATOR
|
||||
administers one module. An administrator is a moderator of everything, so the row shows whichever
|
||||
is the stronger claim rather than both. */
|
||||
account at all. Three words, used exactly: ADMINISTRATOR is platform-wide, MODERATOR administers
|
||||
one module, USER may open one. An administrator reaches everything, so the row shows that rather
|
||||
than a list; for everyone else it shows the modules they may open, and names the moderated ones.
|
||||
No chips at all means an account that can sign in and open nothing, which is a real state and
|
||||
the default for a new person. */
|
||||
const tierChips = (u) => (u.is_admin
|
||||
? '<span class="chip">Administrator</span>'
|
||||
: (u.moderates || []).map((s) => `<span class="chip">Moderator: ${dat(moduleName(s))}</span>`).join(''))
|
||||
: Object.entries(u.modules || {}).map(([s, role]) => `<span class="chip">${
|
||||
role === 'moderator' ? 'Moderator: ' : ''}${dat(moduleName(s))}</span>`).join(''))
|
||||
|| '<span class="faint tiny">—</span>';
|
||||
|
||||
/* The catalogue, read once for the pickers and the chip labels. A slug always renders, even for a
|
||||
@@ -1563,8 +1601,8 @@ async function openUserAccess(id) {
|
||||
await ensureModules();
|
||||
const u = (state.users || []).find((x) => x.id === id);
|
||||
if (!u) { toast('Nie znaleziono użytkownika.'); return; }
|
||||
const mods = u.moderates || [];
|
||||
const free = moderatable().filter((m) => !mods.includes(m.slug));
|
||||
const held = u.modules || {};
|
||||
const free = grantable().filter((m) => !(m.slug in held));
|
||||
const self = u.id === state.user.id;
|
||||
|
||||
/* The platform-wide tier. The checkbox writes on change rather than on a Save button, because
|
||||
@@ -1574,22 +1612,26 @@ async function openUserAccess(id) {
|
||||
<div class="faint tiny">Pełne uprawnienia na całej platformie: wszystkie moduły i sam Atrium. Ostatniego administratora nie da się odebrać ani dezaktywować.</div>
|
||||
${self && u.is_admin ? '<div class="banner warn">To twoje własne konto. Po odebraniu sobie roli nie przywrócisz jej samodzielnie.</div>' : ''}`;
|
||||
|
||||
/* The per-module tier, which only exists when this Atrium is the hub of a platform. On a
|
||||
standalone install the whole section is absent rather than present and refused. */
|
||||
const roster = mods.length
|
||||
? `<div class="tablewrap"><table><tbody>${mods.map((s) => `<tr>
|
||||
/* Which modules this person may open, and at what role — the same `module_permission` rows a
|
||||
module's own page lists, seen from the other side. Only exists when this Atrium is the hub of
|
||||
a platform; on a standalone install the whole section is absent rather than present and
|
||||
refused. */
|
||||
const roster = Object.keys(held).length
|
||||
? `<div class="tablewrap"><table><tbody>${Object.entries(held).map(([s, role]) => `<tr>
|
||||
<td>${dat(moduleName(s))}<div class="mono tiny faint">${dat(s)}</div></td>
|
||||
<td class="shrink"><button class="btn sm danger" onclick="removeModeratorFor('${esc(s)}','${esc(id)}')" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||||
<td class="shrink">${roleSelect(`ua-${esc(s)}`, role, `setModuleFor('${esc(s)}','${esc(id)}', this.value)`)}</td>
|
||||
<td class="shrink"><button class="btn sm danger" onclick="removeModuleFor('${esc(s)}','${esc(id)}')" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||||
</tr>`).join('')}</tbody></table></div>`
|
||||
: '<div class="faint tiny">Nie moderuje żadnego modułu.</div>';
|
||||
: '<div class="faint tiny">Nie ma dostępu do żadnego modułu.</div>';
|
||||
const picker = free.length
|
||||
? `<div class="row" style="margin-top:12px">
|
||||
<select id="uaModule">${free.map((m) => `<option value="${esc(m.slug)}">${esc(m.name)}</option>`).join('')}</select>
|
||||
<button class="btn sm primary" onclick="addModeratorFor('${esc(id)}')">${svg(ICN.plus, 14)}<span>Dodaj</span></button></div>`
|
||||
${roleSelect('uaRole', 'user')}
|
||||
<button class="btn sm primary" onclick="addModuleFor('${esc(id)}')">${svg(ICN.plus, 14)}<span>Dodaj</span></button></div>`
|
||||
: '';
|
||||
const moderator = !sharesIdentity() ? '' : `<h4 class="minor">Moderowane moduły</h4>
|
||||
<div class="faint tiny" style="margin-bottom:6px">Moderator zarządza jednym modułem i nie ma uprawnień w pozostałych.</div>
|
||||
${u.is_admin ? '<div class="faint tiny">Administrator zarządza każdym modułem niezależnie od tej listy.</div>' : ''}
|
||||
const moderator = !sharesIdentity() ? '' : `<h4 class="minor">Dostęp do modułów</h4>
|
||||
<div class="faint tiny" style="margin-bottom:6px">Bez wpisu na tej liście osoba nie wejdzie do modułu. Moderator dodatkowo zarządza jednym modułem i nie ma uprawnień w pozostałych.</div>
|
||||
${u.is_admin ? '<div class="faint tiny">Administrator wchodzi do każdego modułu i zarządza nim niezależnie od tej listy.</div>' : ''}
|
||||
${roster}${picker}`;
|
||||
|
||||
modal('Uprawnienia', u.email, administrator + moderator,
|
||||
@@ -1608,12 +1650,18 @@ function setAdministrator(id, isAdmin) {
|
||||
{ reopen: () => _reopenUserAccess(id) });
|
||||
}
|
||||
|
||||
function addModeratorFor(id) {
|
||||
mutate('POST', `/admin/modules/${enc($('uaModule').value)}/moderators`, () => ({ user_id: id }),
|
||||
function addModuleFor(id) {
|
||||
mutate('POST', `/admin/modules/${enc($('uaModule').value)}/moderators`,
|
||||
() => ({ user_id: id, role: $('uaRole').value }),
|
||||
{ reopen: () => _reopenUserAccess(id) });
|
||||
}
|
||||
|
||||
function removeModeratorFor(slug, id) {
|
||||
function setModuleFor(slug, id, role) {
|
||||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`, { user_id: id, role },
|
||||
{ reopen: () => _reopenUserAccess(id) });
|
||||
}
|
||||
|
||||
function removeModuleFor(slug, id) {
|
||||
mutate('DELETE', `/admin/modules/${enc(slug)}/moderators/${enc(id)}`, undefined,
|
||||
{ reopen: () => _reopenUserAccess(id) });
|
||||
}
|
||||
@@ -1671,16 +1719,20 @@ function saveUserPassword(id) {
|
||||
|
||||
async function openUserNew() {
|
||||
await ensureModules();
|
||||
const choices = moderatable();
|
||||
const choices = grantable();
|
||||
/* Both tiers on the creation form, so an administrator can finish the job in one dialog instead
|
||||
of creating the person and then visiting a module page. Both default to off. */
|
||||
/* Access is off by default and granted as USER here — promoting somebody is a deliberate act on
|
||||
that module's own page, one person at a time. Modules with availability „Wszyscy” arrive
|
||||
anyway, without being named: the server materialises those rows as the account is created. */
|
||||
const tiers = `<label class="check"><input type="checkbox" id="unAdmin" /> <span>Administrator</span></label>
|
||||
<div class="faint tiny">${sharesIdentity()
|
||||
? 'Konto działa od razu we wszystkich modułach. Obie role są domyślnie wyłączone — nadaje się je świadomie.'
|
||||
? 'Konto samo w sobie nie otwiera żadnego modułu — dostęp nadaje się poniżej albo później. Rola administratora jest domyślnie wyłączona.'
|
||||
: 'Rola jest domyślnie wyłączona — nadaje się ją świadomie.'}</div>`
|
||||
+ (sharesIdentity() && choices.length ? `<label class="field">Moderowane moduły
|
||||
+ (sharesIdentity() && choices.length ? `<label class="field">Dostęp do modułów
|
||||
<select id="unMods" multiple size="${Math.min(5, Math.max(2, choices.length))}">${
|
||||
choices.map((m) => `<option value="${esc(m.slug)}">${esc(m.name)}</option>`).join('')}</select></label>` : '');
|
||||
choices.map((m) => `<option value="${esc(m.slug)}">${esc(m.name)}</option>`).join('')}</select></label>
|
||||
<div class="faint tiny">Jako użytkownik. Moderatora nadaje się na stronie danego modułu.</div>` : '');
|
||||
modal('Nowy użytkownik', '',
|
||||
`<label class="field">Imię i nazwisko<input id="unFull" maxlength="200" /></label>
|
||||
<label class="field">E-mail<input id="unEmail" type="email" /></label>
|
||||
@@ -1694,8 +1746,10 @@ function saveUserNew() {
|
||||
mutate('POST', '/users', () => ({
|
||||
full_name: $('unFull').value, email: $('unEmail').value,
|
||||
password: $('unPass').value, is_admin: $('unAdmin').checked,
|
||||
// Absent on a standalone install, where the field is not rendered at all.
|
||||
moderates: $('unMods') ? Array.from($('unMods').selectedOptions).map((o) => o.value) : [],
|
||||
// slug -> role. Absent on a standalone install, where the field is not rendered at all.
|
||||
modules: $('unMods')
|
||||
? Object.fromEntries(Array.from($('unMods').selectedOptions).map((o) => [o.value, 'user']))
|
||||
: {},
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user