Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
639dc38ca1
|
||
|
|
616e3a8135
|
||
|
|
077d9abbe8
|
||
|
|
746b5ee5d0 | ||
|
|
97fe594130
|
||
|
|
645f782e42
|
||
|
|
ebd56d6ca4
|
||
|
|
c2a5c3265f
|
||
|
|
775e5ea7bd
|
||
|
|
25a8516400 | ||
|
|
5154cd202a | ||
|
|
76931a1861 |
No files matched your search
@@ -57,7 +57,7 @@ workflows:
|
||||
branches:
|
||||
ignore: /.*/
|
||||
tags:
|
||||
only: [/v.*/]
|
||||
only: [/^v\d+\.\d+\.\d+$/]
|
||||
|
||||
publish_hotfix_release:
|
||||
jobs:
|
||||
|
||||
@@ -4,6 +4,38 @@ All notable changes to this project are documented here. Format: [Keep a Changel
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added (policy editor, phase 5b: DESIGN.md section 12.4)
|
||||
- **Edit Policy** record action on groups and on policies (feature `POLICIES`, permission `authentik.policies.manage`): a standard streamed-ETL action whose step shows the `AUTHENTIK_POLICY_EDITOR` widget (Next UI). Review parses the submitted document (fail closed), regenerates it in canonical form with the round-trip check, refuses new resources this app does not define, applies the subset rule to the permissions it adds, and lists what is added and removed. Result merge-patches `qqq.io/policy` into the group's current attributes (removed when empty). Optional second-person approval (`policyTwoPersonApproval`).
|
||||
- **`PolicyCatalog`**: every app, table, process (hidden record actions included), report and protected widget a policy can grant, with the actions QQQ checks, grouped by app. Its permission names join the permission catalog.
|
||||
- **`authentik_policy`** local table (one row per group; field-level audit is the change history; DDL in `docs/schema.sql`), in the nav under Access and as a child list on the group.
|
||||
- Widget `authentikPolicyEditor` (type `AUTHENTIK_POLICY_EDITOR`): the catalog and the group's live document, with a flag when it was changed in Authentik since the last save in QQQ.
|
||||
|
||||
### Added (policies, phase 5a: DESIGN.md section 12, docs/POLICY-FORMAT.md)
|
||||
- **Policy documents** (IAM-style statements) on Authentik groups: `PolicyParser` (fails closed: unknown spec or version, non-Allow effect, unknown action, bad resource or malformed JSON grant nothing), `PolicyGenerator` (canonical form with a round-trip check), `PolicyFormat` and the config `policySpec`, `policyVersion`, `policyAttribute`, `policyClaim`, `policyTwoPersonApproval`.
|
||||
- **Runtime**: `AuthentikPolicyClaimMapper` (reads the `qqq_policy` claim from the ID token or access token; `applySecurityKeys` hook for record locks) and `PolicyPermissions.fromClaims` for a host's own customizer. `AuthentikGroupPermissionMapper` also adds the claim, and the group graph and `EffectivePermissionResolver` read each group's `qqq.io/policy`, so effective permissions, the subset rule and the last-admin check see policy grants. An invalid policy on a group is listed as malformed.
|
||||
- **Blueprint example** for the scope mapping that puts the merged policies into the token, pinned by `PolicyClaimMappingIT` on Authentik 2026.8.3.
|
||||
|
||||
### Added (v1: full user lifecycle and group/permission management, phases 2-3)
|
||||
- **Writes through the Authentik API**, behind the features `USERS`, `GROUPS`, `MEMBERSHIP`, `CREDENTIALS` and `SESSIONS` (read-only stays the default; `readOnly` is a hard kill switch). Every change goes through `AuthentikAdmin`: it plans against live Authentik data (the guardrails of DESIGN.md 5.4), audits first, calls Authentik, posts a `custom_qqq_admin_action` event naming the operator, and finishes the audit row. `AuthentikActionUtil.write` needs a `WriteAuthorization`, which only `AuthentikGuard.authorize` can mint.
|
||||
- **Actions** (table and record actions with Review and Result steps; none in the nav): Create User, Invite User, Edit User, Deactivate User, Reactivate User, Add To Group, Remove From Group, Send Password Reset Email, Reset MFA, Revoke App Passwords, Revoke Sessions, Create Group, Edit Group, Edit Permissions And App Access, Add Members, Remove Members, Cancel Invitation, Approve And Apply, Reject.
|
||||
- **Safety**: the subset (no escalation) rule evaluated from the operator's live groups; protected accounts and superuser groups; no self-edits; last-administrator protection; reasons; typed confirmations (and a typed count above 25 targets); a 100-target cap; stale checks by fingerprint (groups have no `last_updated`); attribute edits merge only the `qqq.io/*` keys into the current attributes; two-person approval for granting `authentik.*`.
|
||||
- **Local tables** `authentik_admin_action` (append-only audit) and `authentik_approval_request` (DDL in `docs/schema.sql`), on the new `localBackendName`.
|
||||
- **Read tables** `authentik_application`, `authentik_policy_binding`, `authentik_blueprint`, `authentik_role`, `authentik_token` (metadata only, never a key) and `authentik_invitation`. Sub-tables appear as child lists on their parents; the nav lists only the main tables.
|
||||
- **Home**: the `authentikHome` widget (needs attention, people, groups and permissions, recent changes, connection).
|
||||
- Config: `localBackendName` (replaces `mirrorBackendName`), `twoPersonApproval`, `schedulerName`, `linkPrefix`.
|
||||
- Tests: an in-memory Authentik for the rules, process tests through `RunProcessAction`, and write contract tests on Authentik 2026.8.3 (`QbitWriteContractIT`, including the recovery email arriving in Mailpit).
|
||||
|
||||
### Security
|
||||
- `bootstrapOperators` (emails) is replaced by `bootstrapOperatorSubjects` (env `AUTHENTIK_QBIT_BOOTSTRAP_SUBJECTS`): users can change their own email in Authentik, so an email must never confer identity permissions. A bootstrap operator is now matched on the token `sub` (email-looking subs ignored) or, with a verified email, on the single active Authentik user with that email whose pk or uuid is configured. Spoofed, duplicate or unverified emails are denied; entries containing `@` fail validation. The admin service uses the same rule.
|
||||
|
||||
### Fixed
|
||||
- Count reported no distinct count, so a process Review showed no total; group lists now include member pks (member counts were 0).
|
||||
- Spec: multi-value filters are repeated plain names (`type=a&type=b`), never `type[]=a` (which Authentik silently ignores); stale role-state, `check_access`, re-parenting-risk, private-repo and backend-name wording corrected (spec revision 4).
|
||||
|
||||
### Not in this release
|
||||
- The Authentik webhook, the local mirror tables and reconcile, the access-matrix widget, snapshot export, RBAC role management (phase 4) and the Alerts producer integration. `MIRROR`, `WEBHOOK`, `ACCESS_MATRIX`, `SNAPSHOT_EXPORT` and `RBAC` are refused by config validation.
|
||||
|
||||
|
||||
### Changed
|
||||
- **Permissions renamed `identity.*` → `authentik.*`** (same suffixes; owner naming rule, 2026-10-12; spec #1065 amended). Legacy names are reported as unknown and never granted. The old names are kept as `@Deprecated` `IdentityPermission.LEGACY_PREFIX`/`LEGACY_WILDCARD`/`getLegacyShortName()`. Update the `qqq.io/permissions` group attributes before deploying; see [UPGRADE.md](UPGRADE.md).
|
||||
- **Table names are lowercase snake_case with the `authentik_` prefix** (owner naming rule, 2026-10-12): `authentik_user`, `authentik_group`, `authentik_group_member`, `authentik_session`, `authentik_event` (were `authentikUser`, ...). New `AuthentikQBitConfig.applyTablePrefix` and `toSnakeCase`; apps, widgets, the backend and processes keep camelCase names (`authentikAdmin`, `authentikApi`). The old names are kept as `@Deprecated` `AuthentikTables.LEGACY_*_TABLE_NAME` constants. See [UPGRADE.md](UPGRADE.md).
|
||||
|
||||
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code when working with code in this reposi
|
||||
|
||||
## Project Overview
|
||||
|
||||
**QBit Authentik**: a QQQ QBit to manage Authentik users, groups, memberships and group-granted QQQ permissions from a QQQ app. Authentik's database is the source of truth; the qbit reads live and (from phase 2) writes through the Authentik API. Design: `docs/DESIGN.md` (approved spec, QRun-IO/qqq#1065). Current line: 0.1 = read-only (phases 0-1).
|
||||
**QBit Authentik**: a QQQ QBit to manage Authentik users, groups, memberships and group-granted QQQ permissions from a QQQ app. Authentik's database is the source of truth; the qbit reads live and writes through the Authentik API (never its DB). Design: `docs/DESIGN.md` (approved spec, QRun-IO/qqq#1065). Current line: 0.1 = the full user lifecycle and group/permission management (phases 0-3), read-only by default.
|
||||
|
||||
## Build Commands
|
||||
|
||||
@@ -29,14 +29,17 @@ CI=true ./mvnw verify # + contract ITs: Authentik 2026.8.3 server+worker, Post
|
||||
- `AuthentikRuntime` (registry by API backend name): config, `TokenBucketThrottle` (10 rps, burst 20 by default), `AuthentikGuard`, `AuthentikFilterMapper`, response cache, and the table-name to `AuthentikTableSpec` map.
|
||||
- `client/AuthentikActionUtil extends BaseAPIActionUtil` is the only code that talks to Authentik.
|
||||
- `doQuery`/`doCount`/`doGet` use page/page_size paging (max 100). Key-only filters become per-id GETs. The user scope and type filters are applied server-side and re-checked per record.
|
||||
- Writes go to the guard, which refuses them in 0.1.
|
||||
- The generic table writes (`doInsert`/`doUpdate`/`doDelete`) are refused. The only way to change Authentik is `write(WriteAuthorization, ...)`, and only `AuthentikGuard.authorize(AdminAction)` mints a `WriteAuthorization` (an architecture test pins that only `AuthentikAdmin` calls it).
|
||||
- `execute()` is the single request loop: throttle, bearer header, 429/5xx retry, error mapping, logging.
|
||||
- `send()` is the test seam (`FixtureActionUtil`, `QbitReadContractIT.RecordingActionUtil`).
|
||||
- `client/AuthentikTables` maps tables to the pinned schema (users, groups, sessions, events), plus the **virtual** `groupMember` table, which `AuthentikActionUtil.memberships()` serves from a group, a user, or a bounded sweep. `client/AuthentikApiSurface` lists every operation and parameter used. `SchemaDriftTest` and `SchemaDriftIT` check that surface.
|
||||
- `client/AuthentikFilterMapper` maps a QQQ filter to Authentik params, or rejects it with a `QUserFacingException`. It never filters client-side.
|
||||
- `security/AuthentikGuard` handles read and write permission checks, the user scope, and protected-account detection. `security/IdentityPermission` is the `identity.*` catalog (session form `<name>.hasAccess`).
|
||||
- `security/AuthentikGuard` handles read permission checks, write authorization, the user scope, and protected-account detection. `security/IdentityPermission` is the `authentik.*` catalog (session form `<name>.hasAccess`).
|
||||
- `admin/AuthentikAdmin` plans and performs every change (`AdminAction`, `AdminRequest`, `AdminPlan`): the guardrails of DESIGN.md 5.4 run against LIVE Authentik data and the operator's LIVE groups (never the session claim) at plan time and again at execute time; the audit row (`AdminActionAuditor`, table `authentik_admin_action`) is written BEFORE the call and the call is not made if that fails; then the change, then an Authentik `custom_qqq_admin_action` event. `AuthentikSafety` holds the pure rules (subset rule helpers, last-admin, fingerprints). Granting `authentik.*` queues an `authentik_approval_request` for a second person (`approve`/`reject`).
|
||||
- `processes/AuthentikProcesses`: every action is a standard streamed-ETL table or record action (details screen, Review = dry run, Result), never in the nav. The ETL defaults to full validation, so the Review screen already holds the dry-run lines. The preview step's record count is NOT carried to later steps (and a client count needs `setDistinctCount`), so steps count targets themselves.
|
||||
- `app/`: `AuthentikHomeData`/`AuthentikHomeView` (the single home widget, HTML with no tables) and `AuthentikRelations` (joins, child-list widgets and sections so sub-tables appear on their parents, not in the nav).
|
||||
- `permissions/GroupGraph` + `EffectivePermissionResolver` (pure) turn groups and their ancestors into QQQ permissions. The util caches the graph for `groupCacheTtlSeconds` and uses it for derived fields.
|
||||
- `drift/AuthentikDriftReport` holds the drift checks, using only the service account's read permissions. It is rendered by `metadata/AuthentikDriftReportWidgetRenderer`, a standard TABLE widget gated by `identity.admin`.
|
||||
- `drift/AuthentikDriftReport` holds the drift checks, using only the service account's read permissions. It is rendered by `metadata/AuthentikDriftReportWidgetRenderer`, a standard TABLE widget gated by `authentik.admin`.
|
||||
|
||||
## Invariants (do not break)
|
||||
|
||||
@@ -46,6 +49,8 @@ CI=true ./mvnw verify # + contract ITs: Authentik 2026.8.3 server+worker, Post
|
||||
- Multi-value params are repeated plain names (`type=a&type=b`). Authentik silently ignores `type[]=`.
|
||||
- The user detail GET takes no `include_*` params. Groups have no `last_updated` in 2026.8.
|
||||
- `check_access?for_user=` is useless for the service account: it is silently evaluated for the caller. Never use it for other users.
|
||||
- Nothing but `AuthentikAdmin` may call `AuthentikActionUtil.write`. Every write needs a reason, passes the guard, and is audited first.
|
||||
- `recovery_email` needs the brand to have a recovery flow ("No recovery flow set." otherwise), the role's `add_user` (DRF maps POST to add) plus `reset_user_password`, and `view_emailstage` on the stage.
|
||||
- The service account must never be a superuser and never hold `enable_group_superuser`, token-key, impersonate or delete permissions.
|
||||
|
||||
## Code Style
|
||||
|
||||
@@ -1,50 +1,73 @@
|
||||
# QBit Authentik
|
||||
|
||||
A QQQ QBit for managing [Authentik](https://goauthentik.io) identities (users, groups, memberships, and the QQQ permissions a group grants) from a QQQ app. **Authentik stays the source of truth.** The qbit reads Authentik live and will write through the Authentik API. Changes made in the Authentik admin UI are equally valid.
|
||||
A QQQ QBit to manage [Authentik](https://goauthentik.io) identities from a QQQ app: **the full user lifecycle, and groups with the permissions they grant**. Authentik stays the source of truth. The qbit reads Authentik live and writes through the Authentik API, never its database. Changes made in the Authentik admin UI are equally valid, and the qbit never overwrites them blindly.
|
||||
|
||||
Design: [`docs/DESIGN.md`](docs/DESIGN.md) (copy of the approved spec, QRun-IO/qqq#1065). Phase 0 owner steps: [`docs/PHASE0-OWNER-CHECKLIST.md`](docs/PHASE0-OWNER-CHECKLIST.md). Status and linked PRs: [`docs/STATUS.md`](docs/STATUS.md).
|
||||
Design: [`docs/DESIGN.md`](docs/DESIGN.md) (the approved spec, QRun-IO/qqq#1065). Status: [`docs/STATUS.md`](docs/STATUS.md). Phase 0 owner steps: [`docs/PHASE0-OWNER-CHECKLIST.md`](docs/PHASE0-OWNER-CHECKLIST.md). Table DDL: [`docs/schema.sql`](docs/schema.sql).
|
||||
|
||||
## Status
|
||||
## What you get
|
||||
|
||||
`0.1.0-SNAPSHOT`, the **read-only** release line (phases 0 and 1 of DESIGN.md section 11):
|
||||
|
||||
| Available | Not yet (refused by config validation) |
|
||||
| | |
|
||||
|---|---|
|
||||
| `READ`: Authentik tables over the API | `MEMBERSHIP`, `GROUPS`, `USERS`, `CREDENTIALS`, `SESSIONS` writes (phases 2-3) |
|
||||
| `MIRROR` (phase 1) | `RBAC` (phase 4), `WEBHOOK`, `SNAPSHOT_EXPORT` |
|
||||
| **People** | Create a user (Authentik emails them a link to set their own password; QQQ never sets or sees one), invite, edit, deactivate and reactivate, send a password reset email, reset MFA, revoke app passwords, revoke sessions, cancel invitations. No hard delete. |
|
||||
| **Groups and permissions** | Create and edit groups (parents), add and remove members, and edit the QQQ permissions and app sign-in a group grants (`qqq.io/permissions`, `qqq.io/app-access` on the Authentik group). |
|
||||
| **Safety** | Operators can only grant permissions they hold themselves. No self-edits. Break-glass, the service account and superusers are untouchable, and superuser groups cannot be managed. The last administrator cannot be removed. Granting `authentik.*` needs a second person. Destructive actions need a reason and a typed confirmation. A change made in the Authentik UI after you opened a form is detected, not overwritten. |
|
||||
| **Audit** | Every attempt is a row in `authentik_admin_action` (written before the call), and Authentik's own event log gets a `custom_qqq_admin_action` event naming the human operator. |
|
||||
| **Screens** | A home dashboard (what needs attention, people, groups, recent changes, connection), standard tables with full record screens, and every action as a table or record action with the usual Review and Result steps. Nothing is in the nav except the main tables. |
|
||||
|
||||
Every write is refused by `AuthentikGuard` in this release.
|
||||
Everything is a standard QQQ table, action and widget, so it works in any QQQ UI and over the QQQ API.
|
||||
|
||||
## Usage
|
||||
|
||||
```java
|
||||
AuthentikQBitConfig config = new AuthentikQBitConfig()
|
||||
.withBaseUrl("https://auth.example.com") // host root; /api/v3 is appended
|
||||
.withApiToken("${env.AUTHENTIK_API_TOKEN}") // service-account token, resolved by the qbit
|
||||
.withAppKey("my-app-admin") // service account: qqq-my-app-admin-idadmin
|
||||
.withApplicationsInScope(List.of("my-app-prod"));
|
||||
.withBaseUrl("https://auth.example.com") // host root; /api/v3 is appended
|
||||
.withApiToken("${env.AUTHENTIK_API_TOKEN}") // service-account token, resolved by the qbit
|
||||
.withAppKey("my-app-admin") // service account: qqq-my-app-admin-idadmin
|
||||
.withFeatures(EnumSet.of(READ, USERS, GROUPS, MEMBERSHIP, CREDENTIALS, SESSIONS))
|
||||
.withLocalBackendName("rdbms") // audit trail and approval requests (see docs/schema.sql)
|
||||
.withRecoveryEmailStage("my-recovery-email") // Authentik email stage (name or uuid)
|
||||
.withInvitationFlow("my-enrollment"); // optional: enables invitations
|
||||
|
||||
new AuthentikQBitProducer().withQBitConfig(config).produce(qInstance);
|
||||
```
|
||||
|
||||
This produces:
|
||||
- an API backend `authentikApi`
|
||||
- read-only tables `authentik_user`, `authentik_group`, `authentik_group_member`, `authentik_session` and `authentik_event`
|
||||
- the Identity Drift Report widget
|
||||
- an app `authentikAdmin`, labelled "Identity", that hosts can nest, for example under Admin
|
||||
Read-only is the default (`features` = `READ`). `readOnly=true` is a hard kill switch that refuses every write whatever the features say.
|
||||
|
||||
Access is controlled by QQQ permissions:
|
||||
### What it produces
|
||||
|
||||
| Permission (held as `<name>.hasAccess`) | Grants |
|
||||
| | |
|
||||
|---|---|
|
||||
| `authentik.users.read` | the Identity app and its tables |
|
||||
| `authentik.audit.read` | sensitive fields and tables |
|
||||
| API backend | `authentikApi` |
|
||||
| Main tables (nav) | `authentik_user`, `authentik_invitation`, `authentik_group`, `authentik_application`, `authentik_approval_request`, `authentik_admin_action` |
|
||||
| Child lists (on their parents, not in the nav) | `authentik_group_member`, `authentik_session`, `authentik_token` (metadata only, never a key), `authentik_event`, `authentik_policy_binding`, `authentik_role`, `authentik_blueprint` |
|
||||
| App and home | `authentikAdmin` (label "Identity", hosts may nest it) with the `authentikHome` widget and the drift report |
|
||||
| Actions | Create User, Invite User, Edit User, Deactivate User, Reactivate User, Add To Group, Remove From Group, Send Password Reset Email, Reset MFA, Revoke App Passwords, Revoke Sessions, Create Group, Edit Group, Edit Permissions And App Access, Add Members, Remove Members, Cancel Invitation, Approve And Apply, Reject |
|
||||
|
||||
The full `authentik.*` set is in DESIGN.md section 5.2.
|
||||
### Permissions
|
||||
|
||||
QQQ permissions, held as `<name>.hasAccess`, granted through the group attribute `qqq.io/permissions` and read by `AuthentikGroupPermissionMapper`:
|
||||
|
||||
| Permission | Grants |
|
||||
|---|---|
|
||||
| `authentik.users.read` | the Identity app, home, users, groups, applications, bindings, roles, blueprints |
|
||||
| `authentik.users.manage` | create, invite, edit, deactivate, reactivate users; cancel invitations |
|
||||
| `authentik.groups.manage` | create and edit groups |
|
||||
| `authentik.memberships.manage` | add and remove members (subset rule) |
|
||||
| `authentik.permissions.manage` | edit a group's permissions and app access (subset rule) |
|
||||
| `authentik.credentials.reset` | password reset email, reset MFA, revoke app passwords |
|
||||
| `authentik.sessions.revoke` | revoke sessions |
|
||||
| `authentik.audit.read` | sessions, tokens, events, the audit trail, sensitive fields |
|
||||
| `authentik.approve` | approve or reject a second person's request |
|
||||
| `authentik.admin` | the drift report |
|
||||
| `authentik.roles.manage` | reserved (role management is phase 4) |
|
||||
|
||||
`authentik.*` grants all of them.
|
||||
|
||||
### Authentik side
|
||||
|
||||
The qbit's API token belongs to a dedicated Authentik service account whose role holds only the read permissions it needs. The bootstrap blueprint that creates it lives in the host's GitOps repo. One host's version, which the contract tests exercise, is [`src/test/resources/blueprints/kof22-identity-bootstrap.yaml`](src/test/resources/blueprints/kof22-identity-bootstrap.yaml); treat it as an example, not something to apply as is.
|
||||
The qbit's API token belongs to a dedicated Authentik service account whose role holds only the permissions it needs (DESIGN.md section 5.1), created by a bootstrap blueprint in the host's GitOps repository. It is never a superuser and never holds `enable_group_superuser`, token-key, impersonate or delete permissions. [`src/test/resources/blueprints/kof22-identity-bootstrap.yaml`](src/test/resources/blueprints/kof22-identity-bootstrap.yaml) is one host's worked example.
|
||||
|
||||
Write features need these in the role, on top of the read set: `add_user`, `change_user`, `reset_user_password`, `add_group`, `change_group`, `add_user_to_group`, `remove_user_from_group`, `view_token`, `delete_token`, `delete_authenticatedsession`, invitation `view`/`add`/`delete` (if you use invitations), `authentik_flows.view_flow` (to find the invitation flow by slug), and `view_emailstage` on the recovery stage. The contract tests grant exactly this list.
|
||||
|
||||
## Adopting in another app
|
||||
|
||||
@@ -52,22 +75,21 @@ See also the QQQ [adoption checklist](https://github.com/QRun-IO/qqq/blob/develo
|
||||
|
||||
| Item | What to do |
|
||||
|---|---|
|
||||
| Coordinates | `com.kingsrook.qbits:qbit-authentik`. No release candidate or release is on Maven Central yet; CircleCI publishes snapshots from `develop`. Build from source or use a snapshot until `0.1.0` ships. |
|
||||
| Coordinates | `com.kingsrook.qbits:qbit-authentik`. No release is on Maven Central yet; CircleCI publishes snapshots from `develop`. |
|
||||
| QQQ version | QQQ 4.1 (see `pom.xml` for the exact RC). Java 21. |
|
||||
| Infrastructure | Authentik, contract-tested against 2026.8.3. The API must be reachable from the app at `baseUrl` (`/api/v3` is appended). |
|
||||
| Authentik setup | A dedicated service account (default username `qqq-<appKey>-idadmin`) whose role holds only the read permissions the QBit needs, created by a bootstrap blueprint in the host's GitOps repository. `src/test/resources/blueprints/kof22-identity-bootstrap.yaml` is a worked example from one host, not something to apply as is. |
|
||||
| Registration | `new AuthentikQBitProducer().withQBitConfig(config).produce(qInstance)`. Produces the `authentikApi` API backend, read-only tables (`authentik_user`, `authentik_group`, `authentik_group_member`, `authentik_session`, `authentik_event`), the drift report widget, and the `authentikAdmin` ("Identity") app, which the host may nest. |
|
||||
| Required config | `baseUrl`, `apiToken`, `appKey` (lower-case letters, digits, dashes; chooses the service-account name), `applicationsInScope` (Authentik application slugs). Optional: `userScopePathStartsWith`, `groupScopeNamePrefix`, `mirrorBackendName` (phase 1 `MIRROR`), `throttleRequestsPerSecond` (default 10). |
|
||||
| Secrets / env | `apiToken` as a `${env.X}` reference (the example uses `AUTHENTIK_API_TOKEN`); `bootstrapOperators` defaults to `${env.AUTHENTIK_QBIT_BOOTSTRAP_OPERATORS}` and `webhookSecret` to `${env.AUTHENTIK_WEBHOOK_SECRET}`. Keep them in the host's secret store, never in config files. |
|
||||
| Permissions | `authentik.users.read` (Identity app and tables), `authentik.audit.read` (sensitive fields and tables); the full `authentik.*` set is in DESIGN.md section 5.2. Granted through the Authentik group attribute `qqq.io/permissions`, read by `AuthentikGroupPermissionMapper`. |
|
||||
| Storage | None for the read-only line, except the mirror tables when `MIRROR` is enabled on `mirrorBackendName`. |
|
||||
| Known limitations | Read-only: every write is refused by `AuthentikGuard` until phases 2-3. `RBAC`, `WEBHOOK` and `SNAPSHOT_EXPORT` are refused by config validation. |
|
||||
| Upgrading | First release line; nothing to migrate. |
|
||||
| Infrastructure | Authentik, contract-tested against 2026.8.3. The API must be reachable from the app at `baseUrl`. |
|
||||
| Tables | Create `authentik_admin_action` and `authentik_approval_request` on your local RDBMS backend (`docs/schema.sql`) before turning write features on. |
|
||||
| Registration | `new AuthentikQBitProducer().withQBitConfig(config).produce(qInstance)`. |
|
||||
| Required config | `baseUrl`, `apiToken`, `appKey`. For writes: `features`, `localBackendName`, `recoveryEmailStage` (users and credentials). Optional: `invitationFlow`, `twoPersonApproval` (default on), `userScopePathStartsWith`, `protectedUsernames`, `applicationsInScope`, `linkPrefix` (default `/app`), `throttleRequestsPerSecond` (default 10), `bulkPacingMillis`. |
|
||||
| Secrets / env | `apiToken` as a `${env.X}` reference; `bootstrapOperatorSubjects` (the lockout escape hatch) defaults to `${env.AUTHENTIK_QBIT_BOOTSTRAP_SUBJECTS}`: immutable ids only (the Authentik user pk or uuid, or the token `sub`), never emails, because users can change their own email. Empty it once real group grants exist. Keep secrets in the host's secret store. |
|
||||
| Optional host wiring | ESB: publish the local tables with `EsbTableMetaData.ofOrWithNew(table).withPublication(...)`. Quick Search: register `authentik_user` and `authentik_group` with the Quick Search qbit. Alerts: see Known limitations. |
|
||||
| Known limitations | Not in this release: the Authentik webhook, the local mirror tables and reconcile, the access-matrix widget, snapshot export, RBAC role management (phase 4), Alerts producer integration. Invitations add people but not their groups (add them to groups after they sign up). Group and user lists are read live (cached 30 s). |
|
||||
| Upgrading | See `UPGRADE.md`. |
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
./mvnw test # unit tests (recorded 2026.8.3 fixtures, no network)
|
||||
./mvnw test # unit tests (recorded 2026.8.3 fixtures and an in-memory Authentik, no network)
|
||||
CI=true ./mvnw verify # + contract tests against Authentik 2026.8.3 in Docker (Testcontainers)
|
||||
./mvnw verify -Dauthentik.test.image=ghcr.io/goauthentik/server:2026.10.0 # rehearse an upgrade
|
||||
./mvnw verify -Dauthentik.fixtures.record=true # refresh unit fixtures
|
||||
|
||||
+203
-26
@@ -1,6 +1,6 @@
|
||||
# Authentik qbit: Design Spec
|
||||
|
||||
Status: Approved, revision 3 (phase 0 findings applied) · 2026-10-11 · Author: James Maes (drafted with Claude)
|
||||
Status: Approved, revision 5 (adds §12 policies and full user/group CRUD; owner decisions of 2026-10-13) · 2026-10-13 · Author: James Maes (drafted with Claude)
|
||||
Targets: QQQ 4.1.x, QQQ Next UI 1.0.x, Authentik 2026.8.x (researched against the live `auth.kof22.com` schema, `info.version: 2026.8.3`), new repo `QRun-IO/qbit-authentik`
|
||||
|
||||
## 0. Summary
|
||||
@@ -38,6 +38,8 @@ Seven design rules shape everything below:
|
||||
|
||||
### 0.1 Owner decisions (2026-10-11)
|
||||
|
||||
**Owner decisions (2026-10-12): all recommendations accepted.** Every open question in this spec (§11.2, and the options marked *recommended* anywhere) is decided as the spec recommends, and the design is approved to build in phase order; adjustments follow once it can be seen working. The earlier decisions are below.
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| 1 | **Source of truth.** Authentik's database. Users, groups, memberships, roles and permissions can be edited from **both** QQQ and the Authentik admin UI. Blueprints cover infrastructure plus `state: created` bootstrap objects only, with no member lists. A nightly read-only export to Git is optional (for audit and DR, not authoritative). |
|
||||
@@ -47,6 +49,17 @@ Seven design rules shape everything below:
|
||||
| 5–16 | The recommendations in the first revision are accepted: recovery email only, MFA view and reset, typed confirmation plus reason with two-person approval for role changes, read-through plus webhook→ESB plus mirror, Authentik-specific with neutral names, the mapper, list-and-revoke for service accounts, new repo, cluster-gitops housekeeping, no Enterprise features, and the retention defaults. Decision 11 (attribute-driven permissions) moves **into v1**, because decision 3 depends on it. |
|
||||
| §11.2 | All six smaller questions take the recommended answer: snapshot repo `KofTwentyTwo/identity-snapshots` (private); two-person approval **on** for `authentik.*` grants, with the Authentik UI as break-glass while James is the only identity admin; a new `kof22-breakglass` superuser; all four seed groups; service accounts listed but only deactivate/revoke; `kof-website-drafters` created with **no** app access until the owner decides (one attribute later). |
|
||||
|
||||
**Owner decisions (2026-10-13): policies and full CRUD.** The owner asked for create, edit, delete and query of users and groups, and for IAM-style permission statements with a UI to create and edit them (§12). Decided:
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| 17 | **Policies are edited in QQQ and stored on Authentik groups.** The qbit's screens are the editor; each policy is a QQQ record (`authentik_policy`) with change history. Saving writes the policy document into the group's attributes through the Authentik API. The sign-in token carries the merged document as a claim, so Authentik is the source of truth at sign-in. |
|
||||
| 18 | **Statement model: the same as the IAM-style documents already used with Authentik in another QQQ app.** `PolicySpec`, `PolicyVersion` (semver), `Statement[]`; `Effect` `Allow`; `Action` from `hasAccess`, `read`, `insert`, `edit`, `delete`, `*`; `Resource` = QQQ table, process, app, report and widget permission names (`[A-Za-z0-9_]+`). Parsing fails closed. No `Deny`, wildcard resources, conditions or field-level rules yet. |
|
||||
| 19 | **The format belongs to this qbit** (`docs/POLICY-FORMAT.md`). The spec name and version are config with a generic default (`qqq-iam`, `1.0.0`), so a host app can keep its existing spec name. No host-specific names in this repo. |
|
||||
| 20 | **A policy editor** lists the app's apps, tables, processes, reports and widgets from metadata, grouped by app, with search, a per-resource action matrix (select all per row, per column and per app), a live read-only JSON preview, round-trip validation, and opens existing documents back into the matrix. Saving writes to Authentik. |
|
||||
| 21 | **Delete is allowed as an explicit action** (supersedes decision 4's "no hard delete"): deactivate stays the default; *Delete User* and *Delete Group* are separate typed-confirmation actions behind the new `DELETE` feature (off by default), which also needs Authentik's `delete_user` / `delete_group`. |
|
||||
| 22 | **Write permissions split as read / users / groups / policies**: `authentik.users.read`, `authentik.users.manage`, `authentik.groups.manage` (+ `authentik.memberships.manage`), and the new `authentik.policies.manage`. Two-person approval for policy saves is optional (`policyTwoPersonApproval`, off by default). |
|
||||
|
||||
### 0.2 Phase 0 findings (2026-10-11, verified on Authentik 2026.8.3)
|
||||
|
||||
The four open points of revision 2 were resolved against a disposable Authentik 2026.8.3 (Testcontainers contract tests in `QRun-IO/qbit-authentik`). Six further facts changed the design; each is pinned by a contract test, so an Authentik upgrade that changes it fails CI.
|
||||
@@ -138,7 +151,7 @@ These starting objects use `state: created`. Authentik's blueprint importer skip
|
||||
- later: Authentik RBAC roles
|
||||
- **See** who has access and why:
|
||||
- groups (hierarchy), effective QQQ permissions per user, roles
|
||||
- application access (`check_access`) and policy bindings
|
||||
- application access (computed by the qbit from `qqq.io/app-access` and the app's bindings, §0.2 iii) and policy bindings
|
||||
- sessions, MFA devices (metadata only), tokens (metadata only), invitations, events
|
||||
- **Work alongside the Authentik admin UI**, with no lost updates and no "wrong" place to make a change.
|
||||
- **Integrate with the host app.**
|
||||
@@ -170,7 +183,7 @@ These starting objects use `state: created`. Authentik's blueprint importer skip
|
||||
|
||||
**A. "Add Sam as a publisher."**
|
||||
- James opens Users → *Create user* and enters name, email and group `kof-website-publishers`.
|
||||
- The preview shows the effective QQQ permissions Sam will get (`cms.publish`, …) and the `check_access` result for `kof22-website-prod` ("will be able to sign in: yes").
|
||||
- The preview shows the effective QQQ permissions Sam will get (`cms.publish`, …) and the computed access result for `kof22-website-prod` ("will be able to sign in: yes", from `qqq.io/app-access` and the app's bindings; not Authentik's `check_access`, §0.2 iii).
|
||||
- James confirms. QQQ calls `POST /core/users/` and `add_user`, then `recovery_email`, so Sam sets his own password.
|
||||
- The local audit row and the Authentik event are written, and the webhook refreshes the mirror.
|
||||
|
||||
@@ -202,10 +215,10 @@ Facts come from the live OpenAPI schema at `https://auth.kof22.com/api/v3/schema
|
||||
| Sessions | `GET /core/authenticated_sessions/` (filter `user__username`), `DELETE …/{uuid}/`, `DELETE …/bulk_delete/?user_pks=` | Fields: `last_ip`, `last_user_agent`, `last_used`, `expires`, `geo_ip`, `asn`. Deactivating a user deletes their sessions (2026.8). |
|
||||
| MFA devices | `GET /authenticators/admin/all/?user=<pk>`. Per type, CRUD on `/authenticators/admin/{totp,webauthn,static,duo,sms,email}/{id}/` | Device metadata only: name, type, confirmed, created, last_used. |
|
||||
| Tokens | `GET/POST /core/tokens/`, `GET/PUT/PATCH/DELETE /core/tokens/{identifier}/`, `GET …/view_key/`, `POST …/set_key/` | Intents: `api`, `app_password`, `recovery`, `verification`. Keyed by identifier. `view_token_key` is a separate permission, and the qbit must never hold it. **Any user may create tokens for itself and read their keys** without `add_token` (§0.2 v). |
|
||||
| Groups | `GET/POST /core/groups/`, `GET/PUT/PATCH/DELETE /core/groups/{uuid}/`, `POST …/add_user/` and `…/remove_user/` (`{pk}`) | **`parents` is many-to-many since 2025.12.** Groups inherit roles **and superuser status** from every ancestor. Names are unique (2025.12). Filters: `members_by_username[]`, `include_users`, `include_children`, `include_parents`, `include_inherited_roles`, `is_superuser`, `attributes`. Custom permissions: `add_user_to_group`, `remove_user_from_group`, `enable_group_superuser`, `disable_group_superuser`. |
|
||||
| Groups | `GET/POST /core/groups/`, `GET/PUT/PATCH/DELETE /core/groups/{uuid}/`, `POST …/add_user/` and `…/remove_user/` (`{pk}`) | **`parents` is many-to-many since 2025.12.** Groups inherit roles **and superuser status** from every ancestor. Names are unique (2025.12). Filters: `members_by_username` (repeat the plain name for several values), `include_users`, `include_children`, `include_parents`, `include_inherited_roles`, `is_superuser`, `attributes`. Custom permissions: `add_user_to_group`, `remove_user_from_group`, `enable_group_superuser`, `disable_group_superuser`. |
|
||||
| RBAC | `GET/POST /rbac/roles/`, `…/{uuid}/add_user/` and `…/remove_user/`, `GET /rbac/permissions/` (catalogue), `GET /rbac/permissions/assigned_by_roles/?model=&object_pk=`, `POST …/assigned_by_roles/{uuid}/assign/`, `PATCH …/unassign/`, `GET /rbac/permissions/roles/?uuid=`, `/rbac/initial_permissions/` | **RBAC has been fully role-based since 2025.12.** Roles are assigned to users directly or through groups; there are no direct user permissions. `assign` with `object_pk` grants an object permission; without it, a global one. Initial permissions automatically grant a role permissions on objects that its members create. |
|
||||
| Apps and policies | `GET /core/applications/{slug}/`, `GET /core/applications/{slug}/check_access/?for_user=`, `GET/POST /policies/bindings/` (target = `pbm_uuid`, plus exactly one of policy/group/user), `/policies/all/`, `POST /policies/all/{uuid}/test/` | **`for_user` is honoured only for superusers** (silently ignored otherwise), the policy test endpoint returns 500 for non-superusers, and the app list shows a non-superuser only its own apps (§0.2 iii). Bindings can expire (2026.8). |
|
||||
| Events | `GET /events/events/` (filters `action`, `actions[]`, `username`, `client_ip`, `context_model_app`, `context_model_name`, `context_model_pk`, `context_authorized_app`), `POST /events/events/` (custom `custom_*` actions), `/actions/`, `/volume/`, `/top_per_user/` | Relevant actions: `login`, `login_failed`, `logout`, `password_set`, `model_created/updated/deleted`, `impersonation_*`, `secret_view`, `invitation_used`, `user_write`, `suspicious_request`, `custom_`. |
|
||||
| Events | `GET /events/events/` (filters `action`, `actions` (repeated plain name), `username`, `client_ip`, `context_model_app`, `context_model_name`, `context_model_pk`, `context_authorized_app`), `POST /events/events/` (custom `custom_*` actions), `/actions/`, `/volume/`, `/top_per_user/` | Relevant actions: `login`, `login_failed`, `logout`, `password_set`, `model_created/updated/deleted`, `impersonation_*`, `secret_view`, `invitation_used`, `user_write`, `suspicious_request`, `custom_`. |
|
||||
| Notifications | `/events/transports/` (mode `webhook` with `webhook_mapping_body`/`_headers`), `/events/rules/` (needs `destination_group` or `destination_event_user`), `/policies/event_matcher/` (action, app, model, client_ip) | Delivery runs as Dramatiq tasks with 5 retries, at least once, with no idempotency key and no ordering guarantee. The default body has no event id or model, so a custom body mapping is required. |
|
||||
| Invitations | `GET/POST /stages/invitation/invitations/` (`fixed_data`, `expires`, `single_use`, `flow`), `POST …/{uuid}/send_email/` | Needs an enrollment flow with an invitation stage, plus working email. |
|
||||
| Blueprints | `GET /managed/blueprints/`, `POST …/{uuid}/apply/`, `GET …/available/` | Each instance has `status`, `last_applied`, `managed_models`. |
|
||||
@@ -299,7 +312,7 @@ MHP learned this the hard way. Blueprint drift caused incident APPS-1462, which
|
||||
│ /qqq/v1/... (normal QQQ routes) /qqq/v1/authentik/* (widgets)
|
||||
┌──────────────▼──────────────── qbit-authentik (Java) ────────────────────┐
|
||||
│ AuthentikQBitProducer / AuthentikQBitConfig │
|
||||
│ ├─ API backend "authentik" ── AuthentikActionUtil (BaseAPIActionUtil) │
|
||||
│ ├─ API backend "authentikApi" ── AuthentikActionUtil (BaseAPIActionUtil) │
|
||||
│ │ ├─ AuthentikGuard (QQQ permission, escalation, protection) │
|
||||
│ │ ├─ FilterMapper (QQueryFilter → Authentik query params) │
|
||||
│ │ └─ Throttle (token bucket, bulk pacing) │
|
||||
@@ -314,7 +327,7 @@ MHP learned this the hard way. Blueprint drift caused incident APPS-1462, which
|
||||
│ Bearer token of service account "qqq-<appKey>-idadmin"
|
||||
┌──────────────▼──────────────── Authentik (source of truth) ──────────────┐
|
||||
│ DB: users, groups, memberships, attributes, roles ◄── Authentik admin UI│
|
||||
│ role qqq-<appKey>-idadmin (bootstrap blueprint, state: created + perms) │
|
||||
│ role qqq-<appKey>-idadmin (bootstrap blueprint, present, perms only) │
|
||||
│ notification rule + event_matcher policy + webhook transport → QQQ │
|
||||
│ blueprints: flows/stages/providers/apps/policies/branding (present) │
|
||||
└───────────────────────────────────────────────────────────────────────────┘
|
||||
@@ -328,14 +341,14 @@ MHP learned this the hard way. Blueprint drift caused incident APPS-1462, which
|
||||
|---|---|---|
|
||||
| `baseUrl` | required | Authentik host root, e.g. `https://auth.kof22.com`. `/api/v3` is appended. This is separate from the OAuth2 issuer URL, as MHP learned. |
|
||||
| `apiToken` | required | Usually `${env.AUTHENTIK_API_TOKEN}`. Interpolated by the qbit (because `APIBackendMetaData.enrich()` is disabled) and redacted in `toString()` |
|
||||
| `tableNamePrefix` / namespace | `authentik` | Prefix for tables (joined with `_`, snake_case: `authentik_user`), processes and widgets (camelCase: `authentikAdmin`) |
|
||||
| `features` | `{READ}` | A subset of `READ`, `USERS` (create, invite, edit, deactivate), `GROUPS` (create, edit, permissions and app-access attributes), `MEMBERSHIP`, `CREDENTIALS` (recovery email, MFA reset, app-password revoke), `SESSIONS`, `RBAC` (phase 4), `ACCESS_MATRIX`, `MIRROR`, `WEBHOOK`, `SNAPSHOT_EXPORT`. A feature that is off produces no metadata. |
|
||||
| `tableNamePrefix` / namespace | `authentik` | Prefix for tables (joined with `_`: `authentik_user`), processes and widgets (camel-cased: `authentikResyncMirror`) |
|
||||
| `features` | `{READ}` | A subset of `READ`, `USERS` (create, invite, edit, deactivate), `GROUPS` (create, edit, permissions and app-access attributes), `POLICIES` (§12), `DELETE` (§12.5), `MEMBERSHIP`, `CREDENTIALS` (recovery email, MFA reset, app-password revoke), `SESSIONS`, `RBAC` (phase 4), `ACCESS_MATRIX`, `MIRROR`, `WEBHOOK`, `SNAPSHOT_EXPORT`. A feature that is off produces no metadata. |
|
||||
| `readOnly` | `false` | Hard kill switch. Every write is refused. |
|
||||
| `appKey` | required | Identifies this QQQ app in attributes, audit and the app-access attribute, e.g. `kof22-admin` |
|
||||
| `userScope` | `internal` + `external` users | Optional `path_startswith` and/or `groups_by_name` filter, to partition a shared Authentik between apps. Out-of-scope users are invisible and cannot be written. |
|
||||
| `groupScope` | all non-superuser groups | Optional name prefix or attribute filter (`qqq.io/app: <appKey>`) for multi-app Authentiks |
|
||||
| `protectedUsernames` | `[]` | Added to the built-in protected set: the service account, users with `qqq.io/protected: true`, and superusers (§5.4) |
|
||||
| `bootstrapOperators` | `${env.AUTHENTIK_QBIT_BOOTSTRAP_OPERATORS}` (empty) | Emails that receive all `authentik.*` permissions even if the group attributes are wrong. A lockout escape hatch that logs a warning while in use; intended to be emptied after go-live. |
|
||||
| `bootstrapOperatorSubjects` | `${env.AUTHENTIK_QBIT_BOOTSTRAP_SUBJECTS}` (empty) | **Immutable ids, never emails** (users can change their own email in Authentik, and emails are not unique). A person is a bootstrap operator when the token `sub` equals an entry (a `sub` that looks like an email is ignored; kof22's provider uses `sub_mode: user_email`), or when the token email is verified, exactly ONE active Authentik user has it, and that user's pk or uuid equals an entry. Find the value in Authentik admin: Directory, Users, the user's numeric id (pk) or uuid. Grants all `authentik.*` permissions even if the group attributes are wrong: a lockout escape hatch that logs a warning while in use. **Empty it once real group grants exist** (after `identity-admins` membership is verified). Entries containing `@` fail validation. |
|
||||
| `permissionCatalog` | derived | The QQQ permission names that can be granted through `qqq.io/permissions`, taken from `PermissionsHelper.getAllAvailablePermissions` plus the `authentik.*` names. Unknown names are rejected. |
|
||||
| `recoveryEmailStage` | required if `CREDENTIALS` or `USERS` | Email stage slug or uuid for `recovery_email`, e.g. `kof22-recovery-email` |
|
||||
| `invitationFlow` | required for invites | Enrollment flow slug, e.g. `kof22-enrollment` |
|
||||
@@ -343,7 +356,7 @@ MHP learned this the hard way. Blueprint drift caused incident APPS-1462, which
|
||||
| `applicationsInScope` | all visible | Application slugs shown in the access matrix and the app-access editor |
|
||||
| `confirmations` | see §6.3 | Per-action confirmation level: `CONFIRM`, `TYPED`, `TWO_PERSON` |
|
||||
| `throttle` | 10 req/s, burst 20; bulk pacing 100 ms | Self-imposed; authenticated calls are not throttled server-side |
|
||||
| `cacheTtl` | 30 s lists, 60 s group attributes, 5 min `check_access` | Memoization TTLs |
|
||||
| `cacheTtl` | 30 s lists, 60 s group attributes, 5 min computed app access | Memoization TTLs |
|
||||
| `mirror` | backend name, 15-minute reconcile, 30-day inbox retention | Used if `MIRROR` is on |
|
||||
| `webhookSecret` | `${env.AUTHENTIK_WEBHOOK_SECRET}` | Shared secret in a header set by the transport's header mapping |
|
||||
| `esbDestinationName` | optional | If set, webhook events go through the ESB; otherwise they are processed inline |
|
||||
@@ -364,7 +377,7 @@ MHP learned this the hard way. Blueprint drift caused incident APPS-1462, which
|
||||
| Concern | Lives in | Edited from | Blueprint state |
|
||||
|---|---|---|---|
|
||||
| Users, groups, memberships, group parents, group attributes (`qqq.io/permissions`, `qqq.io/app-access`), user attributes | **Authentik DB** | QQQ qbit **and** Authentik admin UI | none (data); bootstrap seeds only, as `created` |
|
||||
| Authentik RBAC roles and their assignments | Authentik DB | Authentik UI (v1); QQQ (phase 4) | the qbit's own role: `created`, with `permissions:` |
|
||||
| Authentik RBAC roles and their assignments | Authentik DB | Authentik UI (v1); QQQ (phase 4) | the qbit's own role: `present`, `permissions` only (§4.3) |
|
||||
| Flows, stages, prompts, email templates | Git | cluster-gitops PR | `present` |
|
||||
| OAuth2/other providers, applications, scope mappings | Git | cluster-gitops PR | `present` |
|
||||
| Policies and policy bindings (incl. the app sign-in policy) | Git | cluster-gitops PR | `present` |
|
||||
@@ -515,7 +528,7 @@ Notes (resolved in phase 0, §0.2):
|
||||
- **Global permissions** are the role's `attrs.permissions` (finding i). The role is `present` with nothing but `permissions`, so it is re-asserted additively on every apply and carries no users or groups. `roles:` on the `created` service account applies on first create only; the role's later permission changes still reach it.
|
||||
- **Ordering on a fresh install** (finding iv): the leading `metaapplyblueprint` entry applies `kof22-oauth2-apps` first, inside the bootstrap's transaction. Verified on an empty 2026.8.3. If the infra instance did not exist yet, only the bootstrap fails, and it retries on the next discovery.
|
||||
- **Object permission** on `kof22-recovery-email` (needed by `recovery_email`, phase 3) is applied through the bare `created` stage entry's `permissions:` on every run.
|
||||
- **Seeding James's membership.** `groups:` on a `created` user only applies when the user is first created. James's account already exists, so his `identity-admins` membership is a one-time manual step in the Authentik UI (owner checklist item 10). `bootstrapOperators` covers the window before it's done.
|
||||
- **Seeding James's membership.** `groups:` on a `created` user only applies when the user is first created. James's account already exists, so his `identity-admins` membership is a one-time manual step in the Authentik UI (owner checklist item 10). `bootstrapOperatorSubjects` covers the window before it's done.
|
||||
- **Break-glass password.** The break-glass admin has no usable password from the blueprint. Its password is set once by hand and stored in 1Password. Its recovery path is `ak create_recovery_key` on the worker pod.
|
||||
|
||||
### 4.4 Migration from today's blueprint
|
||||
@@ -596,7 +609,7 @@ The role `qqq-<appKey>-idadmin` is assigned directly to the service account (boo
|
||||
**Never granted:**
|
||||
- `enable_group_superuser` / `disable_group_superuser`. Authentik then refuses every route into superuser ancestry: membership (direct, bulk, by user or by group), `parents` under a superuser group or any descendant, creating a group under one, and flipping `is_superuser` (verified, §0.2 ii).
|
||||
- `view_token_key`, `set_token_key`, `add_token` (MHP APPS-1462)
|
||||
- `impersonate`, `delete_user`
|
||||
- `impersonate`; `delete_user` and `delete_group` unless the `DELETE` feature is on (§12.5)
|
||||
- any `change_*` on flows, stages, providers, applications, policies, bindings, brands or blueprints
|
||||
- any change on its own role. Role permissions are object permissions excluding `qqq-*` roles, and the guard also refuses.
|
||||
|
||||
@@ -624,6 +637,7 @@ This is weaker than revision 1's per-group object permissions. That is the cost
|
||||
| `authentik.groups.manage` | Create groups, rename them, set parents (within `groupScope`), edit non-reserved attributes |
|
||||
| `authentik.memberships.manage` | Add and remove members (subject to the escalation rule) |
|
||||
| `authentik.permissions.manage` | Edit a group's `qqq.io/permissions` and `qqq.io/app-access` (subject to the escalation rule) |
|
||||
| `authentik.policies.manage` | Create and edit group policies (§12) through *Edit Policy*, subject to the escalation rule |
|
||||
| `authentik.roles.manage` | Assign and unassign Authentik RBAC roles (phase 4) |
|
||||
| `authentik.credentials.reset` | Send recovery email, reset MFA, revoke app passwords |
|
||||
| `authentik.sessions.revoke` | Revoke sessions |
|
||||
@@ -682,7 +696,7 @@ The mapper is a `QAuthenticationModuleCustomizerInterface` component. It replace
|
||||
|
||||
1. It takes the user's group names from the `groups` claim. The current kof22 `profile` mapping emits **direct** groups only.
|
||||
2. It resolves each group through `EffectivePermissionResolver`: group attributes plus all ancestors via `include_parents`, from the mirror or the API, cached 60 s. The result is the union of `qqq.io/permissions`, with `authentik.*` and other wildcard prefixes expanded against `permissionCatalog`.
|
||||
3. It adds static fallbacks if configured, through `withGroupPermissions(...)` (useful in tests and dev), plus `bootstrapOperators`.
|
||||
3. It adds static fallbacks if configured, through `withGroupPermissions(...)` (useful in tests and dev), plus `bootstrapOperatorSubjects`.
|
||||
4. It sets QQQ session permissions, user, email and full name.
|
||||
|
||||
**Freshness.** Permissions are computed at session creation. The QQQ session is re-validated on each access-token refresh (1 hour in kof22), and the mapper runs again then. A webhook on a group or membership change also marks affected sessions in `qqq_user_session` for re-evaluation on their next request (phase 2). Phase 0 checks this is possible through the OAuth2 module's session store. If it isn't, the staleness is up to 1 hour, which is documented.
|
||||
@@ -692,7 +706,9 @@ The mapper is a `QAuthenticationModuleCustomizerInterface` component. It replace
|
||||
---
|
||||
## 6. Data model
|
||||
|
||||
### 6.1 API-backed tables (backend `authentik`, `AuthentikActionUtil`)
|
||||
**Naming (owner rule, 2026-10-12):** "table names should always be lowercase and use _, and qbits should always be prefixed with their name, ie, cdn_ etc". Every table, API-backed or local, is lowercase snake_case with the `authentik_` prefix (`authentik_user`, `authentik_admin_action`). Where QQQ separates the table name from the backend name, both are identical; possible-value sources use the table name. Permissions follow the same rule (owner, 2026-10-12): the former `identity.*` permissions are now `authentik.*` (`authentik.users.read`, `authentik.memberships.manage`, ...); the shorthand `users.read` etc. in the action tables means the `authentik.` name. Java classes stay CamelCase; field, process and widget names are unchanged. The one name that is not a table is the API backend, a connection rather than a table: it is `authentikApi` everywhere (diagram, README, code), camel-cased like the process and widget names. No version of qbit-authentik has been released yet, so this is a rename in the design and in the unreleased branch code (whose `applyPrefix` camel-joins `authentik` + name today), not a migration.
|
||||
|
||||
### 6.1 API-backed tables (backend `authentikApi`, `AuthentikActionUtil`)
|
||||
|
||||
| Table | Source | Key | Capabilities | Notes |
|
||||
|---|---|---|---|---|
|
||||
@@ -713,7 +729,7 @@ The mapper is a `QAuthenticationModuleCustomizerInterface` component. It replace
|
||||
|
||||
**`FilterMapper`** maps QQQ criteria to Authentik query params:
|
||||
- `EQUALS` → `field=`
|
||||
- `IN` → repeated `field[]=` where supported (`groups_by_name`, `type`, `actions`)
|
||||
- `IN` → the plain name repeated once per value, e.g. `type=a&type=b` (`groups_by_name`, `type`, `actions`). **Never the bracketed `field[]=a` form: Authentik silently ignores it and returns unfiltered results (§0.2 vi).**
|
||||
- `GREATER_THAN` / `LESS_THAN` on date fields → `__gt` / `__lt`
|
||||
- `IS_BLANK` → `__isnull=true`
|
||||
- `CONTAINS` / `STARTS_WITH` on text fields → `search=` (or `path_startswith`)
|
||||
@@ -735,6 +751,7 @@ Unsupported criteria (OR across fields, `NOT_EQUALS`, nested filters) are **reje
|
||||
| Table | Purpose |
|
||||
|---|---|
|
||||
| `authentik_admin_action` | **Append-only audit and outbox** of every write the qbit attempts. Columns: id, correlationId, actionName, operator (QQQ user + Authentik username), reason, targetType, targetKey, targetLabel, beforeJson, afterJson, status (`PENDING_APPROVAL`, `RUNNING`, `SUCCEEDED`, `FAILED`, `REFUSED`), errorMessage, authentikEventPk, approver, timestamps. The row is inserted *before* the API call, following the sql-workbench `ExecutionAuditor` pattern; if that insert fails, the call is not made. Insert, update and delete capabilities are removed for everyone. |
|
||||
| `authentik_policy` | One row per group with a policy (§12): groupPk (unique), groupName, policyJson (canonical pretty JSON), statementCount, permissionCount, savedBy, savedAt, authentikFingerprint. Field-level QQQ audit is the change history. Changed only by *Edit Policy*; generic insert, edit and delete are off. |
|
||||
| `authentik_approval_request` | Two-person requests: action payload, requester, approver, 24 h expiry, approver ≠ requester. Used for RBAC (phase 4) and, by default, for permission edits that add `authentik.*` (§6.3). |
|
||||
| `authentik_user_mirror` | `MIRROR` feature: pk, uuid, username, email, name, type, isActive, lastLogin, isSuperuser, isProtected, groupNames, effectivePermissions (text), mfaDeviceCount, failedLogins24h, refreshedAt. Unique on username and email. Web Users joins here (`qqq_user_session.user_id` = email in kof22). The mapper falls back to it. |
|
||||
| `authentik_group_mirror` | pk, name, parentPks, attributes `qqq.io/*` only, memberCount, isSuperuser (inherited), refreshedAt. Feeds the resolver and the tree widget. |
|
||||
@@ -745,7 +762,7 @@ Unsupported criteria (OR across fields, `NOT_EQUALS`, nested filters) are **reje
|
||||
|
||||
Each process:
|
||||
- is bound with `withTableName(...)` and placed in `QMenu` slots (`isHidden(true)` for navigation)
|
||||
- uses `StreamedETLWithFrontendProcess` with steps: **input** (targets and values; **reason** is required for writes), **preview** (server-computed per-target before → after, effective-permission deltas, `check_access` deltas, guard results, and skipped targets with reasons), **confirm** (per `confirmations`), **execute** (audit row → stale check → API call → Authentik custom event → cache and mirror invalidation), and **result** (per-record outcome with links to audit rows)
|
||||
- uses `StreamedETLWithFrontendProcess` with steps: **input** (targets and values; **reason** is required for writes), **preview** (server-computed per-target before → after, effective-permission deltas, computed-access deltas, guard results, and skipped targets with reasons), **confirm** (per `confirmations`), **execute** (audit row → stale check → API call → Authentik custom event → cache and mirror invalidation), and **result** (per-record outcome with links to audit rows)
|
||||
|
||||
| Process | Table / slot | Records | Permission | Default confirmation | Authentik calls |
|
||||
|---|---|---|---|---|---|
|
||||
@@ -759,7 +776,7 @@ Each process:
|
||||
| Create group | `authentik_group` query action | 0 | `authentik.groups.manage` (+ `permissions.manage` if permissions given) | CONFIRM | `POST /core/groups/` (name, parents, attributes) |
|
||||
| Edit group | `authentik_group` view | 1 | `authentik.groups.manage` | CONFIRM | `PATCH` name, parents and non-reserved attributes (merge-patch) |
|
||||
| Edit permissions and app access | `authentik_group` view | 1 | `authentik.permissions.manage` | CONFIRM; **TWO_PERSON** when adding any `authentik.*` permission | `PATCH attributes` (`qqq.io/permissions`, `qqq.io/app-access`), re-read first |
|
||||
| Check access / Effective permissions | `authentik_user` view | 1 | `authentik.users.read` | none | `check_access` per in-scope app; the resolver |
|
||||
| Check access / Effective permissions | `authentik_user` view | 1 | `authentik.users.read` | none | computed access per in-scope app (§5.1, not `check_access`); the resolver |
|
||||
| Send password reset email | `authentik_user` | 1–25 | `authentik.credentials.reset` | CONFIRM | `recovery_email` |
|
||||
| Reset MFA | `authentik_user` | 1 | `authentik.credentials.reset` | TYPED | per-device `DELETE` |
|
||||
| Revoke app passwords | `authentik_user`, `authentik_token` | 1–25 | `authentik.credentials.reset` | TYPED | `DELETE /core/tokens/{identifier}/` |
|
||||
@@ -844,20 +861,21 @@ The qbit produces an app `authentikAdmin` (label **"Identity"**, icon `badge`).
|
||||
| Groups | `AUTHENTIK_GROUP_TREE` widget + generic list | Tree over `parents` (many-to-many; shared children marked). Badges: superuser (red, locked), has-permissions, app-access. Member counts. |
|
||||
| Group detail | generic view + child widgets | Members (Add/Remove); **Permissions** (own + inherited, with an editor that offers only permissions the operator holds); **App access**; parents and children; roles (read); other attributes (`authentik.audit.read`) |
|
||||
| Access matrix | `AUTHENTIK_ACCESS_MATRIX` widget | Users in scope × `applicationsInScope`, cells computed by the qbit (not `check_access`, §0.2 iii; cached 5 min, 25 rows per page) |
|
||||
| Health | `AUTHENTIK_HEALTH` widget | API reachability and version, token expiry, blueprint instance status, webhook lag, last reconcile, possible blueprint reversions, `bootstrapOperators` in use |
|
||||
| Health | `AUTHENTIK_HEALTH` widget | API reachability and version, token expiry, blueprint instance status, webhook lag, last reconcile, possible blueprint reversions, `bootstrapOperatorSubjects` in use |
|
||||
| Audit | generic query on `authentik_admin_action` + `authentik_event` | Filter by operator, target, action, status, and source (QQQ vs Authentik UI) |
|
||||
|
||||
### 8.3 Admin-home widgets (standard widget types, from the mirror)
|
||||
|
||||
- Statistics: active users, inactive users, service accounts, users without MFA, failed logins in 24 h.
|
||||
- Table: recent auth events.
|
||||
- Table: "attention" items: admins without MFA, tokens expiring within 14 days (including the qbit's own token), blueprint status not `successful`, `bootstrapOperators` still set.
|
||||
- Table: "attention" items: admins without MFA, tokens expiring within 14 days (including the qbit's own token), blueprint status not `successful`, `bootstrapOperatorSubjects` still set.
|
||||
|
||||
### 8.4 Frontend delivery
|
||||
|
||||
- Custom widget types `AUTHENTIK_GROUP_TREE`, `AUTHENTIK_ACCESS_MATRIX` and `AUTHENTIK_HEALTH` are added to `WidgetRenderer.tsx` as `React.lazy` cases, following the `SQL_WORKBENCH` and `ESB_OVERVIEW` pattern.
|
||||
- `src/lib/api/authentik.ts` calls `/qqq/v1/authentik/{tree,matrix,health,permission-catalog}`, all guarded.
|
||||
- A permission-picker field component for the group permissions editor.
|
||||
- `AUTHENTIK_POLICY_EDITOR` (§12.4), lazy-loaded and seeded through the standard process widget route, so no qbit route is needed.
|
||||
- Mocks in `src/mocks/fixtures/authentik.ts`; e2e in `tests/e2e/authentik.spec.ts`.
|
||||
- Everything else uses the generic UI.
|
||||
|
||||
@@ -911,7 +929,7 @@ Authenticated API calls are not throttled by Authentik, and kof22's Authentik sh
|
||||
|---|---|
|
||||
| A compromised QQQ backend escalates in Authentik | The service account can't create superusers, touch superuser groups, read or mint tokens, impersonate, delete users, or change flows and policies (§5.1) |
|
||||
| A QQQ operator escalates themselves or a friend | Subset rule, no self-edits, two-person approval for `authentik.*` grants, protected accounts |
|
||||
| Lockout (last admin removed or deactivated) | Last-admin guard; break-glass superuser outside QQQ; `bootstrapOperators` |
|
||||
| Lockout (last admin removed or deactivated) | Last-admin guard; break-glass superuser outside QQQ; `bootstrapOperatorSubjects` |
|
||||
| A blueprint re-apply reverts QQQ edits | No `present` identity entries, no member lists (CI lint); bootstrap as `created` (verified, §4.2); reversion detector |
|
||||
| Lost update between QQQ and the Authentik UI | Stale check at execute; attribute merge-patch after a fresh read |
|
||||
| Account takeover through a recovery link | Links are never shown; email only |
|
||||
@@ -958,7 +976,7 @@ The estimates assume one senior engineer with AI assistance, plus about 20% of a
|
||||
| **0. Foundations and migration** | See the task list below | Contract tests (b), (c), (d), (h) green; the kof22 migration done in staging; read-only token wired | 2 wk |
|
||||
| **1. Read-only + permissions model** | Tables (users, groups, members, roles, applications, bindings, blueprints; sensitive tables behind `audit.read`). `EffectivePermissionResolver` + `AuthentikGroupPermissionMapper` (kof22 cut over, sign-in policy fallback removed). Group tree, Effective permissions and Access tabs. Health widget. Mirror with scheduled reconcile. Admin-home widgets. | kof22 Web Users shows groups, last login and MFA; kof22 permissions come from `qqq.io/permissions`; guard matrix green for reads | 2.5 wk |
|
||||
| **2. Memberships and permission editing** | Add/remove (both sides, bulk), the subset rule, the last-admin guard, the group permissions and app-access editor with two-person approval for `authentik.*`, `authentik_admin_action` + Authentik custom events, webhook route + ESB trigger + inbox, session re-evaluation marking | Scenarios B and D end to end; safety matrix 100%; webhook latency < 10 s | 2.5 wk |
|
||||
| **3. Full user lifecycle** | Create user, invite (+ enrollment flow in Git), edit, deactivate/reactivate, recovery email, revoke sessions, reset MFA, revoke app passwords, create and edit groups, cancel invitations; optional snapshot export | Scenarios A and C end to end; contract tests (a), (e), (f), (g) green | 3 wk |
|
||||
| **3. Full user lifecycle** | Create user, invite (+ enrollment flow in Git), edit, deactivate/reactivate, recovery email, revoke sessions, reset MFA, revoke app passwords, create and edit groups, cancel invitations; optional snapshot export | Scenarios A and C end to end; contract tests (a), (e), (f) green; access computation pinned by `AccessCheckIT` and `SignInPolicyIT` (§10 g) | 3 wk |
|
||||
| **4. RBAC (post-v1)** | Authentik role assignment with two-person approval, access-matrix polish, MHP migration off `AuthentikAdminApiClient` | MHP running on the qbit | 3 wk |
|
||||
|
||||
**v1 (phases 0–3) is about 10 weeks**, and phase 4 adds about 3 more.
|
||||
@@ -969,7 +987,7 @@ The estimates assume one senior engineer with AI assistance, plus about 20% of a
|
||||
|
||||
| # | Task | Who |
|
||||
|---|---|---|
|
||||
| 1 | Create repo `QRun-IO/qbit-authentik` from `qbit-template-extension`; copy this spec to `docs/DESIGN.md`; add `AGENTS.md`/`CLAUDE.md` | agent: **done** (repo private for now, see the owner checklist) |
|
||||
| 1 | Create repo `QRun-IO/qbit-authentik` from `qbit-template-extension`; copy this spec to `docs/DESIGN.md`; add `AGENTS.md`/`CLAUDE.md` | agent: **done** (the repo is public) |
|
||||
| 2 | `AuthentikQBitConfig` + producer skeleton; `AuthentikActionUtil` (bearer auth, page/page_size paging, FilterMapper, throttle, redaction); pinned `schema.yml` + drift test | agent |
|
||||
| 3 | Testcontainers harness (Authentik 2026.8.3 + Postgres + Mailpit), fixture recorder; contract tests (b), (c), (d), (h) | agent |
|
||||
| 4 | Verify on the container: (i) how to grant *global* role permissions declaratively in 2026.8.3; (ii) whether a `parents` change under a superuser group is refused without `enable_group_superuser`; (iii) the permission `check_access` needs; (iv) the `metaapplyblueprint` ordering. Then fix §4.3 and §5.1. | agent: **done**, §0.2 |
|
||||
@@ -988,9 +1006,9 @@ The estimates assume one senior engineer with AI assistance, plus about 20% of a
|
||||
| The service account holds global user/group change rights (decision 1), so its blast radius is wider than revision 1's | Hard Authentik floor (no superuser, tokens, impersonation or delete); `userScope`/`groupScope`; guard; audit on both sides; 90-day token |
|
||||
| Someone reintroduces a `present` identity entry, and members get wiped | CI lint; contract test (d); reversion detector |
|
||||
| A bootstrap entry error rolls back the infrastructure blueprint | Separate bootstrap file; `metaapplyblueprint` ordering; minimal attrs; health widget |
|
||||
| A lockout through bad permission edits | Last-admin guard, break-glass, `bootstrapOperators`, two-person approval for `authentik.*` |
|
||||
| A lockout through bad permission edits | Last-admin guard, break-glass, `bootstrapOperatorSubjects`, two-person approval for `authentik.*` |
|
||||
| Session permissions go stale after a demotion | Token-refresh re-evaluation, webhook marking, live checks in the guard |
|
||||
| `parents` re-parenting under a superuser group isn't refused by Authentik | Guard refusal; phase 0 check (ii) |
|
||||
| The service account can lock administrators out (remove members from `authentik Admins`, deactivate break-glass, strip `qqq.io/protected`, §0.2 ii-b). Re-parenting under a superuser group **is** refused by Authentik (§0.2 ii) | Guard refusal of every write that targets a protected account or a superuser group; drift report; recovery through cluster access |
|
||||
| Load on the shared Postgres | Throttle, caps, mirror |
|
||||
| Webhook loss | Inbox, 15-minute reconcile, nightly sweep |
|
||||
| QQQ core gaps (#1061, #1062) | Guard in the backend util, ArchUnit, field stripping |
|
||||
@@ -1022,6 +1040,165 @@ The decisions taken on 2026-10-11 are in §0.1. The remaining questions are smal
|
||||
|
||||
---
|
||||
|
||||
## 12. Policies: IAM-style permission statements (revision 5)
|
||||
|
||||
### 12.1 What a policy is
|
||||
|
||||
A **policy** is a JSON document on an Authentik group that grants QQQ permissions to everyone in the group (and in its child groups). The format is defined in [`POLICY-FORMAT.md`](POLICY-FORMAT.md); in short:
|
||||
|
||||
```json
|
||||
{
|
||||
"PolicySpec": "qqq-iam",
|
||||
"PolicyVersion": "1.0.0",
|
||||
"Statement": [
|
||||
{ "Effect": "Allow", "Action": ["hasAccess"], "Resource": ["contentApp", "publishPage"] },
|
||||
{ "Effect": "Allow", "Action": ["read", "edit"], "Resource": ["cms_page"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each `Allow` statement grants `{resource}.{action}` for every listed resource and action (`*` = all five actions). Those are QQQ permission names, so a QQQ session that holds them passes QQQ's own permission checks. Policies cover the instance's tables, processes, apps, reports and widgets. Named permissions that are not `{resource}.{action}` (for example `authentik.users.manage`) stay in `qqq.io/permissions` (§5.6); a policy cannot grant them, because a resource cannot contain a dot.
|
||||
|
||||
**Fail closed.** Any of these grants **zero** permissions from that document and logs a warning:
|
||||
- an unknown `PolicySpec` or an unsupported `PolicyVersion`
|
||||
- a document that is not a JSON object, or a `Statement` that is not an array
|
||||
- a statement whose `Effect` is not `Allow`
|
||||
- an unknown action
|
||||
- a resource that does not match `[A-Za-z0-9_]+`
|
||||
- any other parse error
|
||||
|
||||
This is stricter than the reference implementation in two places. The reference ignores unknown actions, while this qbit rejects the whole document. `Deny` is not supported yet, so a `Deny` statement also rejects the document; ignoring it would grant more than its author intended.
|
||||
|
||||
### 12.2 Where it is stored, and how it reaches the session
|
||||
|
||||
| Step | Where | Detail |
|
||||
|---|---|---|
|
||||
| Edit | QQQ, *Edit Policy* on a group (§12.4) | The editor builds the document; the server validates it and checks the round trip |
|
||||
| Save | Authentik group attribute `qqq.io/policy` (config `policyAttribute`) | The compact JSON **string** (the reference format; the parser also reads a JSON object). Merge-patch of that one key into the group's current attributes, re-read immediately before the write (§5.4 rule 7). |
|
||||
| History | QQQ table `authentik_policy`, one row per group | The canonical pretty JSON, counts, who saved it and when, and the fingerprint of what Authentik held. Field-level QQQ audit gives the change history; `authentik_admin_action` holds before/after of every save. |
|
||||
| Sign-in | Authentik scope mapping (blueprint example in `POLICY-FORMAT.md`) | Merges the statements of all the user's groups, **including inherited parents** (`request.user.all_groups()`), into one document in the claim `qqq_policy` (config `policyClaim`) |
|
||||
| Session | `AuthentikPolicyClaimMapper`, or `PolicyPermissions.fromClaims` in a host's own customizer | Reads the claim from the ID token, else the access-token payload; parses it fail-closed; adds the permissions to the QQQ session |
|
||||
|
||||
`AuthentikGroupPermissionMapper` (§5.6) also reads `qqq.io/policy` from the group graph. So the following all see policy grants:
|
||||
- `EffectivePermissionResolver`
|
||||
- the subset rule
|
||||
- the effective-permissions view
|
||||
- the last-admin check
|
||||
|
||||
An app that uses the API-backed mapper therefore gets policy grants even before the scope mapping is installed. The claim and the graph hold the same Authentik data, and the session gets their union.
|
||||
|
||||
**Record locks (extension point).** Row-level security keys are out of scope for now. `AuthentikPolicyClaimMapper` has a protected `applySecurityKeys(QSession, JSONObject claims)` hook, a no-op by default.
|
||||
- A host overrides it to read its own explicit claims and set security key values.
|
||||
- It is called after the identity is set and before the permissions.
|
||||
- It must trust only explicit claims, never group names.
|
||||
|
||||
### 12.3 Config
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `policySpec` | `qqq-iam` | The `PolicySpec` this app accepts and writes. A host that already has documents keeps its own name. |
|
||||
| `policyVersion` | `1.0.0` | The one supported `PolicyVersion` (exact match, like the reference) |
|
||||
| `policyAttribute` | `qqq.io/policy` | Group attribute holding the document. A host with existing documents may point it at its own key. |
|
||||
| `policyClaim` | `qqq_policy` | Token claim holding the merged document |
|
||||
| `policyTwoPersonApproval` | `false` | When true, every policy save is queued for a second person (`authentik.approve`) |
|
||||
|
||||
The feature `POLICIES` turns on the editor, the `authentik_policy` table and the save action. It needs `GROUPS`. Reading policies at sign-in needs no feature.
|
||||
|
||||
### 12.4 The policy editor
|
||||
|
||||
*Edit Policy* is a record action on `authentik_group` and on `authentik_policy`, never in the nav. It is a standard streamed-ETL process with three steps.
|
||||
|
||||
**1. Edit** (frontend step). The step shows the widget `authentikPolicyEditor`, type `AUTHENTIK_POLICY_EDITOR`, a lazy-loaded Next UI widget. The server sends it two things.
|
||||
|
||||
The **catalog** lists every app, table, process, report and protected widget in the QInstance. Each entry has its permission base name, label, kind, app, and the actions QQQ actually checks for it:
|
||||
- `hasAccess` for apps, processes, reports and widgets
|
||||
- `read`, `insert`, `edit` and `delete` for tables, limited by the table's capabilities and permission level
|
||||
|
||||
The catalog also follows these rules:
|
||||
- Hidden processes are included. Record actions are hidden from the nav but are still permission-checked.
|
||||
- Objects that are in no app are listed under "Other".
|
||||
- Tables that use `READ_WRITE` permissions are shown with `read` only, and a note, because `write` is not in the action set yet.
|
||||
- Objects with a custom permission checker, or `NOT_PROTECTED`, are left out because a policy cannot grant them.
|
||||
|
||||
The **current document** is read live from the group in Authentik, the source of truth, together with the group's fingerprint for the stale check. If it differs from the last QQQ save, a notice says it was changed in Authentik.
|
||||
|
||||
The screen works like this:
|
||||
- Resources are grouped by app, with a search box.
|
||||
- Each row has a checkbox per action, plus *all* for the row. Each action column and each app has *select all*.
|
||||
- A read-only JSON preview updates live.
|
||||
- Unknown resources in an opened document (for example a table that was removed) are listed, and kept until the operator removes them.
|
||||
- The widget writes the generated document into the process value `policyJson`. Clients without the widget post `policyJson` directly.
|
||||
|
||||
**2. Review** (dry run). The server:
|
||||
- parses the submitted document, failing closed
|
||||
- regenerates it in canonical form and checks that parse(generate(x)) = x (the round-trip invariant)
|
||||
- flags unknown resources
|
||||
- shows the permissions added and removed, and how many members are affected
|
||||
- applies the subset rule (§5.4 rule 4): the operator must hold every **added** permission
|
||||
|
||||
Refusals name the reason.
|
||||
|
||||
**3. Result.** The qbit:
|
||||
- writes the attribute (merge-patch)
|
||||
- inserts or updates the audited `authentik_policy` row
|
||||
- writes the `authentik_admin_action` row and the Authentik event
|
||||
- clears the caches
|
||||
|
||||
Saving an empty matrix removes the attribute. The canonical form is the reference generator's:
|
||||
- one statement per action, in the order `hasAccess`, `read`, `insert`, `edit`, `delete`
|
||||
- resources sorted
|
||||
- a resource with every action is still written as five statements, not `*`, so diffs stay readable
|
||||
|
||||
### 12.5 Full user and group CRUD (revision 5 additions)
|
||||
|
||||
| Action | Table / slot | Permission | Feature | Confirmation | Authentik |
|
||||
|---|---|---|---|---|---|
|
||||
| Edit user (adds username and non-reserved attributes) | `authentik_user` record | `authentik.users.manage` | `USERS` | CONFIRM | `PATCH /core/users/{pk}/` (`username`, `name`, `email`, `path`; attributes merge-patch, `qqq.io/*` keys refused) |
|
||||
| Delete user | `authentik_user` record | `authentik.users.manage` | `DELETE` | TYPED (username) | `DELETE /core/users/{pk}/` |
|
||||
| Edit group (adds non-reserved attributes) | `authentik_group` record | `authentik.groups.manage` | `GROUPS` | CONFIRM | `PATCH /core/groups/{pk}/` |
|
||||
| Delete group | `authentik_group` record | `authentik.groups.manage` | `DELETE` | TYPED (group name) | `DELETE /core/groups/{pk}/`. Refused while it has members or child groups. |
|
||||
| Edit policy | `authentik_group`, `authentik_policy` records | `authentik.policies.manage` | `POLICIES` | CONFIRM (TWO_PERSON if configured) | `PATCH /core/groups/{pk}/` attributes |
|
||||
|
||||
The existing guardrails apply unchanged:
|
||||
- protected accounts and superuser groups
|
||||
- no self-edits (an operator cannot delete or rename themselves)
|
||||
- last-admin protection (deleting one of the last identity admins is refused)
|
||||
- a reason for every change
|
||||
- audit before the call
|
||||
|
||||
Deactivate stays the default for people, and *Delete User* says so in its help text.
|
||||
|
||||
**Authentik permissions** the service account needs for these writes, on top of §5.1. All are global on the qbit's role:
|
||||
|
||||
| Permission | For |
|
||||
|---|---|
|
||||
| `authentik_core.change_group` | Saving a policy (already in §5.1 for phase 3) |
|
||||
| `authentik_core.delete_user` | Delete user (only with `DELETE`) |
|
||||
| `authentik_core.delete_group` | Delete group (only with `DELETE`) |
|
||||
|
||||
The token needs these only when writes are on. A read-only deployment (`readOnly`, or no write features) keeps the phase 1 read set.
|
||||
|
||||
### 12.6 Tests
|
||||
|
||||
- **Parser:** every fail-closed case (null, blank, not JSON, unknown spec, unsupported version, `Deny`, unknown action, bad resource, non-array fields), `*` expansion, and merging several statements.
|
||||
- **Generator:** the canonical form, the round trip over generated permission sets, and rejection of anything that cannot round-trip.
|
||||
- **Catalog:** apps, tables (capabilities, levels, custom base names), hidden processes, reports, widgets, and "Other".
|
||||
- **Editor process:** review lines, the subset rule, the stale fingerprint, round-trip refusal, and a save that writes both the attribute and the `authentik_policy` row.
|
||||
- **Runtime:** the claim from the ID token and from the access token, string and object claims, fail closed, a custom spec name, and the security-key hook.
|
||||
- **CRUD:** edit user (username, attributes, reserved keys refused) and delete user and group with their refusals, on the in-memory Authentik.
|
||||
- **Contract tests** on Authentik 2026.8.3: policy save, delete, and the scope-mapping example (`propertymappings/all/{uuid}/test/` returns a claim the parser accepts).
|
||||
- **Permission gating:** each new action is refused without its permission or feature.
|
||||
|
||||
### 12.7 Delivery
|
||||
|
||||
| Phase | Scope |
|
||||
|---|---|
|
||||
| 5a | Policy model, parser, generator, runtime mapper, resolver integration, format doc and blueprint example |
|
||||
| 5b | Catalog, `authentik_policy`, *Edit Policy* with save to Authentik; the Next UI widget `AUTHENTIK_POLICY_EDITOR` (separate PR to qqq-frontend-next) |
|
||||
| 5c | The user and group CRUD additions (§12.5) |
|
||||
|
||||
---
|
||||
|
||||
## Appendix A: Example API mapping (`authentik_user`)
|
||||
|
||||
| QQQ | Authentik |
|
||||
|
||||
@@ -5,13 +5,13 @@ These are the steps only James can take: items 6, 7, 8 and 10 of DESIGN.md secti
|
||||
Links:
|
||||
- cluster-gitops draft PR: KofTwentyTwo/cluster-gitops#72 (the identity bootstrap blueprint, the removal of the `present` entries, the attribute-driven sign-in policy, inert webhook plumbing, and the blueprint lint)
|
||||
- Website-Backend and cluster-gitops wiring draft PRs: see `docs/STATUS.md`
|
||||
- Spec: QRun-IO/qqq#1065 (revision 3 records the phase 0 findings)
|
||||
- Spec: QRun-IO/qqq#1065 (revision 4: phase 0 findings, review fixes, owner decisions of 2026-10-12)
|
||||
|
||||
## 0. Decisions surfaced by phase 0 (read first)
|
||||
|
||||
| # | Decision | Recommendation |
|
||||
|---|---|---|
|
||||
| D1 | **Repo visibility.** `QRun-IO/qbit-authentik` was created **private**, because creating a public repo was blocked for the agent. Other generic qbits (quick-search, sql-workbench) are public, and the spec is already public in qqq#1065. CI publishes `develop` snapshots and `release/*` RCs to Maven Central / Sonatype (with sources jars), which would make the code public anyway. | Make it public before the first publish: *Settings → General → Change visibility*. Then check that CircleCI follows the repo (it must, for PR CI). |
|
||||
| D1 | **Repo visibility.** Resolved: `QRun-IO/qbit-authentik` is public. | Check that CircleCI follows the repo (it does for PR CI); nothing else to do. |
|
||||
| D2 | **Lockout risk.** Authentik stops the service account from *escalating*, but not from *locking out*. With the phase 2/3 permissions it can do all of the following (contract test `SuperuserFloorIT`): remove members from `authentik Admins`, deactivate `kof22-breakglass`, strip `qqq.io/protected`, and rename the superuser group. The qbit guard refuses all of these; Authentik does not. | Accept, with the mitigations in the spec (§5.1, revision 3). The real break-glass for a compromised QQQ is cluster access: `kubectl exec` into the Authentik worker and run `ak shell` to reactivate or re-add. Optionally, phase 2 grants `remove_user_from_group` per group (object permissions) instead of globally. |
|
||||
| D3 | **Self-minted tokens.** Any authenticated user, including the service account, can create API tokens **for itself** without `add_token`, and read their keys. A compromised QQQ could therefore keep a second token alive after you rotate the first. | Accept. The phase 1 drift report flags service-account tokens beyond the expected one. Check that list after every rotation (item 8). |
|
||||
| D4 | **Access matrix.** `check_access?for_user=` only works for superusers. For the service account it silently answers *for itself*. The policy-test endpoint returns HTTP 500 for non-superusers on 2026.8.3. | Accepted in the spec: the qbit computes app access itself from `qqq.io/app-access` and the app's bindings, and shows other expression policies as "not evaluated". |
|
||||
@@ -77,6 +77,7 @@ Do these in order, in one sitting.
|
||||
```yaml
|
||||
qqq.io/app-access: ["kof22-website-prod"]
|
||||
qqq.io/permissions:
|
||||
- authentik.users.read
|
||||
- esbView.hasAccess
|
||||
- esbOperate.hasAccess
|
||||
- esbDelete.hasAccess
|
||||
@@ -90,7 +91,7 @@ Do these in order, in one sitting.
|
||||
- quickSearchFailedEvent.write
|
||||
- dataHealth.hasAccess
|
||||
```
|
||||
Keep the existing attributes of the group. Add only these two keys.
|
||||
Keep the existing attributes of the group. Add only these two keys. `authentik.users.read` lets `kof22-admins` open the Identity app; the seed group `identity-admins` already carries `authentik.*` (all identity permissions) from the blueprint, so you get everything through it once you join it (step 1).
|
||||
3. On group **`kof-website-publishers`** → *Attributes*: `qqq.io/app-access: ["kof22-website-prod"]`. This keeps the `kof-publisher-prod` service account's client-credentials tokens working once the name fallback is removed.
|
||||
4. **`kof-website-drafters`**: leave it without `qqq.io/app-access` until you decide that drafters should sign in to the admin. Granting it later is that one attribute.
|
||||
5. **Break-glass password**:
|
||||
@@ -101,3 +102,26 @@ Do these in order, in one sitting.
|
||||
## After items 6-10
|
||||
|
||||
Tell the agent "phase 0 owner steps done". Next come item 11 (the qbit in read-only mode on staging, behind `AUTHENTIK_QBIT_ENABLED`), then the phase 1 mapper cut-over, then removal of the sign-in name fallback.
|
||||
|
||||
|
||||
## Item 12: turn on the full lifecycle (v1)
|
||||
|
||||
The qbit can now create and change users and groups, not just read. Do this only after items 6-11 are done and the read-only screens look right on staging. Nothing here is applied by an agent.
|
||||
|
||||
1. **Add the write permissions to the service account's role.** In the identity bootstrap blueprint, append these to `qqq-kof22-admin-idadmin`'s `permissions` list (they are re-asserted additively on every apply; the PR is prepared as a separate commit on cluster-gitops#72):
|
||||
```
|
||||
authentik_core.add_user authentik_core.change_user
|
||||
authentik_core.reset_user_password authentik_core.add_group
|
||||
authentik_core.change_group authentik_core.add_user_to_group
|
||||
authentik_core.remove_user_from_group
|
||||
authentik_core.view_token authentik_core.delete_token
|
||||
authentik_core.delete_authenticatedsession
|
||||
authentik_stages_authenticator_{totp,static,webauthn,email,sms,duo}.view_<kind>device
|
||||
authentik_stages_authenticator_{totp,static,webauthn,email,sms,duo}.delete_<kind>device
|
||||
```
|
||||
Never add `enable_group_superuser`, `view_token_key`, `set_token_key`, `add_token`, `impersonate` or `delete_user`. Invitations are not used at kof22 yet (there is no enrollment flow), so the invitation permissions and `view_flow` are left out; add them with the enrollment flow.
|
||||
2. **Check the brand's recovery flow.** The password reset email (also used by Create User) fails with "No recovery flow set." unless the brand that serves `auth.kof22.com` has a recovery flow. In Authentik admin, *System → Brands*, edit the brand and set *Recovery flow* to `kof22-recovery`. This is a one-time setting.
|
||||
3. **Create the two local tables** (`authentik_admin_action`, `authentik_approval_request`) with the Liquibase change in the Website-Backend PR (see `docs/schema.sql` for the DDL it follows).
|
||||
4. **Turn the features on** in the Website-Backend deployment (the draft PR defines the flags; the default stays read-only). Start with `AUTHENTIK_QBIT_WRITES=false`, check the Identity home, then switch writes on.
|
||||
5. **Try it on a test user**: create one, add them to `kof-website-publishers`, deactivate them. Check that Authentik's *Events* shows `custom_qqq_admin_action` events naming you, and that *Identity → Admin Actions* shows the rows.
|
||||
6. **Two-person approval.** Granting `authentik.*` to a group needs a second person with `authentik.approve`. While you are the only identity administrator, make those grants in the Authentik UI (the break-glass in the spec), or turn `twoPersonApproval` off until a second administrator exists.
|
||||
@@ -0,0 +1,114 @@
|
||||
# QQQ policy format
|
||||
|
||||
Version 1.0.0 of the policy documents that `qbit-authentik` reads and writes. The design is in [DESIGN.md §12](DESIGN.md#12-policies-iam-style-permission-statements-revision-5).
|
||||
|
||||
A **policy** grants QQQ permissions to the members of an Authentik group. It is stored on the group as an attribute. At sign-in, the policies of all the user's groups, including inherited parent groups, become QQQ session permissions.
|
||||
|
||||
## Document
|
||||
|
||||
```json
|
||||
{
|
||||
"PolicySpec": "qqq-iam",
|
||||
"PolicyVersion": "1.0.0",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["hasAccess"],
|
||||
"Resource": ["contentApp", "publishPage"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["read", "insert", "edit"],
|
||||
"Resource": ["cms_page", "cms_media"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Rule |
|
||||
|---|---|---|
|
||||
| `PolicySpec` | string | Must equal the app's configured spec name (`policySpec`, default `qqq-iam`) |
|
||||
| `PolicyVersion` | string, semver | Must equal the supported version (`policyVersion`, default `1.0.0`) |
|
||||
| `Statement` | array of statements | May be empty (grants nothing) |
|
||||
| `Statement[].Effect` | string | `Allow` (the only effect in 1.0.0) |
|
||||
| `Statement[].Action` | array of strings | Each one of `hasAccess`, `read`, `insert`, `edit`, `delete`, `*` |
|
||||
| `Statement[].Resource` | array of strings | Each one a QQQ permission base name matching `[A-Za-z0-9_]+`: a table, process, app, report or widget name (or its custom `permissionBaseName`) |
|
||||
|
||||
## Meaning
|
||||
|
||||
Each statement grants `{resource}.{action}` for every resource and action it lists. `*` stands for all five actions. The result is the union over all statements, and over all of the user's groups.
|
||||
|
||||
| Action | QQQ permission | Applies to |
|
||||
|---|---|---|
|
||||
| `hasAccess` | `{name}.hasAccess` | apps, processes, reports, widgets, and tables with `HAS_ACCESS` permissions |
|
||||
| `read` | `{name}.read` | tables (query, get) |
|
||||
| `insert` | `{name}.insert` | tables |
|
||||
| `edit` | `{name}.edit` | tables |
|
||||
| `delete` | `{name}.delete` | tables |
|
||||
|
||||
Examples:
|
||||
- `{"Action": ["read"], "Resource": ["cms_page"]}` grants `cms_page.read`.
|
||||
- `{"Action": ["*"], "Resource": ["cms_page"]}` grants `cms_page.hasAccess`, `cms_page.read`, `cms_page.insert`, `cms_page.edit` and `cms_page.delete`.
|
||||
|
||||
A grant that QQQ never checks (for example `hasAccess` on a table with insert/edit/delete permissions) is harmless.
|
||||
|
||||
**Not in 1.0.0:** `Deny`, wildcard or prefix resources, conditions, and field-level rules. Named permissions such as `authentik.users.manage` cannot be written as a resource, because they contain dots. They stay in the group attribute `qqq.io/permissions`.
|
||||
|
||||
## Parsing fails closed
|
||||
|
||||
A document grants **nothing**, and the parser logs a warning, when any of these is true:
|
||||
- it is missing, blank, not JSON, or not a JSON object
|
||||
- `PolicySpec` is missing or is not the configured name
|
||||
- `PolicyVersion` is missing or is not the supported version
|
||||
- `Statement` is present but not an array, or a statement is not an object
|
||||
- a statement's `Effect` is not `Allow` (including `Deny`, which is not supported yet)
|
||||
- `Action` or `Resource` is missing or not an array of strings
|
||||
- an action is not one of the six above
|
||||
- a resource does not match `[A-Za-z0-9_]+`
|
||||
|
||||
There is no partial credit: one bad statement voids the whole document. When the qbit reads policies from the group graph, each group's document is parsed on its own, so one bad group voids only that group. In the merged token claim, one bad statement voids the claim.
|
||||
|
||||
## Canonical form
|
||||
|
||||
The qbit always writes the canonical form:
|
||||
- one statement per action that is granted, in the order `hasAccess`, `read`, `insert`, `edit`, `delete`
|
||||
- each statement lists its resources sorted
|
||||
- no `*`
|
||||
- stored on the group as a compact JSON **string**
|
||||
|
||||
Before every save, the qbit checks the round trip: parsing the generated document must give back exactly the permissions it was generated from. A document that fails this check is never written.
|
||||
|
||||
## Where it lives
|
||||
|
||||
| What | Default | Config |
|
||||
|---|---|---|
|
||||
| Group attribute holding a group's document | `qqq.io/policy` | `policyAttribute` |
|
||||
| Token claim holding the merged document | `qqq_policy` | `policyClaim` |
|
||||
| Spec name | `qqq-iam` | `policySpec` |
|
||||
| Version | `1.0.0` | `policyVersion` |
|
||||
|
||||
An app that already stores documents of this shape under its own spec name, attribute and claim sets those four values and keeps its data unchanged. The parser accepts the attribute or claim as a JSON string or as a JSON object.
|
||||
|
||||
## Getting policies into the token
|
||||
|
||||
Authentik puts the merged document into the token through a scope mapping. Steps:
|
||||
|
||||
1. Apply the example blueprint, [`src/test/resources/blueprints/qqq-policy-claim.yaml`](../src/test/resources/blueprints/qqq-policy-claim.yaml). Edit its spec, version, attribute and claim name to match your config.
|
||||
2. Add the mapping to the OAuth2 provider's `property_mappings`. It uses the scope `profile`, which every QQQ sign-in requests.
|
||||
3. Keep `include_claims_in_id_token: true` on the provider (the default).
|
||||
4. Register the customizer in your app:
|
||||
- `AuthentikPolicyClaimMapper` on its own, or
|
||||
- `AuthentikGroupPermissionMapper`, which also reads the claim and the group graph, or
|
||||
- your own customizer, calling `PolicyPermissions.fromClaims(claims, config.getPolicyFormat())`.
|
||||
|
||||
The mapping merges the statements of every group in `request.user.all_groups()` (direct groups and their ancestors) whose document has the right spec and version. It always emits a document, with an empty `Statement` array when the user has no policies.
|
||||
|
||||
The contract test `PolicyClaimMappingIT` runs this blueprint on Authentik 2026.8.3. It puts generated policies on a parent and a child group (one as a string, one as a JSON object), then runs the mapping through Authentik's property-mapping test endpoint for a member of the child group. It checks that the parser turns the claim into the union of the groups' permissions, that a document with another spec is skipped, and that a user without policies gets a valid empty document.
|
||||
|
||||
### Freshness
|
||||
|
||||
The claim is computed when the token is issued, so a policy change reaches a signed-in user at their next token refresh. In kof22 that is within 1 hour. To apply a change at once, revoke the user's sessions (*Revoke Sessions*).
|
||||
|
||||
## Record locks (not yet)
|
||||
|
||||
Row-level security keys are not part of the format. `AuthentikPolicyClaimMapper.applySecurityKeys(QSession, JSONObject)` is the extension point. A host overrides it to set security key values from its own explicit claims, and must never infer them from group names.
|
||||
+42
-25
@@ -2,41 +2,58 @@
|
||||
|
||||
The Authentik qbit's progress through DESIGN.md section 11, with links. Updated with each PR.
|
||||
|
||||
## v1 = phases 0-3 (the full user lifecycle and group/permission management)
|
||||
|
||||
| Phase | State |
|
||||
|---|---|
|
||||
| 0. Foundations and migration | agent items done; **owner items open** (checklist items 6-8, 10, then 12) |
|
||||
| 1. Read-only plus the permissions model | done, except the mirror tables, reconcile and the access-matrix widget (see "Not built yet") |
|
||||
| 2. Memberships and permission editing | done, except the webhook route, ESB trigger, inbox and session re-evaluation marking |
|
||||
| 3. Full user lifecycle | done, except the optional snapshot export |
|
||||
| 4. RBAC role management | post-v1, not started |
|
||||
| 5. Policies and full CRUD (DESIGN.md section 12) | spec approved 2026-10-13; 5a policy model, 5b editor, 5c CRUD additions in progress |
|
||||
|
||||
### Built in this line (0.1)
|
||||
|
||||
| Area | What |
|
||||
|---|---|
|
||||
| People | Create, invite, edit, deactivate, reactivate, password reset email, reset MFA, revoke app passwords, revoke sessions, cancel invitations |
|
||||
| Groups | Create, edit (parents), add and remove members (bulk), edit permissions and app access |
|
||||
| Safety | Subset rule on live groups, protected accounts and superuser groups, no self-edits, last-admin protection, reasons, typed confirmations, bulk caps, stale checks, two-person approval for `authentik.*` |
|
||||
| Audit | `authentik_admin_action` (before the call), Authentik `custom_qqq_admin_action` events, approval requests |
|
||||
| Screens | Home dashboard, main tables in the nav, child lists on parents, every action as a table or record action |
|
||||
| Tests | Unit tests on an in-memory Authentik (rules, processes, app, home), contract tests on Authentik 2026.8.3 |
|
||||
|
||||
### Not built yet (and why)
|
||||
|
||||
| Item | Note |
|
||||
|---|---|
|
||||
| Authentik webhook, ESB trigger, inbox, session re-evaluation marking | Needs the notification transport in cluster-gitops (inert today); reads are live (30 s cache) so screens are correct without it |
|
||||
| Mirror tables and reconcile | For Web Users joins and widget counts; the home reads live |
|
||||
| Access matrix widget, group tree widget | Needs Next UI custom widgets (separate frontend PRs) |
|
||||
| Snapshot export | Optional in the spec |
|
||||
| RBAC role management | Phase 4 |
|
||||
| Alerts producer integration | Optional until the Alerts qbit SPI (QRun-IO/qqq#1090) lands |
|
||||
| Quick Search for users and groups | They are API-backed (read-through), so they are searched with the table's own search box, which Authentik evaluates live |
|
||||
| Invitations add groups | Groups for invited people are added after they sign up (needs the webhook) |
|
||||
|
||||
## Phase 0: foundations (agent items done; owner items open)
|
||||
|
||||
| # | Item | State | Where |
|
||||
|---|---|---|---|
|
||||
| 1 | Repo, DESIGN.md, CI, README, CLAUDE.md | done | this repo (`develop`); private for now, see owner checklist D1 |
|
||||
| 1 | Repo, DESIGN.md, CI, README, CLAUDE.md | done | this repo (`develop`); public |
|
||||
| 2 | Config, producer, `AuthentikActionUtil`, pinned schema + drift test | done | phase 0 PR |
|
||||
| 3 | Testcontainers harness, fixture recorder, contract tests (b), (c), (d), (h) | done | phase 0 PR, `src/test/java/.../contract` |
|
||||
| 4 | Open points (i)-(iv) resolved | done | DESIGN.md section 0.2; QRun-IO/qqq#1065 revision 3 |
|
||||
| 3 | Testcontainers harness, fixture recorder, contract tests (b), (c), (d), (h) | done | `src/test/java/.../contract` |
|
||||
| 4 | Open points (i)-(iv) resolved | done | DESIGN.md section 0.2 |
|
||||
| 5 | cluster-gitops PR (bootstrap, removals, sign-in policy, webhook, lint) | draft | KofTwentyTwo/cluster-gitops#72 |
|
||||
| 6 | Staging rehearsal | **owner** | `docs/PHASE0-OWNER-CHECKLIST.md`, `docs/cluster-gitops-phase0/rehearse-phase0.sh` |
|
||||
| 7 | Production apply | **owner** | checklist |
|
||||
| 8 | Service-account token, Infisical, webhook secret | **owner** | checklist |
|
||||
| 9 | Website-Backend wiring (ExternalSecret + env, qbit behind a disabled flag) | draft | KofTwentyTwo/cluster-gitops#73, Website-Backend draft PR |
|
||||
| 9 | Website-Backend wiring (ExternalSecret + env, qbit behind a disabled flag) | draft | KofTwentyTwo/cluster-gitops#73, Website-Backend#94 |
|
||||
| 10 | Seed attributes, break-glass password | **owner** | checklist |
|
||||
| 11 | Read-only on staging | after 6-10 | flip `AUTHENTIK_QBIT_ENABLED` |
|
||||
| 12 | Turn on the full lifecycle (role permissions, brand recovery flow, tables, flags) | after 11 | checklist item 12 |
|
||||
|
||||
## Phase 1: read-only MVP
|
||||
## Contract and unit tests (Authentik 2026.8.3)
|
||||
|
||||
| Item | State |
|
||||
|---|---|
|
||||
| Users, groups, memberships, sessions, events tables | done (phase 1 PR) |
|
||||
| Effective permissions (resolver), inherited superuser | done |
|
||||
| Identity drift report (widget) | done |
|
||||
| Identity app under Admin, after Web Users (kof22) | Website-Backend draft PR #94 |
|
||||
| `AuthentikGroupPermissionMapper` (sign-in permissions from groups) | done in the qbit; the kof22 cut-over (replacing `AuthentikAuthenticationCustomizer`) waits for owner item 10 |
|
||||
| Code review (general + silent-failure) | done; all high and most medium findings fixed, with regression tests |
|
||||
| Mirror tables, group tree, access-matrix widgets | next PRs |
|
||||
|
||||
## Contract test results (Authentik 2026.8.3)
|
||||
|
||||
`CI=true ./mvnw verify`:
|
||||
|
||||
| Phase | Unit tests | Contract tests |
|
||||
|---|---|---|
|
||||
| 0 | 48 | 27 |
|
||||
| 1 | 68 | 31 |
|
||||
|
||||
All green, JaCoCo gate met. CircleCI is not enabled for this repo yet (owner checklist D1).
|
||||
`CI=true ./mvnw verify`. The numbers are filled in at the end of each PR; see the PR description.
|
||||
@@ -0,0 +1,70 @@
|
||||
-- The qbit's own tables (DESIGN.md section 6.2) for the host's local RDBMS backend.
|
||||
-- Column names are the snake_case of the QQQ field names. PostgreSQL syntax; adapt the
|
||||
-- types for another database. The tables are written only by the qbit (the generic
|
||||
-- insert, update and delete capabilities are off); authentik_admin_action is append-only
|
||||
-- in practice (rows move from RUNNING to a final status, and are never deleted).
|
||||
-- Retention: the audit trail is kept 2 years (DESIGN.md section 9.4).
|
||||
|
||||
CREATE TABLE authentik_admin_action
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
create_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
modify_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
correlation_id VARCHAR(64),
|
||||
action_name VARCHAR(60) NOT NULL,
|
||||
operator VARCHAR(255),
|
||||
reason TEXT,
|
||||
target_type VARCHAR(30),
|
||||
target_key VARCHAR(100),
|
||||
target_label VARCHAR(255),
|
||||
before_text TEXT,
|
||||
after_text TEXT,
|
||||
status VARCHAR(30) NOT NULL,
|
||||
error_message TEXT,
|
||||
authentik_event_pk VARCHAR(64),
|
||||
approver VARCHAR(255)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_authentik_admin_action_create_date ON authentik_admin_action (create_date);
|
||||
CREATE INDEX idx_authentik_admin_action_target ON authentik_admin_action (target_type, target_key);
|
||||
CREATE INDEX idx_authentik_admin_action_operator ON authentik_admin_action (operator);
|
||||
|
||||
CREATE TABLE authentik_approval_request
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
create_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
modify_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
action_name VARCHAR(60) NOT NULL,
|
||||
target_key VARCHAR(100),
|
||||
target_label VARCHAR(255),
|
||||
summary TEXT,
|
||||
reason TEXT,
|
||||
payload_json TEXT NOT NULL,
|
||||
requester VARCHAR(255) NOT NULL,
|
||||
approver VARCHAR(255),
|
||||
status VARCHAR(30) NOT NULL,
|
||||
expires_date TIMESTAMP WITH TIME ZONE,
|
||||
decided_date TIMESTAMP WITH TIME ZONE,
|
||||
error_message TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_authentik_approval_request_status ON authentik_approval_request (status);
|
||||
|
||||
-- authentik_policy (DESIGN.md section 12): the QQQ record of each group's last policy save.
|
||||
-- Authentik holds the live document (group attribute qqq.io/policy); field-level QQQ audit on
|
||||
-- this table is the policy's change history.
|
||||
CREATE TABLE authentik_policy
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
create_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
modify_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
group_pk VARCHAR(64) NOT NULL,
|
||||
group_name VARCHAR(255),
|
||||
policy_json TEXT,
|
||||
statement_count INTEGER,
|
||||
permission_count INTEGER,
|
||||
saved_by VARCHAR(255),
|
||||
saved_date TIMESTAMP WITH TIME ZONE,
|
||||
authentik_fingerprint VARCHAR(64),
|
||||
CONSTRAINT uk_authentik_policy_group_pk UNIQUE (group_pk)
|
||||
);
|
||||
@@ -32,6 +32,12 @@ public enum AuthentikFeature
|
||||
/** Create and edit groups, permissions and app-access attributes (phase 2/3). */
|
||||
GROUPS,
|
||||
|
||||
/** Edit group policies (IAM-style statements) with the policy editor (DESIGN.md section 12). */
|
||||
POLICIES,
|
||||
|
||||
/** Delete users and groups as an explicit action (DESIGN.md section 12.5). */
|
||||
DELETE,
|
||||
|
||||
/** Add and remove members (phase 2). */
|
||||
MEMBERSHIP,
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qqq.backend.core.instances.QMetaDataVariableInterpreter;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
|
||||
@@ -44,7 +45,12 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
public class AuthentikQBitConfig implements QBitConfig
|
||||
{
|
||||
/** Features implemented in this release. Others are refused by validate(). */
|
||||
public static final Set<AuthentikFeature> AVAILABLE_FEATURES = EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MIRROR);
|
||||
public static final Set<AuthentikFeature> AVAILABLE_FEATURES = EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES);
|
||||
|
||||
/** Features that change Authentik data; they need a local backend for the audit trail. */
|
||||
public static final Set<AuthentikFeature> WRITE_FEATURES = EnumSet.of(AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES);
|
||||
|
||||
private static final Pattern APP_KEY_PATTERN = Pattern.compile("[a-z0-9][a-z0-9-]{0,48}[a-z0-9]");
|
||||
private static final Pattern PREFIX_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9]{0,30}");
|
||||
@@ -60,9 +66,12 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
private List<String> userScopeGroupNames = new ArrayList<>();
|
||||
private String groupScopeNamePrefix;
|
||||
private List<String> protectedUsernames = new ArrayList<>();
|
||||
private String bootstrapOperators = "${env.AUTHENTIK_QBIT_BOOTSTRAP_OPERATORS}";
|
||||
private String bootstrapOperatorSubjects = "${env.AUTHENTIK_QBIT_BOOTSTRAP_SUBJECTS}";
|
||||
private List<String> applicationsInScope = new ArrayList<>();
|
||||
private String mirrorBackendName;
|
||||
private String localBackendName;
|
||||
private Boolean twoPersonApproval = true;
|
||||
private String schedulerName;
|
||||
private String linkPrefix = "/app";
|
||||
private String recoveryEmailStage;
|
||||
private String invitationFlow;
|
||||
private String newUserPath = "users";
|
||||
@@ -76,6 +85,11 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
private Integer socketTimeoutMillis = 30_000;
|
||||
private String expectedServerVersion = "2026.8";
|
||||
private Boolean allowInsecureHttp = false;
|
||||
private String policySpec = PolicyFormat.DEFAULT_SPEC;
|
||||
private String policyVersion = PolicyFormat.DEFAULT_VERSION;
|
||||
private String policyAttribute = PolicyFormat.DEFAULT_ATTRIBUTE;
|
||||
private String policyClaim = PolicyFormat.DEFAULT_CLAIM;
|
||||
private Boolean policyTwoPersonApproval = false;
|
||||
|
||||
|
||||
|
||||
@@ -147,15 +161,16 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
}
|
||||
}
|
||||
|
||||
if(requested.contains(AuthentikFeature.MIRROR))
|
||||
boolean writes = requested.stream().anyMatch(WRITE_FEATURES::contains);
|
||||
if(writes || StringUtils.hasContent(localBackendName))
|
||||
{
|
||||
if(!StringUtils.hasContent(mirrorBackendName))
|
||||
if(!StringUtils.hasContent(localBackendName))
|
||||
{
|
||||
errors.add("feature MIRROR needs mirrorBackendName (an RDBMS backend of the instance)");
|
||||
errors.add("features that change Authentik data need localBackendName (an RDBMS backend of the instance, for the audit trail)");
|
||||
}
|
||||
else if(qInstance != null && qInstance.getBackends() != null && qInstance.getBackend(mirrorBackendName) == null)
|
||||
else if(qInstance != null && qInstance.getBackends() != null && qInstance.getBackend(localBackendName) == null)
|
||||
{
|
||||
errors.add("mirrorBackendName: backend not found: " + mirrorBackendName);
|
||||
errors.add("localBackendName: backend not found: " + localBackendName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,11 +179,25 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
errors.add("features USERS and CREDENTIALS need recoveryEmailStage");
|
||||
}
|
||||
|
||||
if(requested.contains(AuthentikFeature.POLICIES) && !requested.contains(AuthentikFeature.GROUPS))
|
||||
{
|
||||
errors.add("feature POLICIES needs GROUPS");
|
||||
}
|
||||
|
||||
if(requested.contains(AuthentikFeature.WEBHOOK) && !StringUtils.hasContent(getResolvedWebhookSecret()))
|
||||
{
|
||||
errors.add("feature WEBHOOK needs webhookSecret");
|
||||
}
|
||||
|
||||
for(String subject : getResolvedBootstrapSubjects())
|
||||
{
|
||||
if(subject.contains("@"))
|
||||
{
|
||||
errors.add("bootstrapOperatorSubjects must be immutable ids (the token sub, or the Authentik user pk or uuid), never emails: users can change their own email");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for(Integer value : new Integer[] { throttleRequestsPerSecond, throttleBurst, listCacheTtlSeconds, groupCacheTtlSeconds, connectTimeoutMillis, socketTimeoutMillis })
|
||||
{
|
||||
if(value == null || value < 0)
|
||||
@@ -177,6 +206,12 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
break;
|
||||
}
|
||||
}
|
||||
String policyProblem = getPolicyFormat().problem();
|
||||
if(policyProblem != null)
|
||||
{
|
||||
errors.add(policyProblem);
|
||||
}
|
||||
|
||||
if(throttleRequestsPerSecond != null && throttleRequestsPerSecond == 0)
|
||||
{
|
||||
errors.add("throttleRequestsPerSecond must be at least 1");
|
||||
@@ -347,20 +382,22 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Bootstrap operator emails, resolved and split on commas, lower-cased.
|
||||
** Bootstrap operator subjects, resolved and split on commas. Each is an
|
||||
** IMMUTABLE identifier (the token's sub, or the Authentik user pk or uuid);
|
||||
** never an email, because users can change their own email.
|
||||
*******************************************************************************/
|
||||
@JsonIgnore
|
||||
public Set<String> getResolvedBootstrapOperators()
|
||||
public Set<String> getResolvedBootstrapSubjects()
|
||||
{
|
||||
Set<String> rs = new LinkedHashSet<>();
|
||||
String resolved = resolve(bootstrapOperators);
|
||||
String resolved = resolve(bootstrapOperatorSubjects);
|
||||
if(StringUtils.hasContent(resolved))
|
||||
{
|
||||
for(String part : resolved.split(","))
|
||||
{
|
||||
if(StringUtils.hasContent(part))
|
||||
{
|
||||
rs.add(part.trim().toLowerCase());
|
||||
rs.add(part.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -704,21 +741,21 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for bootstrapOperators (raw value)
|
||||
** Getter for bootstrapOperatorSubjects (raw value)
|
||||
*******************************************************************************/
|
||||
public String getBootstrapOperators()
|
||||
public String getBootstrapOperatorSubjects()
|
||||
{
|
||||
return (this.bootstrapOperators);
|
||||
return (this.bootstrapOperatorSubjects);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for bootstrapOperators (comma-separated emails or ${env.X})
|
||||
** Fluent setter for bootstrapOperatorSubjects (comma-separated emails or ${env.X})
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withBootstrapOperators(String bootstrapOperators)
|
||||
public AuthentikQBitConfig withBootstrapOperatorSubjects(String bootstrapOperatorSubjects)
|
||||
{
|
||||
this.bootstrapOperators = bootstrapOperators;
|
||||
this.bootstrapOperatorSubjects = bootstrapOperatorSubjects;
|
||||
return (this);
|
||||
}
|
||||
|
||||
@@ -748,21 +785,87 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for mirrorBackendName
|
||||
** Getter for localBackendName: the RDBMS backend holding the qbit's own
|
||||
** tables (admin actions, approval requests).
|
||||
*******************************************************************************/
|
||||
public String getMirrorBackendName()
|
||||
public String getLocalBackendName()
|
||||
{
|
||||
return (this.mirrorBackendName);
|
||||
return (this.localBackendName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for mirrorBackendName
|
||||
** Fluent setter for localBackendName
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withMirrorBackendName(String mirrorBackendName)
|
||||
public AuthentikQBitConfig withLocalBackendName(String localBackendName)
|
||||
{
|
||||
this.mirrorBackendName = mirrorBackendName;
|
||||
this.localBackendName = localBackendName;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for twoPersonApproval: whether adding authentik.* permissions to a
|
||||
** group needs a second person (authentik.approve) to approve it.
|
||||
*******************************************************************************/
|
||||
public Boolean getTwoPersonApproval()
|
||||
{
|
||||
return (this.twoPersonApproval);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for twoPersonApproval
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withTwoPersonApproval(Boolean twoPersonApproval)
|
||||
{
|
||||
this.twoPersonApproval = twoPersonApproval;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for linkPrefix: the path prefix of table and record links the home
|
||||
** page renders (the Next UI serves tables at /app/{table}).
|
||||
*******************************************************************************/
|
||||
public String getLinkPrefix()
|
||||
{
|
||||
return (this.linkPrefix);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for linkPrefix
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withLinkPrefix(String linkPrefix)
|
||||
{
|
||||
this.linkPrefix = linkPrefix;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for schedulerName (optional; runs the reconcile/attention checks)
|
||||
*******************************************************************************/
|
||||
public String getSchedulerName()
|
||||
{
|
||||
return (this.schedulerName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for schedulerName
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withSchedulerName(String schedulerName)
|
||||
{
|
||||
this.schedulerName = schedulerName;
|
||||
return (this);
|
||||
}
|
||||
|
||||
@@ -1019,4 +1122,120 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for policySpec: the PolicySpec this app accepts and writes (docs/POLICY-FORMAT.md).
|
||||
*******************************************************************************/
|
||||
public String getPolicySpec()
|
||||
{
|
||||
return (this.policySpec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for policySpec
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withPolicySpec(String policySpec)
|
||||
{
|
||||
this.policySpec = policySpec;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for policyVersion: the one supported PolicyVersion (semver).
|
||||
*******************************************************************************/
|
||||
public String getPolicyVersion()
|
||||
{
|
||||
return (this.policyVersion);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for policyVersion
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withPolicyVersion(String policyVersion)
|
||||
{
|
||||
this.policyVersion = policyVersion;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for policyAttribute: the Authentik group attribute that holds a group's policy document.
|
||||
*******************************************************************************/
|
||||
public String getPolicyAttribute()
|
||||
{
|
||||
return (this.policyAttribute);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for policyAttribute
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withPolicyAttribute(String policyAttribute)
|
||||
{
|
||||
this.policyAttribute = policyAttribute;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for policyClaim: the token claim that holds the merged policy document.
|
||||
*******************************************************************************/
|
||||
public String getPolicyClaim()
|
||||
{
|
||||
return (this.policyClaim);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for policyClaim
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withPolicyClaim(String policyClaim)
|
||||
{
|
||||
this.policyClaim = policyClaim;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for policyTwoPersonApproval: whether every policy save needs a second person (authentik.approve).
|
||||
*******************************************************************************/
|
||||
public Boolean getPolicyTwoPersonApproval()
|
||||
{
|
||||
return (this.policyTwoPersonApproval);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for policyTwoPersonApproval
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withPolicyTwoPersonApproval(Boolean policyTwoPersonApproval)
|
||||
{
|
||||
this.policyTwoPersonApproval = policyTwoPersonApproval;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policy names (spec, version, attribute, claim) as one value.
|
||||
*******************************************************************************/
|
||||
@JsonIgnore
|
||||
public PolicyFormat getPolicyFormat()
|
||||
{
|
||||
return (new PolicyFormat(policySpec, policyVersion, policyAttribute, policyClaim));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,11 +21,17 @@ import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.app.AuthentikRelations;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qbits.authentik.metadata.AuthentikAppMetaDataProducer;
|
||||
import com.kingsrook.qbits.authentik.processes.AuthentikProcesses;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
@@ -178,6 +184,13 @@ public class AuthentikQBitProducer implements QBitMetaDataProducer<AuthentikQBit
|
||||
MetaDataProducerMultiOutput output = QBitMetaDataProducer.super.produce(qInstance);
|
||||
output.addSelfToInstance(qInstance);
|
||||
|
||||
addPossibleValueSources(qInstance);
|
||||
AuthentikRelations.apply(qInstance, qBitConfig);
|
||||
for(QProcessMetaData process : AuthentikProcesses.processes(qBitConfig))
|
||||
{
|
||||
qInstance.addProcess(process);
|
||||
}
|
||||
|
||||
LOG.info("Authentik QBit produced", logPair("version", VERSION), logPair("appKey", qBitConfig.getAppKey()),
|
||||
logPair("features", qBitConfig.getFeatures()), logPair("readOnly", qBitConfig.getReadOnly()));
|
||||
return (new MetaDataProducerMultiOutput());
|
||||
@@ -185,6 +198,31 @@ public class AuthentikQBitProducer implements QBitMetaDataProducer<AuthentikQBit
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Possible-value sources: the user and group tables (for the group pickers
|
||||
** on the actions) and the local tables' status enums.
|
||||
*******************************************************************************/
|
||||
private void addPossibleValueSources(QInstance qInstance)
|
||||
{
|
||||
for(String spec : List.of(AuthentikTables.USER, AuthentikTables.GROUP))
|
||||
{
|
||||
String name = qBitConfig.applyTablePrefix(spec);
|
||||
if(qInstance.getPossibleValueSource(name) == null)
|
||||
{
|
||||
qInstance.addPossibleValueSource(QPossibleValueSource.newForTable(name));
|
||||
}
|
||||
}
|
||||
if(qBitConfig.getLocalBackendName() != null)
|
||||
{
|
||||
for(QPossibleValueSource source : AuthentikLocalTables.possibleValueSources())
|
||||
{
|
||||
qInstance.addPossibleValueSource(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The artifact version, from the Maven-filtered qbit-authentik.properties.
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -24,6 +24,7 @@ import com.kingsrook.qbits.authentik.client.AuthentikFilterMapper;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTableSpec;
|
||||
import com.kingsrook.qbits.authentik.client.TokenBucketThrottle;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyCatalog;
|
||||
import com.kingsrook.qbits.authentik.security.AuthentikGuard;
|
||||
import com.kingsrook.qqq.backend.core.utils.memoization.Memoization;
|
||||
|
||||
@@ -45,6 +46,7 @@ public class AuthentikRuntime
|
||||
private final Memoization<String, String> responseCache;
|
||||
private final Memoization<String, GroupGraph> groupGraphCache;
|
||||
private volatile java.util.Set<String> permissionCatalog;
|
||||
private volatile PolicyCatalog policyCatalog;
|
||||
private final Map<String, AuthentikTableSpec> specsByTableName = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
@@ -149,14 +151,39 @@ public class AuthentikRuntime
|
||||
if(permissionCatalog == null)
|
||||
{
|
||||
com.kingsrook.qqq.backend.core.model.metadata.QInstance qInstance = com.kingsrook.qqq.backend.core.context.QContext.getQInstance();
|
||||
permissionCatalog = qInstance == null ? java.util.Set.of()
|
||||
: new java.util.TreeSet<>(com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper.getAllAvailablePermissionNames(qInstance));
|
||||
if(qInstance == null)
|
||||
{
|
||||
return (java.util.Set.of());
|
||||
}
|
||||
java.util.Set<String> catalog = new java.util.TreeSet<>(com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper.getAllAvailablePermissionNames(qInstance));
|
||||
catalog.addAll(getPolicyCatalog().permissionNames());
|
||||
permissionCatalog = catalog;
|
||||
}
|
||||
return (permissionCatalog);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a policy can grant in the current instance (built once, lazily: the
|
||||
** instance is complete by the first request).
|
||||
*******************************************************************************/
|
||||
public PolicyCatalog getPolicyCatalog()
|
||||
{
|
||||
if(policyCatalog == null)
|
||||
{
|
||||
com.kingsrook.qqq.backend.core.model.metadata.QInstance qInstance = com.kingsrook.qqq.backend.core.context.QContext.getQInstance();
|
||||
if(qInstance == null)
|
||||
{
|
||||
return (PolicyCatalog.of(new com.kingsrook.qqq.backend.core.model.metadata.QInstance()));
|
||||
}
|
||||
policyCatalog = PolicyCatalog.of(qInstance);
|
||||
}
|
||||
return (policyCatalog);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for config
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every change the qbit can make to Authentik (DESIGN.md section 6.3), with
|
||||
** the QQQ permission and feature it needs and how strongly it is confirmed.
|
||||
*******************************************************************************/
|
||||
public enum AdminAction
|
||||
{
|
||||
CREATE_USER("Create user", "user", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.CONFIRM),
|
||||
INVITE_USER("Invite user", "invitation", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.CONFIRM),
|
||||
EDIT_USER("Edit user", "user", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.CONFIRM),
|
||||
DEACTIVATE_USER("Deactivate user", "user", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.TYPED),
|
||||
REACTIVATE_USER("Reactivate user", "user", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.CONFIRM),
|
||||
CANCEL_INVITATION("Cancel invitation", "invitation", IdentityPermission.USERS_MANAGE, AuthentikFeature.USERS, Confirmation.CONFIRM),
|
||||
ADD_MEMBER("Add to group", "membership", IdentityPermission.MEMBERSHIPS_MANAGE, AuthentikFeature.MEMBERSHIP, Confirmation.CONFIRM),
|
||||
REMOVE_MEMBER("Remove from group", "membership", IdentityPermission.MEMBERSHIPS_MANAGE, AuthentikFeature.MEMBERSHIP, Confirmation.CONFIRM),
|
||||
CREATE_GROUP("Create group", "group", IdentityPermission.GROUPS_MANAGE, AuthentikFeature.GROUPS, Confirmation.CONFIRM),
|
||||
EDIT_GROUP("Edit group", "group", IdentityPermission.GROUPS_MANAGE, AuthentikFeature.GROUPS, Confirmation.CONFIRM),
|
||||
EDIT_PERMISSIONS("Edit permissions and app access", "group", IdentityPermission.PERMISSIONS_MANAGE, AuthentikFeature.GROUPS, Confirmation.CONFIRM),
|
||||
SAVE_POLICY("Save policy", "group", IdentityPermission.POLICIES_MANAGE, AuthentikFeature.POLICIES, Confirmation.CONFIRM),
|
||||
SEND_RECOVERY_EMAIL("Send password reset email", "user", IdentityPermission.CREDENTIALS_RESET, AuthentikFeature.CREDENTIALS, Confirmation.CONFIRM),
|
||||
RESET_MFA("Reset MFA", "user", IdentityPermission.CREDENTIALS_RESET, AuthentikFeature.CREDENTIALS, Confirmation.TYPED),
|
||||
REVOKE_APP_PASSWORDS("Revoke app passwords", "user", IdentityPermission.CREDENTIALS_RESET, AuthentikFeature.CREDENTIALS, Confirmation.TYPED),
|
||||
REVOKE_SESSIONS("Revoke sessions", "user", IdentityPermission.SESSIONS_REVOKE, AuthentikFeature.SESSIONS, Confirmation.CONFIRM);
|
||||
|
||||
/** How strongly an action is confirmed (DESIGN.md section 6.3). */
|
||||
public enum Confirmation
|
||||
{
|
||||
/** The Review screen is the confirmation. */
|
||||
CONFIRM,
|
||||
/** The operator also types the target's name (or the number of targets). */
|
||||
TYPED
|
||||
}
|
||||
|
||||
private final String label;
|
||||
private final String targetType;
|
||||
private final IdentityPermission permission;
|
||||
private final AuthentikFeature feature;
|
||||
private final Confirmation confirmation;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
AdminAction(String label, String targetType, IdentityPermission permission, AuthentikFeature feature, Confirmation confirmation)
|
||||
{
|
||||
this.label = label;
|
||||
this.targetType = targetType;
|
||||
this.permission = permission;
|
||||
this.feature = feature;
|
||||
this.confirmation = confirmation;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for label
|
||||
*******************************************************************************/
|
||||
public String getLabel()
|
||||
{
|
||||
return (label);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for targetType
|
||||
*******************************************************************************/
|
||||
public String getTargetType()
|
||||
{
|
||||
return (targetType);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for permission
|
||||
*******************************************************************************/
|
||||
public IdentityPermission getPermission()
|
||||
{
|
||||
return (permission);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for feature
|
||||
*******************************************************************************/
|
||||
public AuthentikFeature getFeature()
|
||||
{
|
||||
return (feature);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for confirmation
|
||||
*******************************************************************************/
|
||||
public Confirmation getConfirmation()
|
||||
{
|
||||
return (confirmation);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Writes the local, append-only audit row (DESIGN.md sections 6.2 and 9.2).
|
||||
** The row is inserted BEFORE the Authentik call; if that insert fails the call
|
||||
** is not made. After the call the same row moves to its final status. Rows are
|
||||
** never deleted.
|
||||
*******************************************************************************/
|
||||
public class AdminActionAuditor
|
||||
{
|
||||
private final AuthentikQBitConfig config;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
public AdminActionAuditor(AuthentikQBitConfig config)
|
||||
{
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Insert the row for a plan before it runs (or is refused / queued) and
|
||||
** return its id. Throws when the audit trail cannot be written, so the
|
||||
** caller must not proceed.
|
||||
*******************************************************************************/
|
||||
public Serializable begin(AdminPlan plan, String correlationId, String operator, AuthentikLocalTables.ActionStatus status, String approver) throws QException
|
||||
{
|
||||
QRecord record = new QRecord()
|
||||
.withValue("correlationId", correlationId)
|
||||
.withValue("actionName", plan.getRequest().action().name())
|
||||
.withValue("operator", operator)
|
||||
.withValue("reason", plan.getRequest().reason())
|
||||
.withValue("targetType", plan.getTargetType())
|
||||
.withValue("targetKey", plan.getRequest().targetKey())
|
||||
.withValue("targetLabel", plan.getTargetLabel())
|
||||
.withValue("beforeText", plan.getBefore())
|
||||
.withValue("afterText", plan.getAfter())
|
||||
.withValue("status", status.name())
|
||||
.withValue("approver", approver)
|
||||
.withValue("errorMessage", status == AuthentikLocalTables.ActionStatus.REFUSED ? plan.getMessage() : null)
|
||||
.withValue("createDate", Instant.now())
|
||||
.withValue("modifyDate", Instant.now());
|
||||
|
||||
InsertInput insertInput = new InsertInput();
|
||||
insertInput.setTableName(config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION));
|
||||
insertInput.setRecords(List.of(record));
|
||||
InsertOutput output = new InsertAction().execute(insertInput);
|
||||
QRecord saved = output.getRecords().isEmpty() ? null : output.getRecords().get(0);
|
||||
if(saved == null || saved.getValue("id") == null || !saved.getErrors().isEmpty())
|
||||
{
|
||||
throw (new QException("The audit row could not be written, so nothing was changed in Authentik."));
|
||||
}
|
||||
return (saved.getValue("id"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Move a row to its final status. A failure here is logged by the caller;
|
||||
** the Authentik change has already happened.
|
||||
*******************************************************************************/
|
||||
public void finish(Serializable id, AuthentikLocalTables.ActionStatus status, String errorMessage, String eventPk, String approver) throws QException
|
||||
{
|
||||
QRecord update = new QRecord()
|
||||
.withValue("id", id)
|
||||
.withValue("status", status.name())
|
||||
.withValue("errorMessage", errorMessage)
|
||||
.withValue("authentikEventPk", eventPk)
|
||||
.withValue("modifyDate", Instant.now());
|
||||
if(approver != null)
|
||||
{
|
||||
update.withValue("approver", approver);
|
||||
}
|
||||
UpdateInput updateInput = new UpdateInput();
|
||||
updateInput.setTableName(config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION));
|
||||
updateInput.setRecords(List.of(update));
|
||||
new UpdateAction().execute(updateInput);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a request would do, computed by the guard rules before anything is
|
||||
** sent: whether it may run, why not, the target, a before and after, and
|
||||
** whether it needs a second person. The Review screen shows it; the Result
|
||||
** step executes it (after computing it again against live data).
|
||||
*******************************************************************************/
|
||||
public class AdminPlan
|
||||
{
|
||||
/** The outcome of planning. */
|
||||
public enum State
|
||||
{
|
||||
/** Will run. */
|
||||
READY,
|
||||
/** Already in the wanted state; nothing to do. */
|
||||
NO_CHANGE,
|
||||
/** Refused by a rule (the message says which). */
|
||||
REFUSED,
|
||||
/** Allowed, but needs a second person to approve first. */
|
||||
NEEDS_APPROVAL
|
||||
}
|
||||
|
||||
private final AdminRequest request;
|
||||
private State state = State.READY;
|
||||
private String message;
|
||||
private String targetType;
|
||||
private String targetLabel;
|
||||
private String before;
|
||||
private String after;
|
||||
private final List<String> notes = new ArrayList<>();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
public AdminPlan(AdminRequest request)
|
||||
{
|
||||
this.request = request;
|
||||
this.targetType = request.action().getTargetType();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Refuse, with the reason shown to the operator.
|
||||
*******************************************************************************/
|
||||
public AdminPlan refuse(String reason)
|
||||
{
|
||||
this.state = State.REFUSED;
|
||||
this.message = reason;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Mark as already done.
|
||||
*******************************************************************************/
|
||||
public AdminPlan noChange(String why)
|
||||
{
|
||||
this.state = State.NO_CHANGE;
|
||||
this.message = why;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the plan will make a change when executed.
|
||||
*******************************************************************************/
|
||||
public boolean isRunnable()
|
||||
{
|
||||
return (state == State.READY);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for request
|
||||
*******************************************************************************/
|
||||
public AdminRequest getRequest()
|
||||
{
|
||||
return (request);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for state
|
||||
*******************************************************************************/
|
||||
public State getState()
|
||||
{
|
||||
return (state);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for state
|
||||
*******************************************************************************/
|
||||
public AdminPlan withState(State state)
|
||||
{
|
||||
this.state = state;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for message
|
||||
*******************************************************************************/
|
||||
public String getMessage()
|
||||
{
|
||||
return (message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for message
|
||||
*******************************************************************************/
|
||||
public AdminPlan withMessage(String message)
|
||||
{
|
||||
this.message = message;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for targetType
|
||||
*******************************************************************************/
|
||||
public String getTargetType()
|
||||
{
|
||||
return (targetType);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for targetLabel
|
||||
*******************************************************************************/
|
||||
public String getTargetLabel()
|
||||
{
|
||||
return (targetLabel);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for targetLabel
|
||||
*******************************************************************************/
|
||||
public AdminPlan withTargetLabel(String targetLabel)
|
||||
{
|
||||
this.targetLabel = targetLabel;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for before
|
||||
*******************************************************************************/
|
||||
public String getBefore()
|
||||
{
|
||||
return (before);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for after
|
||||
*******************************************************************************/
|
||||
public String getAfter()
|
||||
{
|
||||
return (after);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Set the before and after text.
|
||||
*******************************************************************************/
|
||||
public AdminPlan withChange(String before, String after)
|
||||
{
|
||||
this.before = before;
|
||||
this.after = after;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Notes for the operator (warnings and consequences).
|
||||
*******************************************************************************/
|
||||
public List<String> getNotes()
|
||||
{
|
||||
return (notes);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A one-line description for review lines and audit.
|
||||
*******************************************************************************/
|
||||
public String describe()
|
||||
{
|
||||
return (request.action().getLabel() + ": " + (targetLabel == null ? request.targetKey() : targetLabel)
|
||||
+ (before != null || after != null ? " (" + (before == null ? "" : before) + " -> " + (after == null ? "" : after) + ")" : ""));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One requested change: the action, its target key (a user pk, a group uuid,
|
||||
** "groupPk:userPk" for memberships, an invitation uuid, or blank when
|
||||
** creating), its parameters, and the operator's reason. Serializable to JSON
|
||||
** so a two-person request can be stored and applied later.
|
||||
**
|
||||
** @param action what to do
|
||||
** @param targetKey the target (see above)
|
||||
** @param params action parameters (strings and booleans)
|
||||
** @param reason why (required for every write)
|
||||
*******************************************************************************/
|
||||
public record AdminRequest(AdminAction action, String targetKey, Map<String, Serializable> params, String reason)
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** A request with no parameters.
|
||||
*******************************************************************************/
|
||||
public static AdminRequest of(AdminAction action, String targetKey, String reason)
|
||||
{
|
||||
return (new AdminRequest(action, targetKey, new LinkedHashMap<>(), reason));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent parameter setter (returns this request).
|
||||
*******************************************************************************/
|
||||
public AdminRequest with(String name, Serializable value)
|
||||
{
|
||||
params.put(name, value);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A parameter as trimmed text, or "" when absent.
|
||||
*******************************************************************************/
|
||||
public String str(String name)
|
||||
{
|
||||
Serializable value = params.get(name);
|
||||
return (value == null ? "" : String.valueOf(value).trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A parameter as a boolean (true for true or "true").
|
||||
*******************************************************************************/
|
||||
public boolean bool(String name)
|
||||
{
|
||||
Serializable value = params.get(name);
|
||||
return (value instanceof Boolean b ? b : value != null && "true".equalsIgnoreCase(String.valueOf(value).trim()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** To JSON (for a stored approval request).
|
||||
*******************************************************************************/
|
||||
public String toJson()
|
||||
{
|
||||
return (new JSONObject()
|
||||
.put("action", action.name())
|
||||
.put("targetKey", targetKey)
|
||||
.put("reason", reason)
|
||||
.put("params", new JSONObject(params)).toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** From JSON written by toJson.
|
||||
*******************************************************************************/
|
||||
public static AdminRequest fromJson(String json)
|
||||
{
|
||||
JSONObject object = new JSONObject(json);
|
||||
Map<String, Serializable> params = new LinkedHashMap<>();
|
||||
JSONObject stored = object.optJSONObject("params");
|
||||
if(stored != null)
|
||||
{
|
||||
for(String key : stored.keySet())
|
||||
{
|
||||
Object value = stored.get(key);
|
||||
params.put(key, value instanceof Boolean || value instanceof Number ? (Serializable) value : String.valueOf(value));
|
||||
}
|
||||
}
|
||||
return (new AdminRequest(AdminAction.valueOf(object.getString("action")), object.optString("targetKey", ""), params, object.optString("reason", "")));
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.audits.AuditLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.audits.QAuditRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.PossibleValueEnum;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.UniqueKey;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The qbit's own tables (DESIGN.md section 6.2), standard visible QQQ tables on
|
||||
** the host's local RDBMS backend, named authentik_* (lowercase snake_case).
|
||||
** Both are written only by the qbit: the generic insert, update and delete
|
||||
** capabilities are off for everyone, and the audit table is append-only.
|
||||
**
|
||||
** The host creates the SQL tables (see docs/schema.sql).
|
||||
*******************************************************************************/
|
||||
public final class AuthentikLocalTables
|
||||
{
|
||||
public static final String ADMIN_ACTION = "admin_action";
|
||||
public static final String APPROVAL_REQUEST = "approval_request";
|
||||
public static final String POLICY = "policy";
|
||||
public static final String PVS_ACTION_STATUS = "authentik_action_status";
|
||||
public static final String PVS_APPROVAL_STATUS = "authentik_approval_status";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikLocalTables()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Status of an audited action.
|
||||
*******************************************************************************/
|
||||
public enum ActionStatus implements PossibleValueEnum<String>
|
||||
{
|
||||
PENDING_APPROVAL("Waiting for approval"),
|
||||
RUNNING("Running"),
|
||||
SUCCEEDED("Succeeded"),
|
||||
FAILED("Failed"),
|
||||
REFUSED("Refused");
|
||||
|
||||
private final String label;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
ActionStatus(String label)
|
||||
{
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for possibleValueId.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getPossibleValueId()
|
||||
{
|
||||
return (name());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for possibleValueLabel.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getPossibleValueLabel()
|
||||
{
|
||||
return (label);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Status of a two-person approval request.
|
||||
*******************************************************************************/
|
||||
public enum ApprovalStatus implements PossibleValueEnum<String>
|
||||
{
|
||||
PENDING("Waiting for approval"),
|
||||
APPROVED("Approved and applied"),
|
||||
REJECTED("Rejected"),
|
||||
EXPIRED("Expired"),
|
||||
FAILED("Approved but failed");
|
||||
|
||||
private final String label;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
ApprovalStatus(String label)
|
||||
{
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for possibleValueId.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getPossibleValueId()
|
||||
{
|
||||
return (name());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for possibleValueLabel.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getPossibleValueLabel()
|
||||
{
|
||||
return (label);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The possible-value sources the local tables use.
|
||||
*******************************************************************************/
|
||||
public static List<QPossibleValueSource> possibleValueSources()
|
||||
{
|
||||
return (List.of(
|
||||
QPossibleValueSource.newForEnum(PVS_ACTION_STATUS, ActionStatus.values()),
|
||||
QPossibleValueSource.newForEnum(PVS_APPROVAL_STATUS, ApprovalStatus.values())));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_admin_action: append-only audit and outbox of every write the
|
||||
** qbit attempts. The row is inserted BEFORE the API call.
|
||||
*******************************************************************************/
|
||||
public static QTableMetaData adminAction(AuthentikQBitConfig config)
|
||||
{
|
||||
return (base(config, ADMIN_ACTION, "Admin Actions", "history", IdentityPermission.AUDIT_READ)
|
||||
.withRecordLabelFormatAndFields("%s %s", "actionName", "targetLabel")
|
||||
.withField(ro("correlationId", QFieldType.STRING).withMaxLength(64))
|
||||
.withField(ro("actionName", QFieldType.STRING).withMaxLength(60))
|
||||
.withField(ro("operator", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(ro("reason", QFieldType.TEXT))
|
||||
.withField(ro("targetType", QFieldType.STRING).withMaxLength(30))
|
||||
.withField(ro("targetKey", QFieldType.STRING).withMaxLength(100))
|
||||
.withField(ro("targetLabel", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(ro("beforeText", QFieldType.TEXT))
|
||||
.withField(ro("afterText", QFieldType.TEXT))
|
||||
.withField(ro("status", QFieldType.STRING).withPossibleValueSourceName(PVS_ACTION_STATUS))
|
||||
.withField(ro("errorMessage", QFieldType.TEXT))
|
||||
.withField(ro("authentikEventPk", QFieldType.STRING).withMaxLength(64))
|
||||
.withField(ro("approver", QFieldType.STRING).withMaxLength(255)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_approval_request: two-person requests (a second person with
|
||||
** authentik.approve applies or rejects the stored change).
|
||||
*******************************************************************************/
|
||||
public static QTableMetaData approvalRequest(AuthentikQBitConfig config)
|
||||
{
|
||||
return (base(config, APPROVAL_REQUEST, "Approval Requests", "how_to_reg", IdentityPermission.APPROVE)
|
||||
.withRecordLabelFormatAndFields("%s %s", "actionName", "targetLabel")
|
||||
.withField(ro("actionName", QFieldType.STRING).withMaxLength(60))
|
||||
.withField(ro("targetKey", QFieldType.STRING).withMaxLength(100))
|
||||
.withField(ro("targetLabel", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(ro("summary", QFieldType.TEXT))
|
||||
.withField(ro("reason", QFieldType.TEXT))
|
||||
.withField(ro("payloadJson", QFieldType.TEXT))
|
||||
.withField(ro("requester", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(ro("approver", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(ro("status", QFieldType.STRING).withPossibleValueSourceName(PVS_APPROVAL_STATUS))
|
||||
.withField(ro("expiresDate", QFieldType.DATE_TIME))
|
||||
.withField(ro("decidedDate", QFieldType.DATE_TIME))
|
||||
.withField(ro("errorMessage", QFieldType.TEXT)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_policy: one row per group with a policy (DESIGN.md section 12).
|
||||
** Authentik holds the live document; this row is the QQQ record of the last
|
||||
** save, and field-level audit is its change history. Written only by the
|
||||
** Edit Policy action.
|
||||
*******************************************************************************/
|
||||
public static QTableMetaData policy(AuthentikQBitConfig config)
|
||||
{
|
||||
return (base(config, POLICY, "Policies", "policy", IdentityPermission.USERS_READ)
|
||||
.withRecordLabelFormatAndFields("%s", "groupName")
|
||||
.withUniqueKey(new UniqueKey("groupPk"))
|
||||
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
|
||||
.withField(ro("groupPk", QFieldType.STRING).withLabel("Group Id").withMaxLength(64))
|
||||
.withField(ro("groupName", QFieldType.STRING).withLabel("Group").withMaxLength(255))
|
||||
.withField(ro("policyJson", QFieldType.TEXT).withLabel("Policy Document"))
|
||||
.withField(ro("statementCount", QFieldType.INTEGER).withLabel("Statements"))
|
||||
.withField(ro("permissionCount", QFieldType.INTEGER).withLabel("Permissions"))
|
||||
.withField(ro("savedBy", QFieldType.STRING).withLabel("Saved By").withMaxLength(255))
|
||||
.withField(ro("savedDate", QFieldType.DATE_TIME).withLabel("Saved"))
|
||||
.withField(ro("authentikFingerprint", QFieldType.STRING).withLabel("Authentik Fingerprint").withMaxLength(64)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Common shape: id, create and modify dates, no generic writes.
|
||||
*******************************************************************************/
|
||||
private static QTableMetaData base(AuthentikQBitConfig config, String name, String label, String icon, IdentityPermission permission)
|
||||
{
|
||||
return (new QTableMetaData()
|
||||
.withName(config.applyTablePrefix(name))
|
||||
.withLabel(label)
|
||||
.withIcon(new QIcon(icon))
|
||||
.withBackendName(config.getLocalBackendName())
|
||||
.withPrimaryKeyField("id")
|
||||
.withPermissionRules(permission.rules())
|
||||
.withCapabilities(Capability.TABLE_QUERY, Capability.TABLE_GET, Capability.TABLE_COUNT, Capability.TABLE_EXPORT)
|
||||
.withoutCapabilities(Capability.TABLE_INSERT, Capability.TABLE_UPDATE, Capability.TABLE_DELETE)
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER).withIsEditable(false))
|
||||
.withField(new QFieldMetaData("createDate", QFieldType.DATE_TIME).withIsEditable(false))
|
||||
.withField(new QFieldMetaData("modifyDate", QFieldType.DATE_TIME).withIsEditable(false)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A read-only field.
|
||||
*******************************************************************************/
|
||||
private static QFieldMetaData ro(String name, QFieldType type)
|
||||
{
|
||||
return (new QFieldMetaData(name, type).withIsEditable(false));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikJson;
|
||||
import com.kingsrook.qbits.authentik.permissions.EffectivePermissionResolver;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The pure rules of DESIGN.md section 5.4, separated from I/O so they can be
|
||||
** tested exhaustively: the subset (no escalation) rule, last-admin
|
||||
** protection, descendant checks and group fingerprints.
|
||||
*******************************************************************************/
|
||||
public final class AuthentikSafety
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikSafety()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a user is, for last-admin protection.
|
||||
**
|
||||
** @param pk Authentik user pk
|
||||
** @param active whether the account is active
|
||||
** @param human internal or external (not a service account)
|
||||
** @param protectedAccount break-glass, superuser, service account
|
||||
*******************************************************************************/
|
||||
public record UserFacts(int pk, boolean active, boolean human, boolean protectedAccount)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions in needed that held does not contain (the subset rule:
|
||||
** an operator may only grant what they hold).
|
||||
*******************************************************************************/
|
||||
public static Set<String> missing(Collection<String> needed, Collection<String> held)
|
||||
{
|
||||
Set<String> rs = new TreeSet<>(needed);
|
||||
rs.removeAll(held);
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** pks of the users who qualify as identity administrators in a graph: active,
|
||||
** human, not protected, and holding both authentik.memberships.manage and
|
||||
** authentik.permissions.manage through their groups (inherited included).
|
||||
*******************************************************************************/
|
||||
public static Set<Integer> qualifyingAdmins(GroupGraph graph, EffectivePermissionResolver resolver, Collection<UserFacts> users)
|
||||
{
|
||||
Set<Integer> rs = new LinkedHashSet<>();
|
||||
for(UserFacts user : users)
|
||||
{
|
||||
if(!user.active() || !user.human() || user.protectedAccount())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
EffectivePermissionResolver.Resolution resolution = resolver.resolveGroups(graph.groupsOfUser(user.pk()));
|
||||
if(EffectivePermissionResolver.holdsAll(resolution, List.of(IdentityPermission.MEMBERSHIPS_MANAGE, IdentityPermission.PERMISSIONS_MANAGE)))
|
||||
{
|
||||
rs.add(user.pk());
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether a change leaves the qbit without an administrator that it had
|
||||
** before: some admin existed, and none does after. A state that already had
|
||||
** none (for example a bootstrap window) is not made worse, so it never
|
||||
** blocks.
|
||||
*******************************************************************************/
|
||||
public static boolean removesLastAdmin(Set<Integer> before, Set<Integer> after)
|
||||
{
|
||||
return (!before.isEmpty() && after.isEmpty());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A copy of a graph with some nodes replaced (matched by pk), for
|
||||
** simulating a change.
|
||||
*******************************************************************************/
|
||||
public static GroupGraph withNodes(GroupGraph graph, GroupGraph.Node... replacements)
|
||||
{
|
||||
GroupGraph copy = new GroupGraph();
|
||||
graph.nodes().forEach(copy::add);
|
||||
for(GroupGraph.Node node : replacements)
|
||||
{
|
||||
copy.add(node);
|
||||
}
|
||||
return (copy);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A node without a member.
|
||||
*******************************************************************************/
|
||||
public static GroupGraph.Node withoutMember(GroupGraph.Node node, int userPk)
|
||||
{
|
||||
List<Integer> members = new ArrayList<>(node.memberPks());
|
||||
members.remove(Integer.valueOf(userPk));
|
||||
return (new GroupGraph.Node(node.pk(), node.name(), node.ownSuperuser(), node.parentPks(), node.permissions(), node.appAccess(), members, node.malformed(), node.policyPermissions()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A node with other permissions and app access.
|
||||
*******************************************************************************/
|
||||
public static GroupGraph.Node withPermissions(GroupGraph.Node node, List<String> permissions, List<String> appAccess)
|
||||
{
|
||||
return (new GroupGraph.Node(node.pk(), node.name(), node.ownSuperuser(), node.parentPks(), permissions, appAccess, node.memberPks(), node.malformed(), node.policyPermissions()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A node with other parents.
|
||||
*******************************************************************************/
|
||||
public static GroupGraph.Node withParents(GroupGraph.Node node, List<String> parentPks)
|
||||
{
|
||||
return (new GroupGraph.Node(node.pk(), node.name(), node.ownSuperuser(), parentPks, node.permissions(), node.appAccess(), node.memberPks(), node.malformed(), node.policyPermissions()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every group below a group (children, their children, ...), cycle-safe.
|
||||
*******************************************************************************/
|
||||
public static Set<String> descendantPks(GroupGraph graph, String pk)
|
||||
{
|
||||
Set<String> rs = new HashSet<>();
|
||||
for(GroupGraph.Node node : graph.nodes())
|
||||
{
|
||||
if(!node.pk().equals(pk) && graph.ancestorPks(node.pk()).contains(pk))
|
||||
{
|
||||
rs.add(node.pk());
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Split free text (new lines or commas) into distinct trimmed entries.
|
||||
*******************************************************************************/
|
||||
public static List<String> parseList(String text)
|
||||
{
|
||||
List<String> rs = new ArrayList<>();
|
||||
if(text == null)
|
||||
{
|
||||
return (rs);
|
||||
}
|
||||
for(String part : text.split("[\\r\\n,;]+"))
|
||||
{
|
||||
String trimmed = part.trim();
|
||||
if(!trimmed.isEmpty() && !rs.contains(trimmed))
|
||||
{
|
||||
rs.add(trimmed);
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A short fingerprint of a group's editable state: name, parents,
|
||||
** qqq.io/* attributes and member count. Authentik groups have no
|
||||
** last_updated (DESIGN.md section 0.2 vi), so this is how a change made in
|
||||
** the Authentik UI after a preview is noticed.
|
||||
*******************************************************************************/
|
||||
public static String groupFingerprint(JSONObject group)
|
||||
{
|
||||
JSONObject attributes = group.optJSONObject("attributes");
|
||||
Map<String, Object> qqq = new java.util.TreeMap<>();
|
||||
if(attributes != null)
|
||||
{
|
||||
for(String key : attributes.keySet())
|
||||
{
|
||||
if(key.startsWith(AuthentikJson.QQQ_ATTRIBUTE_PREFIX))
|
||||
{
|
||||
qqq.put(key, String.valueOf(attributes.get(key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> parents = new ArrayList<>();
|
||||
JSONArray array = group.optJSONArray("parents");
|
||||
for(int i = 0; array != null && i < array.length(); i++)
|
||||
{
|
||||
Object value = array.get(i);
|
||||
parents.add(value instanceof JSONObject object ? object.optString("pk") : String.valueOf(value));
|
||||
}
|
||||
java.util.Collections.sort(parents);
|
||||
|
||||
int members = group.optJSONArray("users") == null ? -1 : group.getJSONArray("users").length();
|
||||
return (sha(group.optString("name") + "|" + parents + "|" + qqq + "|" + members));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A short fingerprint of a user's editable state (name, email, path, type,
|
||||
** active, last_updated).
|
||||
*******************************************************************************/
|
||||
public static String userFingerprint(JSONObject user)
|
||||
{
|
||||
return (sha(user.optString("username") + "|" + user.optString("name") + "|" + user.optString("email") + "|" + user.optString("path") + "|"
|
||||
+ user.optString("type") + "|" + user.optBoolean("is_active", true) + "|" + user.optString("last_updated")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String sha(String text)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for(int i = 0; i < 8; i++)
|
||||
{
|
||||
hex.append(String.format("%02x", digest[i]));
|
||||
}
|
||||
return (hex.toString());
|
||||
}
|
||||
catch(NoSuchAlgorithmException e)
|
||||
{
|
||||
throw (new IllegalStateException(e));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.app;
|
||||
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikJson;
|
||||
import com.kingsrook.qbits.authentik.drift.AuthentikDriftReport;
|
||||
import com.kingsrook.qbits.authentik.drift.DriftFinding;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import com.kingsrook.qbits.authentik.security.AuthentikGuard;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import org.json.JSONObject;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Everything the Identity home shows (DESIGN.md section 8.3), read live from
|
||||
** Authentik and the qbit's own tables. Each section is loaded on its own, so a
|
||||
** failure shows as "unavailable" for that card instead of hiding the page.
|
||||
** Sections that expose sensitive data need authentik.audit.read.
|
||||
*******************************************************************************/
|
||||
public class AuthentikHomeData
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AuthentikHomeData.class);
|
||||
|
||||
public static final int TOKEN_WARNING_DAYS = 14;
|
||||
|
||||
private boolean peopleAvailable;
|
||||
private int activePeople;
|
||||
private int inactivePeople;
|
||||
private int serviceAccounts;
|
||||
private int neverSignedIn;
|
||||
private int protectedAccounts;
|
||||
|
||||
private boolean groupsAvailable;
|
||||
private int groups;
|
||||
private int groupsWithPermissions;
|
||||
private int groupsWithAppAccess;
|
||||
private int superuserGroups;
|
||||
private int emptyGroups;
|
||||
|
||||
private boolean approvalsAvailable;
|
||||
private int pendingApprovals;
|
||||
|
||||
private boolean driftAvailable;
|
||||
private int driftErrors;
|
||||
private int driftWarnings;
|
||||
|
||||
private boolean mayAudit;
|
||||
private boolean actionsAvailable;
|
||||
private List<QRecord> recentActions = new ArrayList<>();
|
||||
private List<String> attention = new ArrayList<>();
|
||||
|
||||
private AuthentikQBitConfig config;
|
||||
private String version;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Load everything for the current session.
|
||||
*******************************************************************************/
|
||||
public static AuthentikHomeData load(AuthentikQBitConfig config) throws Exception
|
||||
{
|
||||
AuthentikHomeData data = new AuthentikHomeData();
|
||||
data.config = config;
|
||||
data.mayAudit = AuthentikGuard.has(QContext.getQSession(), IdentityPermission.AUDIT_READ);
|
||||
AuthentikActionUtil util = AuthentikActionUtil.forBackend(config.getApiBackendName());
|
||||
|
||||
data.loadPeople(util);
|
||||
data.loadGroups(util);
|
||||
data.loadApprovals();
|
||||
data.loadActions();
|
||||
data.loadAttention(util);
|
||||
data.version = util.fetchServerVersion().orElse(null);
|
||||
return (data);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void loadPeople(AuthentikActionUtil util)
|
||||
{
|
||||
try
|
||||
{
|
||||
for(JSONObject user : util.allUsers())
|
||||
{
|
||||
String type = user.optString("type");
|
||||
if("service_account".equals(type))
|
||||
{
|
||||
serviceAccounts++;
|
||||
}
|
||||
else if(user.optBoolean("is_active", true))
|
||||
{
|
||||
activePeople++;
|
||||
}
|
||||
else
|
||||
{
|
||||
inactivePeople++;
|
||||
}
|
||||
if(user.isNull("last_login") && !"service_account".equals(type) && user.optBoolean("is_active", true))
|
||||
{
|
||||
neverSignedIn++;
|
||||
}
|
||||
if(util.getRuntime().getGuard().protection(user).isProtected())
|
||||
{
|
||||
protectedAccounts++;
|
||||
}
|
||||
}
|
||||
peopleAvailable = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.info("Identity home: people unavailable", logPair("error", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void loadGroups(AuthentikActionUtil util)
|
||||
{
|
||||
try
|
||||
{
|
||||
GroupGraph graph = util.groupGraphWithMembers();
|
||||
for(GroupGraph.Node node : graph.nodes())
|
||||
{
|
||||
groups++;
|
||||
if(!node.permissions().isEmpty())
|
||||
{
|
||||
groupsWithPermissions++;
|
||||
}
|
||||
if(!node.appAccess().isEmpty())
|
||||
{
|
||||
groupsWithAppAccess++;
|
||||
}
|
||||
if(graph.isSuperuserInherited(node.pk()))
|
||||
{
|
||||
superuserGroups++;
|
||||
}
|
||||
if(node.memberPks().isEmpty())
|
||||
{
|
||||
emptyGroups++;
|
||||
}
|
||||
}
|
||||
groupsAvailable = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.info("Identity home: groups unavailable", logPair("error", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void loadApprovals()
|
||||
{
|
||||
if(!hasLocal() || !config.getTwoPersonApproval() || !config.hasFeature(AuthentikFeature.GROUPS))
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
CountInput countInput = new CountInput();
|
||||
countInput.setTableName(config.applyTablePrefix(AuthentikLocalTables.APPROVAL_REQUEST));
|
||||
countInput.setFilter(new QQueryFilter(new QFilterCriteria("status", QCriteriaOperator.EQUALS, AuthentikLocalTables.ApprovalStatus.PENDING.name())));
|
||||
pendingApprovals = new CountAction().execute(countInput).getCount();
|
||||
approvalsAvailable = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.info("Identity home: approvals unavailable", logPair("error", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The latest admin actions (audit.read only).
|
||||
*******************************************************************************/
|
||||
private void loadActions()
|
||||
{
|
||||
if(!hasLocal() || !mayAudit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
QueryInput queryInput = new QueryInput();
|
||||
queryInput.setTableName(config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION));
|
||||
queryInput.setFilter(new QQueryFilter().withOrderBy(new QFilterOrderBy("id", false)).withLimit(8));
|
||||
recentActions = new QueryAction().execute(queryInput).getRecords();
|
||||
actionsAvailable = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.info("Identity home: admin actions unavailable", logPair("error", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Things that need a person: drift findings, blueprint state, tokens about
|
||||
** to expire, bootstrap operators still set.
|
||||
*******************************************************************************/
|
||||
private void loadAttention(AuthentikActionUtil util)
|
||||
{
|
||||
if(!config.getResolvedBootstrapSubjects().isEmpty())
|
||||
{
|
||||
attention.add("bootstrapOperatorSubjects is still set: remove it once an identity administrator is set up in Authentik.");
|
||||
}
|
||||
if(Boolean.TRUE.equals(config.getReadOnly()))
|
||||
{
|
||||
attention.add("The Identity screens are in read-only mode: no change can be made from here.");
|
||||
}
|
||||
if(AuthentikGuard.has(QContext.getQSession(), IdentityPermission.ADMIN))
|
||||
{
|
||||
try
|
||||
{
|
||||
for(DriftFinding finding : new AuthentikDriftReport(util, config).run())
|
||||
{
|
||||
if(finding.severity() == DriftFinding.Severity.ERROR)
|
||||
{
|
||||
driftErrors++;
|
||||
}
|
||||
else if(finding.severity() == DriftFinding.Severity.WARNING)
|
||||
{
|
||||
driftWarnings++;
|
||||
}
|
||||
}
|
||||
driftAvailable = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.info("Identity home: drift report unavailable", logPair("error", e.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
if(mayAudit)
|
||||
{
|
||||
try
|
||||
{
|
||||
Instant soon = Instant.now().plus(TOKEN_WARNING_DAYS, ChronoUnit.DAYS);
|
||||
for(JSONObject token : util.getAllPages("/core/tokens/?user__username=" + java.net.URLEncoder.encode(config.getEffectiveServiceAccountUsername(), java.nio.charset.StandardCharsets.UTF_8), 50))
|
||||
{
|
||||
Instant expires = AuthentikJson.parseInstant(token.optString("expires", null));
|
||||
if(token.optBoolean("expiring", true) && expires != null && expires.isBefore(soon))
|
||||
{
|
||||
attention.add("The qbit's API token (" + token.optString("identifier") + ") expires on "
|
||||
+ java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(java.time.ZoneOffset.UTC).format(expires) + ": rotate it (owner checklist).");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.debug("Identity home: token expiry not checked", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private boolean hasLocal()
|
||||
{
|
||||
return (config.getLocalBackendName() != null && QContext.getQInstance().getTable(config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION)) != null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for config
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig getConfig()
|
||||
{
|
||||
return (config);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for version
|
||||
*******************************************************************************/
|
||||
public String getVersion()
|
||||
{
|
||||
return (version);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for peopleAvailable
|
||||
*******************************************************************************/
|
||||
public boolean isPeopleAvailable()
|
||||
{
|
||||
return (peopleAvailable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for activePeople
|
||||
*******************************************************************************/
|
||||
public int getActivePeople()
|
||||
{
|
||||
return (activePeople);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for inactivePeople
|
||||
*******************************************************************************/
|
||||
public int getInactivePeople()
|
||||
{
|
||||
return (inactivePeople);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for serviceAccounts
|
||||
*******************************************************************************/
|
||||
public int getServiceAccounts()
|
||||
{
|
||||
return (serviceAccounts);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for neverSignedIn
|
||||
*******************************************************************************/
|
||||
public int getNeverSignedIn()
|
||||
{
|
||||
return (neverSignedIn);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for protectedAccounts
|
||||
*******************************************************************************/
|
||||
public int getProtectedAccounts()
|
||||
{
|
||||
return (protectedAccounts);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for groupsAvailable
|
||||
*******************************************************************************/
|
||||
public boolean isGroupsAvailable()
|
||||
{
|
||||
return (groupsAvailable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for groups
|
||||
*******************************************************************************/
|
||||
public int getGroups()
|
||||
{
|
||||
return (groups);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for groupsWithPermissions
|
||||
*******************************************************************************/
|
||||
public int getGroupsWithPermissions()
|
||||
{
|
||||
return (groupsWithPermissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for groupsWithAppAccess
|
||||
*******************************************************************************/
|
||||
public int getGroupsWithAppAccess()
|
||||
{
|
||||
return (groupsWithAppAccess);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for superuserGroups
|
||||
*******************************************************************************/
|
||||
public int getSuperuserGroups()
|
||||
{
|
||||
return (superuserGroups);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for emptyGroups
|
||||
*******************************************************************************/
|
||||
public int getEmptyGroups()
|
||||
{
|
||||
return (emptyGroups);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for approvalsAvailable
|
||||
*******************************************************************************/
|
||||
public boolean isApprovalsAvailable()
|
||||
{
|
||||
return (approvalsAvailable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for pendingApprovals
|
||||
*******************************************************************************/
|
||||
public int getPendingApprovals()
|
||||
{
|
||||
return (pendingApprovals);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for driftAvailable
|
||||
*******************************************************************************/
|
||||
public boolean isDriftAvailable()
|
||||
{
|
||||
return (driftAvailable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for driftErrors
|
||||
*******************************************************************************/
|
||||
public int getDriftErrors()
|
||||
{
|
||||
return (driftErrors);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for driftWarnings
|
||||
*******************************************************************************/
|
||||
public int getDriftWarnings()
|
||||
{
|
||||
return (driftWarnings);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for mayAudit
|
||||
*******************************************************************************/
|
||||
public boolean isMayAudit()
|
||||
{
|
||||
return (mayAudit);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for actionsAvailable
|
||||
*******************************************************************************/
|
||||
public boolean isActionsAvailable()
|
||||
{
|
||||
return (actionsAvailable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for recentActions
|
||||
*******************************************************************************/
|
||||
public List<QRecord> getRecentActions()
|
||||
{
|
||||
return (recentActions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for attention
|
||||
*******************************************************************************/
|
||||
public List<String> getAttention()
|
||||
{
|
||||
return (attention);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.app;
|
||||
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Renders the Identity home as one responsive HTML block (no tables, so it
|
||||
** stays readable at every width): cards stack to one column on narrow
|
||||
** screens, long values wrap, every card has an honest empty or unavailable
|
||||
** state, and it follows the app's light and dark theme (inherited colors).
|
||||
*******************************************************************************/
|
||||
public final class AuthentikHomeView
|
||||
{
|
||||
private static final DateTimeFormatter WHEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private static final String GRID = "display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,22rem),1fr));gap:1rem;";
|
||||
private static final String CARD = "border:1px solid rgba(127,127,127,.3);border-radius:8px;padding:1rem;min-width:0;overflow-wrap:anywhere;";
|
||||
private static final String LIST = "display:grid;grid-template-columns:minmax(8rem,auto) 1fr;gap:.25rem .75rem;margin:0 0 .75rem;font-size:.9rem;";
|
||||
private static final String ITEMS = "margin:0 0 .75rem;padding-left:1.25rem;font-size:.9rem;";
|
||||
private static final String MUTED = "opacity:.75;";
|
||||
private static final String WARN = "font-weight:600;";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikHomeView()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The whole home.
|
||||
*******************************************************************************/
|
||||
public static String render(AuthentikHomeData data)
|
||||
{
|
||||
AuthentikQBitConfig config = data.getConfig();
|
||||
StringBuilder html = new StringBuilder("<div class=\"authentik-home\" style=\"" + GRID + "\">");
|
||||
attention(html, data, config);
|
||||
people(html, data, config);
|
||||
groups(html, data, config);
|
||||
activity(html, data, config);
|
||||
connection(html, data);
|
||||
return (html.append("</div>").toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Needs attention: the first thing a person should see.
|
||||
*******************************************************************************/
|
||||
private static void attention(StringBuilder html, AuthentikHomeData data, AuthentikQBitConfig config)
|
||||
{
|
||||
open(html, "Needs attention");
|
||||
boolean any = false;
|
||||
html.append("<ul style=\"").append(ITEMS).append("\">");
|
||||
if(data.isApprovalsAvailable() && data.getPendingApprovals() > 0)
|
||||
{
|
||||
any = true;
|
||||
html.append("<li style=\"").append(WARN).append("\">").append(data.getPendingApprovals()).append(" change(s) waiting for a second person to approve. ")
|
||||
.append(link(config, AuthentikLocalTables.APPROVAL_REQUEST, "Open approval requests")).append("</li>");
|
||||
}
|
||||
if(data.isDriftAvailable() && data.getDriftErrors() + data.getDriftWarnings() > 0)
|
||||
{
|
||||
any = true;
|
||||
html.append("<li>").append(data.getDriftErrors()).append(" drift error(s) and ").append(data.getDriftWarnings()).append(" warning(s) in the identity drift report below.</li>");
|
||||
}
|
||||
for(String line : data.getAttention())
|
||||
{
|
||||
any = true;
|
||||
html.append("<li>").append(esc(line)).append("</li>");
|
||||
}
|
||||
if(data.isPeopleAvailable() && data.getNeverSignedIn() > 0)
|
||||
{
|
||||
any = true;
|
||||
html.append("<li>").append(data.getNeverSignedIn()).append(" active person(s) have never signed in.</li>");
|
||||
}
|
||||
html.append("</ul>");
|
||||
if(!any)
|
||||
{
|
||||
empty(html, "Nothing needs attention.");
|
||||
}
|
||||
close(html);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void people(StringBuilder html, AuthentikHomeData data, AuthentikQBitConfig config)
|
||||
{
|
||||
open(html, "People");
|
||||
if(!data.isPeopleAvailable())
|
||||
{
|
||||
empty(html, "People are unavailable right now (Authentik could not be reached).");
|
||||
}
|
||||
else
|
||||
{
|
||||
html.append("<dl style=\"").append(LIST).append("\">");
|
||||
row(html, "Active", String.valueOf(data.getActivePeople()));
|
||||
row(html, "Inactive", String.valueOf(data.getInactivePeople()));
|
||||
row(html, "Service accounts", String.valueOf(data.getServiceAccounts()));
|
||||
row(html, "Protected", data.getProtectedAccounts() + " (cannot be changed from here)");
|
||||
html.append("</dl>");
|
||||
}
|
||||
html.append(link(config, AuthentikTables.USER, "Users"));
|
||||
close(html);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void groups(StringBuilder html, AuthentikHomeData data, AuthentikQBitConfig config)
|
||||
{
|
||||
open(html, "Groups and permissions");
|
||||
if(!data.isGroupsAvailable())
|
||||
{
|
||||
empty(html, "Groups are unavailable right now (Authentik could not be reached).");
|
||||
}
|
||||
else
|
||||
{
|
||||
html.append("<dl style=\"").append(LIST).append("\">");
|
||||
row(html, "Groups", String.valueOf(data.getGroups()));
|
||||
row(html, "Grant QQQ permissions", String.valueOf(data.getGroupsWithPermissions()));
|
||||
row(html, "Grant app sign-in", String.valueOf(data.getGroupsWithAppAccess()));
|
||||
row(html, "Superuser (locked)", String.valueOf(data.getSuperuserGroups()));
|
||||
row(html, "Empty", String.valueOf(data.getEmptyGroups()));
|
||||
html.append("</dl>");
|
||||
}
|
||||
html.append(link(config, AuthentikTables.GROUP, "Groups"));
|
||||
close(html);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Recent changes made from here (audit.read only).
|
||||
*******************************************************************************/
|
||||
private static void activity(StringBuilder html, AuthentikHomeData data, AuthentikQBitConfig config)
|
||||
{
|
||||
open(html, "Recent changes");
|
||||
if(!data.isMayAudit())
|
||||
{
|
||||
empty(html, "The change history needs the authentik.audit.read permission.");
|
||||
}
|
||||
else if(!data.isActionsAvailable())
|
||||
{
|
||||
empty(html, "The change history is unavailable right now.");
|
||||
}
|
||||
else if(data.getRecentActions().isEmpty())
|
||||
{
|
||||
empty(html, "No changes have been made from here yet.");
|
||||
}
|
||||
else
|
||||
{
|
||||
html.append("<ul style=\"").append(ITEMS).append("\">");
|
||||
for(QRecord row : data.getRecentActions())
|
||||
{
|
||||
Instant created = ValueUtils.getValueAsInstant(row.getValue("createDate"));
|
||||
html.append("<li><a href=\"").append(esc(prefix(config) + "/" + config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION) + "/" + row.getValue("id"))).append("\">")
|
||||
.append(esc(row.getValueString("actionName"))).append("</a> ").append(esc(row.getValueString("targetLabel"))).append(", ")
|
||||
.append(esc(row.getValueString("status"))).append(created == null ? "" : ", " + WHEN.format(created)).append("</li>");
|
||||
}
|
||||
html.append("</ul>");
|
||||
}
|
||||
if(data.isMayAudit())
|
||||
{
|
||||
html.append(link(config, AuthentikLocalTables.ADMIN_ACTION, "All changes"));
|
||||
}
|
||||
close(html);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void connection(StringBuilder html, AuthentikHomeData data)
|
||||
{
|
||||
open(html, "Connection");
|
||||
html.append("<dl style=\"").append(LIST).append("\">");
|
||||
row(html, "Authentik", data.getConfig().getBaseUrl());
|
||||
row(html, "Version", data.getVersion() == null ? "Not reachable" : data.getVersion());
|
||||
row(html, "Service account", data.getConfig().getEffectiveServiceAccountUsername());
|
||||
row(html, "Changes", Boolean.TRUE.equals(data.getConfig().getReadOnly()) ? "Off (read-only)" : "On, every change is audited here and in Authentik");
|
||||
html.append("</dl>");
|
||||
close(html);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String prefix(AuthentikQBitConfig config)
|
||||
{
|
||||
return (config.getLinkPrefix() == null ? "" : config.getLinkPrefix());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String link(AuthentikQBitConfig config, String table, String text)
|
||||
{
|
||||
String name = AuthentikLocalTables.APPROVAL_REQUEST.equals(table) || AuthentikLocalTables.ADMIN_ACTION.equals(table)
|
||||
? config.applyTablePrefix(table) : config.applyTablePrefix(table);
|
||||
return ("<a href=\"" + esc(prefix(config) + "/" + name) + "\">" + esc(text) + "</a>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void open(StringBuilder html, String title)
|
||||
{
|
||||
html.append("<section style=\"").append(CARD).append("\"><h3 style=\"margin:0 0 .5rem;font-size:1rem;\">").append(esc(title)).append("</h3>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void close(StringBuilder html)
|
||||
{
|
||||
html.append("</section>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void empty(StringBuilder html, String text)
|
||||
{
|
||||
html.append("<p style=\"").append(MUTED).append("\">").append(esc(text)).append("</p>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static void row(StringBuilder html, String label, String value)
|
||||
{
|
||||
html.append("<dt style=\"").append(MUTED).append("\">").append(esc(label)).append("</dt><dd style=\"margin:0;\">").append(esc(value)).append("</dd>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** HTML-escape.
|
||||
*******************************************************************************/
|
||||
static String esc(String text)
|
||||
{
|
||||
if(text == null)
|
||||
{
|
||||
return ("");
|
||||
}
|
||||
return (text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.app;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.metadata.AuthentikHomeWidgetProducer;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Holder of the Identity home widget renderer.
|
||||
*******************************************************************************/
|
||||
public final class AuthentikHomeWidget
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikHomeWidget()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Renders the home. QQQ checks the widget's permission rules (authentik.users.read);
|
||||
** each card checks the finer permissions it needs itself.
|
||||
*******************************************************************************/
|
||||
public static class Renderer extends AbstractWidgetRenderer
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Render.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
|
||||
{
|
||||
String backendName = String.valueOf(((QWidgetMetaData) input.getWidgetMetaData()).getDefaultValues().get(AuthentikHomeWidgetProducer.BACKEND_NAME_KEY));
|
||||
AuthentikQBitConfig config = AuthentikRuntime.forBackend(backendName).getConfig();
|
||||
try
|
||||
{
|
||||
return (new RenderWidgetOutput(new RawHTML(null, AuthentikHomeView.render(AuthentikHomeData.load(config)))));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
throw (e);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw (new QException("The Identity home could not be built: " + e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.app;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.ChildRecordListRenderer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinOn;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.joins.QJoinMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Sub-tables appear on their parents' record screens as child lists, not in
|
||||
** the nav (owner standard): a user shows its memberships, sessions, tokens and
|
||||
** events; a group shows its members; an application shows its policy bindings;
|
||||
** an approval request needs none. The joins are metadata only (the lists
|
||||
** query the child table filtered by the parent's key), so they work on the
|
||||
** API backend.
|
||||
*******************************************************************************/
|
||||
public final class AuthentikRelations
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikRelations()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add the joins, child-list widgets and record sections for the tables the
|
||||
** config produced. Safe to call once per instance.
|
||||
*******************************************************************************/
|
||||
public static void apply(QInstance qInstance, AuthentikQBitConfig config)
|
||||
{
|
||||
String user = config.applyTablePrefix(AuthentikTables.USER);
|
||||
String group = config.applyTablePrefix(AuthentikTables.GROUP);
|
||||
String membership = config.applyTablePrefix(AuthentikTables.GROUP_MEMBER);
|
||||
String session = config.applyTablePrefix(AuthentikTables.SESSION);
|
||||
String token = config.applyTablePrefix(AuthentikTables.TOKEN);
|
||||
String event = config.applyTablePrefix(AuthentikTables.EVENT);
|
||||
String application = config.applyTablePrefix(AuthentikTables.APPLICATION);
|
||||
String binding = config.applyTablePrefix(AuthentikTables.POLICY_BINDING);
|
||||
|
||||
List<QFieldSection> userSections = new ArrayList<>();
|
||||
userSections.add(new QFieldSection("identity", "Identity", new QIcon("badge"), Tier.T1,
|
||||
List.of("username", "name", "email", "isActive", "type", "isProtected", "isSuperuser", "path", "lastLogin", "dateJoined", "lastUpdated", "pk")));
|
||||
userSections.add(new QFieldSection("access", "Access", new QIcon("admin_panel_settings"), Tier.T2,
|
||||
List.of("groupNames", "roleNames", "effectivePermissions")));
|
||||
relate(qInstance, userSections, "memberships", "Memberships", "group_add", user, membership, "pk", "userPk");
|
||||
relate(qInstance, userSections, "sessions", "Sessions", "devices", user, session, "username", "username");
|
||||
relate(qInstance, userSections, "tokens", "Tokens and app passwords", "key", user, token, "username", "username");
|
||||
relate(qInstance, userSections, "events", "History", "history", user, event, "username", "username");
|
||||
userSections.add(new QFieldSection("attributes", "Attributes", new QIcon("data_object"), Tier.T3, List.of("qqqAttributes", "passwordChangeDate", "attributes")));
|
||||
applySections(qInstance, user, userSections);
|
||||
|
||||
List<QFieldSection> groupSections = new ArrayList<>();
|
||||
groupSections.add(new QFieldSection("details", "Details", new QIcon("groups"), Tier.T1,
|
||||
List.of("name", "isSuperuser", "isSuperuserInherited", "parentNames", "childNames", "memberCount", "roleNames", "pk")));
|
||||
groupSections.add(new QFieldSection("permissions", "Permissions and app access", new QIcon("admin_panel_settings"), Tier.T2,
|
||||
List.of("permissions", "effectivePermissions", "appAccess")));
|
||||
relate(qInstance, groupSections, "members", "Members", "group", group, membership, "pk", "groupPk");
|
||||
relate(qInstance, groupSections, "policy", "Policy", "policy", group, config.applyTablePrefix(AuthentikLocalTables.POLICY), "pk", "groupPk");
|
||||
groupSections.add(new QFieldSection("attributes", "Attributes", new QIcon("data_object"), Tier.T3, List.of("attributes")));
|
||||
applySections(qInstance, group, groupSections);
|
||||
|
||||
List<QFieldSection> appSections = new ArrayList<>();
|
||||
appSections.add(new QFieldSection("details", "Details", new QIcon("apps"), Tier.T1,
|
||||
List.of("name", "slug", "group", "providerName", "policyEngineMode", "launchUrl", "publisher", "hiddenFromLibrary")));
|
||||
relate(qInstance, appSections, "bindings", "Who can open it (policy bindings)", "rule", application, binding, "bindingTarget", "target");
|
||||
applySections(qInstance, application, appSections);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One join plus its child-list widget and the section that shows it.
|
||||
*******************************************************************************/
|
||||
private static void relate(QInstance qInstance, List<QFieldSection> sections, String key, String label, String icon,
|
||||
String parentTable, String childTable, String parentField, String childField)
|
||||
{
|
||||
if(qInstance.getTable(parentTable) == null || qInstance.getTable(childTable) == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
String joinName = parentTable + "_" + key;
|
||||
QJoinMetaData join = new QJoinMetaData()
|
||||
.withName(joinName)
|
||||
.withLeftTable(parentTable)
|
||||
.withRightTable(childTable)
|
||||
.withType(JoinType.ONE_TO_MANY)
|
||||
.withJoinOn(new JoinOn(parentField, childField));
|
||||
qInstance.addJoin(join);
|
||||
|
||||
QWidgetMetaData widget = ChildRecordListRenderer.widgetMetaDataBuilder(join).withLabel(label).withMaxRows(20).getWidgetMetaData();
|
||||
qInstance.addWidget(widget);
|
||||
sections.add(new QFieldSection(key, new QIcon(icon), Tier.T2).withLabel(label).withWidgetName(widget.getName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Replace a table's sections (the enricher would otherwise skip the field
|
||||
** sections once a widget section exists).
|
||||
*******************************************************************************/
|
||||
private static void applySections(QInstance qInstance, String tableName, List<QFieldSection> sections)
|
||||
{
|
||||
QTableMetaData table = qInstance.getTable(tableName);
|
||||
if(table != null)
|
||||
{
|
||||
table.setSections(sections);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.permissions.EffectivePermissionResolver;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import com.kingsrook.qbits.authentik.security.AuthentikGuard;
|
||||
import com.kingsrook.qbits.authentik.security.WriteAuthorization;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
@@ -62,9 +63,14 @@ import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPatch;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
@@ -168,6 +174,7 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
if(spec.isVirtual())
|
||||
{
|
||||
output.setCount(memberships(spec, countInput.getFilter()).size());
|
||||
output.setDistinctCount(output.getCount());
|
||||
return (output);
|
||||
}
|
||||
|
||||
@@ -175,11 +182,13 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
if(mapped.isKeyLookup())
|
||||
{
|
||||
output.setCount(fetchByKeys(table, spec, mapped.keyLookup(), null).size());
|
||||
output.setDistinctCount(output.getCount());
|
||||
return (output);
|
||||
}
|
||||
|
||||
JSONObject page = getJson(listUrl(spec, mapped, 1, 1));
|
||||
output.setCount(pagination(page).optInt("count", 0));
|
||||
output.setDistinctCount(output.getCount());
|
||||
return (output);
|
||||
}
|
||||
|
||||
@@ -357,6 +366,61 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Send a request that changes Authentik data. Needs the guard's
|
||||
** authorization; every successful write drops the response and group caches.
|
||||
** The path is relative to /api/v3. Returns the response body as JSON (an
|
||||
** empty object for 204 / empty bodies); a missing target is an error.
|
||||
**
|
||||
** @param method POST, PATCH or DELETE
|
||||
** @param body request body (null for none)
|
||||
*******************************************************************************/
|
||||
public JSONObject write(WriteAuthorization authorization, String method, String pathAndQuery, JSONObject body) throws QException
|
||||
{
|
||||
if(authorization == null)
|
||||
{
|
||||
throw (new QPermissionDeniedException("Authentik data can only be changed through the guard."));
|
||||
}
|
||||
if(pathAndQuery == null || pathAndQuery.contains("..") || !pathAndQuery.startsWith("/"))
|
||||
{
|
||||
throw (new QException("Bad Authentik path"));
|
||||
}
|
||||
|
||||
String url = runtime().getConfig().getApiRoot() + pathAndQuery;
|
||||
HttpRequestBase request = switch(method)
|
||||
{
|
||||
case "POST" -> new HttpPost(url);
|
||||
case "PATCH" -> new HttpPatch(url);
|
||||
case "DELETE" -> new HttpDelete(url);
|
||||
default -> throw (new QException("Unsupported write method " + method));
|
||||
};
|
||||
if(body != null && request instanceof HttpEntityEnclosingRequest entityRequest)
|
||||
{
|
||||
entityRequest.setEntity(new StringEntity(body.toString(), ContentType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
QHttpResponse response = execute(request);
|
||||
if(response.getStatusCode() != null && response.getStatusCode() == 404)
|
||||
{
|
||||
throw (new QUserFacingException("Authentik no longer has that record (it may have been removed in the Authentik admin UI)."));
|
||||
}
|
||||
String content = response.getContent();
|
||||
return (content == null || content.isBlank() ? new JSONObject() : new JSONObject(content));
|
||||
}
|
||||
catch(JSONException e)
|
||||
{
|
||||
return (new JSONObject());
|
||||
}
|
||||
finally
|
||||
{
|
||||
runtime().invalidateCache();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fetch a single Authentik object by key (null when it doesn't exist).
|
||||
** No permission check: callers check first.
|
||||
@@ -397,6 +461,26 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** GET an API path whose response is a bare JSON array (not paged), such as
|
||||
** the MFA device list.
|
||||
*******************************************************************************/
|
||||
public JSONArray getApiArray(String pathAndQuery) throws QException
|
||||
{
|
||||
String url = runtime().getConfig().getApiRoot() + pathAndQuery;
|
||||
String body = getBody(url, false);
|
||||
try
|
||||
{
|
||||
return (new JSONArray(body));
|
||||
}
|
||||
catch(JSONException e)
|
||||
{
|
||||
throw (new QException("Authentik returned an unexpected response for " + pathOf(url)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fetch every page of a list endpoint (relative path with query string,
|
||||
** without page parameters). Bounded by maxObjects.
|
||||
@@ -599,6 +683,7 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
try
|
||||
{
|
||||
QRecord record = new QRecord();
|
||||
record.setTableName(tableNameOf(spec));
|
||||
for(AuthentikFieldSpec field : spec.getFields())
|
||||
{
|
||||
if(field.isSensitive() && !maySeeSensitive)
|
||||
@@ -680,7 +765,7 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
{
|
||||
throw (new QUserFacingException("More than " + MAX_SWEEP_OBJECTS + " Authentik groups; the group graph is not supported at this size."));
|
||||
}
|
||||
GroupGraph graph = GroupGraph.fromGroups(groups);
|
||||
GroupGraph graph = GroupGraph.fromGroups(groups, runtime.getConfig().getPolicyFormat());
|
||||
if(cache)
|
||||
{
|
||||
runtime.getGroupGraphCache().storeResult("all", graph);
|
||||
@@ -690,6 +775,86 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The produced (prefixed) table name for a spec: records must carry it (the
|
||||
** Next UI rejects a record response without a tableName).
|
||||
*******************************************************************************/
|
||||
private String tableNameOf(AuthentikTableSpec spec)
|
||||
{
|
||||
return (runtime().getConfig().applyTablePrefix(spec.getName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The runtime of the backend this util serves (config, guard, caches).
|
||||
*******************************************************************************/
|
||||
public AuthentikRuntime getRuntime()
|
||||
{
|
||||
return (runtime());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The group graph WITH member pks (one sweep; cached like the plain graph
|
||||
** under a separate key). Used by safety checks that need to know who is in
|
||||
** which group (last-admin protection).
|
||||
*******************************************************************************/
|
||||
public GroupGraph groupGraphWithMembers() throws QException
|
||||
{
|
||||
AuthentikRuntime runtime = runtime();
|
||||
boolean cache = runtime.getConfig().getGroupCacheTtlSeconds() != null && runtime.getConfig().getGroupCacheTtlSeconds() > 0;
|
||||
if(cache)
|
||||
{
|
||||
Optional<GroupGraph> cached = runtime.getGroupGraphCache().getMemoizedResult("members").map(m -> m.getResult());
|
||||
if(cached.isPresent())
|
||||
{
|
||||
return (cached.get());
|
||||
}
|
||||
}
|
||||
List<JSONObject> groups = getAllPages("/core/groups/?include_users=true&include_parents=false&include_children=false&ordering=name", MAX_SWEEP_OBJECTS);
|
||||
GroupGraph graph = GroupGraph.fromGroups(groups, runtime.getConfig().getPolicyFormat());
|
||||
if(cache)
|
||||
{
|
||||
runtime.getGroupGraphCache().storeResult("members", graph);
|
||||
}
|
||||
return (graph);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every user the qbit may see (default types, user scope applied), without
|
||||
** group objects. Bounded sweep.
|
||||
*******************************************************************************/
|
||||
public List<JSONObject> allUsers() throws QException
|
||||
{
|
||||
try
|
||||
{
|
||||
URIBuilder builder = new URIBuilder("/core/users/");
|
||||
boolean groupScope = runtime().getConfig().getUserScopeGroupNames() != null && !runtime().getConfig().getUserScopeGroupNames().isEmpty();
|
||||
builder.addParameter("include_groups", String.valueOf(groupScope));
|
||||
builder.addParameter("include_roles", "false");
|
||||
addUserScope(builder, List.of());
|
||||
List<JSONObject> rs = new ArrayList<>();
|
||||
for(JSONObject user : getAllPages(builder.build().toString(), MAX_SWEEP_OBJECTS))
|
||||
{
|
||||
if(runtime().getGuard().isUserInScope(user))
|
||||
{
|
||||
rs.add(user);
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
catch(java.net.URISyntaxException e)
|
||||
{
|
||||
throw (new QException("Bad Authentik URL", e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A resolver over the current group graph and the instance's permissions.
|
||||
*******************************************************************************/
|
||||
@@ -1276,7 +1441,11 @@ public class AuthentikActionUtil extends BaseAPIActionUtil
|
||||
}
|
||||
|
||||
String requestBody = null;
|
||||
if(request instanceof HttpEntityEnclosingRequest entityRequest && entityRequest.getEntity() != null)
|
||||
if("POST".equals(request.getMethod()) && path.endsWith("/core/users/"))
|
||||
{
|
||||
path = path + " [body omitted: user create]";
|
||||
}
|
||||
else if(request instanceof HttpEntityEnclosingRequest entityRequest && entityRequest.getEntity() != null)
|
||||
{
|
||||
requestBody = EntityUtils.toString(entityRequest.getEntity(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@@ -49,6 +49,12 @@ public final class AuthentikTables
|
||||
public static final String GROUP_MEMBER = "groupMember";
|
||||
public static final String SESSION = "session";
|
||||
public static final String EVENT = "event";
|
||||
public static final String APPLICATION = "application";
|
||||
public static final String POLICY_BINDING = "policyBinding";
|
||||
public static final String BLUEPRINT = "blueprint";
|
||||
public static final String ROLE = "role";
|
||||
public static final String TOKEN = "token";
|
||||
public static final String INVITATION = "invitation";
|
||||
|
||||
/*******************************************************************************
|
||||
** Table names produced before the owner naming rule (2026-10-12), with the
|
||||
@@ -78,6 +84,12 @@ public final class AuthentikTables
|
||||
register(groupMembers());
|
||||
register(sessions());
|
||||
register(events());
|
||||
register(applications());
|
||||
register(policyBindings());
|
||||
register(blueprints());
|
||||
register(roles());
|
||||
register(tokens());
|
||||
register(invitations());
|
||||
}
|
||||
|
||||
|
||||
@@ -181,10 +193,10 @@ public final class AuthentikTables
|
||||
static AuthentikTableSpec groups()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(GROUP, "Groups", "groups", "/core/groups/", "pk")
|
||||
.withDefaultListParam("include_users", "false")
|
||||
.withDefaultListParam("include_users", "true")
|
||||
.withDefaultListParam("include_parents", "true")
|
||||
.withDefaultListParam("include_children", "true")
|
||||
.withDefaultGetParam("include_users", "false")
|
||||
.withDefaultGetParam("include_users", "true")
|
||||
.withDefaultGetParam("include_parents", "true")
|
||||
.withDefaultGetParam("include_children", "true")
|
||||
.withDefaultOrdering("name")
|
||||
@@ -303,4 +315,127 @@ public final class AuthentikTables
|
||||
return (spec);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** /core/applications/ (slug). Read only. A non-superuser caller (the service
|
||||
** account) sees only applications it can itself access, so the qbit never
|
||||
** relies on this list for access decisions (DESIGN.md 0.2 iii).
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec applications()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(APPLICATION, "Applications", "apps", "/core/applications/", "slug")
|
||||
.withDefaultOrdering("name")
|
||||
.withRecordLabelFields("name");
|
||||
spec.withField(new AuthentikFieldSpec("slug", "Slug", QFieldType.STRING, string("slug")).withFilter(QCriteriaOperator.EQUALS, "slug"));
|
||||
spec.withField(new AuthentikFieldSpec("name", "Name", QFieldType.STRING, string("name")).withSearchable().withOrdering("name"));
|
||||
spec.withField(new AuthentikFieldSpec("group", "Group", QFieldType.STRING, string("group")).withFilter(QCriteriaOperator.EQUALS, "group"));
|
||||
spec.withField(new AuthentikFieldSpec("providerName", "Provider", QFieldType.STRING, at("provider_obj", "name")));
|
||||
spec.withField(new AuthentikFieldSpec("policyEngineMode", "Policy Engine Mode", QFieldType.STRING, string("policy_engine_mode")));
|
||||
spec.withField(new AuthentikFieldSpec("launchUrl", "Launch URL", QFieldType.STRING, string("launch_url")));
|
||||
spec.withField(new AuthentikFieldSpec("publisher", "Publisher", QFieldType.STRING, string("meta_publisher")).withFilter(QCriteriaOperator.EQUALS, "meta_publisher"));
|
||||
spec.withField(new AuthentikFieldSpec("hiddenFromLibrary", "Hidden", QFieldType.BOOLEAN, bool("meta_hide")));
|
||||
spec.withField(new AuthentikFieldSpec("bindingTarget", "Binding Target", QFieldType.STRING, string("pbm_uuid")).withHidden());
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** /policies/bindings/ (uuid): who or what an application's access policy
|
||||
** binds. Read only.
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec policyBindings()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(POLICY_BINDING, "Policy Bindings", "rule", "/policies/bindings/", "pk")
|
||||
.withDefaultOrdering("order")
|
||||
.withRecordLabelFields("pk");
|
||||
spec.withField(new AuthentikFieldSpec("pk", "Id", QFieldType.STRING, string("pk")));
|
||||
spec.withField(new AuthentikFieldSpec("target", "Target Id", QFieldType.STRING, string("target")).withFilter(QCriteriaOperator.EQUALS, "target").withHidden());
|
||||
spec.withField(new AuthentikFieldSpec("policyName", "Policy", QFieldType.STRING, at("policy_obj", "name")));
|
||||
spec.withField(new AuthentikFieldSpec("groupName", "Group", QFieldType.STRING, at("group_obj", "name")));
|
||||
spec.withField(new AuthentikFieldSpec("username", "User", QFieldType.STRING, at("user_obj", "username")));
|
||||
spec.withField(new AuthentikFieldSpec("negate", "Negate", QFieldType.BOOLEAN, bool("negate")));
|
||||
spec.withField(new AuthentikFieldSpec("enabled", "Enabled", QFieldType.BOOLEAN, bool("enabled")).withFilter(QCriteriaOperator.EQUALS, "enabled"));
|
||||
spec.withField(new AuthentikFieldSpec("order", "Order", QFieldType.INTEGER, integer("order")).withFilter(QCriteriaOperator.EQUALS, "order").withOrdering("order"));
|
||||
spec.withField(new AuthentikFieldSpec("expires", "Expires", QFieldType.DATE_TIME, instant("expires")));
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** /managed/blueprints/ (uuid). Read only; the drift report uses it too.
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec blueprints()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(BLUEPRINT, "Blueprints", "description", "/managed/blueprints/", "pk")
|
||||
.withDefaultOrdering("name")
|
||||
.withRecordLabelFields("name");
|
||||
spec.withField(new AuthentikFieldSpec("pk", "Id", QFieldType.STRING, string("pk")));
|
||||
spec.withField(new AuthentikFieldSpec("name", "Name", QFieldType.STRING, string("name")).withSearchable().withOrdering("name"));
|
||||
spec.withField(new AuthentikFieldSpec("path", "Path", QFieldType.STRING, string("path")).withFilter(QCriteriaOperator.EQUALS, "path"));
|
||||
spec.withField(new AuthentikFieldSpec("status", "Status", QFieldType.STRING, string("status")));
|
||||
spec.withField(new AuthentikFieldSpec("enabled", "Enabled", QFieldType.BOOLEAN, bool("enabled")));
|
||||
spec.withField(new AuthentikFieldSpec("lastApplied", "Last Applied", QFieldType.DATE_TIME, instant("last_applied")));
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** /rbac/roles/ (uuid). Read only in v1 (role management is phase 4);
|
||||
** system-managed roles are hidden.
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec roles()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(ROLE, "Roles", "admin_panel_settings", "/rbac/roles/", "pk")
|
||||
.withDefaultListParam("managed__isnull", "true")
|
||||
.withDefaultOrdering("name")
|
||||
.withRecordLabelFields("name");
|
||||
spec.withField(new AuthentikFieldSpec("pk", "Id", QFieldType.STRING, string("pk")));
|
||||
spec.withField(new AuthentikFieldSpec("name", "Name", QFieldType.STRING, string("name")).withSearchable().withOrdering("name"));
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** /core/tokens/ (identifier). Metadata only: there is NO key field, and the
|
||||
** service account is never given token-key permissions. Needs audit.read.
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec tokens()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(TOKEN, "Tokens", "key", "/core/tokens/", "identifier")
|
||||
.withReadPermission(IdentityPermission.AUDIT_READ)
|
||||
.withDefaultOrdering("identifier")
|
||||
.withRecordLabelFields("identifier");
|
||||
spec.withField(new AuthentikFieldSpec("identifier", "Identifier", QFieldType.STRING, string("identifier")).withSearchable().withOrdering("identifier"));
|
||||
spec.withField(new AuthentikFieldSpec("intent", "Intent", QFieldType.STRING, string("intent")).withFilter(QCriteriaOperator.EQUALS, "intent"));
|
||||
spec.withField(new AuthentikFieldSpec("username", "User", QFieldType.STRING, at("user_obj", "username")).withFilter(QCriteriaOperator.EQUALS, "user__username"));
|
||||
spec.withField(new AuthentikFieldSpec("description", "Description", QFieldType.STRING, string("description")));
|
||||
spec.withField(new AuthentikFieldSpec("expires", "Expires", QFieldType.DATE_TIME, instant("expires")));
|
||||
spec.withField(new AuthentikFieldSpec("expiring", "Expiring", QFieldType.BOOLEAN, bool("expiring")).withFilter(QCriteriaOperator.EQUALS, "expiring"));
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** /stages/invitation/invitations/ (uuid). Created by the Invite User action;
|
||||
** cancelled by Cancel Invitation.
|
||||
*******************************************************************************/
|
||||
static AuthentikTableSpec invitations()
|
||||
{
|
||||
AuthentikTableSpec spec = new AuthentikTableSpec(INVITATION, "Invitations", "mail", "/stages/invitation/invitations/", "pk")
|
||||
.withDefaultOrdering("name")
|
||||
.withRecordLabelFields("name");
|
||||
spec.withField(new AuthentikFieldSpec("pk", "Id", QFieldType.STRING, string("pk")));
|
||||
spec.withField(new AuthentikFieldSpec("name", "Name", QFieldType.STRING, string("name")).withSearchable().withOrdering("name"));
|
||||
spec.withField(new AuthentikFieldSpec("email", "Email", QFieldType.STRING, at("fixed_data", "email")));
|
||||
spec.withField(new AuthentikFieldSpec("singleUse", "Single Use", QFieldType.BOOLEAN, bool("single_use")));
|
||||
spec.withField(new AuthentikFieldSpec("expires", "Expires", QFieldType.DATE_TIME, instant("expires")));
|
||||
spec.withField(new AuthentikFieldSpec("flowSlug", "Flow", QFieldType.STRING, at("flow_obj", "slug")));
|
||||
spec.withField(new AuthentikFieldSpec("createdBy", "Created By", QFieldType.STRING, at("created_by", "username")));
|
||||
return (spec);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -304,7 +304,7 @@ public class AuthentikDriftReport
|
||||
void checkIdentityAdmins(List<DriftFinding> findings) throws QException
|
||||
{
|
||||
List<JSONObject> groups = client.getAllPages("/core/groups/?include_users=true&ordering=name", AuthentikActionUtil.MAX_SWEEP_OBJECTS);
|
||||
GroupGraph graph = GroupGraph.fromGroups(groups);
|
||||
GroupGraph graph = GroupGraph.fromGroups(groups, config.getPolicyFormat());
|
||||
EffectivePermissionResolver resolver = new EffectivePermissionResolver(graph, null);
|
||||
|
||||
List<IdentityPermission> required = List.of(IdentityPermission.MEMBERSHIPS_MANAGE, IdentityPermission.PERMISSIONS_MANAGE);
|
||||
@@ -345,7 +345,7 @@ public class AuthentikDriftReport
|
||||
|
||||
if(admins.isEmpty())
|
||||
{
|
||||
String bootstrap = config.getResolvedBootstrapOperators().isEmpty() ? "" : " bootstrapOperators is set, which covers sign-in for now.";
|
||||
String bootstrap = config.getResolvedBootstrapSubjects().isEmpty() ? "" : " bootstrapOperatorSubjects is set, which covers sign-in for now.";
|
||||
findings.add(DriftFinding.error("identity admins", "-", "Nobody can administer identities from QQQ: no active, unprotected human user holds authentik.memberships.manage and authentik.permissions.manage. Add an administrator to a group carrying authentik.* (e.g. identity-admins) in the Authentik UI." + bootstrap));
|
||||
}
|
||||
else if(admins.size() == 1)
|
||||
@@ -426,7 +426,7 @@ public class AuthentikDriftReport
|
||||
continue;
|
||||
}
|
||||
String modelName = model.optString("model_name");
|
||||
String pk = model.optString("pk");
|
||||
String pk = dashed(model.optString("pk"));
|
||||
boolean sensitive = false;
|
||||
if(!"user".equals(modelName) && !"group".equals(modelName))
|
||||
{
|
||||
@@ -458,4 +458,19 @@ public class AuthentikDriftReport
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Authentik events carry group pks as 32 hex characters without dashes;
|
||||
** the graph is keyed by the dashed uuid.
|
||||
*******************************************************************************/
|
||||
static String dashed(String pk)
|
||||
{
|
||||
if(pk != null && pk.matches("[0-9a-fA-F]{32}"))
|
||||
{
|
||||
return (pk.substring(0, 8) + "-" + pk.substring(8, 12) + "-" + pk.substring(12, 16) + "-" + pk.substring(16, 20) + "-" + pk.substring(20));
|
||||
}
|
||||
return (pk);
|
||||
}
|
||||
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_admin_action: the append-only audit trail of every change made from QQQ.
|
||||
*******************************************************************************/
|
||||
public class AuthentikAdminActionTableProducer extends QBitComponentMetaDataProducer<QTableMetaData, AuthentikQBitConfig>
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Needs the local backend.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return (getQBitConfig() != null && getQBitConfig().getLocalBackendName() != null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QTableMetaData produce(QInstance qInstance) throws QException
|
||||
{
|
||||
return (AuthentikLocalTables.adminAction(getQBitConfig()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the backend.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (300);
|
||||
}
|
||||
|
||||
}
|
||||
+43
-10
@@ -18,12 +18,17 @@ package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppSection;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitProductionContext;
|
||||
@@ -59,26 +64,54 @@ public class AuthentikAppMetaDataProducer extends QBitComponentMetaDataProducer<
|
||||
MetaDataProducerMultiOutput produced = QBitProductionContext.peekMetaDataProducerMultiOutput();
|
||||
if(produced != null)
|
||||
{
|
||||
for(String specName : AuthentikTables.all().keySet())
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the nav lists only the main tables; memberships, sessions, tokens, //
|
||||
// events, bindings, roles and blueprints are reached from their parent //
|
||||
// records as child lists //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
addSection(app, produced, config, "people", "People", "person", AuthentikTables.USER, AuthentikTables.INVITATION);
|
||||
addSection(app, produced, config, "access", "Access", "admin_panel_settings", AuthentikTables.GROUP, AuthentikLocalTables.POLICY, AuthentikTables.APPLICATION);
|
||||
addSection(app, produced, config, "activity", "Activity", "history", AuthentikLocalTables.APPROVAL_REQUEST, AuthentikLocalTables.ADMIN_ACTION);
|
||||
|
||||
List<String> widgets = new ArrayList<>();
|
||||
for(String widgetName : List.of(config.applyPrefix(AuthentikHomeWidgetProducer.NAME), config.applyPrefix(AuthentikDriftReportWidgetProducer.NAME)))
|
||||
{
|
||||
QTableMetaData table = produced.get(QTableMetaData.class, config.applyTablePrefix(specName));
|
||||
if(table != null)
|
||||
if(produced.get(QWidgetMetaData.class, widgetName) != null)
|
||||
{
|
||||
app.withChild(table);
|
||||
widgets.add(widgetName);
|
||||
}
|
||||
}
|
||||
|
||||
String driftReport = config.applyPrefix(AuthentikDriftReportWidgetProducer.NAME);
|
||||
if(produced.get(com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData.class, driftReport) != null)
|
||||
{
|
||||
app.withWidgets(java.util.List.of(driftReport));
|
||||
}
|
||||
app.withWidgets(widgets);
|
||||
}
|
||||
return (app);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add a nav section with the main tables that were produced.
|
||||
*******************************************************************************/
|
||||
private static void addSection(QAppMetaData app, MetaDataProducerMultiOutput produced, AuthentikQBitConfig config, String name, String label, String icon, String... specNames)
|
||||
{
|
||||
List<String> names = new ArrayList<>();
|
||||
for(String specName : specNames)
|
||||
{
|
||||
String tableName = config.applyTablePrefix(specName);
|
||||
QTableMetaData table = produced.get(QTableMetaData.class, tableName);
|
||||
if(table != null)
|
||||
{
|
||||
app.withChild(table);
|
||||
names.add(tableName);
|
||||
}
|
||||
}
|
||||
if(!names.isEmpty())
|
||||
{
|
||||
app.withSection(new QAppSection().withName(name).withLabel(label).withIcon(new QIcon(icon)).withTables(names));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Last, so the tables exist in the output.
|
||||
*******************************************************************************/
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_application: /core/applications/.
|
||||
*******************************************************************************/
|
||||
public class AuthentikApplicationTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.APPLICATION);
|
||||
}
|
||||
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_approval_request: changes waiting for a second person.
|
||||
*******************************************************************************/
|
||||
public class AuthentikApprovalRequestTableProducer extends QBitComponentMetaDataProducer<QTableMetaData, AuthentikQBitConfig>
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Needs the local backend.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return (getQBitConfig() != null && getQBitConfig().getLocalBackendName() != null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QTableMetaData produce(QInstance qInstance) throws QException
|
||||
{
|
||||
return (AuthentikLocalTables.approvalRequest(getQBitConfig()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the backend.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (300);
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_blueprint: /managed/blueprints/.
|
||||
*******************************************************************************/
|
||||
public class AuthentikBlueprintTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.BLUEPRINT);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.app.AuthentikHomeWidget;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Identity home widget: the single dashboard of this qbit (what needs
|
||||
** attention, people, groups, recent changes). Other screens only link to it.
|
||||
*******************************************************************************/
|
||||
public class AuthentikHomeWidgetProducer extends QBitComponentMetaDataProducer<QWidgetMetaData, AuthentikQBitConfig>
|
||||
{
|
||||
public static final String NAME = "home";
|
||||
public static final String BACKEND_NAME_KEY = "backendName";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QWidgetMetaData produce(QInstance qInstance) throws QException
|
||||
{
|
||||
AuthentikQBitConfig config = getQBitConfig();
|
||||
return (new QWidgetMetaData()
|
||||
.withName(config.applyPrefix(NAME))
|
||||
.withLabel("Identity")
|
||||
.withType(WidgetType.HTML.getType())
|
||||
.withGridColumns(12)
|
||||
.withIsCard(false)
|
||||
.withCodeReference(new QCodeReference(AuthentikHomeWidget.Renderer.class))
|
||||
.withPermissionRules(IdentityPermission.USERS_READ.rules())
|
||||
.withDefaultValue(BACKEND_NAME_KEY, config.getApiBackendName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the tables, before the app.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (450);
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_invitation: /stages/invitation/invitations/.
|
||||
*******************************************************************************/
|
||||
public class AuthentikInvitationTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Only when invitations are configured (an enrollment flow).
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return (super.isEnabled() && getQBitConfig().getInvitationFlow() != null && !getQBitConfig().getInvitationFlow().isBlank());
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.INVITATION);
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_policy_binding: /policies/bindings/.
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyBindingTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.POLICY_BINDING);
|
||||
}
|
||||
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyEditorWidget;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policy editor widget (DESIGN.md section 12.4), shown on the Edit Policy
|
||||
** step. Gated by authentik.policies.manage.
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyEditorWidgetProducer extends QBitComponentMetaDataProducer<QWidgetMetaData, AuthentikQBitConfig>
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Only with the POLICIES feature.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return (getQBitConfig() != null && getQBitConfig().hasFeature(AuthentikFeature.POLICIES));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QWidgetMetaData produce(QInstance qInstance) throws QException
|
||||
{
|
||||
AuthentikQBitConfig config = getQBitConfig();
|
||||
return (new QWidgetMetaData()
|
||||
.withName(config.applyPrefix(PolicyEditorWidget.NAME))
|
||||
.withLabel("Policy")
|
||||
.withType(PolicyEditorWidget.TYPE)
|
||||
.withGridColumns(12)
|
||||
.withIsCard(false)
|
||||
.withCodeReference(new QCodeReference(PolicyEditorWidget.Renderer.class))
|
||||
.withPermissionRules(IdentityPermission.POLICIES_MANAGE.rules())
|
||||
.withDefaultValue(PolicyEditorWidget.BACKEND_NAME_KEY, config.getApiBackendName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the tables, before the app.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (460);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_policy: the QQQ record (with change history) of each group policy.
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyTableProducer extends QBitComponentMetaDataProducer<QTableMetaData, AuthentikQBitConfig>
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Needs the local backend and the POLICIES feature.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return (getQBitConfig() != null && getQBitConfig().getLocalBackendName() != null && getQBitConfig().hasFeature(AuthentikFeature.POLICIES));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QTableMetaData produce(QInstance qInstance) throws QException
|
||||
{
|
||||
return (AuthentikLocalTables.policy(getQBitConfig()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the backend.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (300);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_role: /rbac/roles/.
|
||||
*******************************************************************************/
|
||||
public class AuthentikRoleTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.ROLE);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.metadata;
|
||||
|
||||
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** authentik_token: /core/tokens/ (metadata only, never a key).
|
||||
*******************************************************************************/
|
||||
public class AuthentikTokenTableProducer extends AbstractAuthentikTableProducer
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
protected String getSpecName()
|
||||
{
|
||||
return (AuthentikTables.TOKEN);
|
||||
}
|
||||
|
||||
}
|
||||
+38
-7
@@ -27,6 +27,9 @@ import java.util.TreeSet;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikRedactor;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyPermissions;
|
||||
import com.kingsrook.qbits.authentik.security.BootstrapOperators;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
@@ -49,7 +52,7 @@ import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
** 2. Each group is resolved with its ancestors through the cached group
|
||||
** graph; the union of qqq.io/permissions becomes session permissions,
|
||||
** expanded and checked against the instance's permission catalog.
|
||||
** 3. Static fallbacks (withGroupPermissions) and bootstrapOperators are added.
|
||||
** 3. Static fallbacks (withGroupPermissions) and bootstrapOperatorSubjects are added.
|
||||
** 4. If Authentik cannot be read, only the static fallbacks (and bootstrap
|
||||
** operators) apply: it never grants everything.
|
||||
**
|
||||
@@ -101,9 +104,19 @@ public class AuthentikGroupPermissionMapper implements QAuthenticationModuleCust
|
||||
return;
|
||||
}
|
||||
List<String> groups = groupNames(claims);
|
||||
String email = claims.optString("email", "").trim().toLowerCase();
|
||||
String email = claims.optString("email", "").trim();
|
||||
String sub = claims.optString("sub", "").trim();
|
||||
boolean verified = claims.optBoolean("email_verified", false);
|
||||
|
||||
Set<String> permissions = new TreeSet<>(resolve(qInstance, groups, email));
|
||||
Set<String> permissions = new TreeSet<>(resolve(qInstance, groups, sub, email, verified));
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// the policy claim (docs/POLICY-FORMAT.md) carries the same group data //
|
||||
// as the graph read above; the union also covers an unreachable API //
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
AuthentikRuntime runtime = runtime();
|
||||
PolicyFormat format = runtime == null ? PolicyFormat.DEFAULT : runtime.getConfig().getPolicyFormat();
|
||||
permissions.addAll(PolicyPermissions.fromClaims(PolicyPermissions.claimsWithPolicy(context, format), format));
|
||||
if(qSession.getPermissions() != null)
|
||||
{
|
||||
permissions.addAll(qSession.getPermissions());
|
||||
@@ -114,9 +127,10 @@ public class AuthentikGroupPermissionMapper implements QAuthenticationModuleCust
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions for a user's group names and email.
|
||||
** The permissions for a user's group names and token identity (sub, email,
|
||||
** email_verified). Bootstrap operators are matched on immutable ids only.
|
||||
*******************************************************************************/
|
||||
public Set<String> resolve(QInstance qInstance, Collection<String> groupNames, String email)
|
||||
public Set<String> resolve(QInstance qInstance, Collection<String> groupNames, String sub, String email, boolean emailVerified)
|
||||
{
|
||||
Set<String> rs = new TreeSet<>();
|
||||
for(String group : groupNames)
|
||||
@@ -125,9 +139,9 @@ public class AuthentikGroupPermissionMapper implements QAuthenticationModuleCust
|
||||
}
|
||||
|
||||
AuthentikRuntime runtime = runtime();
|
||||
if(runtime != null && email != null && runtime.getConfig().getResolvedBootstrapOperators().contains(email))
|
||||
if(runtime != null && !runtime.getConfig().getResolvedBootstrapSubjects().isEmpty() && isBootstrap(qInstance, runtime, sub, email, emailVerified))
|
||||
{
|
||||
LOG.warn("bootstrapOperators grants all identity permissions; remove it once an identity administrator is set up in Authentik", logPair("email", email));
|
||||
LOG.warn("bootstrapOperatorSubjects grants all identity permissions; empty it once an identity administrator is set up in Authentik", logPair("sub", sub));
|
||||
for(IdentityPermission permission : IdentityPermission.values())
|
||||
{
|
||||
rs.add(permission.getSessionPermission());
|
||||
@@ -164,6 +178,23 @@ public class AuthentikGroupPermissionMapper implements QAuthenticationModuleCust
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private boolean isBootstrap(QInstance qInstance, AuthentikRuntime runtime, String sub, String email, boolean emailVerified)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (BootstrapOperators.matches(runtime.getConfig().getResolvedBootstrapSubjects(), client(qInstance), sub, email, emailVerified));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
|
||||
+4
-1
@@ -17,6 +17,7 @@
|
||||
package com.kingsrook.qbits.authentik.permissions;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -101,7 +102,9 @@ public class EffectivePermissionResolver
|
||||
continue;
|
||||
}
|
||||
appAccess.addAll(node.appAccess());
|
||||
for(String raw : node.permissions())
|
||||
List<String> raws = new ArrayList<>(node.permissions());
|
||||
raws.addAll(node.policyPermissions());
|
||||
for(String raw : raws)
|
||||
{
|
||||
Set<String> expanded = expand(raw);
|
||||
if(expanded.isEmpty())
|
||||
|
||||
@@ -27,6 +27,9 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikJson;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyParseException;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyParser;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
@@ -42,8 +45,16 @@ public class GroupGraph
|
||||
/*******************************************************************************
|
||||
** One group.
|
||||
*******************************************************************************/
|
||||
public record Node(String pk, String name, boolean ownSuperuser, List<String> parentPks, List<String> permissions, List<String> appAccess, List<Integer> memberPks, List<String> malformed)
|
||||
public record Node(String pk, String name, boolean ownSuperuser, List<String> parentPks, List<String> permissions, List<String> appAccess, List<Integer> memberPks, List<String> malformed,
|
||||
List<String> policyPermissions)
|
||||
{
|
||||
/*******************************************************************************
|
||||
** A group without a policy document.
|
||||
*******************************************************************************/
|
||||
public Node(String pk, String name, boolean ownSuperuser, List<String> parentPks, List<String> permissions, List<String> appAccess, List<Integer> memberPks, List<String> malformed)
|
||||
{
|
||||
this(pk, name, ownSuperuser, parentPks, permissions, appAccess, memberPks, malformed, List.of());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,9 +70,25 @@ public class GroupGraph
|
||||
*******************************************************************************/
|
||||
public static GroupGraph fromGroups(Collection<JSONObject> groups)
|
||||
{
|
||||
GroupGraph graph = new GroupGraph();
|
||||
return (fromGroups(groups, PolicyFormat.DEFAULT));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build from Authentik group objects, reading each group's policy document
|
||||
** (docs/POLICY-FORMAT.md) from the format's attribute. A document that does
|
||||
** not parse grants nothing and is listed in the node's malformed entries.
|
||||
*******************************************************************************/
|
||||
public static GroupGraph fromGroups(Collection<JSONObject> groups, PolicyFormat format)
|
||||
{
|
||||
PolicyFormat f = format == null ? PolicyFormat.DEFAULT : format;
|
||||
GroupGraph graph = new GroupGraph();
|
||||
for(JSONObject group : groups)
|
||||
{
|
||||
JSONObject attributes = group.optJSONObject("attributes");
|
||||
List<String> malformed = malformed(attributes);
|
||||
List<String> policy = policyPermissions(attributes, f, malformed);
|
||||
graph.add(new Node(
|
||||
group.getString("pk"),
|
||||
group.optString("name", ""),
|
||||
@@ -70,7 +97,8 @@ public class GroupGraph
|
||||
nonNull(AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_PERMISSIONS)),
|
||||
nonNull(AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_APP_ACCESS)),
|
||||
ints(group.optJSONArray("users")),
|
||||
malformed(group.optJSONObject("attributes"))));
|
||||
malformed,
|
||||
policy));
|
||||
}
|
||||
return (graph);
|
||||
}
|
||||
@@ -257,6 +285,30 @@ public class GroupGraph
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions of a group's policy document; none (and a malformed entry)
|
||||
** when it does not parse.
|
||||
*******************************************************************************/
|
||||
private static List<String> policyPermissions(JSONObject attributes, PolicyFormat format, List<String> malformed)
|
||||
{
|
||||
Object document = attributes == null ? null : attributes.opt(format.attribute());
|
||||
if(document == null || JSONObject.NULL.equals(document) || "".equals(document))
|
||||
{
|
||||
return (List.of());
|
||||
}
|
||||
try
|
||||
{
|
||||
return (List.copyOf(PolicyParser.parseStrict(document, format).permissions()));
|
||||
}
|
||||
catch(PolicyParseException e)
|
||||
{
|
||||
malformed.add(format.attribute() + ": " + e.getMessage());
|
||||
return (List.of());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleCustomizerInterface;
|
||||
import org.json.JSONObject;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Authentication customizer that adds the QQQ permissions granted by the
|
||||
** policy claim of the sign-in token (docs/POLICY-FORMAT.md). It needs no
|
||||
** Authentik API access: Authentik merges the user's group policies into the
|
||||
** claim at sign-in (the scope mapping in the format doc).
|
||||
**
|
||||
** Order: applySecurityKeys (a no-op hook for hosts), then permissions. The
|
||||
** permissions are added to whatever the session already holds. A missing or
|
||||
** invalid claim adds nothing (fail closed).
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyClaimMapper implements QAuthenticationModuleCustomizerInterface
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AuthentikPolicyClaimMapper.class);
|
||||
|
||||
private PolicyFormat format = PolicyFormat.DEFAULT;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Use these names (the qbit config's getPolicyFormat()) instead of the
|
||||
** defaults.
|
||||
*******************************************************************************/
|
||||
public AuthentikPolicyClaimMapper withFormat(PolicyFormat format)
|
||||
{
|
||||
this.format = format == null ? PolicyFormat.DEFAULT : format;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for format.
|
||||
*******************************************************************************/
|
||||
public PolicyFormat getFormat()
|
||||
{
|
||||
return (format);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add the permissions from the policy claim.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void customizeSession(QInstance qInstance, QSession qSession, Map<String, Object> context)
|
||||
{
|
||||
JSONObject claims = PolicyPermissions.claimsWithPolicy(context, format);
|
||||
JSONObject any = claims;
|
||||
if(any == null && context != null)
|
||||
{
|
||||
any = PolicyPermissions.asClaims(context.get(PolicyPermissions.ID_TOKEN_CONTEXT_KEY));
|
||||
if(any == null)
|
||||
{
|
||||
any = PolicyPermissions.asClaims(context.get(PolicyPermissions.ACCESS_TOKEN_CONTEXT_KEY));
|
||||
}
|
||||
}
|
||||
if(any != null)
|
||||
{
|
||||
applySecurityKeys(qSession, any);
|
||||
}
|
||||
|
||||
if(claims == null)
|
||||
{
|
||||
LOG.info("No policy claim in the token; no policy permissions added", logPair("claim", format.claim()));
|
||||
return;
|
||||
}
|
||||
|
||||
Set<String> permissions = new TreeSet<>(PolicyPermissions.fromClaims(claims, format));
|
||||
if(qSession.getPermissions() != null)
|
||||
{
|
||||
permissions.addAll(qSession.getPermissions());
|
||||
}
|
||||
qSession.setPermissions(permissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Extension point for record locks (security keys); a no-op here. A host
|
||||
** overrides it to set security key values from its OWN explicit claims, and
|
||||
** must never infer them from group names.
|
||||
*******************************************************************************/
|
||||
protected void applySecurityKeys(QSession qSession, JSONObject claims)
|
||||
{
|
||||
////////////////////////////////////////////////////////
|
||||
// no record locks in policy format 1.0.0 (by design) //
|
||||
////////////////////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The actions a policy statement can grant, in canonical statement order. Each
|
||||
** maps to the QQQ permission suffix of the same name ({resource}.{action}).
|
||||
*******************************************************************************/
|
||||
public enum PolicyAction
|
||||
{
|
||||
HAS_ACCESS("hasAccess"),
|
||||
READ("read"),
|
||||
INSERT("insert"),
|
||||
EDIT("edit"),
|
||||
DELETE("delete");
|
||||
|
||||
/** "All five actions" in a statement's Action array. */
|
||||
public static final String WILDCARD = "*";
|
||||
|
||||
private final String jsonName;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
PolicyAction(String jsonName)
|
||||
{
|
||||
this.jsonName = jsonName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The name used in documents and as the QQQ permission suffix.
|
||||
*******************************************************************************/
|
||||
public String getJsonName()
|
||||
{
|
||||
return (jsonName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The QQQ permission this action grants on a resource.
|
||||
*******************************************************************************/
|
||||
public String permission(String resource)
|
||||
{
|
||||
return (resource + "." + jsonName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Look up by document name (case-sensitive, like QQQ permission names).
|
||||
*******************************************************************************/
|
||||
public static Optional<PolicyAction> fromJsonName(String name)
|
||||
{
|
||||
for(PolicyAction action : values())
|
||||
{
|
||||
if(action.jsonName.equals(name))
|
||||
{
|
||||
return (Optional.of(action));
|
||||
}
|
||||
}
|
||||
return (Optional.empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppChildMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.reporting.QReportMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a policy can grant in a QInstance (DESIGN.md section 12.4): every app,
|
||||
** table, process, report and protected widget, with its permission base name
|
||||
** (the policy resource) and the actions QQQ checks for it, grouped by app.
|
||||
**
|
||||
** Unlike PermissionsHelper.getAllAvailablePermissions, hidden tables and
|
||||
** processes are included: record actions are hidden from the nav but still
|
||||
** permission-checked. Objects with a custom permission checker or that are
|
||||
** NOT_PROTECTED are left out (a policy cannot grant them).
|
||||
*******************************************************************************/
|
||||
public final class PolicyCatalog
|
||||
{
|
||||
/** Group label of objects that are in no app. */
|
||||
public static final String OTHER = "Other";
|
||||
|
||||
/** Kinds of resources. */
|
||||
public enum Kind
|
||||
{
|
||||
APP, TABLE, PROCESS, REPORT, WIDGET
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One grantable resource.
|
||||
**
|
||||
** @param name the policy resource (permission base name)
|
||||
** @param label what operators see
|
||||
** @param kind app, table, process, report or widget
|
||||
** @param actions the actions QQQ checks, in canonical order
|
||||
** @param note a plain note (e.g. why an action is missing), or null
|
||||
*******************************************************************************/
|
||||
public record Resource(String name, String label, Kind kind, List<PolicyAction> actions, String note)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The resources of one app (or of no app: OTHER).
|
||||
*******************************************************************************/
|
||||
public record Group(String app, String label, List<Resource> resources)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
private final List<Group> groups;
|
||||
private final Map<String, Resource> byName;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
private PolicyCatalog(List<Group> groups)
|
||||
{
|
||||
this.groups = groups;
|
||||
this.byName = new LinkedHashMap<>();
|
||||
for(Group group : groups)
|
||||
{
|
||||
for(Resource resource : group.resources())
|
||||
{
|
||||
byName.putIfAbsent(resource.name(), resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build the catalog of an instance.
|
||||
*******************************************************************************/
|
||||
public static PolicyCatalog of(QInstance qInstance)
|
||||
{
|
||||
Map<String, String> appOfObject = appsOfObjects(qInstance);
|
||||
Map<String, Map<String, ResourceDraft>> byApp = new LinkedHashMap<>();
|
||||
|
||||
List<QAppMetaData> apps = new ArrayList<>(qInstance.getApps().values());
|
||||
apps.sort(Comparator.comparing((QAppMetaData a) -> a.getSortOrder() == null ? 500 : a.getSortOrder()).thenComparing(a -> label(a.getLabel(), a.getName())));
|
||||
for(QAppMetaData app : apps)
|
||||
{
|
||||
byApp.put(app.getName(), new LinkedHashMap<>());
|
||||
}
|
||||
byApp.put(null, new LinkedHashMap<>());
|
||||
|
||||
for(QAppMetaData app : apps)
|
||||
{
|
||||
add(byApp, app.getName(), qInstance, app, Kind.APP, label(app.getLabel(), app.getName()), EnumSet.of(PolicyAction.HAS_ACCESS), null);
|
||||
}
|
||||
|
||||
List<QTableMetaData> tables = new ArrayList<>(qInstance.getTables().values());
|
||||
tables.sort(Comparator.comparing(t -> label(t.getLabel(), t.getName())));
|
||||
for(QTableMetaData table : tables)
|
||||
{
|
||||
QPermissionRules rules = PermissionsHelper.getEffectivePermissionRules(table, qInstance);
|
||||
Set<PolicyAction> actions = EnumSet.noneOf(PolicyAction.class);
|
||||
String note = null;
|
||||
if(rules.getLevel() == PermissionLevel.HAS_ACCESS_PERMISSION)
|
||||
{
|
||||
actions.add(PolicyAction.HAS_ACCESS);
|
||||
}
|
||||
else
|
||||
{
|
||||
QBackendMetaData backend = qInstance.getBackend(table.getBackendName());
|
||||
if(table.isCapabilityEnabled(backend, Capability.TABLE_QUERY) || table.isCapabilityEnabled(backend, Capability.TABLE_GET))
|
||||
{
|
||||
actions.add(PolicyAction.READ);
|
||||
}
|
||||
if(rules.getLevel() == PermissionLevel.READ_WRITE_PERMISSIONS)
|
||||
{
|
||||
note = "This table uses one write permission, which policies cannot grant yet; only read is offered.";
|
||||
}
|
||||
else
|
||||
{
|
||||
if(table.isCapabilityEnabled(backend, Capability.TABLE_INSERT))
|
||||
{
|
||||
actions.add(PolicyAction.INSERT);
|
||||
}
|
||||
if(table.isCapabilityEnabled(backend, Capability.TABLE_UPDATE))
|
||||
{
|
||||
actions.add(PolicyAction.EDIT);
|
||||
}
|
||||
if(table.isCapabilityEnabled(backend, Capability.TABLE_DELETE))
|
||||
{
|
||||
actions.add(PolicyAction.DELETE);
|
||||
}
|
||||
}
|
||||
}
|
||||
add(byApp, appOfObject.get("table:" + table.getName()), qInstance, table, Kind.TABLE, label(table.getLabel(), table.getName()), actions, note);
|
||||
}
|
||||
|
||||
List<QProcessMetaData> processes = new ArrayList<>(qInstance.getProcesses().values());
|
||||
processes.sort(Comparator.comparing(p -> label(p.getLabel(), p.getName())));
|
||||
for(QProcessMetaData process : processes)
|
||||
{
|
||||
String app = appOfObject.get("process:" + process.getName());
|
||||
if(app == null && process.getTableName() != null)
|
||||
{
|
||||
app = appOfObject.get("table:" + process.getTableName());
|
||||
}
|
||||
String label = label(process.getLabel(), process.getName());
|
||||
if(process.getTableName() != null && qInstance.getTable(process.getTableName()) != null)
|
||||
{
|
||||
label = label + " (" + label(qInstance.getTable(process.getTableName()).getLabel(), process.getTableName()) + " action)";
|
||||
}
|
||||
add(byApp, app, qInstance, process, Kind.PROCESS, label, EnumSet.of(PolicyAction.HAS_ACCESS), null);
|
||||
}
|
||||
|
||||
List<QReportMetaData> reports = new ArrayList<>(qInstance.getReports().values());
|
||||
reports.sort(Comparator.comparing(r -> label(r.getLabel(), r.getName())));
|
||||
for(QReportMetaData report : reports)
|
||||
{
|
||||
add(byApp, appOfObject.get("report:" + report.getName()), qInstance, report, Kind.REPORT, label(report.getLabel(), report.getName()), EnumSet.of(PolicyAction.HAS_ACCESS), null);
|
||||
}
|
||||
|
||||
List<QWidgetMetaDataInterface> widgets = new ArrayList<>(qInstance.getWidgets().values());
|
||||
widgets.sort(Comparator.comparing(w -> label(w.getLabel(), w.getName())));
|
||||
for(QWidgetMetaDataInterface widget : widgets)
|
||||
{
|
||||
add(byApp, appOfObject.get("widget:" + widget.getName()), qInstance, widget, Kind.WIDGET, label(widget.getLabel(), widget.getName()), EnumSet.of(PolicyAction.HAS_ACCESS), null);
|
||||
}
|
||||
|
||||
List<Group> groups = new ArrayList<>();
|
||||
for(Map.Entry<String, Map<String, ResourceDraft>> entry : byApp.entrySet())
|
||||
{
|
||||
if(entry.getValue().isEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
String groupLabel = entry.getKey() == null ? OTHER : label(qInstance.getApp(entry.getKey()).getLabel(), entry.getKey());
|
||||
List<Resource> resources = new ArrayList<>();
|
||||
for(ResourceDraft draft : entry.getValue().values())
|
||||
{
|
||||
resources.add(new Resource(draft.name, String.join(" / ", draft.labels), draft.kind, new ArrayList<>(draft.actions), draft.note));
|
||||
}
|
||||
groups.add(new Group(entry.getKey(), groupLabel, resources));
|
||||
}
|
||||
return (new PolicyCatalog(groups));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Accumulates one resource while building (several objects can share a
|
||||
** permission base name).
|
||||
*******************************************************************************/
|
||||
private static class ResourceDraft
|
||||
{
|
||||
private final String name;
|
||||
private final Kind kind;
|
||||
private final Set<String> labels = new LinkedHashSet<>();
|
||||
private final Set<PolicyAction> actions = new TreeSet<>();
|
||||
private String note;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
ResourceDraft(String name, Kind kind)
|
||||
{
|
||||
this.name = name;
|
||||
this.kind = kind;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add an object under its app, unless a policy cannot grant it.
|
||||
*******************************************************************************/
|
||||
private static void add(Map<String, Map<String, ResourceDraft>> byApp, String app, QInstance qInstance, MetaDataWithPermissionRules object, Kind kind, String label,
|
||||
Set<PolicyAction> actions, String note)
|
||||
{
|
||||
QPermissionRules rules = PermissionsHelper.getEffectivePermissionRules(object, qInstance);
|
||||
if(rules == null || rules.getLevel() == null || rules.getLevel() == PermissionLevel.NOT_PROTECTED || rules.getCustomPermissionChecker() != null || actions.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
String name = StringUtils.hasContent(rules.getPermissionBaseName()) ? rules.getPermissionBaseName() : nameOf(object);
|
||||
if(!PolicyParser.RESOURCE_PATTERN.matcher(name).matches())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// a base name shared with an object already listed (in any app) //
|
||||
// joins that entry, so a resource appears once //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
for(Map<String, ResourceDraft> resources : byApp.values())
|
||||
{
|
||||
ResourceDraft existing = resources.get(name);
|
||||
if(existing != null)
|
||||
{
|
||||
existing.labels.add(label);
|
||||
existing.actions.addAll(actions);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ResourceDraft draft = new ResourceDraft(name, kind);
|
||||
draft.labels.add(label);
|
||||
draft.actions.addAll(actions);
|
||||
draft.note = note;
|
||||
byApp.computeIfAbsent(byApp.containsKey(app) ? app : null, k -> new LinkedHashMap<>()).put(name, draft);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Which app directly lists each object ("table:x", "process:y", ...): app
|
||||
** children (sections included) and app widgets. The first app wins.
|
||||
*******************************************************************************/
|
||||
private static Map<String, String> appsOfObjects(QInstance qInstance)
|
||||
{
|
||||
Map<String, String> rs = new LinkedHashMap<>();
|
||||
for(QAppMetaData app : qInstance.getApps().values())
|
||||
{
|
||||
if(app.getChildren() != null)
|
||||
{
|
||||
for(QAppChildMetaData child : app.getChildren())
|
||||
{
|
||||
String type = child instanceof QTableMetaData ? "table" : child instanceof QProcessMetaData ? "process" : child instanceof QReportMetaData ? "report" : null;
|
||||
if(type != null)
|
||||
{
|
||||
rs.putIfAbsent(type + ":" + child.getName(), app.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
if(app.getWidgets() != null)
|
||||
{
|
||||
for(String widget : app.getWidgets())
|
||||
{
|
||||
rs.putIfAbsent("widget:" + widget, app.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String nameOf(MetaDataWithPermissionRules object)
|
||||
{
|
||||
if(object instanceof QTableMetaData t)
|
||||
{
|
||||
return (t.getName());
|
||||
}
|
||||
if(object instanceof QProcessMetaData p)
|
||||
{
|
||||
return (p.getName());
|
||||
}
|
||||
if(object instanceof QAppMetaData a)
|
||||
{
|
||||
return (a.getName());
|
||||
}
|
||||
if(object instanceof QReportMetaData r)
|
||||
{
|
||||
return (r.getName());
|
||||
}
|
||||
if(object instanceof QWidgetMetaDataInterface w)
|
||||
{
|
||||
return (w.getName());
|
||||
}
|
||||
return ("");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String label(String label, String name)
|
||||
{
|
||||
return (StringUtils.hasContent(label) ? label : name);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The groups, in app order, "Other" last.
|
||||
*******************************************************************************/
|
||||
public List<Group> getGroups()
|
||||
{
|
||||
return (groups);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A resource by policy name, or null.
|
||||
*******************************************************************************/
|
||||
public Resource get(String name)
|
||||
{
|
||||
return (byName.get(name));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every QQQ permission a policy can grant here ({resource}.{action}).
|
||||
*******************************************************************************/
|
||||
public Set<String> permissionNames()
|
||||
{
|
||||
Set<String> rs = new TreeSet<>();
|
||||
for(Resource resource : byName.values())
|
||||
{
|
||||
for(PolicyAction action : resource.actions())
|
||||
{
|
||||
rs.add(action.permission(resource.name()));
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The resources of a permission set this catalog does not know, or that
|
||||
** grant an action the resource does not have (sorted, as permission names).
|
||||
*******************************************************************************/
|
||||
public Set<String> unknownPermissions(Set<String> permissions)
|
||||
{
|
||||
Set<String> known = permissionNames();
|
||||
Set<String> rs = new TreeSet<>();
|
||||
for(String permission : permissions)
|
||||
{
|
||||
if(!known.contains(permission))
|
||||
{
|
||||
rs.add(permission);
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** As JSON for the editor widget.
|
||||
*******************************************************************************/
|
||||
public JSONArray toJson()
|
||||
{
|
||||
JSONArray rs = new JSONArray();
|
||||
for(Group group : groups)
|
||||
{
|
||||
JSONArray resources = new JSONArray();
|
||||
for(Resource resource : group.resources())
|
||||
{
|
||||
JSONArray actions = new JSONArray();
|
||||
resource.actions().forEach(a -> actions.put(a.getJsonName()));
|
||||
JSONObject json = new JSONObject()
|
||||
.put("name", resource.name())
|
||||
.put("label", resource.label())
|
||||
.put("kind", resource.kind().name())
|
||||
.put("actions", actions);
|
||||
if(resource.note() != null)
|
||||
{
|
||||
json.put("note", resource.note());
|
||||
}
|
||||
resources.put(json);
|
||||
}
|
||||
rs.put(new JSONObject().put("app", group.app() == null ? JSONObject.NULL : group.app()).put("label", group.label()).put("resources", resources));
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikAdmin;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.QWidgetData;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policy editor widget (type AUTHENTIK_POLICY_EDITOR, DESIGN.md section
|
||||
** 12.4). It is shown on the Edit Policy step; the Next UI widget of the same
|
||||
** type draws the matrix and hands the generated document back to the step as
|
||||
** the process value policyDocument. The data here: the catalog of what a
|
||||
** policy can grant, and the group's current document read live from
|
||||
** Authentik.
|
||||
*******************************************************************************/
|
||||
public final class PolicyEditorWidget
|
||||
{
|
||||
/** The widget type the Next UI renders. */
|
||||
public static final String TYPE = "AUTHENTIK_POLICY_EDITOR";
|
||||
|
||||
/** Short widget name (prefixed with the qbit namespace). */
|
||||
public static final String NAME = "policyEditor";
|
||||
|
||||
/** Widget default value naming the qbit's API backend. */
|
||||
public static final String BACKEND_NAME_KEY = "backendName";
|
||||
|
||||
/** Widget parameter (process value) with the group's pk. */
|
||||
public static final String GROUP_PK_PARAM = "groupPk";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyEditorWidget()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The data for a group (or for none: an empty document).
|
||||
*******************************************************************************/
|
||||
public static Data load(AuthentikQBitConfig config, String groupPk) throws QException
|
||||
{
|
||||
AuthentikRuntime runtime = AuthentikRuntime.forBackend(config.getApiBackendName());
|
||||
PolicyFormat format = config.getPolicyFormat();
|
||||
Data data = new Data()
|
||||
.withSpec(format.spec())
|
||||
.withVersion(format.version())
|
||||
.withCatalog(runtime.getPolicyCatalog().toJson().toList())
|
||||
.withOutputFieldName(AuthentikAdmin.POLICY_DOCUMENT);
|
||||
|
||||
if(!StringUtils.hasContent(groupPk))
|
||||
{
|
||||
return (data);
|
||||
}
|
||||
if(!groupPk.matches("[A-Za-z0-9-]+"))
|
||||
{
|
||||
throw (new QUserFacingException("Not a group id: " + groupPk));
|
||||
}
|
||||
|
||||
JSONObject group = AuthentikActionUtil.forBackend(config.getApiBackendName()).getApiJsonOrNull("/core/groups/" + groupPk + "/?include_users=false&include_parents=false&include_children=false");
|
||||
if(group == null)
|
||||
{
|
||||
throw (new QUserFacingException("That group no longer exists."));
|
||||
}
|
||||
data.withGroupLabel(group.optString("name"));
|
||||
|
||||
Object stored = group.optJSONObject("attributes") == null ? null : group.getJSONObject("attributes").opt(format.attribute());
|
||||
if(stored != null && !JSONObject.NULL.equals(stored) && !"".equals(stored))
|
||||
{
|
||||
try
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////
|
||||
// canonical form of what is stored (unknown resources survive) //
|
||||
/////////////////////////////////////////////////////////////////
|
||||
data.withDocument(PolicyGenerator.toPretty(PolicyGenerator.canonical(stored, format)));
|
||||
}
|
||||
catch(PolicyParseException e)
|
||||
{
|
||||
data.withDocumentProblem(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
QRecord row = PolicyStore.find(config, groupPk);
|
||||
if(row != null)
|
||||
{
|
||||
data.withChangedInAuthentik(!Objects.equals(row.getValueString("authentikFingerprint"), PolicyStore.fingerprint(stored, format)));
|
||||
}
|
||||
return (data);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Renderer. QQQ checks the widget's permission rules
|
||||
** (authentik.policies.manage) before calling it.
|
||||
*******************************************************************************/
|
||||
public static class Renderer extends AbstractWidgetRenderer
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Render.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
|
||||
{
|
||||
String backendName = String.valueOf(((QWidgetMetaData) input.getWidgetMetaData()).getDefaultValues().get(BACKEND_NAME_KEY));
|
||||
AuthentikQBitConfig config = AuthentikRuntime.forBackend(backendName).getConfig();
|
||||
Map<String, String> params = input.getQueryParams();
|
||||
return (new RenderWidgetOutput(load(config, params == null ? null : params.get(GROUP_PK_PARAM))));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The widget's data (see the Next UI's PolicyEditorPayload).
|
||||
*******************************************************************************/
|
||||
public static class Data extends QWidgetData
|
||||
{
|
||||
private String spec;
|
||||
private String version;
|
||||
private String groupLabel;
|
||||
private List<Object> catalog;
|
||||
private String document;
|
||||
private String documentProblem;
|
||||
private Boolean changedInAuthentik = false;
|
||||
private String outputFieldName;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getType()
|
||||
{
|
||||
return (TYPE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for spec
|
||||
*******************************************************************************/
|
||||
public String getSpec()
|
||||
{
|
||||
return (spec);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for spec
|
||||
*******************************************************************************/
|
||||
public Data withSpec(String spec)
|
||||
{
|
||||
this.spec = spec;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for version
|
||||
*******************************************************************************/
|
||||
public String getVersion()
|
||||
{
|
||||
return (version);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for version
|
||||
*******************************************************************************/
|
||||
public Data withVersion(String version)
|
||||
{
|
||||
this.version = version;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for groupLabel
|
||||
*******************************************************************************/
|
||||
public String getGroupLabel()
|
||||
{
|
||||
return (groupLabel);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for groupLabel
|
||||
*******************************************************************************/
|
||||
public Data withGroupLabel(String groupLabel)
|
||||
{
|
||||
this.groupLabel = groupLabel;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for catalog (groups of resources, as plain JSON values)
|
||||
*******************************************************************************/
|
||||
public List<Object> getCatalog()
|
||||
{
|
||||
return (catalog);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for catalog
|
||||
*******************************************************************************/
|
||||
public Data withCatalog(List<Object> catalog)
|
||||
{
|
||||
this.catalog = catalog;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for document (the group's current document, pretty; null for none)
|
||||
*******************************************************************************/
|
||||
public String getDocument()
|
||||
{
|
||||
return (document);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for document
|
||||
*******************************************************************************/
|
||||
public Data withDocument(String document)
|
||||
{
|
||||
this.document = document;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for documentProblem (why the stored document is invalid)
|
||||
*******************************************************************************/
|
||||
public String getDocumentProblem()
|
||||
{
|
||||
return (documentProblem);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for documentProblem
|
||||
*******************************************************************************/
|
||||
public Data withDocumentProblem(String documentProblem)
|
||||
{
|
||||
this.documentProblem = documentProblem;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for changedInAuthentik (differs from the last save in QQQ)
|
||||
*******************************************************************************/
|
||||
public Boolean getChangedInAuthentik()
|
||||
{
|
||||
return (changedInAuthentik);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for changedInAuthentik
|
||||
*******************************************************************************/
|
||||
public Data withChangedInAuthentik(Boolean changedInAuthentik)
|
||||
{
|
||||
this.changedInAuthentik = changedInAuthentik;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for outputFieldName (the process value the editor writes)
|
||||
*******************************************************************************/
|
||||
public String getOutputFieldName()
|
||||
{
|
||||
return (outputFieldName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for outputFieldName
|
||||
*******************************************************************************/
|
||||
public Data withOutputFieldName(String outputFieldName)
|
||||
{
|
||||
this.outputFieldName = outputFieldName;
|
||||
return (this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The names a host uses for its policy documents (docs/POLICY-FORMAT.md): the
|
||||
** PolicySpec it accepts, the one supported PolicyVersion, the Authentik group
|
||||
** attribute that holds a group's document, and the token claim that holds the
|
||||
** merged document.
|
||||
**
|
||||
** @param spec PolicySpec, e.g. "qqq-iam"
|
||||
** @param version PolicyVersion (semver), e.g. "1.0.0"
|
||||
** @param attribute group attribute key, e.g. "qqq.io/policy"
|
||||
** @param claim token claim name, e.g. "qqq_policy"
|
||||
*******************************************************************************/
|
||||
public record PolicyFormat(String spec, String version, String attribute, String claim)
|
||||
{
|
||||
/** Default PolicySpec. */
|
||||
public static final String DEFAULT_SPEC = "qqq-iam";
|
||||
|
||||
/** Default (and only) PolicyVersion of this qbit's format. */
|
||||
public static final String DEFAULT_VERSION = "1.0.0";
|
||||
|
||||
/** Default group attribute. */
|
||||
public static final String DEFAULT_ATTRIBUTE = "qqq.io/policy";
|
||||
|
||||
/** Default token claim. */
|
||||
public static final String DEFAULT_CLAIM = "qqq_policy";
|
||||
|
||||
/** The generic defaults. */
|
||||
public static final PolicyFormat DEFAULT = new PolicyFormat(DEFAULT_SPEC, DEFAULT_VERSION, DEFAULT_ATTRIBUTE, DEFAULT_CLAIM);
|
||||
|
||||
/** A valid spec name: letters, digits, dot, dash and underscore. */
|
||||
public static final Pattern SPEC_PATTERN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,63}");
|
||||
|
||||
/** Semver MAJOR.MINOR.PATCH. */
|
||||
public static final Pattern VERSION_PATTERN = Pattern.compile("(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)");
|
||||
|
||||
/** A valid claim name. */
|
||||
public static final Pattern CLAIM_PATTERN = Pattern.compile("[A-Za-z_][A-Za-z0-9_.-]{0,63}");
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether every name is well formed (used by the config's validate()).
|
||||
*******************************************************************************/
|
||||
public String problem()
|
||||
{
|
||||
if(spec == null || !SPEC_PATTERN.matcher(spec).matches())
|
||||
{
|
||||
return ("policySpec must be letters, digits, '.', '-' or '_': " + spec);
|
||||
}
|
||||
if(version == null || !VERSION_PATTERN.matcher(version).matches())
|
||||
{
|
||||
return ("policyVersion must be semver MAJOR.MINOR.PATCH: " + version);
|
||||
}
|
||||
if(attribute == null || attribute.isBlank())
|
||||
{
|
||||
return ("policyAttribute is required");
|
||||
}
|
||||
if(claim == null || !CLAIM_PATTERN.matcher(claim).matches())
|
||||
{
|
||||
return ("policyClaim must be a plain claim name: " + claim);
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Builds the canonical policy document for a set of QQQ permissions
|
||||
** (docs/POLICY-FORMAT.md, "Canonical form"): one Allow statement per granted
|
||||
** action in the order hasAccess, read, insert, edit, delete; resources sorted;
|
||||
** no "*". Every generated document is checked to round-trip through
|
||||
** PolicyParser to exactly the permissions it came from; one that does not is
|
||||
** never returned.
|
||||
*******************************************************************************/
|
||||
public final class PolicyGenerator
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyGenerator()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The canonical document for these permissions ({resource}.{action} names).
|
||||
**
|
||||
** @throws PolicyParseException when a permission is not {resource}.{action}
|
||||
** with a known action and a valid resource, or the document does not
|
||||
** round-trip
|
||||
*******************************************************************************/
|
||||
public static JSONObject generate(Collection<String> permissions, PolicyFormat format) throws PolicyParseException
|
||||
{
|
||||
PolicyFormat f = format == null ? PolicyFormat.DEFAULT : format;
|
||||
|
||||
Map<PolicyAction, Set<String>> byAction = new LinkedHashMap<>();
|
||||
for(PolicyAction action : PolicyAction.values())
|
||||
{
|
||||
byAction.put(action, new TreeSet<>());
|
||||
}
|
||||
|
||||
Set<String> expected = new TreeSet<>();
|
||||
for(String permission : permissions)
|
||||
{
|
||||
int dot = permission == null ? -1 : permission.lastIndexOf('.');
|
||||
if(dot <= 0 || dot == permission.length() - 1)
|
||||
{
|
||||
throw (new PolicyParseException("\"" + permission + "\" is not {resource}.{action}"));
|
||||
}
|
||||
String resource = permission.substring(0, dot);
|
||||
String name = permission.substring(dot + 1);
|
||||
PolicyAction action = PolicyAction.fromJsonName(name).orElseThrow(() -> new PolicyParseException("\"" + permission + "\": unknown action \"" + name + "\""));
|
||||
if(!PolicyParser.RESOURCE_PATTERN.matcher(resource).matches())
|
||||
{
|
||||
throw (new PolicyParseException("\"" + permission + "\": resource must match [A-Za-z0-9_]+"));
|
||||
}
|
||||
byAction.get(action).add(resource);
|
||||
expected.add(permission);
|
||||
}
|
||||
|
||||
JSONArray statements = new JSONArray();
|
||||
for(Map.Entry<PolicyAction, Set<String>> entry : byAction.entrySet())
|
||||
{
|
||||
if(!entry.getValue().isEmpty())
|
||||
{
|
||||
statements.put(new JSONObject()
|
||||
.put("Effect", PolicyParser.ALLOW)
|
||||
.put("Action", new JSONArray().put(entry.getKey().getJsonName()))
|
||||
.put("Resource", new JSONArray(entry.getValue())));
|
||||
}
|
||||
}
|
||||
|
||||
JSONObject document = new JSONObject()
|
||||
.put("PolicySpec", f.spec())
|
||||
.put("PolicyVersion", f.version())
|
||||
.put("Statement", statements);
|
||||
|
||||
Set<String> parsed = PolicyParser.parseStrict(toCompact(document), f).permissions();
|
||||
if(!parsed.equals(expected))
|
||||
{
|
||||
Set<String> missing = new TreeSet<>(expected);
|
||||
missing.removeAll(parsed);
|
||||
Set<String> extra = new TreeSet<>(parsed);
|
||||
extra.removeAll(expected);
|
||||
throw (new PolicyParseException("The generated document does not round-trip. Missing: " + missing + "; unexpected: " + extra));
|
||||
}
|
||||
return (document);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Re-generate any valid document in canonical form (parse, then generate).
|
||||
*******************************************************************************/
|
||||
public static JSONObject canonical(Object document, PolicyFormat format) throws PolicyParseException
|
||||
{
|
||||
return (generate(PolicyParser.parseStrict(document, format).permissions(), format));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compact JSON in a fixed key order (PolicySpec, PolicyVersion, Statement;
|
||||
** Effect, Action, Resource), as stored in the group attribute.
|
||||
*******************************************************************************/
|
||||
public static String toCompact(JSONObject document)
|
||||
{
|
||||
return (write(document, false));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Pretty JSON (2-space indent, LF, trailing newline) in the fixed key order.
|
||||
*******************************************************************************/
|
||||
public static String toPretty(JSONObject document)
|
||||
{
|
||||
return (write(document, true));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Write in the fixed key order (org.json does not keep insertion order).
|
||||
*******************************************************************************/
|
||||
private static String write(JSONObject document, boolean pretty)
|
||||
{
|
||||
String nl = pretty ? "\n" : "";
|
||||
String i1 = pretty ? " " : "";
|
||||
String i2 = pretty ? " " : "";
|
||||
String i3 = pretty ? " " : "";
|
||||
String i4 = pretty ? " " : "";
|
||||
String sep = pretty ? ": " : ":";
|
||||
|
||||
StringBuilder sb = new StringBuilder("{").append(nl);
|
||||
sb.append(i1).append(JSONObject.quote("PolicySpec")).append(sep).append(JSONObject.quote(document.optString("PolicySpec"))).append(",").append(nl);
|
||||
sb.append(i1).append(JSONObject.quote("PolicyVersion")).append(sep).append(JSONObject.quote(document.optString("PolicyVersion"))).append(",").append(nl);
|
||||
sb.append(i1).append(JSONObject.quote("Statement")).append(sep).append("[");
|
||||
|
||||
JSONArray statements = document.optJSONArray("Statement");
|
||||
int count = statements == null ? 0 : statements.length();
|
||||
for(int s = 0; s < count; s++)
|
||||
{
|
||||
JSONObject statement = statements.getJSONObject(s);
|
||||
sb.append(s == 0 ? nl : "," + nl).append(i2).append("{").append(nl);
|
||||
sb.append(i3).append(JSONObject.quote("Effect")).append(sep).append(JSONObject.quote(statement.optString("Effect"))).append(",").append(nl);
|
||||
sb.append(i3).append(JSONObject.quote("Action")).append(sep).append(inline(statement.optJSONArray("Action"), pretty)).append(",").append(nl);
|
||||
sb.append(i3).append(JSONObject.quote("Resource")).append(sep).append("[");
|
||||
JSONArray resources = statement.optJSONArray("Resource");
|
||||
int n = resources == null ? 0 : resources.length();
|
||||
for(int r = 0; r < n; r++)
|
||||
{
|
||||
sb.append(r == 0 ? nl : "," + nl).append(i4).append(JSONObject.quote(resources.optString(r)));
|
||||
}
|
||||
sb.append(n == 0 ? "" : nl + i3).append("]").append(nl);
|
||||
sb.append(i2).append("}");
|
||||
}
|
||||
sb.append(count == 0 ? "" : nl + i1).append("]").append(nl);
|
||||
sb.append("}").append(nl);
|
||||
return (sb.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A short string array on one line.
|
||||
*******************************************************************************/
|
||||
private static String inline(JSONArray array, boolean pretty)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
int n = array == null ? 0 : array.length();
|
||||
for(int i = 0; i < n; i++)
|
||||
{
|
||||
sb.append(i == 0 ? "" : (pretty ? ", " : ",")).append(JSONObject.quote(array.optString(i)));
|
||||
}
|
||||
return (sb.append("]").toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A policy document that cannot be accepted; the message names the problem
|
||||
** in plain words (shown to operators in the editor's Review step).
|
||||
*******************************************************************************/
|
||||
public class PolicyParseException extends Exception
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor.
|
||||
*******************************************************************************/
|
||||
public PolicyParseException(String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Pattern;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Parses a policy document (docs/POLICY-FORMAT.md) into QQQ permission names.
|
||||
**
|
||||
** parse() FAILS CLOSED: any problem (unknown spec, unsupported version, a
|
||||
** statement that is not Allow, an unknown action, a bad resource, malformed
|
||||
** JSON, ...) grants zero permissions and logs a warning. parseStrict() throws
|
||||
** a PolicyParseException naming the problem instead (for the editor).
|
||||
*******************************************************************************/
|
||||
public final class PolicyParser
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(PolicyParser.class);
|
||||
|
||||
/** A valid resource: a QQQ permission base name. */
|
||||
public static final Pattern RESOURCE_PATTERN = Pattern.compile("[A-Za-z0-9_]+");
|
||||
|
||||
/** The only effect in 1.0.0. */
|
||||
public static final String ALLOW = "Allow";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The result of a successful parse.
|
||||
**
|
||||
** @param permissions QQQ permission names ({resource}.{action}), sorted
|
||||
** @param resources every resource named, in document order
|
||||
*******************************************************************************/
|
||||
public record Parsed(Set<String> permissions, Set<String> resources)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyParser()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions a document grants, or none (with a warning) when it is
|
||||
** missing or invalid in any way.
|
||||
**
|
||||
** @param document a JSONObject, a Map, or a JSON string (as stored in a group
|
||||
** attribute or a token claim); null grants nothing
|
||||
*******************************************************************************/
|
||||
public static Set<String> parse(Object document, PolicyFormat format)
|
||||
{
|
||||
if(document == null || JSONObject.NULL.equals(document))
|
||||
{
|
||||
return (Collections.emptySet());
|
||||
}
|
||||
try
|
||||
{
|
||||
return (parseStrict(document, format).permissions());
|
||||
}
|
||||
catch(PolicyParseException e)
|
||||
{
|
||||
LOG.warn("Policy document rejected; it grants no permissions", logPair("reason", e.getMessage()));
|
||||
return (Collections.emptySet());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Parse, throwing a PolicyParseException that names the first problem.
|
||||
*******************************************************************************/
|
||||
public static Parsed parseStrict(Object document, PolicyFormat format) throws PolicyParseException
|
||||
{
|
||||
JSONObject json = asObject(document);
|
||||
PolicyFormat f = format == null ? PolicyFormat.DEFAULT : format;
|
||||
|
||||
Object spec = json.opt("PolicySpec");
|
||||
if(!(spec instanceof String s) || !s.equals(f.spec()))
|
||||
{
|
||||
throw (new PolicyParseException("PolicySpec must be \"" + f.spec() + "\" (found " + describe(spec) + ")"));
|
||||
}
|
||||
Object version = json.opt("PolicyVersion");
|
||||
if(!(version instanceof String v) || !v.equals(f.version()))
|
||||
{
|
||||
throw (new PolicyParseException("PolicyVersion must be \"" + f.version() + "\" (found " + describe(version) + ")"));
|
||||
}
|
||||
|
||||
Set<String> permissions = new TreeSet<>();
|
||||
Set<String> resources = new LinkedHashSet<>();
|
||||
Object statements = json.opt("Statement");
|
||||
if(statements == null)
|
||||
{
|
||||
return (new Parsed(permissions, resources));
|
||||
}
|
||||
if(!(statements instanceof JSONArray array))
|
||||
{
|
||||
throw (new PolicyParseException("Statement must be an array"));
|
||||
}
|
||||
|
||||
for(int i = 0; i < array.length(); i++)
|
||||
{
|
||||
final int number = i + 1;
|
||||
if(!(array.opt(i) instanceof JSONObject statement))
|
||||
{
|
||||
throw (new PolicyParseException("Statement " + (i + 1) + " must be an object"));
|
||||
}
|
||||
Object effect = statement.opt("Effect");
|
||||
if(!ALLOW.equals(effect))
|
||||
{
|
||||
throw (new PolicyParseException("Statement " + (i + 1) + ": Effect must be \"Allow\" (found " + describe(effect) + "); Deny is not supported yet"));
|
||||
}
|
||||
|
||||
Set<PolicyAction> actions = EnumSet.noneOf(PolicyAction.class);
|
||||
for(String name : strings(statement.opt("Action"), "Statement " + (i + 1) + ": Action"))
|
||||
{
|
||||
if(PolicyAction.WILDCARD.equals(name))
|
||||
{
|
||||
actions.addAll(EnumSet.allOf(PolicyAction.class));
|
||||
}
|
||||
else
|
||||
{
|
||||
actions.add(PolicyAction.fromJsonName(name).orElseThrow(() -> new PolicyParseException("Statement " + number + ": unknown action \"" + name + "\"")));
|
||||
}
|
||||
}
|
||||
|
||||
for(String resource : strings(statement.opt("Resource"), "Statement " + (i + 1) + ": Resource"))
|
||||
{
|
||||
if(!RESOURCE_PATTERN.matcher(resource).matches())
|
||||
{
|
||||
throw (new PolicyParseException("Statement " + (i + 1) + ": resource \"" + resource + "\" must match [A-Za-z0-9_]+"));
|
||||
}
|
||||
resources.add(resource);
|
||||
for(PolicyAction action : actions)
|
||||
{
|
||||
permissions.add(action.permission(resource));
|
||||
}
|
||||
}
|
||||
}
|
||||
return (new Parsed(permissions, resources));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The document as a JSON object.
|
||||
*******************************************************************************/
|
||||
static JSONObject asObject(Object document) throws PolicyParseException
|
||||
{
|
||||
if(document instanceof JSONObject object)
|
||||
{
|
||||
return (object);
|
||||
}
|
||||
if(document instanceof Map<?, ?> map)
|
||||
{
|
||||
return (new JSONObject(map));
|
||||
}
|
||||
if(document instanceof String text)
|
||||
{
|
||||
if(text.isBlank())
|
||||
{
|
||||
throw (new PolicyParseException("The document is empty"));
|
||||
}
|
||||
try
|
||||
{
|
||||
return (new JSONObject(text));
|
||||
}
|
||||
catch(JSONException e)
|
||||
{
|
||||
throw (new PolicyParseException("The document is not a JSON object"));
|
||||
}
|
||||
}
|
||||
throw (new PolicyParseException("The document is not a JSON object"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An array of strings, or a PolicyParseException.
|
||||
*******************************************************************************/
|
||||
private static Set<String> strings(Object value, String what) throws PolicyParseException
|
||||
{
|
||||
if(!(value instanceof JSONArray array))
|
||||
{
|
||||
throw (new PolicyParseException(what + " must be an array of strings"));
|
||||
}
|
||||
Set<String> rs = new LinkedHashSet<>();
|
||||
for(int i = 0; i < array.length(); i++)
|
||||
{
|
||||
if(!(array.opt(i) instanceof String text))
|
||||
{
|
||||
throw (new PolicyParseException(what + " must be an array of strings"));
|
||||
}
|
||||
rs.add(text);
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A short description of a found value for messages (never the whole value).
|
||||
*******************************************************************************/
|
||||
private static String describe(Object value)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return ("nothing");
|
||||
}
|
||||
if(value instanceof String text)
|
||||
{
|
||||
return ("\"" + (text.length() > 40 ? text.substring(0, 40) + "..." : text) + "\"");
|
||||
}
|
||||
return (value.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Helpers a host's own authentication customizer can call to turn the policy
|
||||
** claim of a sign-in token into QQQ permissions (docs/POLICY-FORMAT.md).
|
||||
*******************************************************************************/
|
||||
public final class PolicyPermissions
|
||||
{
|
||||
/** Customizer context key of the ID token claims (QQQ OAuth2 module). */
|
||||
public static final String ID_TOKEN_CONTEXT_KEY = "idToken";
|
||||
|
||||
/** Customizer context key of the access token claims. */
|
||||
public static final String ACCESS_TOKEN_CONTEXT_KEY = "jwtPayloadJsonObject";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyPermissions()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions granted by the policy claim in these token claims; none
|
||||
** when the claim is missing or invalid (fail closed).
|
||||
*******************************************************************************/
|
||||
public static Set<String> fromClaims(JSONObject claims, PolicyFormat format)
|
||||
{
|
||||
PolicyFormat f = format == null ? PolicyFormat.DEFAULT : format;
|
||||
if(claims == null || !claims.has(f.claim()))
|
||||
{
|
||||
return (Collections.emptySet());
|
||||
}
|
||||
return (PolicyParser.parse(claims.opt(f.claim()), f));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The claims that carry the policy in a customizer context: the ID token's
|
||||
** when it has the claim (Authentik puts scope-mapping claims there), else the
|
||||
** access token's (the only ones on a session resume). Null when neither has
|
||||
** the claim.
|
||||
*******************************************************************************/
|
||||
public static JSONObject claimsWithPolicy(Map<String, Object> context, PolicyFormat format)
|
||||
{
|
||||
PolicyFormat f = format == null ? PolicyFormat.DEFAULT : format;
|
||||
if(context == null)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
for(String key : new String[] { ID_TOKEN_CONTEXT_KEY, ACCESS_TOKEN_CONTEXT_KEY })
|
||||
{
|
||||
JSONObject claims = asClaims(context.get(key));
|
||||
if(claims != null && claims.has(f.claim()))
|
||||
{
|
||||
return (claims);
|
||||
}
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Claims as a JSONObject (QQQ passes a JSONObject; tests may pass a Map).
|
||||
*******************************************************************************/
|
||||
public static JSONObject asClaims(Object value)
|
||||
{
|
||||
if(value instanceof JSONObject object)
|
||||
{
|
||||
return (object);
|
||||
}
|
||||
if(value instanceof Map<?, ?> map)
|
||||
{
|
||||
return (new JSONObject(map));
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The authentik_policy rows (DESIGN.md section 12.2): the QQQ record of each
|
||||
** group's last policy save, plus the fingerprint used to tell when the policy
|
||||
** was changed in Authentik since.
|
||||
*******************************************************************************/
|
||||
public final class PolicyStore
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyStore()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A fingerprint of a group's policy attribute value: of its canonical form
|
||||
** when it parses (so formatting differences do not count), else of the raw
|
||||
** text. Null for no policy.
|
||||
*******************************************************************************/
|
||||
public static String fingerprint(Object attributeValue, PolicyFormat format)
|
||||
{
|
||||
if(attributeValue == null || JSONObject.NULL.equals(attributeValue) || "".equals(attributeValue))
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
String text;
|
||||
try
|
||||
{
|
||||
text = PolicyGenerator.toCompact(PolicyGenerator.canonical(attributeValue, format));
|
||||
}
|
||||
catch(PolicyParseException e)
|
||||
{
|
||||
text = String.valueOf(attributeValue);
|
||||
}
|
||||
try
|
||||
{
|
||||
return (HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))));
|
||||
}
|
||||
catch(NoSuchAlgorithmException e)
|
||||
{
|
||||
throw (new IllegalStateException(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The row of a group, or null (also null when the table is not set up).
|
||||
*******************************************************************************/
|
||||
public static QRecord find(AuthentikQBitConfig config, String groupPk) throws QException
|
||||
{
|
||||
String table = config.applyTablePrefix(AuthentikLocalTables.POLICY);
|
||||
if(QContext.getQInstance() == null || QContext.getQInstance().getTable(table) == null)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
QueryInput queryInput = new QueryInput();
|
||||
queryInput.setTableName(table);
|
||||
queryInput.setFilter(new QQueryFilter(new QFilterCriteria("groupPk", QCriteriaOperator.EQUALS, groupPk)));
|
||||
QueryOutput output = new QueryAction().execute(queryInput);
|
||||
return (output.getRecords().isEmpty() ? null : output.getRecords().get(0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Insert or update the row of a group after a save to Authentik.
|
||||
**
|
||||
** @param document the canonical document that was saved (empty statements
|
||||
** when the policy was removed)
|
||||
*******************************************************************************/
|
||||
public static void save(AuthentikQBitConfig config, String groupPk, String groupName, JSONObject document, int permissionCount, String savedBy, String fingerprint) throws QException
|
||||
{
|
||||
String table = config.applyTablePrefix(AuthentikLocalTables.POLICY);
|
||||
QRecord existing = find(config, groupPk);
|
||||
QRecord record = new QRecord()
|
||||
.withValue("groupPk", groupPk)
|
||||
.withValue("groupName", groupName)
|
||||
.withValue("policyJson", PolicyGenerator.toPretty(document))
|
||||
.withValue("statementCount", document.optJSONArray("Statement") == null ? 0 : document.getJSONArray("Statement").length())
|
||||
.withValue("permissionCount", permissionCount)
|
||||
.withValue("savedBy", savedBy)
|
||||
.withValue("savedDate", Instant.now())
|
||||
.withValue("authentikFingerprint", fingerprint)
|
||||
.withValue("modifyDate", Instant.now());
|
||||
|
||||
if(existing == null)
|
||||
{
|
||||
record.setValue("createDate", Instant.now());
|
||||
InsertInput insertInput = new InsertInput();
|
||||
insertInput.setTableName(table);
|
||||
insertInput.setRecords(List.of(record));
|
||||
InsertOutput output = new InsertAction().execute(insertInput);
|
||||
if(output.getRecords().isEmpty() || !output.getRecords().get(0).getErrors().isEmpty())
|
||||
{
|
||||
throw (new QException("The policy record could not be written: " + (output.getRecords().isEmpty() ? "no record" : output.getRecords().get(0).getErrors())));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
record.setValue("id", existing.getValue("id"));
|
||||
UpdateInput updateInput = new UpdateInput();
|
||||
updateInput.setTableName(table);
|
||||
updateInput.setRecords(List.of(record));
|
||||
UpdateOutput output = new UpdateAction().execute(updateInput);
|
||||
if(output.getRecords().isEmpty() || !output.getRecords().get(0).getErrors().isEmpty())
|
||||
{
|
||||
throw (new QException("The policy record could not be written: " + (output.getRecords().isEmpty() ? "no record" : output.getRecords().get(0).getErrors())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,896 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.processes;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminAction;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminPlan;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminRequest;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikAdmin;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikSafety;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikJson;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyEditorWidget;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFunctionInputMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QRecordListMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractExtractStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ExtractViaQueryStep;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every change the qbit makes is a table or record action (DESIGN.md section
|
||||
** 6.3); none is ever in the nav. Each is a standard streamed-ETL process with
|
||||
** an optional details screen first, a Review step (the dry run: what each
|
||||
** target would become, and which are refused and why) and a Result step
|
||||
** (summary lines per outcome). The rules live in AuthentikAdmin; these steps
|
||||
** only ask it to plan (Review) and to execute (Result).
|
||||
*******************************************************************************/
|
||||
public final class AuthentikProcesses
|
||||
{
|
||||
/** What the process is launched on. */
|
||||
public enum Kind
|
||||
{
|
||||
/** Selected users (authentik_user). */
|
||||
USERS,
|
||||
/** Selected groups, each with a list of usernames (members actions). */
|
||||
GROUP_USERNAMES,
|
||||
/** Selected groups (authentik_group). */
|
||||
GROUPS,
|
||||
/** No records: a form creates something (table action). */
|
||||
CREATE,
|
||||
/** Selected invitations. */
|
||||
INVITATIONS,
|
||||
/** Selected approval requests. */
|
||||
APPROVALS,
|
||||
/** Selected policy records (authentik_policy); the target is the record's group. */
|
||||
POLICIES
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** One process definition.
|
||||
**
|
||||
** @param key short key; the process is named applyPrefix("<key>")
|
||||
** @param label plain label shown in the Actions menu
|
||||
** @param action what it does (null for approvals)
|
||||
** @param kind what it is launched on
|
||||
** @param table unprefixed table name it is bound to
|
||||
** @param icon material icon
|
||||
** @param prefill whether a prepare step fills the form from the record
|
||||
** @param fields details screen fields
|
||||
** @param help help text on the details screen
|
||||
*******************************************************************************/
|
||||
public record Def(String key, String label, AdminAction action, Kind kind, String table, String icon, boolean prefill, List<QFieldMetaData> fields, String help)
|
||||
{
|
||||
}
|
||||
|
||||
private static final Map<String, Def> DEFS_BY_PROCESS = new HashMap<>();
|
||||
private static final Map<String, AuthentikQBitConfig> CONFIGS_BY_PROCESS = new HashMap<>();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AuthentikProcesses()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The definitions enabled by the config's features.
|
||||
*******************************************************************************/
|
||||
public static List<Def> definitions(AuthentikQBitConfig config)
|
||||
{
|
||||
List<Def> defs = new ArrayList<>();
|
||||
QFieldMetaData reason = new QFieldMetaData("reason", QFieldType.TEXT).withLabel("Reason").withIsRequired(true);
|
||||
QFieldMetaData typed = new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Type the username to confirm").withIsRequired(true);
|
||||
QFieldMetaData group = new QFieldMetaData("group", QFieldType.STRING).withLabel("Group").withIsRequired(true)
|
||||
.withPossibleValueSourceName(config.applyTablePrefix(AuthentikTables.GROUP));
|
||||
|
||||
String users = AuthentikTables.USER;
|
||||
String groups = AuthentikTables.GROUP;
|
||||
|
||||
defs.add(new Def("createUser", "Create User", AdminAction.CREATE_USER, Kind.CREATE, users, "person_add", false, List.of(
|
||||
new QFieldMetaData("username", QFieldType.STRING).withLabel("Username").withIsRequired(true),
|
||||
new QFieldMetaData("name", QFieldType.STRING).withLabel("Full Name").withIsRequired(true),
|
||||
new QFieldMetaData("email", QFieldType.STRING).withLabel("Email").withIsRequired(true),
|
||||
new QFieldMetaData("groups", QFieldType.TEXT).withLabel("Groups (names, one per line)"),
|
||||
new QFieldMetaData("sendRecovery", QFieldType.BOOLEAN).withLabel("Email them a link to set their own password").withDefaultValue(true),
|
||||
reason), "No password is set here. Authentik emails the person a link to set their own."));
|
||||
defs.add(new Def("inviteUser", "Invite User", AdminAction.INVITE_USER, Kind.CREATE, users, "mail", false, List.of(
|
||||
new QFieldMetaData("email", QFieldType.STRING).withLabel("Email").withIsRequired(true),
|
||||
new QFieldMetaData("name", QFieldType.STRING).withLabel("Full Name"),
|
||||
reason), "Authentik emails a single-use sign-up invitation that expires in 7 days."));
|
||||
defs.add(new Def("editUser", "Edit User", AdminAction.EDIT_USER, Kind.USERS, users, "edit", true, List.of(
|
||||
new QFieldMetaData("name", QFieldType.STRING).withLabel("Full Name"),
|
||||
new QFieldMetaData("email", QFieldType.STRING).withLabel("Email"),
|
||||
new QFieldMetaData("path", QFieldType.STRING).withLabel("Path"),
|
||||
hidden("expectedFingerprint"), reason), "Change a person's name, email or path."));
|
||||
defs.add(new Def("deactivateUser", "Deactivate User", AdminAction.DEACTIVATE_USER, Kind.USERS, users, "block", false, List.of(
|
||||
new QFieldMetaData("revokeAppPasswords", QFieldType.BOOLEAN).withLabel("Also revoke their app passwords").withDefaultValue(false),
|
||||
typed, reason), "Deactivating ends their sessions immediately and deletes nothing. Type the username to confirm (when you select several people, type the username of the first one)."));
|
||||
defs.add(new Def("reactivateUser", "Reactivate User", AdminAction.REACTIVATE_USER, Kind.USERS, users, "check_circle", false, List.of(reason), null));
|
||||
defs.add(new Def("addToGroup", "Add To Group", AdminAction.ADD_MEMBER, Kind.USERS, users, "group_add", false, List.of(group,
|
||||
new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Confirm the number of people (needed only above 25)").withIsHidden(false), reason),
|
||||
"You can only add people to a group whose permissions you hold yourself."));
|
||||
defs.add(new Def("removeFromGroup", "Remove From Group", AdminAction.REMOVE_MEMBER, Kind.USERS, users, "group_remove", false, List.of(group,
|
||||
new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Confirm the number of people (needed only above 25)").withIsHidden(false), reason), null));
|
||||
defs.add(new Def("sendPasswordReset", "Send Password Reset Email", AdminAction.SEND_RECOVERY_EMAIL, Kind.USERS, users, "lock_reset", false, List.of(reason),
|
||||
"Authentik emails the person a link. You never see the link."));
|
||||
defs.add(new Def("resetMfa", "Reset MFA", AdminAction.RESET_MFA, Kind.USERS, users, "phonelink_erase", false, List.of(typed, reason),
|
||||
"Removes every MFA device; the person sets MFA up again at next sign-in."));
|
||||
defs.add(new Def("revokeAppPasswords", "Revoke App Passwords", AdminAction.REVOKE_APP_PASSWORDS, Kind.USERS, users, "key_off", false, List.of(typed, reason),
|
||||
"Revokes app passwords only; API tokens are never touched."));
|
||||
defs.add(new Def("revokeSessions", "Revoke Sessions", AdminAction.REVOKE_SESSIONS, Kind.USERS, users, "logout", false, List.of(reason), "Signs the person out everywhere."));
|
||||
|
||||
defs.add(new Def("createGroup", "Create Group", AdminAction.CREATE_GROUP, Kind.CREATE, groups, "group_add", false, List.of(
|
||||
new QFieldMetaData("name", QFieldType.STRING).withLabel("Group Name").withIsRequired(true),
|
||||
new QFieldMetaData("parents", QFieldType.TEXT).withLabel("Parent groups (names, one per line)"),
|
||||
new QFieldMetaData("permissions", QFieldType.TEXT).withLabel("QQQ permissions (one per line)"),
|
||||
new QFieldMetaData("appAccess", QFieldType.TEXT).withLabel("App access (app keys, one per line)"),
|
||||
reason), "A group's QQQ permissions apply to everyone in it, and to groups below it."));
|
||||
defs.add(new Def("editGroup", "Edit Group", AdminAction.EDIT_GROUP, Kind.GROUPS, groups, "edit", true, List.of(
|
||||
new QFieldMetaData("name", QFieldType.STRING).withLabel("Group Name"),
|
||||
new QFieldMetaData("parents", QFieldType.TEXT).withLabel("Parent groups (names, one per line; none to clear)"),
|
||||
hidden("expectedFingerprint"), reason), "Rename a group or change its parents."));
|
||||
defs.add(new Def("editPermissions", "Edit Permissions And App Access", AdminAction.EDIT_PERMISSIONS, Kind.GROUPS, groups, "admin_panel_settings", true, List.of(
|
||||
new QFieldMetaData("permissions", QFieldType.TEXT).withLabel("QQQ permissions (one per line)"),
|
||||
new QFieldMetaData("appAccess", QFieldType.TEXT).withLabel("App access (app keys, one per line)"),
|
||||
hidden("expectedFingerprint"), reason),
|
||||
"You can only add permissions you hold yourself. Adding authentik.* needs a second person to approve."));
|
||||
String policyHelp = "Tick what members of this group, and of the groups below it, may do. The document is what is saved to Authentik. "
|
||||
+ "You can only grant permissions you hold yourself.";
|
||||
List<QFieldMetaData> policyFields = List.of(hidden("groupPk"), hidden("expectedFingerprint"), reason);
|
||||
defs.add(new Def("editPolicy", "Edit Policy", AdminAction.SAVE_POLICY, Kind.GROUPS, groups, "policy", true, policyFields, policyHelp));
|
||||
defs.add(new Def("editPolicyRecord", "Edit Policy", AdminAction.SAVE_POLICY, Kind.POLICIES, AuthentikLocalTables.POLICY, "policy", true, policyFields, policyHelp));
|
||||
defs.add(new Def("addMembers", "Add Members", AdminAction.ADD_MEMBER, Kind.GROUP_USERNAMES, groups, "person_add", false, List.of(
|
||||
new QFieldMetaData("usernames", QFieldType.TEXT).withLabel("Usernames (one per line)").withIsRequired(true),
|
||||
new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Confirm the number of people (needed only above 25)").withIsHidden(false), reason), null));
|
||||
defs.add(new Def("removeMembers", "Remove Members", AdminAction.REMOVE_MEMBER, Kind.GROUP_USERNAMES, groups, "person_remove", false, List.of(
|
||||
new QFieldMetaData("usernames", QFieldType.TEXT).withLabel("Usernames (one per line)").withIsRequired(true),
|
||||
new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Confirm the number of people (needed only above 25)").withIsHidden(false), reason), null));
|
||||
|
||||
defs.add(new Def("cancelInvitation", "Cancel Invitation", AdminAction.CANCEL_INVITATION, Kind.INVITATIONS, "invitation", "cancel", false, List.of(reason), null));
|
||||
defs.add(new Def("approve", "Approve And Apply", null, Kind.APPROVALS, AuthentikLocalTables.APPROVAL_REQUEST, "check", false, List.of(), "A second person applies the change. The change is checked again against live data."));
|
||||
defs.add(new Def("reject", "Reject", null, Kind.APPROVALS, AuthentikLocalTables.APPROVAL_REQUEST, "close", false, List.of(), null));
|
||||
|
||||
defs.removeIf(def -> def.action() != null && !config.hasFeature(def.action().getFeature()));
|
||||
if(!config.hasFeature(com.kingsrook.qbits.authentik.AuthentikFeature.GROUPS) || !config.getTwoPersonApproval())
|
||||
{
|
||||
defs.removeIf(def -> def.kind() == Kind.APPROVALS);
|
||||
}
|
||||
if(StringUtils.hasContent(config.getInvitationFlow()))
|
||||
{
|
||||
return (defs);
|
||||
}
|
||||
defs.removeIf(def -> def.action() == AdminAction.INVITE_USER || def.action() == AdminAction.CANCEL_INVITATION);
|
||||
return (defs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A hidden form field (carries a stale-check fingerprint).
|
||||
*******************************************************************************/
|
||||
private static QFieldMetaData hidden(String name)
|
||||
{
|
||||
return (new QFieldMetaData(name, QFieldType.STRING).withIsHidden(true));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The process names for a config's definitions (for the app and tests).
|
||||
*******************************************************************************/
|
||||
public static String processName(AuthentikQBitConfig config, Def def)
|
||||
{
|
||||
return (config.applyPrefix(def.key()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** All processes for a config.
|
||||
*******************************************************************************/
|
||||
public static List<QProcessMetaData> processes(AuthentikQBitConfig config)
|
||||
{
|
||||
List<QProcessMetaData> processes = new ArrayList<>();
|
||||
for(Def def : definitions(config))
|
||||
{
|
||||
processes.add(build(config, def));
|
||||
}
|
||||
return (processes);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build one process.
|
||||
*******************************************************************************/
|
||||
static QProcessMetaData build(AuthentikQBitConfig config, Def def)
|
||||
{
|
||||
String name = processName(config, def);
|
||||
String table = config.applyTablePrefix(def.table());
|
||||
DEFS_BY_PROCESS.put(name, def);
|
||||
CONFIGS_BY_PROCESS.put(name, config);
|
||||
|
||||
Map<String, Serializable> values = new HashMap<>();
|
||||
values.put(StreamedETLWithFrontendProcess.FIELD_SOURCE_TABLE, table);
|
||||
values.put(StreamedETLWithFrontendProcess.FIELD_DESTINATION_TABLE, table);
|
||||
values.put(StreamedETLWithFrontendProcess.FIELD_SUPPORTS_FULL_VALIDATION, true);
|
||||
values.put(StreamedETLWithFrontendProcess.FIELD_DO_FULL_VALIDATION, true);
|
||||
values.put(StreamedETLWithFrontendProcess.FIELD_PREVIEW_MESSAGE, "This is a preview of what will change. Nothing has been sent to Authentik yet.");
|
||||
|
||||
Class<? extends AbstractExtractStep> extract = def.kind() == Kind.CREATE ? SingleRecordExtractStep.class : ExtractViaQueryStep.class;
|
||||
QProcessMetaData process = StreamedETLWithFrontendProcess.defineProcessMetaData(extract, ActionTransformStep.class, ActionLoadStep.class, values);
|
||||
process.setName(name);
|
||||
process.setLabel(def.label());
|
||||
process.setTableName(table);
|
||||
process.setIcon(new QIcon(def.icon()));
|
||||
process.setPermissionRules((def.action() == null ? IdentityPermission.APPROVE : def.action().getPermission()).rules());
|
||||
switch(def.kind())
|
||||
{
|
||||
case CREATE -> process.setMaxInputRecords(0);
|
||||
case USERS, GROUP_USERNAMES, GROUPS, INVITATIONS, APPROVALS, POLICIES ->
|
||||
{
|
||||
process.setMinInputRecords(1);
|
||||
process.setMaxInputRecords(def.action() == AdminAction.EDIT_USER || def.action() == AdminAction.EDIT_GROUP || def.action() == AdminAction.EDIT_PERMISSIONS
|
||||
|| def.action() == AdminAction.SAVE_POLICY ? 1 : AuthentikAdmin.MAX_BULK);
|
||||
}
|
||||
default ->
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if(!def.fields().isEmpty())
|
||||
{
|
||||
QFrontendStepMetaData details = new QFrontendStepMetaData().withName("details").withLabel(def.label()).withFormFields(def.fields());
|
||||
if(StringUtils.hasContent(def.help()))
|
||||
{
|
||||
details.withComponent(new QFrontendComponentMetaData().withType(QComponentType.HELP_TEXT).withValue("text", def.help()));
|
||||
}
|
||||
if(def.action() == AdminAction.SAVE_POLICY)
|
||||
{
|
||||
details.withComponent(new QFrontendComponentMetaData().withType(QComponentType.WIDGET).withValue("widgetName", config.applyPrefix(PolicyEditorWidget.NAME)));
|
||||
}
|
||||
details.withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM));
|
||||
process.withStep(0, details);
|
||||
if(def.prefill())
|
||||
{
|
||||
process.withStep(0, new QBackendStepMetaData().withName("prepare").withCode(new QCodeReference(PrepareStep.class))
|
||||
.withInputData(new QFunctionInputMetaData().withRecordListMetaData(new QRecordListMetaData().withTableName(table))));
|
||||
}
|
||||
}
|
||||
return (process);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The definition behind a process name.
|
||||
*******************************************************************************/
|
||||
static Def defFor(String processName)
|
||||
{
|
||||
Def def = DEFS_BY_PROCESS.get(processName);
|
||||
if(def == null)
|
||||
{
|
||||
throw (new IllegalStateException("Not an Authentik qbit process: " + processName));
|
||||
}
|
||||
return (def);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The summary-line wording of an action: future (Review) and past (Result).
|
||||
*******************************************************************************/
|
||||
static String[] wording(AdminAction action)
|
||||
{
|
||||
if(action == null)
|
||||
{
|
||||
return (new String[] { "approval request will be decided", "approval requests will be decided", "approval request was decided", "approval requests were decided" });
|
||||
}
|
||||
return switch(action)
|
||||
{
|
||||
case CREATE_USER -> w("user will be created", "users will be created", "user was created", "users were created");
|
||||
case INVITE_USER -> w("invitation will be sent", "invitations will be sent", "invitation was sent", "invitations were sent");
|
||||
case EDIT_USER -> w("user will be updated", "users will be updated", "user was updated", "users were updated");
|
||||
case DEACTIVATE_USER -> w("user will be deactivated", "users will be deactivated", "user was deactivated", "users were deactivated");
|
||||
case REACTIVATE_USER -> w("user will be reactivated", "users will be reactivated", "user was reactivated", "users were reactivated");
|
||||
case CANCEL_INVITATION -> w("invitation will be cancelled", "invitations will be cancelled", "invitation was cancelled", "invitations were cancelled");
|
||||
case ADD_MEMBER -> w("membership will be added", "memberships will be added", "membership was added", "memberships were added");
|
||||
case REMOVE_MEMBER -> w("membership will be removed", "memberships will be removed", "membership was removed", "memberships were removed");
|
||||
case CREATE_GROUP -> w("group will be created", "groups will be created", "group was created", "groups were created");
|
||||
case EDIT_GROUP -> w("group will be updated", "groups will be updated", "group was updated", "groups were updated");
|
||||
case EDIT_PERMISSIONS -> w("group's permissions will be updated", "groups' permissions will be updated", "group's permissions were updated", "groups' permissions were updated");
|
||||
case SAVE_POLICY -> w("group's policy will be saved to Authentik", "groups' policies will be saved to Authentik", "group's policy was saved to Authentik", "groups' policies were saved to Authentik");
|
||||
case SEND_RECOVERY_EMAIL -> w("password reset email will be sent", "password reset emails will be sent", "password reset email was sent", "password reset emails were sent");
|
||||
case RESET_MFA -> w("user's MFA will be reset", "users' MFA will be reset", "user's MFA was reset", "users' MFA were reset");
|
||||
case REVOKE_APP_PASSWORDS -> w("user's app passwords will be revoked", "users' app passwords will be revoked", "user's app passwords were revoked", "users' app passwords were revoked");
|
||||
case REVOKE_SESSIONS -> w("user's sessions will be revoked", "users' sessions will be revoked", "user's sessions were revoked", "users' sessions were revoked");
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String[] w(String a, String b, String c, String d)
|
||||
{
|
||||
return (new String[] { a, b, c, d });
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A summary line with future (Review) and past (Result) wording.
|
||||
*******************************************************************************/
|
||||
static ProcessSummaryLine line(Status status, String singularFuture, String pluralFuture, String singularPast, String pluralPast)
|
||||
{
|
||||
ProcessSummaryLine line = new ProcessSummaryLine(status, 0, null);
|
||||
line.setSingularFutureMessage(singularFuture);
|
||||
line.setPluralFutureMessage(pluralFuture);
|
||||
line.setSingularPastMessage(singularPast);
|
||||
line.setPluralPastMessage(pluralPast);
|
||||
return (line);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build the requests a record stands for, from the process's form values.
|
||||
*******************************************************************************/
|
||||
static List<AdminRequest> requests(Def def, RunBackendStepInput input, QRecord record, AuthentikAdmin admin) throws QException
|
||||
{
|
||||
String reason = input.getValueString("reason");
|
||||
List<AdminRequest> rs = new ArrayList<>();
|
||||
switch(def.kind())
|
||||
{
|
||||
case CREATE -> rs.add(withParams(AdminRequest.of(def.action(), "", reason), def, input));
|
||||
case USERS ->
|
||||
{
|
||||
String userPk = String.valueOf(record.getValue("pk"));
|
||||
if(def.action() == AdminAction.ADD_MEMBER || def.action() == AdminAction.REMOVE_MEMBER)
|
||||
{
|
||||
rs.add(withParams(AdminRequest.of(def.action(), input.getValueString("group") + ":" + userPk, reason), def, input));
|
||||
}
|
||||
else
|
||||
{
|
||||
rs.add(withParams(AdminRequest.of(def.action(), userPk, reason), def, input));
|
||||
}
|
||||
}
|
||||
case GROUP_USERNAMES ->
|
||||
{
|
||||
String groupPk = String.valueOf(record.getValue("pk"));
|
||||
for(String username : AuthentikSafety.parseList(input.getValueString("usernames")))
|
||||
{
|
||||
Integer userPk = admin.userPkByUsername(username);
|
||||
AdminRequest request = AdminRequest.of(def.action(), groupPk + ":" + (userPk == null ? "0" : userPk), reason);
|
||||
withParams(request, def, input);
|
||||
request.with("username", username);
|
||||
rs.add(request);
|
||||
}
|
||||
}
|
||||
case GROUPS, INVITATIONS -> rs.add(withParams(AdminRequest.of(def.action(), String.valueOf(record.getValue("pk") != null ? record.getValue("pk") : record.getValue("uuid")), reason), def, input));
|
||||
case POLICIES -> rs.add(withParams(AdminRequest.of(def.action(), record.getValueString("groupPk"), reason), def, input));
|
||||
default ->
|
||||
{
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Copy the details-screen values onto a request.
|
||||
*******************************************************************************/
|
||||
private static AdminRequest withParams(AdminRequest request, Def def, RunBackendStepInput input)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// the policy editor widget writes the document as a process value //
|
||||
// (not a form field), as does an API client //
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
if(def.action() == AdminAction.SAVE_POLICY && input.getValue(AuthentikAdmin.POLICY_DOCUMENT) != null)
|
||||
{
|
||||
request.with(AuthentikAdmin.POLICY_DOCUMENT, input.getValueString(AuthentikAdmin.POLICY_DOCUMENT));
|
||||
}
|
||||
for(QFieldMetaData field : def.fields())
|
||||
{
|
||||
if(field.getName().equals("reason"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Serializable value = input.getValue(field.getName());
|
||||
if(value != null)
|
||||
{
|
||||
request.with(field.getName(), value);
|
||||
}
|
||||
}
|
||||
return (request);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** How many records the run covers: counted from the same filter the extract
|
||||
** step uses (the preview step's count is not carried into later steps).
|
||||
*******************************************************************************/
|
||||
static Integer countTargets(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
if(defFor(input.getProcessName()).kind() == Kind.CREATE)
|
||||
{
|
||||
return (1);
|
||||
}
|
||||
ExtractViaQueryStep extract = new ExtractViaQueryStep();
|
||||
extract.preRun(input, output);
|
||||
return (extract.doCount(input));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The admin for the current backend.
|
||||
*******************************************************************************/
|
||||
static AuthentikAdmin admin(RunBackendStepInput input) throws QException
|
||||
{
|
||||
AuthentikQBitConfig config = CONFIGS_BY_PROCESS.get(input.getProcessName());
|
||||
if(config == null)
|
||||
{
|
||||
throw (new QException("The Authentik qbit is not set up in this instance."));
|
||||
}
|
||||
return (AuthentikAdmin.forBackend(config.getApiBackendName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The details screen is filled from the selected record (edit actions).
|
||||
*******************************************************************************/
|
||||
public static class PrepareStep implements BackendStep
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Fill the form fields and the stale-check fingerprint.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
Def def = defFor(input.getProcessName());
|
||||
if(input.getRecords() == null || input.getRecords().isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
QRecord record = input.getRecords().get(0);
|
||||
AuthentikAdmin admin = admin(input);
|
||||
String pk = def.kind() == Kind.POLICIES ? record.getValueString("groupPk") : String.valueOf(record.getValue("pk"));
|
||||
switch(def.action())
|
||||
{
|
||||
case SAVE_POLICY ->
|
||||
{
|
||||
JSONObject group = admin.getUtil().getApiJsonOrNull("/core/groups/" + AuthentikAdmin.safeKey(pk) + "/?include_users=true&include_parents=true&include_children=true");
|
||||
output.addValue(PolicyEditorWidget.GROUP_PK_PARAM, pk);
|
||||
if(group != null)
|
||||
{
|
||||
output.addValue("expectedFingerprint", AuthentikSafety.groupFingerprint(group));
|
||||
}
|
||||
}
|
||||
case EDIT_USER ->
|
||||
{
|
||||
JSONObject user = admin.getUtil().getObject(AuthentikTables.get(AuthentikTables.USER), pk);
|
||||
if(user != null)
|
||||
{
|
||||
output.addValue("name", user.optString("name"));
|
||||
output.addValue("email", user.optString("email"));
|
||||
output.addValue("path", user.optString("path"));
|
||||
output.addValue("expectedFingerprint", AuthentikSafety.userFingerprint(user));
|
||||
}
|
||||
}
|
||||
case EDIT_GROUP, EDIT_PERMISSIONS ->
|
||||
{
|
||||
JSONObject group = admin.getUtil().getApiJsonOrNull("/core/groups/" + pk + "/?include_users=true&include_parents=true&include_children=true");
|
||||
if(group != null)
|
||||
{
|
||||
output.addValue("expectedFingerprint", AuthentikSafety.groupFingerprint(group));
|
||||
if(def.action() == AdminAction.EDIT_GROUP)
|
||||
{
|
||||
output.addValue("name", group.optString("name"));
|
||||
JSONArray parents = group.optJSONArray("parents_obj");
|
||||
List<String> names = new ArrayList<>();
|
||||
for(int i = 0; parents != null && i < parents.length(); i++)
|
||||
{
|
||||
names.add(parents.getJSONObject(i).optString("name"));
|
||||
}
|
||||
output.addValue("parents", String.join("\n", names));
|
||||
}
|
||||
else
|
||||
{
|
||||
output.addValue("permissions", String.join("\n", AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_PERMISSIONS) == null
|
||||
? List.of() : AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_PERMISSIONS)));
|
||||
output.addValue("appAccess", String.join("\n", AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_APP_ACCESS) == null
|
||||
? List.of() : AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_APP_ACCESS)));
|
||||
}
|
||||
}
|
||||
}
|
||||
default ->
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The extract step of actions that create something: one placeholder record
|
||||
** (the form values carry the data).
|
||||
*******************************************************************************/
|
||||
public static class SingleRecordExtractStep extends AbstractExtractStep
|
||||
{
|
||||
/*******************************************************************************
|
||||
** One record, so the transform and load run once.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
getRecordPipe().addRecord(new QRecord().withValue("pk", "new"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One record.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public Integer doCount(RunBackendStepInput input)
|
||||
{
|
||||
return (1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Review (and the full validation): plan every target against live data.
|
||||
*******************************************************************************/
|
||||
public static class ActionTransformStep extends AbstractTransformStep implements ProcessSummaryProviderInterface
|
||||
{
|
||||
private final Map<String, ProcessSummaryLine> lines = new LinkedHashMap<>();
|
||||
private final List<String> details = new ArrayList<>();
|
||||
private final Map<String, List<String>> targetsByLine = new LinkedHashMap<>();
|
||||
private final List<String> notes = new ArrayList<>();
|
||||
private AuthentikAdmin admin;
|
||||
private Integer totalTargets;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remember how many records the run covers (for the more-than-25 rule).
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void preRun(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
totalTargets = countTargets(input, output);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Plan each record's requests.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
Def def = defFor(input.getProcessName());
|
||||
if(admin == null)
|
||||
{
|
||||
admin = admin(input);
|
||||
}
|
||||
|
||||
for(QRecord record : input.getRecords())
|
||||
{
|
||||
List<AdminRequest> requests = def.kind() == Kind.APPROVALS ? List.of() : requests(def, input, record, admin);
|
||||
if(def.kind() == Kind.APPROVALS)
|
||||
{
|
||||
add(Status.OK, "approval request will be decided", "approval requests will be decided", "approval request was decided", "approval requests were decided", "approve");
|
||||
output.getRecords().add(record);
|
||||
continue;
|
||||
}
|
||||
int total = requests.size();
|
||||
for(AdminRequest request : requests)
|
||||
{
|
||||
AdminPlan plan = admin.plan(request);
|
||||
String problem = bulkProblem(def, request, total, input);
|
||||
if(problem != null && plan.isRunnable())
|
||||
{
|
||||
plan.refuse(problem);
|
||||
}
|
||||
report(def, plan);
|
||||
output.getRecords().add(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** More than 25 targets in one run need the count typed.
|
||||
*******************************************************************************/
|
||||
private String bulkProblem(Def def, AdminRequest request, int total, RunBackendStepInput input)
|
||||
{
|
||||
Integer count = totalTargets;
|
||||
int n = Math.max(total, count == null ? 0 : count);
|
||||
if(n > AuthentikAdmin.TYPED_ABOVE && (def.action() == AdminAction.ADD_MEMBER || def.action() == AdminAction.REMOVE_MEMBER)
|
||||
&& !String.valueOf(n).equals(request.str("confirmText")))
|
||||
{
|
||||
return ("More than " + AuthentikAdmin.TYPED_ABOVE + " people: type " + n + " in the confirmation field.");
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add a plan to the summary.
|
||||
*******************************************************************************/
|
||||
private void report(Def def, AdminPlan plan)
|
||||
{
|
||||
String[] w = wording(def.action());
|
||||
switch(plan.getState())
|
||||
{
|
||||
case READY ->
|
||||
{
|
||||
add(Status.OK, w[0], w[1], w[2], w[3], "ready");
|
||||
name("ready", plan);
|
||||
plan.getNotes().forEach(note ->
|
||||
{
|
||||
if(!notes.contains(note))
|
||||
{
|
||||
notes.add(note);
|
||||
}
|
||||
});
|
||||
}
|
||||
case NEEDS_APPROVAL ->
|
||||
{
|
||||
add(Status.WARNING, "change needs a second person's approval and will be requested", "changes need a second person's approval and will be requested",
|
||||
"change was sent for approval", "changes were sent for approval", "approval");
|
||||
name("approval", plan);
|
||||
}
|
||||
case NO_CHANGE -> add(Status.INFO, "target needs no change: " + plan.getMessage(), "targets need no change: " + plan.getMessage(),
|
||||
"target needed no change: " + plan.getMessage(), "targets needed no change: " + plan.getMessage(), "nochange:" + plan.getMessage());
|
||||
default -> {
|
||||
add(Status.ERROR, "target is refused: " + plan.getMessage(), "targets are refused: " + plan.getMessage(),
|
||||
"target was refused: " + plan.getMessage(), "targets were refused: " + plan.getMessage(), "refused:" + plan.getMessage());
|
||||
name("refused:" + plan.getMessage(), plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void add(Status status, String sf, String pf, String sp, String pp, String key)
|
||||
{
|
||||
lines.computeIfAbsent(key, k -> line(status, sf, pf, sp, pp)).incrementCount();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remember which target a line is about (shown as bullets, first 10).
|
||||
*******************************************************************************/
|
||||
private void name(String key, AdminPlan plan)
|
||||
{
|
||||
List<String> names = targetsByLine.computeIfAbsent(key, k -> new ArrayList<>());
|
||||
if(names.size() < 10)
|
||||
{
|
||||
names.add(plan.getBefore() != null || plan.getAfter() != null ? plan.describe() : (plan.getTargetLabel() == null ? plan.getRequest().targetKey() : plan.getTargetLabel()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Review lines: one per outcome, then the before and after of the first
|
||||
** targets and any notes.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
|
||||
{
|
||||
ArrayList<ProcessSummaryLineInterface> rs = new ArrayList<>();
|
||||
for(Map.Entry<String, ProcessSummaryLine> entry : lines.entrySet())
|
||||
{
|
||||
List<String> names = targetsByLine.get(entry.getKey());
|
||||
if(names != null && !names.isEmpty() && !isForResultScreen)
|
||||
{
|
||||
entry.getValue().setBulletsOfText(new ArrayList<>(names));
|
||||
}
|
||||
entry.getValue().addSelfToListIfAnyCount(rs);
|
||||
}
|
||||
for(String note : notes)
|
||||
{
|
||||
ProcessSummaryLine noteLine = new ProcessSummaryLine(Status.INFO, note);
|
||||
noteLine.setCount(null);
|
||||
rs.add(noteLine);
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Result: execute each target (the rules are checked again against live
|
||||
** data inside), with a line per outcome.
|
||||
*******************************************************************************/
|
||||
public static class ActionLoadStep extends AbstractLoadStep implements ProcessSummaryProviderInterface
|
||||
{
|
||||
private final Map<String, ProcessSummaryLine> lines = new LinkedHashMap<>();
|
||||
private AuthentikAdmin admin;
|
||||
private Integer totalTargets;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remember how many records the run covers (for the more-than-25 rule).
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void preRun(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
totalTargets = countTargets(input, output);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Execute each record's requests.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
Def def = defFor(input.getProcessName());
|
||||
if(admin == null)
|
||||
{
|
||||
admin = admin(input);
|
||||
}
|
||||
String[] w = wording(def.action());
|
||||
|
||||
for(QRecord record : input.getRecords())
|
||||
{
|
||||
if(def.kind() == Kind.APPROVALS)
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = "approve".equals(def.key()) ? admin.approve(record.getValue("id")) : admin.reject(record.getValue("id"));
|
||||
tally(result, w);
|
||||
output.getRecords().add(record);
|
||||
continue;
|
||||
}
|
||||
|
||||
List<AdminRequest> requests = requests(def, input, record, admin);
|
||||
int total = requests.size();
|
||||
for(AdminRequest request : requests)
|
||||
{
|
||||
Integer count = totalTargets;
|
||||
int n = Math.max(total, count == null ? 0 : count);
|
||||
AuthentikAdmin.AdminResult result;
|
||||
if(n > AuthentikAdmin.TYPED_ABOVE && (def.action() == AdminAction.ADD_MEMBER || def.action() == AdminAction.REMOVE_MEMBER)
|
||||
&& !String.valueOf(n).equals(request.str("confirmText")))
|
||||
{
|
||||
result = new AuthentikAdmin.AdminResult(false, false, false, "More than " + AuthentikAdmin.TYPED_ABOVE + " people: type " + n + " in the confirmation field.", null);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = admin.execute(request);
|
||||
}
|
||||
tally(result, w);
|
||||
output.getRecords().add(record);
|
||||
pace(admin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Pace bulk work (Authentik shares its database with the app).
|
||||
*******************************************************************************/
|
||||
private void pace(AuthentikAdmin admin)
|
||||
{
|
||||
Integer millis = admin.getUtil().getRuntime().getConfig().getBulkPacingMillis();
|
||||
if(millis != null && millis > 0)
|
||||
{
|
||||
com.kingsrook.qqq.backend.core.utils.SleepUtils.sleep(millis, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void tally(AuthentikAdmin.AdminResult result, String[] w)
|
||||
{
|
||||
if(result.ok() && result.pending())
|
||||
{
|
||||
lines.computeIfAbsent("pending", k -> line(Status.WARNING, "change needs approval", "changes need approval", "change was sent for approval", "changes were sent for approval")).incrementCount();
|
||||
}
|
||||
else if(result.ok() && result.noChange())
|
||||
{
|
||||
lines.computeIfAbsent("nochange", k -> line(Status.INFO, "target needed no change", "targets needed no change", "target needed no change", "targets needed no change")).incrementCount();
|
||||
}
|
||||
else if(result.ok())
|
||||
{
|
||||
lines.computeIfAbsent("ok", k -> line(Status.OK, w[0], w[1], w[2], w[3])).incrementCount();
|
||||
}
|
||||
else
|
||||
{
|
||||
lines.computeIfAbsent("error:" + result.message(), k -> line(Status.ERROR, "target was not changed: " + result.message(), "targets were not changed: " + result.message(),
|
||||
"target was not changed: " + result.message(), "targets were not changed: " + result.message())).incrementCount();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Result lines.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
|
||||
{
|
||||
ArrayList<ProcessSummaryLineInterface> rs = new ArrayList<>();
|
||||
lines.values().forEach(line -> line.addSelfToListIfAnyCount(rs));
|
||||
return (rs);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,6 +20,7 @@ package com.kingsrook.qbits.authentik.security;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminAction;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikJson;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTableSpec;
|
||||
@@ -107,6 +108,49 @@ public class AuthentikGuard
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Authorize one change to Authentik for the current session: a signed-in
|
||||
** user (never a system session), the action's feature on, not read-only,
|
||||
** and the action's authentik.* permission. The returned authorization is
|
||||
** what AuthentikActionUtil.write requires (DESIGN.md section 5.3).
|
||||
*******************************************************************************/
|
||||
public WriteAuthorization authorize(AdminAction action) throws QPermissionDeniedException
|
||||
{
|
||||
QSession session = QContext.getQSession();
|
||||
if(session instanceof QSystemUserSession)
|
||||
{
|
||||
throw (new QPermissionDeniedException("System sessions may not change Authentik data."));
|
||||
}
|
||||
requireUser(session);
|
||||
if(Boolean.TRUE.equals(config.getReadOnly()))
|
||||
{
|
||||
throw (new QPermissionDeniedException("The Identity screens are in read-only mode."));
|
||||
}
|
||||
if(!config.hasFeature(action.getFeature()))
|
||||
{
|
||||
throw (new QPermissionDeniedException(action.getLabel() + " is not enabled (feature " + action.getFeature() + ")."));
|
||||
}
|
||||
if(!has(session, action.getPermission()))
|
||||
{
|
||||
throw (new QPermissionDeniedException("You do not have permission to do this (" + action.getPermission().getShortName() + ")."));
|
||||
}
|
||||
return (new WriteAuthorization(action.name(), operatorEmail()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The current operator: the session user's id reference (an email in apps
|
||||
** that sign in through Authentik), or null.
|
||||
*******************************************************************************/
|
||||
public String operatorEmail()
|
||||
{
|
||||
QSession session = QContext.getQSession();
|
||||
return (session == null || session.getUser() == null ? null : session.getUser().getIdReference());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the current session may see and filter sensitive fields.
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.security;
|
||||
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Decides whether a person is a bootstrap operator (the lockout escape hatch).
|
||||
** Users can change their own email in Authentik and emails are not unique, so
|
||||
** an email is NEVER enough. Someone is a bootstrap operator only when:
|
||||
** - the token sub is a configured subject (a hashed or opaque id; a sub that
|
||||
** looks like an email is ignored, since Authentik's user_email sub mode makes
|
||||
** it mutable); or
|
||||
** - the email is verified, exactly ONE Authentik user has it, that user is
|
||||
** active, and that user's pk or uuid is a configured subject.
|
||||
** Anything else is denied.
|
||||
*******************************************************************************/
|
||||
public final class BootstrapOperators
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private BootstrapOperators()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether a token (sub, email, email_verified) is a bootstrap operator.
|
||||
**
|
||||
** @param subjects the configured immutable subjects
|
||||
** @param client an Authentik client for the lookup
|
||||
** @param sub the sub claim (may be null)
|
||||
** @param email the email claim (may be null)
|
||||
** @param emailVerified the email_verified claim
|
||||
*******************************************************************************/
|
||||
public static boolean matches(Set<String> subjects, AuthentikActionUtil client, String sub, String email, boolean emailVerified)
|
||||
{
|
||||
if(subjects == null || subjects.isEmpty())
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
if(sub != null && !sub.isBlank() && !sub.contains("@") && subjects.contains(sub.trim()))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
if(!emailVerified || email == null || email.isBlank() || client == null)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
return (matchesUniqueUser(subjects, client, email.trim()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The email-based path without the verified claim (an admin session has no
|
||||
** claims): still requires exactly one active user with that email whose pk
|
||||
** or uuid is a configured subject.
|
||||
*******************************************************************************/
|
||||
public static boolean matchesUniqueUser(Set<String> subjects, AuthentikActionUtil client, String email)
|
||||
{
|
||||
if(subjects == null || subjects.isEmpty())
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
try
|
||||
{
|
||||
JSONObject found = null;
|
||||
int count = 0;
|
||||
for(JSONObject user : client.getAllPages("/core/users/?email=" + URLEncoder.encode(email, StandardCharsets.UTF_8) + "&include_groups=false&include_roles=false", 10))
|
||||
{
|
||||
if(email.equalsIgnoreCase(user.optString("email")))
|
||||
{
|
||||
found = user;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return (count == 1 && found.optBoolean("is_active", true)
|
||||
&& (subjects.contains(String.valueOf(found.optInt("pk"))) || subjects.contains(found.optString("uuid", "-"))));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -38,6 +38,7 @@ public enum IdentityPermission
|
||||
GROUPS_MANAGE("authentik.groups.manage"),
|
||||
MEMBERSHIPS_MANAGE("authentik.memberships.manage"),
|
||||
PERMISSIONS_MANAGE("authentik.permissions.manage"),
|
||||
POLICIES_MANAGE("authentik.policies.manage"),
|
||||
ROLES_MANAGE("authentik.roles.manage"),
|
||||
CREDENTIALS_RESET("authentik.credentials.reset"),
|
||||
SESSIONS_REVOKE("authentik.sessions.revoke"),
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.security;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Proof that {@link AuthentikGuard} authorized one write. AuthentikActionUtil
|
||||
** refuses to send any request that changes Authentik data without one, and the
|
||||
** constructor is package-private, so only the guard can mint it (DESIGN.md
|
||||
** section 5.3: every write path goes through the guard).
|
||||
*******************************************************************************/
|
||||
public final class WriteAuthorization
|
||||
{
|
||||
private final String action;
|
||||
private final String operator;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Constructor (package-private: only AuthentikGuard authorizes).
|
||||
*******************************************************************************/
|
||||
WriteAuthorization(String action, String operator)
|
||||
{
|
||||
this.action = action;
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for action
|
||||
*******************************************************************************/
|
||||
public String getAction()
|
||||
{
|
||||
return (action);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for operator
|
||||
*******************************************************************************/
|
||||
public String getOperator()
|
||||
{
|
||||
return (operator);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -55,6 +55,24 @@ class AuthentikQBitConfigTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void policyNames()
|
||||
{
|
||||
assertThat(AuthentikTestSupport.unitConfig().getPolicyFormat()).isEqualTo(com.kingsrook.qbits.authentik.policy.PolicyFormat.DEFAULT);
|
||||
assertThat(AuthentikTestSupport.unitConfig().getPolicyTwoPersonApproval()).isFalse();
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withPolicySpec("acme-iam").withPolicyVersion("2.0.0").withPolicyAttribute("policies").withPolicyClaim("policies"))).isEmpty();
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withPolicyVersion("1"))).anyMatch(e -> e.contains("policyVersion"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withPolicySpec(""))).anyMatch(e -> e.contains("policySpec"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withPolicyClaim("a b"))).anyMatch(e -> e.contains("policyClaim"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withPolicyAttribute(null))).anyMatch(e -> e.contains("policyAttribute"));
|
||||
assertThat(AuthentikTestSupport.unitConfig().withPolicyTwoPersonApproval(true).getPolicyTwoPersonApproval()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@@ -89,11 +107,11 @@ class AuthentikQBitConfigTest
|
||||
@Test
|
||||
void unavailableFeaturesAndDependencies()
|
||||
{
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MEMBERSHIP))))
|
||||
.anyMatch(e -> e.contains("MEMBERSHIP is not available"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.MIRROR)))).anyMatch(e -> e.contains("READ is required"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MIRROR)))).anyMatch(e -> e.contains("mirrorBackendName"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MIRROR)).withMirrorBackendName("nope")))
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.RBAC))))
|
||||
.anyMatch(e -> e.contains("RBAC is not available"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.RBAC)))).anyMatch(e -> e.contains("READ is required"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MEMBERSHIP)))).anyMatch(e -> e.contains("localBackendName"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MEMBERSHIP)).withLocalBackendName("nope")))
|
||||
.anyMatch(e -> e.contains("backend not found"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS)))).anyMatch(e -> e.contains("recoveryEmailStage"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.WEBHOOK)).withWebhookSecret(null))).anyMatch(e -> e.contains("webhookSecret"));
|
||||
@@ -151,7 +169,19 @@ class AuthentikQBitConfigTest
|
||||
assertThat(new AuthentikQBitConfig().withTableNamePrefix("").applyTablePrefix("user")).isEqualTo("user");
|
||||
assertThat(new AuthentikQBitConfig().withTableNamePrefix("").applyTablePrefix("groupMember")).isEqualTo("group_member");
|
||||
assertThat(new AuthentikQBitConfig().withTableNamePrefix("myAuth").applyTablePrefix("groupMember")).isEqualTo("my_auth_group_member");
|
||||
assertThat(config.withBootstrapOperators(" A@x.test, ,b@x.test ").getResolvedBootstrapOperators()).containsExactly("a@x.test", "b@x.test");
|
||||
assertThat(config.withBootstrapOperatorSubjects(" A1, ,b2 ").getResolvedBootstrapSubjects()).containsExactly("A1", "b2");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Emails are refused as bootstrap subjects: users can change their own.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void bootstrapSubjectsRejectEmails()
|
||||
{
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withBootstrapOperatorSubjects("owner@example.test"))).anyMatch(e -> e.contains("never emails"));
|
||||
assertThat(errors(AuthentikTestSupport.unitConfig().withBootstrapOperatorSubjects("42"))).noneMatch(e -> e.contains("never emails"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -65,8 +65,9 @@ class AuthentikQBitProducerTest
|
||||
|
||||
QAppMetaData app = qInstance.getApp("authentikAdmin");
|
||||
assertThat(app.getLabel()).isEqualTo("Identity");
|
||||
assertThat(app.getChildren()).extracting(c -> c.getName()).containsExactly("authentik_user", "authentik_group", "authentik_group_member", "authentik_session", "authentik_event");
|
||||
assertThat(app.getWidgets()).containsExactly("authentikDriftReport");
|
||||
assertThat(app.getChildren()).extracting(c -> c.getName()).containsExactly("authentik_user", "authentik_group", "authentik_application");
|
||||
assertThat(app.getWidgets()).containsExactly("authentikHome", "authentikDriftReport");
|
||||
assertThat(qInstance.getTable("authentik_group_member")).isNotNull();
|
||||
assertThat(qInstance.getTable("authentik_session").getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.audit.read");
|
||||
assertThat(qInstance.getWidget("authentikDriftReport").getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.admin");
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitProducer;
|
||||
import com.kingsrook.qbits.authentik.AuthentikTestSupport;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.client.FixtureActionUtil;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QUser;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A QInstance with the qbit (all write features, audit on a memory backend),
|
||||
** two host tables whose permissions operators can grant, and a FakeAuthentik
|
||||
** pre-loaded with a small realistic directory:
|
||||
**
|
||||
** <pre>
|
||||
** identity-admins authentik.* app kof22-website-prod
|
||||
** kof-website-publishers cms.publish.hasAccess app kof22-website-prod
|
||||
** kof-website-analysts kof22.analytics.hasAccess
|
||||
** authentik Admins (superuser group)
|
||||
**
|
||||
** operator (1) identity-admins, kof-website-publishers operator@example.test
|
||||
** second (2) identity-admins
|
||||
** sam (3) -
|
||||
** breakglass (4) authentik Admins (superuser, protected)
|
||||
** qqq-kof22-admin-idadmin (5) the qbit's service account
|
||||
** svc-publisher (6) service account
|
||||
** dormant (7) inactive
|
||||
** </pre>
|
||||
*******************************************************************************/
|
||||
public final class AdminTestSupport
|
||||
{
|
||||
public static final String LOCAL = "memory";
|
||||
|
||||
public QInstance qInstance;
|
||||
public AuthentikQBitConfig config;
|
||||
public FakeAuthentik authentik;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build everything and log in as the operator with every authentik.* permission.
|
||||
*******************************************************************************/
|
||||
public static AdminTestSupport create() throws QException
|
||||
{
|
||||
return (create(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build with chosen features.
|
||||
*******************************************************************************/
|
||||
public static AdminTestSupport create(Set<AuthentikFeature> features) throws QException
|
||||
{
|
||||
AdminTestSupport support = new AdminTestSupport();
|
||||
MemoryRecordStore.getInstance().reset();
|
||||
|
||||
support.authentik = new FakeAuthentik();
|
||||
support.authentik
|
||||
.group("identity-admins", false, List.of("authentik.*"), List.of("kof22-website-prod"))
|
||||
.group("kof-website-publishers", false, List.of("cms.publish.hasAccess"), List.of("kof22-website-prod"))
|
||||
.group("kof-website-analysts", false, List.of("kof22.analytics.hasAccess"), List.of())
|
||||
.group("authentik Admins", true, List.of(), List.of())
|
||||
.user(1, "operator", AuthentikTestSupport.OPERATOR, "internal", true, "identity-admins", "kof-website-publishers")
|
||||
.user(2, "second", "second@example.test", "internal", true, "identity-admins")
|
||||
.user(3, "sam", "sam@example.test", "internal", true)
|
||||
.user(4, "breakglass", "breakglass@example.test", "internal", true, "authentik Admins")
|
||||
.user(5, "qqq-kof22-admin-idadmin", "", "service_account", true)
|
||||
.user(6, "svc-publisher", "", "service_account", true)
|
||||
.user(7, "dormant", "dormant@example.test", "internal", false)
|
||||
.install();
|
||||
|
||||
support.config = AuthentikTestSupport.unitConfig()
|
||||
.withFeatures(features)
|
||||
.withLocalBackendName(LOCAL)
|
||||
.withRecoveryEmailStage("kof22-recovery-email")
|
||||
.withInvitationFlow("kof22-enrollment")
|
||||
.withBulkPacingMillis(0);
|
||||
|
||||
QInstance instance = new QInstance();
|
||||
instance.withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK));
|
||||
instance.addBackend(new QBackendMetaData().withName(LOCAL).withBackendType(MemoryBackendModule.class));
|
||||
for(String[] table : new String[][] { { "post", "cms.publish" }, { "analytics", "kof22.analytics" } })
|
||||
{
|
||||
instance.addTable(new QTableMetaData().withName(table[0]).withBackendName(LOCAL).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION).withPermissionBaseName(table[1])));
|
||||
}
|
||||
if(features.contains(AuthentikFeature.POLICIES))
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////
|
||||
// things a policy can grant: an app with a table (insert, edit, //
|
||||
// delete, read) and a hidden record action on it //
|
||||
//////////////////////////////////////////////////////////////////
|
||||
QTableMetaData page = new QTableMetaData().withName("cms_page").withLabel("Pages").withBackendName(LOCAL).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS));
|
||||
instance.addTable(page);
|
||||
instance.addProcess(new QProcessMetaData().withName("publishPage").withLabel("Publish Page").withTableName("cms_page").withIsHidden(true)
|
||||
.withStep(new QBackendStepMetaData().withName("run").withCode(new QCodeReference(NoopStep.class)))
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addApp(new QAppMetaData().withName("content").withLabel("Content").withChild(page)
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
}
|
||||
new AuthentikQBitProducer().withQBitConfig(support.config).produce(instance);
|
||||
AuthentikTestSupport.useActionUtil(instance, support.config, FixtureActionUtil.class);
|
||||
support.qInstance = instance;
|
||||
|
||||
support.loginAs(AuthentikTestSupport.OPERATOR, IdentityPermission.values());
|
||||
return (support);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Log in as a user with the given authentik.* permissions.
|
||||
*******************************************************************************/
|
||||
public QSession loginAs(String email, IdentityPermission... permissions)
|
||||
{
|
||||
Set<String> names = new HashSet<>();
|
||||
for(IdentityPermission permission : permissions)
|
||||
{
|
||||
names.add(permission.getSessionPermission());
|
||||
}
|
||||
QSession session = new QSession();
|
||||
session.setUser(new QUser().withIdReference(email).withFullName(email));
|
||||
session.setPermissions(names);
|
||||
QContext.init(qInstance, session);
|
||||
return (session);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An admin service for the qbit's backend.
|
||||
*******************************************************************************/
|
||||
public AuthentikAdmin admin() throws QException
|
||||
{
|
||||
return (new AuthentikAdmin(AuthentikActionUtil.forBackend(config.getApiBackendName())));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The writes sent to Authentik so far, as "METHOD path".
|
||||
*******************************************************************************/
|
||||
public List<String> writes()
|
||||
{
|
||||
return (authentik.writes);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The writes other than the audit event.
|
||||
*******************************************************************************/
|
||||
public List<String> changes()
|
||||
{
|
||||
return (authentik.writes.stream().filter(w -> !w.contains("/events/events/")).toList());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A backend step that does nothing (for fixture processes).
|
||||
*******************************************************************************/
|
||||
public static class NoopStep implements BackendStep
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output)
|
||||
{
|
||||
///////////////////////////
|
||||
// nothing; fixture only //
|
||||
///////////////////////////
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikTestSupport;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The guard rules of DESIGN.md section 5.4 and the actions of section 6.3,
|
||||
** exercised against an in-memory Authentik (FakeAuthentik). Each rule is tested
|
||||
** both ways: it refuses what it must, and it allows what it should, and a
|
||||
** refusal never reaches Authentik.
|
||||
*******************************************************************************/
|
||||
class AuthentikAdminTest
|
||||
{
|
||||
private AdminTestSupport t;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws QException
|
||||
{
|
||||
t = AdminTestSupport.create();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AuthentikAdmin.AdminResult run(AdminRequest request) throws QException
|
||||
{
|
||||
return (t.admin().execute(request));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AdminRequest add(int userPk, String group)
|
||||
{
|
||||
return (AdminRequest.of(AdminAction.ADD_MEMBER, t.authentik.pk(group) + ":" + userPk, "because"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private List<QRecord> rows(String table) throws QException
|
||||
{
|
||||
QueryInput input = new QueryInput();
|
||||
input.setTableName(t.config.applyTablePrefix(table));
|
||||
return (new QueryAction().execute(input).getRecords());
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// memberships and the subset (no escalation) rule
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Adding to a group whose permissions the operator holds works, is audited
|
||||
** before the call, and posts an event naming the human operator.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void addMemberHeldPermissions() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-website-publishers"));
|
||||
|
||||
assertThat(result.ok()).isTrue();
|
||||
assertThat(t.authentik.groupNamesOf(3)).containsExactly("kof-website-publishers");
|
||||
assertThat(t.changes()).containsExactly("POST /core/groups/" + t.authentik.pk("kof-website-publishers") + "/add_user/");
|
||||
assertThat(t.authentik.events).hasSize(1);
|
||||
assertThat(t.authentik.events.get(0).getString("action")).isEqualTo("custom_qqq_admin_action");
|
||||
assertThat(t.authentik.events.get(0).getJSONObject("context").getString("operator")).isEqualTo(AuthentikTestSupport.OPERATOR);
|
||||
assertThat(t.authentik.events.get(0).getJSONObject("context").getString("reason")).isEqualTo("because");
|
||||
|
||||
List<QRecord> audit = rows(AuthentikLocalTables.ADMIN_ACTION);
|
||||
assertThat(audit).hasSize(1);
|
||||
assertThat(audit.get(0).getValueString("status")).isEqualTo("SUCCEEDED");
|
||||
assertThat(audit.get(0).getValueString("actionName")).isEqualTo("ADD_MEMBER");
|
||||
assertThat(audit.get(0).getValueString("operator")).isEqualTo(AuthentikTestSupport.OPERATOR);
|
||||
assertThat(audit.get(0).getValueString("targetLabel")).contains("sam");
|
||||
assertThat(audit.get(0).getValueString("authentikEventPk")).isNotBlank();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The subset rule: an operator cannot hand out permissions they do not hold.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void addMemberRefusedWhenGroupGrantsWhatOperatorLacks() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-website-analysts"));
|
||||
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("kof22.analytics.hasAccess");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
assertThat(rows(AuthentikLocalTables.ADMIN_ACTION).get(0).getValueString("status")).isEqualTo("REFUSED");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Adding to a group that gives sign-in to an app the operator cannot open is
|
||||
** refused too (app-access subset).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void addMemberRefusedWhenGroupGrantsAppAccessOperatorLacks() throws QException
|
||||
{
|
||||
t.authentik.group("kof-secret-app", false, List.of(), List.of("secret-app"));
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-secret-app"));
|
||||
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("secret-app");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The subset rule uses the operator's LIVE groups, not the session claim:
|
||||
** an operator whose session says authentik.* but who was removed from the
|
||||
** groups in Authentik holds nothing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void subsetRuleUsesLiveGroupsNotTheSession() throws QException
|
||||
{
|
||||
t.authentik.groupByName("kof-website-publishers").put("users", new JSONArray());
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-website-publishers"));
|
||||
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("cms.publish.hasAccess");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Superuser groups cannot be managed (adding to one would make a superuser).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void superuserGroupsAreProtected() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "authentik Admins"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).containsIgnoringCase("superuser");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
|
||||
t.authentik.group("kof-under-superuser", false, List.of(), List.of(), "authentik Admins");
|
||||
AuthentikAdmin.AdminResult descendant = run(add(3, "kof-under-superuser"));
|
||||
assertThat(descendant.ok()).isFalse();
|
||||
assertThat(descendant.message()).containsIgnoringCase("superuser");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Protected accounts and self-edits are refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void protectedAccountsAndSelfEditsAreRefused() throws QException
|
||||
{
|
||||
for(int pk : new int[] { 4, 5, 1 })
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(add(pk, "kof-website-publishers"));
|
||||
assertThat(result.ok()).as("user " + pk).isFalse();
|
||||
}
|
||||
assertThat(run(add(4, "kof-website-publishers")).message()).containsIgnoringCase("protected");
|
||||
assertThat(run(add(1, "kof-website-publishers")).message()).contains("your own account");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Service accounts are listed but can only be deactivated or have app
|
||||
** passwords revoked.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void serviceAccountsOnlyDeactivateAndRevoke() throws QException
|
||||
{
|
||||
assertThat(run(add(6, "kof-website-publishers")).message()).contains("Service accounts can only");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "6", "because").with("name", "x")).message()).contains("Service accounts can only");
|
||||
|
||||
AuthentikAdmin.AdminResult deactivate = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "6", "because").with("confirmText", "svc-publisher"));
|
||||
assertThat(deactivate.ok()).isTrue();
|
||||
assertThat(t.authentik.users.get(6).getBoolean("is_active")).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Removing a member works and is audited.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void removeMember() throws QException
|
||||
{
|
||||
t.authentik.groupByName("kof-website-publishers").getJSONArray("users").put(3);
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.REMOVE_MEMBER, t.authentik.pk("kof-website-publishers") + ":3", "because"));
|
||||
|
||||
assertThat(result.ok()).isTrue();
|
||||
assertThat(t.authentik.groupNamesOf(3)).isEmpty();
|
||||
assertThat(t.changes()).containsExactly("POST /core/groups/" + t.authentik.pk("kof-website-publishers") + "/remove_user/");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Removing someone who is not a member, or adding a member again, is a no-op
|
||||
** that sends nothing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void alreadyDoneIsNoChange() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult notMember = run(AdminRequest.of(AdminAction.REMOVE_MEMBER, t.authentik.pk("kof-website-publishers") + ":3", "because"));
|
||||
assertThat(notMember.ok()).isTrue();
|
||||
assertThat(notMember.noChange()).isTrue();
|
||||
|
||||
AuthentikAdmin.AdminResult again = run(add(2, "identity-admins"));
|
||||
assertThat(again.noChange()).isTrue();
|
||||
assertThat(t.writes()).isEmpty();
|
||||
assertThat(rows(AuthentikLocalTables.ADMIN_ACTION)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// last-admin protection
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The last person who can manage memberships and permissions cannot be
|
||||
** removed; with a second administrator the same change is allowed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void lastAdminCannotBeRemoved() throws QException
|
||||
{
|
||||
// acting person: holds the session permissions but is not an administrator in Authentik
|
||||
t.loginAs("sam@example.test", IdentityPermission.MEMBERSHIPS_MANAGE);
|
||||
|
||||
AuthentikAdmin.AdminResult allowed = run(AdminRequest.of(AdminAction.REMOVE_MEMBER, t.authentik.pk("identity-admins") + ":2", "because"));
|
||||
assertThat(allowed.ok()).as(allowed.message()).isTrue();
|
||||
|
||||
AuthentikAdmin.AdminResult refused = run(AdminRequest.of(AdminAction.REMOVE_MEMBER, t.authentik.pk("identity-admins") + ":1", "because"));
|
||||
assertThat(refused.ok()).isFalse();
|
||||
assertThat(refused.message()).contains("last person");
|
||||
assertThat(t.authentik.groupNamesOf(1)).contains("identity-admins");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Deactivating the last administrator is refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void lastAdminCannotBeDeactivated() throws QException
|
||||
{
|
||||
t.authentik.groupByName("identity-admins").put("users", new JSONArray(List.of(1)));
|
||||
t.loginAs("sam@example.test", IdentityPermission.USERS_MANAGE);
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "1", "because").with("confirmText", "operator"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("last active person");
|
||||
assertThat(t.authentik.users.get(1).getBoolean("is_active")).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Removing the permissions from the only administrator group is refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void lastAdminCannotLosePermissionsByGroupEdit() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("identity-admins"), "because")
|
||||
.with("permissions", "").with("appAccess", "kof22-website-prod"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("nobody able to manage");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// permissions and app access
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Adding a permission the operator holds works, and the write merges only the
|
||||
** two qqq.io keys into the group's CURRENT attributes (other attributes and
|
||||
** edits made in the Authentik UI survive).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editPermissionsMergesIntoCurrentAttributes() throws QException
|
||||
{
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("note", "set in the Authentik UI");
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with("permissions", "kof22.analytics.hasAccess\ncms.publish.hasAccess").with("appAccess", ""));
|
||||
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject attributes = t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes");
|
||||
assertThat(attributes.getString("note")).isEqualTo("set in the Authentik UI");
|
||||
assertThat(attributes.getJSONArray("qqq.io/permissions").toList()).containsExactly("kof22.analytics.hasAccess", "cms.publish.hasAccess");
|
||||
assertThat(attributes.has("qqq.io/app-access")).isFalse();
|
||||
assertThat(t.changes()).containsExactly("PATCH /core/groups/" + t.authentik.pk("kof-website-analysts") + "/");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A permission the operator does not hold cannot be granted; removing one
|
||||
** needs no subset; unknown names are rejected.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editPermissionsSubsetAndUnknownNames() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult escalation = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-publishers"), "because")
|
||||
.with("permissions", "cms.publish.hasAccess\nkof22.analytics.hasAccess").with("appAccess", "kof22-website-prod"));
|
||||
assertThat(escalation.ok()).isFalse();
|
||||
assertThat(escalation.message()).contains("kof22.analytics.hasAccess");
|
||||
|
||||
AuthentikAdmin.AdminResult unknown = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-publishers"), "because")
|
||||
.with("permissions", "cms.publish.hasAccess\nnot.a.real.permission").with("appAccess", "kof22-website-prod"));
|
||||
assertThat(unknown.ok()).isFalse();
|
||||
assertThat(unknown.message()).contains("Unknown permission");
|
||||
|
||||
AuthentikAdmin.AdminResult removal = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with("permissions", "").with("appAccess", ""));
|
||||
assertThat(removal.ok()).isTrue();
|
||||
assertThat(t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").has("qqq.io/permissions")).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** App access: an operator can only give sign-in to apps they can open.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editAppAccessSubset() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with("permissions", "kof22.analytics.hasAccess").with("appAccess", "secret-app"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("secret-app");
|
||||
|
||||
AuthentikAdmin.AdminResult allowed = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with("permissions", "kof22.analytics.hasAccess").with("appAccess", "kof22-website-prod"));
|
||||
assertThat(allowed.ok()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A change made in the Authentik UI after the form was opened is not
|
||||
** overwritten (stale check by fingerprint).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void staleGroupIsRefused() throws QException
|
||||
{
|
||||
String fingerprint = AuthentikSafety.groupFingerprint(t.authentik.groupByName("kof-website-analysts"));
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("qqq.io/permissions", new JSONArray(List.of("kof22.analytics.hasAccess", "cms.publish.hasAccess")));
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with("permissions", "cms.publish.hasAccess").with("appAccess", "").with("expectedFingerprint", fingerprint));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("changed");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// two-person approval
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Granting authentik.* is queued for a second person: nothing is sent to
|
||||
** Authentik, the request is stored, and the same person cannot approve it. A
|
||||
** different person who holds authentik.approve applies it, and the change is
|
||||
** planned again under their own permissions.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void grantingIdentityPermissionsNeedsASecondPerson() throws QException
|
||||
{
|
||||
AdminRequest request = AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-publishers"), "give them user read")
|
||||
.with("permissions", "cms.publish.hasAccess\nauthentik.users.read").with("appAccess", "kof22-website-prod");
|
||||
AuthentikAdmin.AdminResult queued = run(request);
|
||||
|
||||
assertThat(queued.ok()).isTrue();
|
||||
assertThat(queued.pending()).isTrue();
|
||||
assertThat(t.writes()).isEmpty();
|
||||
List<QRecord> approvals = rows(AuthentikLocalTables.APPROVAL_REQUEST);
|
||||
assertThat(approvals).hasSize(1);
|
||||
assertThat(approvals.get(0).getValueString("status")).isEqualTo("PENDING");
|
||||
assertThat(approvals.get(0).getValueString("requester")).isEqualTo(AuthentikTestSupport.OPERATOR);
|
||||
assertThat(rows(AuthentikLocalTables.ADMIN_ACTION).get(0).getValueString("status")).isEqualTo("PENDING_APPROVAL");
|
||||
|
||||
java.io.Serializable id = approvals.get(0).getValue("id");
|
||||
AuthentikAdmin.AdminResult self = t.admin().approve(id);
|
||||
assertThat(self.ok()).isFalse();
|
||||
assertThat(self.message()).contains("cannot approve your own");
|
||||
|
||||
t.loginAs("second@example.test", IdentityPermission.APPROVE, IdentityPermission.PERMISSIONS_MANAGE);
|
||||
AuthentikAdmin.AdminResult approved = t.admin().approve(id);
|
||||
assertThat(approved.ok()).as(approved.message()).isTrue();
|
||||
assertThat(t.authentik.groupByName("kof-website-publishers").getJSONObject("attributes").getJSONArray("qqq.io/permissions").toList())
|
||||
.containsExactly("cms.publish.hasAccess", "authentik.users.read");
|
||||
assertThat(rows(AuthentikLocalTables.APPROVAL_REQUEST).get(0).getValueString("status")).isEqualTo("APPROVED");
|
||||
assertThat(rows(AuthentikLocalTables.APPROVAL_REQUEST).get(0).getValueString("approver")).isEqualTo("second@example.test");
|
||||
|
||||
AuthentikAdmin.AdminResult twice = t.admin().approve(id);
|
||||
assertThat(twice.ok()).isFalse();
|
||||
assertThat(twice.message()).contains("already decided");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Rejecting stores the decision and changes nothing in Authentik; deciding
|
||||
** needs authentik.approve.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void rejectAndApproverPermission() throws QException
|
||||
{
|
||||
run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-publishers"), "r")
|
||||
.with("permissions", "cms.publish.hasAccess\nauthentik.users.read").with("appAccess", "kof22-website-prod"));
|
||||
java.io.Serializable id = rows(AuthentikLocalTables.APPROVAL_REQUEST).get(0).getValue("id");
|
||||
|
||||
t.loginAs("second@example.test", IdentityPermission.PERMISSIONS_MANAGE);
|
||||
assertThat(t.admin().reject(id).message()).contains("authentik.approve");
|
||||
|
||||
t.loginAs("second@example.test", IdentityPermission.APPROVE);
|
||||
assertThat(t.admin().reject(id).ok()).isTrue();
|
||||
assertThat(rows(AuthentikLocalTables.APPROVAL_REQUEST).get(0).getValueString("status")).isEqualTo("REJECTED");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** With two-person approval off, authentik.* grants apply at once.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void approvalCanBeTurnedOff() throws QException
|
||||
{
|
||||
t.config.withTwoPersonApproval(false);
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-publishers"), "because")
|
||||
.with("permissions", "cms.publish.hasAccess\nauthentik.users.read").with("appAccess", "kof22-website-prod"));
|
||||
assertThat(result.ok()).isTrue();
|
||||
assertThat(result.pending()).isFalse();
|
||||
assertThat(t.changes()).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// groups
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Create a group with a parent, permissions and app access.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createGroup() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "because").with("name", "kof-editors")
|
||||
.with("parents", "kof-website-publishers").with("permissions", "cms.publish.hasAccess").with("appAccess", "kof22-website-prod"));
|
||||
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject group = t.authentik.groupByName("kof-editors");
|
||||
assertThat(group.getJSONArray("parents").getString(0)).isEqualTo(t.authentik.pk("kof-website-publishers"));
|
||||
assertThat(group.getBoolean("is_superuser")).isFalse();
|
||||
assertThat(group.getJSONObject("attributes").getJSONArray("qqq.io/permissions").toList()).containsExactly("cms.publish.hasAccess");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Group creation rules: unique names, no superuser parents, the subset rule
|
||||
** for parents and permissions.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createGroupRules() throws QException
|
||||
{
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "b").with("name", "identity-admins")).message()).contains("already exists");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "b").with("name", "x").with("parents", "authentik Admins")).message()).containsIgnoringCase("superuser");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "b").with("name", "x").with("parents", "kof-website-analysts")).message()).contains("kof22.analytics.hasAccess");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "b").with("name", "x").with("permissions", "kof22.analytics.hasAccess")).message()).contains("do not hold");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "b").with("name", "x").with("parents", "nope")).message()).contains("No parent group");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Re-parenting: loops and superuser parents are refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editGroupParents() throws QException
|
||||
{
|
||||
t.authentik.group("kof-child", false, List.of(), List.of(), "kof-website-publishers");
|
||||
|
||||
AuthentikAdmin.AdminResult loop = run(AdminRequest.of(AdminAction.EDIT_GROUP, t.authentik.pk("kof-website-publishers"), "b").with("parents", "kof-child"));
|
||||
assertThat(loop.message()).contains("loop");
|
||||
|
||||
AuthentikAdmin.AdminResult superuser = run(AdminRequest.of(AdminAction.EDIT_GROUP, t.authentik.pk("kof-child"), "b").with("parents", "authentik Admins"));
|
||||
assertThat(superuser.message()).containsIgnoringCase("superuser");
|
||||
|
||||
String childPk = t.authentik.pk("kof-child");
|
||||
AuthentikAdmin.AdminResult rename = run(AdminRequest.of(AdminAction.EDIT_GROUP, childPk, "b").with("name", "kof-grandchild"));
|
||||
assertThat(rename.ok()).as(rename.message()).isTrue();
|
||||
assertThat(t.authentik.groups.get(childPk).getString("name")).isEqualTo("kof-grandchild");
|
||||
|
||||
AuthentikAdmin.AdminResult superuserGroup = run(AdminRequest.of(AdminAction.EDIT_GROUP, t.authentik.pk("authentik Admins"), "b").with("name", "renamed"));
|
||||
assertThat(superuserGroup.message()).containsIgnoringCase("superuser");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// users
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Create a user: no password is sent, memberships are added, and
|
||||
** Authentik emails the recovery link (QQQ never sees it).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createUserNeverSetsAPassword() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.CREATE_USER, "", "new hire").with("username", "newbie").with("name", "New Bie")
|
||||
.with("email", "newbie@example.test").with("groups", "kof-website-publishers"));
|
||||
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(t.changes()).hasSize(3);
|
||||
assertThat(t.changes().get(0)).isEqualTo("POST /core/users/");
|
||||
assertThat(t.changes().get(1)).endsWith("/add_user/");
|
||||
assertThat(t.changes().get(2)).isEqualTo("POST /core/users/100/recovery_email/");
|
||||
|
||||
JSONObject createBody = t.authentik.writeBodies.get(0);
|
||||
assertThat(createBody.keySet()).doesNotContain("password", "password_hash");
|
||||
assertThat(createBody.getString("username")).isEqualTo("newbie");
|
||||
assertThat(createBody.getBoolean("is_active")).isTrue();
|
||||
assertThat(createBody.getJSONObject("attributes").getString("qqq.io/created-by")).isEqualTo(AuthentikTestSupport.OPERATOR);
|
||||
JSONObject recovery = t.authentik.writeBodies.get(2);
|
||||
assertThat(recovery.getString("email_stage")).isEqualTo("11111111-1111-1111-1111-111111111111");
|
||||
assertThat(t.authentik.groupNamesOf(100)).containsExactly("kof-website-publishers");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Create-user checks.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createUserRules() throws QException
|
||||
{
|
||||
AdminRequest base = AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "newbie").with("name", "New Bie").with("email", "newbie@example.test");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "sam").with("name", "n").with("email", "x@example.test")).message()).contains("already exists");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "x").with("name", "n").with("email", "sam@example.test")).message()).contains("email");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "x").with("name", "n").with("email", "not-an-email")).message()).contains("valid email");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "bad name!").with("name", "n").with("email", "a@example.test")).message()).contains("username");
|
||||
assertThat(run(base.with("groups", "kof-website-analysts")).message()).contains("do not hold");
|
||||
assertThat(run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "x").with("name", "n").with("email", "a@example.test").with("groups", "nope")).message()).contains("No group");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** If a step after the user exists fails, the message says the user was
|
||||
** created and what to do next.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createUserPartialFailureIsExplained() throws QException
|
||||
{
|
||||
com.kingsrook.qbits.authentik.client.FixtureActionUtil.handler = request ->
|
||||
{
|
||||
if(request.getURI().getPath().endsWith("/recovery_email/"))
|
||||
{
|
||||
return (com.kingsrook.qbits.authentik.client.FixtureActionUtil.response(500, "{\"detail\":\"boom\"}"));
|
||||
}
|
||||
return (t.authentik.handle(request));
|
||||
};
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.CREATE_USER, "", "b").with("username", "newbie").with("name", "New Bie").with("email", "newbie@example.test"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("was created").contains("Send password reset email");
|
||||
assertThat(rows(AuthentikLocalTables.ADMIN_ACTION).get(0).getValueString("status")).isEqualTo("FAILED");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Invite a user: an invitation with the email, and its email.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void inviteAndCancel() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.INVITE_USER, "", "b").with("email", "guest@example.test"));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(t.changes().get(0)).isEqualTo("POST /stages/invitation/invitations/");
|
||||
assertThat(t.changes().get(1)).endsWith("/send_email/");
|
||||
JSONObject invitation = t.authentik.writeBodies.get(0);
|
||||
assertThat(invitation.getBoolean("single_use")).isTrue();
|
||||
assertThat(invitation.getJSONObject("fixed_data").getString("email")).isEqualTo("guest@example.test");
|
||||
assertThat(t.authentik.writeBodies.get(1).getJSONArray("email_addresses").getString(0)).isEqualTo("guest@example.test");
|
||||
|
||||
String pk = t.authentik.invitations.keySet().iterator().next();
|
||||
assertThat(run(AdminRequest.of(AdminAction.CANCEL_INVITATION, pk, "b")).ok()).isTrue();
|
||||
assertThat(t.authentik.invitations).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Deactivation is typed-confirmed, protected accounts are untouchable, and
|
||||
** app passwords are revoked only when asked (and never API tokens).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void deactivateAndReactivate() throws QException
|
||||
{
|
||||
t.authentik.tokens.put("sam", new java.util.ArrayList<>(List.of(
|
||||
new JSONObject().put("identifier", "sam-app").put("intent", "app_password"),
|
||||
new JSONObject().put("identifier", "sam-api").put("intent", "api"))));
|
||||
|
||||
AuthentikAdmin.AdminResult untyped = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "3", "b"));
|
||||
assertThat(untyped.ok()).isFalse();
|
||||
assertThat(untyped.message()).contains("Type the username");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "3", "b").with("confirmText", "sam").with("revokeAppPasswords", true));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(t.authentik.users.get(3).getBoolean("is_active")).isFalse();
|
||||
assertThat(t.changes()).containsExactly("PATCH /core/users/3/", "DELETE /core/tokens/sam-app/");
|
||||
assertThat(t.authentik.tokens.get("sam")).extracting(j -> j.getString("identifier")).containsExactly("sam-api");
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "3", "b").with("confirmText", "sam")).noChange()).isTrue();
|
||||
assertThat(run(AdminRequest.of(AdminAction.REACTIVATE_USER, "3", "b")).ok()).isTrue();
|
||||
assertThat(t.authentik.users.get(3).getBoolean("is_active")).isTrue();
|
||||
assertThat(run(AdminRequest.of(AdminAction.DEACTIVATE_USER, "4", "b").with("confirmText", "breakglass")).message()).containsIgnoringCase("protected");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Edit a user: only changed fields are sent; a stale form is refused;
|
||||
** invalid input is refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editUser() throws QException
|
||||
{
|
||||
String fingerprint = AuthentikSafety.userFingerprint(t.authentik.users.get(3));
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_USER, "3", "b").with("name", "Samuel").with("email", "sam@example.test")
|
||||
.with("path", "users").with("expectedFingerprint", fingerprint));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(t.authentik.users.get(3).getString("name")).isEqualTo("Samuel");
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "b").with("name", "Again").with("expectedFingerprint", fingerprint)).message()).contains("was changed");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "b").with("email", "second@example.test")).message()).contains("Another user");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "b").with("name", "")).message()).contains("name cannot be empty");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "b")).noChange()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// credentials and sessions
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Password reset is Authentik's own email; MFA reset deletes every device
|
||||
** (typed confirmation); app passwords only; sessions via bulk delete.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void credentialActions() throws QException
|
||||
{
|
||||
assertThat(run(AdminRequest.of(AdminAction.SEND_RECOVERY_EMAIL, "3", "b")).ok()).isTrue();
|
||||
assertThat(t.changes().get(0)).isEqualTo("POST /core/users/3/recovery_email/");
|
||||
|
||||
t.authentik.devices.put(3, new java.util.ArrayList<>(List.of(
|
||||
new JSONObject().put("pk", "11").put("type", "authentik_stages_authenticator_totp.totpdevice"),
|
||||
new JSONObject().put("pk", "12").put("type", "authentik_stages_authenticator_webauthn.webauthndevice"))));
|
||||
assertThat(run(AdminRequest.of(AdminAction.RESET_MFA, "3", "b")).message()).contains("Type the username");
|
||||
AuthentikAdmin.AdminResult mfa = run(AdminRequest.of(AdminAction.RESET_MFA, "3", "b").with("confirmText", "sam"));
|
||||
assertThat(mfa.ok()).as(mfa.message()).isTrue();
|
||||
assertThat(t.changes()).contains("DELETE /authenticators/admin/totp/11/", "DELETE /authenticators/admin/webauthn/12/");
|
||||
assertThat(run(AdminRequest.of(AdminAction.RESET_MFA, "3", "b").with("confirmText", "sam")).noChange()).isTrue();
|
||||
|
||||
t.authentik.tokens.put("sam", new java.util.ArrayList<>(List.of(new JSONObject().put("identifier", "sam-api").put("intent", "api"))));
|
||||
assertThat(run(AdminRequest.of(AdminAction.REVOKE_APP_PASSWORDS, "3", "b").with("confirmText", "sam")).noChange()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Revoke sessions has nothing to do for a user with no sessions (the fake
|
||||
** has none), and refuses protected users.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void sessionsRules() throws QException
|
||||
{
|
||||
assertThat(run(AdminRequest.of(AdminAction.REVOKE_SESSIONS, "3", "b")).noChange()).isTrue();
|
||||
assertThat(run(AdminRequest.of(AdminAction.REVOKE_SESSIONS, "4", "b")).message()).containsIgnoringCase("protected");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// gates: permission, feature, read-only, reason, audit
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Without the action's authentik.* permission nothing happens.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void permissionIsRequired() throws QException
|
||||
{
|
||||
t.loginAs(AuthentikTestSupport.OPERATOR, IdentityPermission.USERS_READ);
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-website-publishers"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("authentik.memberships.manage");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read-only mode and disabled features refuse every write.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void readOnlyAndFeatureFlags() throws QException
|
||||
{
|
||||
t.config.setReadOnly(true);
|
||||
assertThat(run(add(3, "kof-website-publishers")).message()).contains("read-only");
|
||||
t.config.setReadOnly(false);
|
||||
|
||||
AdminTestSupport readOnlyFeatures = AdminTestSupport.create(EnumSet.of(AuthentikFeature.READ));
|
||||
AuthentikAdmin.AdminResult result = readOnlyFeatures.admin().execute(AdminRequest.of(AdminAction.ADD_MEMBER, readOnlyFeatures.authentik.pk("kof-website-publishers") + ":3", "b"));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("not enabled");
|
||||
assertThat(readOnlyFeatures.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every change needs a reason.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void reasonIsRequired() throws QException
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.ADD_MEMBER, t.authentik.pk("kof-website-publishers") + ":3", " "));
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).contains("reason");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** If the audit row cannot be written, Authentik is not called.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void noAuditRowNoCall() throws QException
|
||||
{
|
||||
t.qInstance.getTables().remove(t.config.applyTablePrefix(AuthentikLocalTables.ADMIN_ACTION));
|
||||
assertThatThrownBy(() -> run(add(3, "kof-website-publishers"))).isInstanceOf(Exception.class);
|
||||
assertThat(t.writes()).isEmpty();
|
||||
assertThat(t.authentik.groupNamesOf(3)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A failed Authentik call is audited as FAILED with the (redacted) reason and
|
||||
** reported to the operator.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void failedCallIsAudited() throws QException
|
||||
{
|
||||
com.kingsrook.qbits.authentik.client.FixtureActionUtil.handler = request ->
|
||||
request.getMethod().equals("POST") && request.getURI().getPath().endsWith("/add_user/")
|
||||
? com.kingsrook.qbits.authentik.client.FixtureActionUtil.response(403, "{\"detail\":\"no permission " + AuthentikTestSupport.TEST_TOKEN + "\"}")
|
||||
: t.authentik.handle(request);
|
||||
AuthentikAdmin.AdminResult result = run(add(3, "kof-website-publishers"));
|
||||
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.message()).doesNotContain(AuthentikTestSupport.TEST_TOKEN);
|
||||
QRecord row = rows(AuthentikLocalTables.ADMIN_ACTION).get(0);
|
||||
assertThat(row.getValueString("status")).isEqualTo("FAILED");
|
||||
assertThat(row.getValueString("errorMessage")).doesNotContain(AuthentikTestSupport.TEST_TOKEN);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Nothing can change Authentik without the guard's authorization: the util
|
||||
** refuses a write with none, and a system session cannot get one.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void writesNeedTheGuard() throws QException
|
||||
{
|
||||
assertThatThrownBy(() -> t.admin().getUtil().write(null, "POST", "/core/groups/x/add_user/", new JSONObject().put("pk", 1)))
|
||||
.hasMessageContaining("through the guard");
|
||||
|
||||
com.kingsrook.qqq.backend.core.context.QContext.init(t.qInstance, new com.kingsrook.qqq.backend.core.model.session.QSystemUserSession());
|
||||
assertThatThrownBy(() -> t.admin().getUtil().getRuntime().getGuard().authorize(AdminAction.ADD_MEMBER)).hasMessageContaining("System sessions");
|
||||
assertThat(t.writes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Bootstrap operators hold every authentik.* permission even when their
|
||||
** groups are wrong (the lockout escape hatch), but still cannot grant what
|
||||
** they do not hold elsewhere.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void bootstrapOperatorSubjectsHoldIdentityPermissions() throws QException
|
||||
{
|
||||
t.authentik.groupByName("identity-admins").put("users", new JSONArray());
|
||||
t.config.withBootstrapOperatorSubjects("1");
|
||||
t.authentik.groupByName("kof-website-publishers").put("users", new JSONArray());
|
||||
|
||||
AuthentikAdmin.AdminResult grantIdentity = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, t.authentik.pk("kof-website-analysts"), "b")
|
||||
.with("permissions", "authentik.users.read").with("appAccess", ""));
|
||||
assertThat(grantIdentity.ok()).as(grantIdentity.message()).isTrue();
|
||||
assertThat(run(add(3, "kof-website-publishers")).message()).contains("cms.publish.hasAccess");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.authentik.permissions.EffectivePermissionResolver;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The pure rules of DESIGN.md section 5.4.
|
||||
*******************************************************************************/
|
||||
class AuthentikSafetyTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static GroupGraph.Node node(String pk, List<String> parents, List<String> permissions, List<Integer> members)
|
||||
{
|
||||
return (new GroupGraph.Node(pk, pk, false, parents, permissions, List.of(), members, List.of()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void missingIsTheSubsetRule()
|
||||
{
|
||||
assertThat(AuthentikSafety.missing(Set.of("a", "b"), Set.of("a", "b", "c"))).isEmpty();
|
||||
assertThat(AuthentikSafety.missing(Set.of("a", "b"), Set.of("a"))).containsExactly("b");
|
||||
assertThat(AuthentikSafety.missing(Set.of(), Set.of())).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Administrators are active, human, not protected, and hold both manage
|
||||
** permissions, directly or through a parent group.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void qualifyingAdmins()
|
||||
{
|
||||
GroupGraph graph = new GroupGraph()
|
||||
.add(node("admins", List.of(), List.of("authentik.*"), List.of(1, 2, 3, 4, 5)))
|
||||
.add(node("child", List.of("admins"), List.of(), List.of(6)))
|
||||
.add(node("readers", List.of(), List.of("authentik.users.read"), List.of(7)));
|
||||
EffectivePermissionResolver resolver = new EffectivePermissionResolver(graph, null);
|
||||
|
||||
Set<Integer> admins = AuthentikSafety.qualifyingAdmins(graph, resolver, List.of(
|
||||
new AuthentikSafety.UserFacts(1, true, true, false),
|
||||
new AuthentikSafety.UserFacts(2, false, true, false),
|
||||
new AuthentikSafety.UserFacts(3, true, false, false),
|
||||
new AuthentikSafety.UserFacts(4, true, true, true),
|
||||
new AuthentikSafety.UserFacts(5, true, true, false),
|
||||
new AuthentikSafety.UserFacts(6, true, true, false),
|
||||
new AuthentikSafety.UserFacts(7, true, true, false)));
|
||||
assertThat(admins).containsExactlyInAnyOrder(1, 5, 6);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Last-admin: only a change that takes the last one away is refused; a
|
||||
** state with none already is not blocked again.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void removesLastAdmin()
|
||||
{
|
||||
assertThat(AuthentikSafety.removesLastAdmin(Set.of(1), Set.of())).isTrue();
|
||||
assertThat(AuthentikSafety.removesLastAdmin(Set.of(1, 2), Set.of(2))).isFalse();
|
||||
assertThat(AuthentikSafety.removesLastAdmin(Set.of(), Set.of())).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Simulations never change the original graph.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void simulationsCopy()
|
||||
{
|
||||
GroupGraph original = new GroupGraph().add(node("g", List.of(), List.of("authentik.*"), List.of(1, 2)));
|
||||
GroupGraph.Node g = original.byPk("g");
|
||||
|
||||
GroupGraph removed = AuthentikSafety.withNodes(original, AuthentikSafety.withoutMember(g, 1));
|
||||
assertThat(removed.byPk("g").memberPks()).containsExactly(2);
|
||||
assertThat(original.byPk("g").memberPks()).containsExactly(1, 2);
|
||||
|
||||
GroupGraph stripped = AuthentikSafety.withNodes(original, AuthentikSafety.withPermissions(g, List.of(), List.of()));
|
||||
assertThat(stripped.byPk("g").permissions()).isEmpty();
|
||||
assertThat(original.byPk("g").permissions()).containsExactly("authentik.*");
|
||||
|
||||
GroupGraph moved = AuthentikSafety.withNodes(original, AuthentikSafety.withParents(g, List.of("x")));
|
||||
assertThat(moved.byPk("g").parentPks()).containsExactly("x");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Descendants include grandchildren and survive cycles.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void descendants()
|
||||
{
|
||||
GroupGraph graph = new GroupGraph()
|
||||
.add(node("a", List.of(), List.of(), List.of()))
|
||||
.add(node("b", List.of("a"), List.of(), List.of()))
|
||||
.add(node("c", List.of("b"), List.of(), List.of()))
|
||||
.add(node("d", List.of(), List.of(), List.of()))
|
||||
.add(node("loop1", List.of("loop2"), List.of(), List.of()))
|
||||
.add(node("loop2", List.of("loop1"), List.of(), List.of()));
|
||||
assertThat(AuthentikSafety.descendantPks(graph, "a")).containsExactlyInAnyOrder("b", "c");
|
||||
assertThat(AuthentikSafety.descendantPks(graph, "d")).isEmpty();
|
||||
assertThat(AuthentikSafety.descendantPks(graph, "loop1")).containsExactly("loop2");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void parseList()
|
||||
{
|
||||
assertThat(AuthentikSafety.parseList("a\nb, c;d\r\n\n a ")).containsExactly("a", "b", "c", "d");
|
||||
assertThat(AuthentikSafety.parseList("")).isEmpty();
|
||||
assertThat(AuthentikSafety.parseList(null)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The group fingerprint tracks the editable state (name, parents, qqq.io
|
||||
** attributes, member count) and ignores everything else.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void groupFingerprint()
|
||||
{
|
||||
JSONObject base = new JSONObject().put("name", "g").put("parents", new JSONArray(List.of("p"))).put("users", new JSONArray(List.of(1)))
|
||||
.put("attributes", new JSONObject().put("qqq.io/permissions", new JSONArray(List.of("a"))).put("other", "x"));
|
||||
String fingerprint = AuthentikSafety.groupFingerprint(base);
|
||||
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("pk", "ignored"))).isEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("attributes", base.getJSONObject("attributes").put("other", "changed")))).isEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("name", "h"))).isNotEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("users", new JSONArray(List.of(1, 2))))).isNotEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("parents", new JSONArray()))).isNotEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.groupFingerprint(new JSONObject(base.toString()).put("attributes",
|
||||
new JSONObject().put("qqq.io/permissions", new JSONArray(List.of("b")))))).isNotEqualTo(fingerprint);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The user fingerprint changes with any editable field or with last_updated.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void userFingerprint()
|
||||
{
|
||||
JSONObject user = new JSONObject().put("username", "u").put("name", "N").put("email", "e@x.test").put("path", "users").put("type", "internal")
|
||||
.put("is_active", true).put("last_updated", "2026-10-01T00:00:00Z");
|
||||
String fingerprint = AuthentikSafety.userFingerprint(user);
|
||||
assertThat(AuthentikSafety.userFingerprint(new JSONObject(user.toString()))).isEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.userFingerprint(new JSONObject(user.toString()).put("name", "M"))).isNotEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.userFingerprint(new JSONObject(user.toString()).put("is_active", false))).isNotEqualTo(fingerprint);
|
||||
assertThat(AuthentikSafety.userFingerprint(new JSONObject(user.toString()).put("last_updated", "2026-10-02T00:00:00Z"))).isNotEqualTo(fingerprint);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import com.kingsrook.qbits.authentik.client.FixtureActionUtil;
|
||||
import com.kingsrook.qqq.backend.module.api.actions.QHttpResponse;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A small in-memory Authentik for unit tests: users, groups (with parents,
|
||||
** attributes and members), tokens, sessions, MFA devices, invitations and the
|
||||
** write endpoints the qbit uses, with the same superuser inheritance the real
|
||||
** server has. Every write request is recorded so tests can assert what was
|
||||
** (and was not) sent. Plug it in with {@link #install()}.
|
||||
*******************************************************************************/
|
||||
public class FakeAuthentik
|
||||
{
|
||||
public final Map<Integer, JSONObject> users = new LinkedHashMap<>();
|
||||
public final Map<String, JSONObject> groups = new LinkedHashMap<>();
|
||||
public final Map<String, List<JSONObject>> tokens = new LinkedHashMap<>();
|
||||
public final Map<String, Integer> sessions = new LinkedHashMap<>();
|
||||
public final Map<Integer, List<JSONObject>> devices = new LinkedHashMap<>();
|
||||
public final Map<String, JSONObject> invitations = new LinkedHashMap<>();
|
||||
public final List<String> writes = new ArrayList<>();
|
||||
public final List<JSONObject> events = new ArrayList<>();
|
||||
public final List<JSONObject> writeBodies = new ArrayList<>();
|
||||
|
||||
private int nextUserPk = 100;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Route the qbit's requests to this fake.
|
||||
*******************************************************************************/
|
||||
public FakeAuthentik install()
|
||||
{
|
||||
FixtureActionUtil.reset();
|
||||
FixtureActionUtil.handler = this::handle;
|
||||
FixtureActionUtil.groupGraphHandler = this::handle;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add a user (groups by name must already exist).
|
||||
*******************************************************************************/
|
||||
public FakeAuthentik user(int pk, String username, String email, String type, boolean active, String... groupNames)
|
||||
{
|
||||
JSONObject user = new JSONObject().put("pk", pk).put("username", username).put("name", username + " Name").put("email", email)
|
||||
.put("is_active", active).put("type", type).put("path", "users").put("attributes", new JSONObject()).put("last_updated", "2026-10-01T00:00:00Z")
|
||||
.put("date_joined", "2026-01-01T00:00:00Z").put("last_login", "2026-10-02T00:00:00Z");
|
||||
users.put(pk, user);
|
||||
for(String groupName : groupNames)
|
||||
{
|
||||
groupByName(groupName).getJSONArray("users").put(pk);
|
||||
}
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add a group with QQQ permissions, app access and parents (names).
|
||||
*******************************************************************************/
|
||||
public FakeAuthentik group(String name, boolean superuser, List<String> permissions, List<String> appAccess, String... parentNames)
|
||||
{
|
||||
JSONObject attributes = new JSONObject();
|
||||
if(!permissions.isEmpty())
|
||||
{
|
||||
attributes.put("qqq.io/permissions", new JSONArray(permissions));
|
||||
}
|
||||
if(!appAccess.isEmpty())
|
||||
{
|
||||
attributes.put("qqq.io/app-access", new JSONArray(appAccess));
|
||||
}
|
||||
JSONArray parents = new JSONArray();
|
||||
for(String parentName : parentNames)
|
||||
{
|
||||
parents.put(groupByName(parentName).getString("pk"));
|
||||
}
|
||||
String pk = UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8)).toString();
|
||||
groups.put(pk, new JSONObject().put("pk", pk).put("name", name).put("is_superuser", superuser).put("parents", parents)
|
||||
.put("attributes", attributes).put("users", new JSONArray()));
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The group pk for a name.
|
||||
*******************************************************************************/
|
||||
public String pk(String groupName)
|
||||
{
|
||||
return (groupByName(groupName).getString("pk"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The group object for a name.
|
||||
*******************************************************************************/
|
||||
public JSONObject groupByName(String name)
|
||||
{
|
||||
return (groups.values().stream().filter(g -> g.getString("name").equals(name)).findFirst().orElseThrow(() -> new IllegalStateException("no group " + name)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Names of the groups a user is a direct member of.
|
||||
*******************************************************************************/
|
||||
public List<String> groupNamesOf(int userPk)
|
||||
{
|
||||
List<String> rs = new ArrayList<>();
|
||||
for(JSONObject group : groups.values())
|
||||
{
|
||||
if(contains(group.getJSONArray("users"), userPk))
|
||||
{
|
||||
rs.add(group.getString("name"));
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether any group in the user's ancestry is a superuser group.
|
||||
*******************************************************************************/
|
||||
private boolean inheritedSuperuser(String groupPk, int depth)
|
||||
{
|
||||
JSONObject group = groups.get(groupPk);
|
||||
if(group == null || depth > 20)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
if(group.getBoolean("is_superuser"))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
for(int i = 0; i < group.getJSONArray("parents").length(); i++)
|
||||
{
|
||||
if(inheritedSuperuser(group.getJSONArray("parents").getString(i), depth + 1))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static boolean contains(JSONArray array, int pk)
|
||||
{
|
||||
for(int i = 0; i < array.length(); i++)
|
||||
{
|
||||
if(array.getInt(i) == pk)
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A user as the API returns it (with groups_obj and derived is_superuser).
|
||||
*******************************************************************************/
|
||||
private JSONObject render(JSONObject user)
|
||||
{
|
||||
JSONObject rs = new JSONObject(user.toString());
|
||||
JSONArray groupsObj = new JSONArray();
|
||||
boolean superuser = false;
|
||||
for(JSONObject group : groups.values())
|
||||
{
|
||||
if(contains(group.getJSONArray("users"), user.getInt("pk")))
|
||||
{
|
||||
groupsObj.put(new JSONObject().put("pk", group.getString("pk")).put("name", group.getString("name")));
|
||||
superuser |= inheritedSuperuser(group.getString("pk"), 0);
|
||||
}
|
||||
}
|
||||
return (rs.put("groups_obj", groupsObj).put("roles_obj", new JSONArray()).put("is_superuser", superuser));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A group as the API returns it.
|
||||
*******************************************************************************/
|
||||
private JSONObject render(JSONObject group, boolean includeUsers)
|
||||
{
|
||||
JSONObject rs = new JSONObject(group.toString());
|
||||
if(!includeUsers)
|
||||
{
|
||||
rs.remove("users");
|
||||
}
|
||||
JSONArray parentsObj = new JSONArray();
|
||||
for(int i = 0; i < group.getJSONArray("parents").length(); i++)
|
||||
{
|
||||
JSONObject parent = groups.get(group.getJSONArray("parents").getString(i));
|
||||
if(parent != null)
|
||||
{
|
||||
parentsObj.put(new JSONObject().put("pk", parent.getString("pk")).put("name", parent.getString("name")));
|
||||
}
|
||||
}
|
||||
return (rs.put("parents_obj", parentsObj).put("children_obj", new JSONArray()).put("roles_obj", new JSONArray()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The fake server.
|
||||
*******************************************************************************/
|
||||
public QHttpResponse handle(HttpRequestBase request)
|
||||
{
|
||||
URI uri = request.getURI();
|
||||
String path = uri.getPath().replace("/api/v3", "");
|
||||
String method = request.getMethod();
|
||||
Map<String, List<String>> query = parseQuery(uri.getRawQuery());
|
||||
JSONObject body = body(request);
|
||||
|
||||
if(!method.equals("GET"))
|
||||
{
|
||||
writes.add(method + " " + path + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()));
|
||||
writeBodies.add(body == null ? new JSONObject() : body);
|
||||
}
|
||||
|
||||
if(method.equals("GET"))
|
||||
{
|
||||
return (get(path, query));
|
||||
}
|
||||
|
||||
if(path.equals("/events/events/"))
|
||||
{
|
||||
events.add(body);
|
||||
return (ok(201, new JSONObject().put("pk", UUID.randomUUID().toString())));
|
||||
}
|
||||
if(path.equals("/core/users/") && method.equals("POST"))
|
||||
{
|
||||
int pk = nextUserPk++;
|
||||
JSONObject user = new JSONObject(body.toString()).put("pk", pk).put("last_updated", "2026-10-12T00:00:00Z");
|
||||
if(!user.has("attributes"))
|
||||
{
|
||||
user.put("attributes", new JSONObject());
|
||||
}
|
||||
users.put(pk, user);
|
||||
return (ok(201, render(user)));
|
||||
}
|
||||
if(path.equals("/core/groups/") && method.equals("POST"))
|
||||
{
|
||||
String pk = UUID.nameUUIDFromBytes(body.getString("name").getBytes(StandardCharsets.UTF_8)).toString();
|
||||
JSONObject group = new JSONObject(body.toString()).put("pk", pk).put("users", new JSONArray());
|
||||
groups.put(pk, group);
|
||||
return (ok(201, render(group, true)));
|
||||
}
|
||||
if(path.matches("/core/users/\\d+/") && method.equals("PATCH"))
|
||||
{
|
||||
JSONObject user = users.get(Integer.parseInt(path.split("/")[3]));
|
||||
for(String key : body.keySet())
|
||||
{
|
||||
user.put(key, body.get(key));
|
||||
}
|
||||
user.put("last_updated", "2026-10-12T01:00:00Z");
|
||||
return (ok(200, render(user)));
|
||||
}
|
||||
if(path.matches("/core/groups/[^/]+/") && method.equals("PATCH"))
|
||||
{
|
||||
JSONObject group = groups.get(path.split("/")[3]);
|
||||
for(String key : body.keySet())
|
||||
{
|
||||
group.put(key, body.get(key));
|
||||
}
|
||||
return (ok(200, render(group, true)));
|
||||
}
|
||||
if(path.matches("/core/groups/[^/]+/(add_user|remove_user)/"))
|
||||
{
|
||||
JSONObject group = groups.get(path.split("/")[3]);
|
||||
int pk = body.getInt("pk");
|
||||
JSONArray users = group.getJSONArray("users");
|
||||
if(path.endsWith("add_user/"))
|
||||
{
|
||||
if(!contains(users, pk))
|
||||
{
|
||||
users.put(pk);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
JSONArray kept = new JSONArray();
|
||||
for(int i = 0; i < users.length(); i++)
|
||||
{
|
||||
if(users.getInt(i) != pk)
|
||||
{
|
||||
kept.put(users.getInt(i));
|
||||
}
|
||||
}
|
||||
group.put("users", kept);
|
||||
}
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.matches("/core/users/\\d+/recovery_email/"))
|
||||
{
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.matches("/core/tokens/[^/]+/") && method.equals("DELETE"))
|
||||
{
|
||||
String identifier = path.split("/")[3];
|
||||
tokens.values().forEach(list -> list.removeIf(t -> t.getString("identifier").equals(identifier)));
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.equals("/core/authenticated_sessions/bulk_delete/"))
|
||||
{
|
||||
sessions.remove(first(query, "user_pks"));
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.matches("/authenticators/admin/[a-z]+/[^/]+/") && method.equals("DELETE"))
|
||||
{
|
||||
String id = path.split("/")[4];
|
||||
devices.values().forEach(list -> list.removeIf(d -> String.valueOf(d.get("pk")).equals(id)));
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.equals("/stages/invitation/invitations/") && method.equals("POST"))
|
||||
{
|
||||
String pk = UUID.randomUUID().toString();
|
||||
invitations.put(pk, new JSONObject(body.toString()).put("pk", pk));
|
||||
return (ok(201, invitations.get(pk)));
|
||||
}
|
||||
if(path.matches("/stages/invitation/invitations/[^/]+/send_email/"))
|
||||
{
|
||||
return (ok(200, new JSONObject()));
|
||||
}
|
||||
if(path.matches("/stages/invitation/invitations/[^/]+/") && method.equals("DELETE"))
|
||||
{
|
||||
invitations.remove(path.split("/")[4]);
|
||||
return (ok(204, null));
|
||||
}
|
||||
return (FixtureActionUtil.response(404, "{\"detail\":\"Not found.\"}"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private QHttpResponse get(String path, Map<String, List<String>> query)
|
||||
{
|
||||
if(path.equals("/core/users/"))
|
||||
{
|
||||
List<JSONObject> rs = new ArrayList<>();
|
||||
for(JSONObject user : users.values())
|
||||
{
|
||||
JSONObject rendered = render(user);
|
||||
if(query.containsKey("email") && !first(query, "email").equalsIgnoreCase(user.optString("email")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if(query.containsKey("username") && !first(query, "username").equalsIgnoreCase(user.optString("username")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if(query.containsKey("type") && !query.get("type").contains(user.optString("type")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
rs.add(rendered);
|
||||
}
|
||||
return (page(rs));
|
||||
}
|
||||
if(path.matches("/core/users/\\d+/"))
|
||||
{
|
||||
JSONObject user = users.get(Integer.parseInt(path.split("/")[3]));
|
||||
return (user == null ? FixtureActionUtil.response(404, "{}") : ok(200, render(user)));
|
||||
}
|
||||
if(path.equals("/core/groups/"))
|
||||
{
|
||||
boolean includeUsers = "true".equals(first(query, "include_users"));
|
||||
List<JSONObject> rs = new ArrayList<>();
|
||||
for(JSONObject group : groups.values())
|
||||
{
|
||||
if(query.containsKey("name") && !first(query, "name").equals(group.getString("name")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
rs.add(render(group, includeUsers));
|
||||
}
|
||||
return (page(rs));
|
||||
}
|
||||
if(path.matches("/core/groups/[^/]+/"))
|
||||
{
|
||||
JSONObject group = groups.get(path.split("/")[3]);
|
||||
return (group == null ? FixtureActionUtil.response(404, "{}") : ok(200, render(group, "true".equals(first(query, "include_users")))));
|
||||
}
|
||||
if(path.equals("/core/tokens/"))
|
||||
{
|
||||
List<JSONObject> rs = new ArrayList<>(tokens.getOrDefault(first(query, "user__username"), List.of()));
|
||||
String intent = first(query, "intent");
|
||||
if(intent != null)
|
||||
{
|
||||
rs.removeIf(t -> !intent.equals(t.optString("intent")));
|
||||
}
|
||||
return (page(rs));
|
||||
}
|
||||
if(path.equals("/core/authenticated_sessions/"))
|
||||
{
|
||||
return (page(new ArrayList<>()));
|
||||
}
|
||||
if(path.equals("/authenticators/admin/all/"))
|
||||
{
|
||||
JSONArray rs = new JSONArray();
|
||||
devices.getOrDefault(Integer.parseInt(first(query, "user")), List.of()).forEach(rs::put);
|
||||
return (ok(200, rs));
|
||||
}
|
||||
if(path.equals("/stages/email/"))
|
||||
{
|
||||
return (page(List.of(new JSONObject().put("pk", "11111111-1111-1111-1111-111111111111").put("name", first(query, "name")))));
|
||||
}
|
||||
if(path.equals("/flows/instances/"))
|
||||
{
|
||||
return (page(List.of(new JSONObject().put("pk", "22222222-2222-2222-2222-222222222222").put("slug", first(query, "slug")))));
|
||||
}
|
||||
if(path.matches("/stages/invitation/invitations/[^/]+/"))
|
||||
{
|
||||
JSONObject invitation = invitations.get(path.split("/")[4]);
|
||||
return (invitation == null ? FixtureActionUtil.response(404, "{}") : ok(200, invitation));
|
||||
}
|
||||
if(path.equals("/events/events/") || path.equals("/managed/blueprints/") || path.equals("/core/applications/"))
|
||||
{
|
||||
return (page(new ArrayList<>()));
|
||||
}
|
||||
return (FixtureActionUtil.response(404, "{\"detail\":\"Not found.\"}"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static QHttpResponse page(List<JSONObject> results)
|
||||
{
|
||||
return (ok(200, new JSONObject().put("pagination", new JSONObject().put("count", results.size()).put("current", 1).put("total_pages", 1))
|
||||
.put("results", new JSONArray(results))));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static QHttpResponse ok(int status, Object body)
|
||||
{
|
||||
return (FixtureActionUtil.response(status, body == null ? "" : body.toString()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static JSONObject body(HttpRequestBase request)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(request instanceof HttpEntityEnclosingRequest entityRequest && entityRequest.getEntity() != null)
|
||||
{
|
||||
return (new JSONObject(EntityUtils.toString(entityRequest.getEntity())));
|
||||
}
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
throw (new IllegalStateException(e));
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static String first(Map<String, List<String>> query, String name)
|
||||
{
|
||||
List<String> values = query.get(name);
|
||||
return (values == null || values.isEmpty() ? null : values.get(0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static Map<String, List<String>> parseQuery(String rawQuery)
|
||||
{
|
||||
Map<String, List<String>> rs = new LinkedHashMap<>();
|
||||
if(rawQuery == null)
|
||||
{
|
||||
return (rs);
|
||||
}
|
||||
for(String pair : rawQuery.split("&"))
|
||||
{
|
||||
String[] kv = pair.split("=", 2);
|
||||
rs.computeIfAbsent(URLDecoder.decode(kv[0], StandardCharsets.UTF_8), k -> new ArrayList<>()).add(kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "");
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.admin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyEditorWidget;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyGenerator;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyParser;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.RenderWidgetAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policy editor (DESIGN.md section 12.4): saving a policy to Authentik,
|
||||
** the guardrails, the authentik_policy history row, the process and widget.
|
||||
*******************************************************************************/
|
||||
class PolicyEditorTest
|
||||
{
|
||||
private static final String PAGE_READ_EDIT = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\",\"edit\"],\"Resource\":[\"cms_page\"]}]}";
|
||||
|
||||
private AdminTestSupport t;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The operator's own group carries a policy, so the subset rule lets them
|
||||
** grant cms_page read/edit and content access (but not delete).
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws Exception
|
||||
{
|
||||
t = AdminTestSupport.create(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP, AuthentikFeature.POLICIES));
|
||||
t.authentik.groupByName("identity-admins").getJSONObject("attributes").put("qqq.io/policy",
|
||||
PolicyGenerator.toCompact(PolicyGenerator.generate(List.of("cms_page.read", "cms_page.edit", "content.hasAccess", "publishPage.hasAccess"), PolicyFormat.DEFAULT)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AuthentikAdmin.AdminResult save(String group, String document) throws QException
|
||||
{
|
||||
return (t.admin().execute(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk(group), "because").with(AuthentikAdmin.POLICY_DOCUMENT, document)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private List<QRecord> policyRows() throws QException
|
||||
{
|
||||
QueryInput input = new QueryInput();
|
||||
input.setTableName(t.config.applyTablePrefix(AuthentikLocalTables.POLICY));
|
||||
return (new QueryAction().execute(input).getRecords());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Save writes the canonical compact string into the CURRENT attributes, and
|
||||
** an authentik_policy row with the pretty document.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void saveWritesCanonicalDocumentAndHistoryRow() throws Exception
|
||||
{
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("note", "set in the Authentik UI");
|
||||
|
||||
AuthentikAdmin.AdminResult result = save("kof-website-analysts", PAGE_READ_EDIT);
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(result.message()).isEqualTo("Policy saved to Authentik.");
|
||||
|
||||
JSONObject attributes = t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes");
|
||||
assertThat(attributes.getString("note")).isEqualTo("set in the Authentik UI");
|
||||
assertThat(attributes.getString("qqq.io/policy")).isEqualTo(PolicyGenerator.toCompact(PolicyGenerator.canonical(PAGE_READ_EDIT, PolicyFormat.DEFAULT)));
|
||||
assertThat(PolicyParser.parse(attributes.get("qqq.io/policy"), PolicyFormat.DEFAULT)).containsExactlyInAnyOrder("cms_page.read", "cms_page.edit");
|
||||
|
||||
List<QRecord> rows = policyRows();
|
||||
assertThat(rows).hasSize(1);
|
||||
assertThat(rows.get(0).getValueString("groupName")).isEqualTo("kof-website-analysts");
|
||||
assertThat(rows.get(0).getValueInteger("permissionCount")).isEqualTo(2);
|
||||
assertThat(rows.get(0).getValueString("policyJson")).contains("\"Action\": [\"read\"]");
|
||||
assertThat(rows.get(0).getValueString("savedBy")).isEqualTo(com.kingsrook.qbits.authentik.AuthentikTestSupport.OPERATOR);
|
||||
|
||||
//////////////////////////////////////////////////////////////
|
||||
// the effective permissions of the group now include them //
|
||||
//////////////////////////////////////////////////////////////
|
||||
t.admin().getUtil().getRuntime().invalidateCache();
|
||||
assertThat(t.admin().getUtil().groupGraph().byName("kof-website-analysts").policyPermissions()).containsExactlyInAnyOrder("cms_page.read", "cms_page.edit");
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// saving it again is no change; removing it drops the attribute //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
assertThat(save("kof-website-analysts", PAGE_READ_EDIT).noChange()).isTrue();
|
||||
AuthentikAdmin.AdminResult removed = save("kof-website-analysts", "");
|
||||
assertThat(removed.message()).contains("removed");
|
||||
assertThat(t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").has("qqq.io/policy")).isFalse();
|
||||
assertThat(policyRows()).hasSize(1);
|
||||
assertThat(policyRows().get(0).getValueInteger("permissionCount")).isEqualTo(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The guardrails: invalid documents, unknown resources, the subset rule,
|
||||
** superuser groups and a stale fingerprint are refused, and nothing is sent.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void refusals() throws Exception
|
||||
{
|
||||
assertThat(save("kof-website-analysts", "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"read\"],\"Resource\":[\"cms_page\"]}]}").message())
|
||||
.contains("not valid").contains("Deny");
|
||||
assertThat(save("kof-website-analysts", "{\"PolicySpec\":\"other\",\"PolicyVersion\":\"1.0.0\"}").message()).contains("PolicySpec");
|
||||
assertThat(save("kof-website-analysts", PAGE_READ_EDIT.replace("cms_page", "no_such_table")).message()).contains("not permissions of this app").contains("no_such_table.read");
|
||||
assertThat(save("kof-website-analysts", PAGE_READ_EDIT.replace("\"edit\"", "\"delete\"")).message()).contains("do not hold yourself").contains("cms_page.delete");
|
||||
assertThat(save("authentik Admins", PAGE_READ_EDIT).message()).contains("Superuser groups");
|
||||
|
||||
AuthentikAdmin.AdminResult stale = t.admin().execute(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with(AuthentikAdmin.POLICY_DOCUMENT, PAGE_READ_EDIT).with("expectedFingerprint", "not-the-fingerprint"));
|
||||
assertThat(stale.message()).contains("changed");
|
||||
|
||||
assertThat(t.changes()).isEmpty();
|
||||
assertThat(policyRows()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Unknown resources already in the stored policy are kept (with a note); a
|
||||
** stored document that is invalid is replaced.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void keptUnknownsAndInvalidStoredDocuments() throws Exception
|
||||
{
|
||||
String withGone = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"gone_table\"]}]}";
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("qqq.io/policy", withGone);
|
||||
AdminPlan plan = t.admin().plan(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk("kof-website-analysts"), "because")
|
||||
.with(AuthentikAdmin.POLICY_DOCUMENT, "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"gone_table\",\"cms_page\"]}]}"));
|
||||
assertThat(plan.isRunnable()).as(plan.getMessage()).isTrue();
|
||||
assertThat(plan.getNotes()).anyMatch(n -> n.startsWith("Adds: cms_page.read")).anyMatch(n -> n.contains("Kept although") && n.contains("gone_table.read"));
|
||||
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("qqq.io/policy", "garbage");
|
||||
AdminPlan replace = t.admin().plan(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk("kof-website-analysts"), "because").with(AuthentikAdmin.POLICY_DOCUMENT, ""));
|
||||
assertThat(replace.isRunnable()).isTrue();
|
||||
assertThat(replace.getNotes()).anyMatch(n -> n.contains("was not valid"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Permission gating: without authentik.policies.manage, or without the
|
||||
** POLICIES feature, there is no save (and no metadata).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void gating() throws Exception
|
||||
{
|
||||
t.loginAs(com.kingsrook.qbits.authentik.AuthentikTestSupport.OPERATOR, IdentityPermission.USERS_READ, IdentityPermission.GROUPS_MANAGE, IdentityPermission.PERMISSIONS_MANAGE);
|
||||
assertThat(save("kof-website-analysts", PAGE_READ_EDIT).ok()).isFalse();
|
||||
assertThat(t.changes()).isEmpty();
|
||||
|
||||
AdminTestSupport off = AdminTestSupport.create();
|
||||
assertThat(off.qInstance.getProcess("authentikEditPolicy")).isNull();
|
||||
assertThat(off.qInstance.getWidget("authentikPolicyEditor")).isNull();
|
||||
assertThat(off.qInstance.getTable("authentik_policy")).isNull();
|
||||
AuthentikAdmin.AdminResult refused = off.admin().execute(AdminRequest.of(AdminAction.SAVE_POLICY, off.authentik.pk("kof-website-analysts"), "because").with(AuthentikAdmin.POLICY_DOCUMENT, PAGE_READ_EDIT));
|
||||
assertThat(refused.ok()).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A second person approves policy saves when policyTwoPersonApproval is on.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void twoPersonApproval() throws Exception
|
||||
{
|
||||
t.config.withPolicyTwoPersonApproval(true);
|
||||
AuthentikAdmin.AdminResult result = save("kof-website-analysts", PAGE_READ_EDIT);
|
||||
assertThat(result.pending()).isTrue();
|
||||
assertThat(t.changes()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The record action: prepare fills the group and fingerprint, the step shows
|
||||
** the editor widget, Review is a dry run, Result saves.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editPolicyProcess() throws Exception
|
||||
{
|
||||
String groupPk = t.authentik.pk("kof-website-analysts");
|
||||
QFrontendStepMetaData details = (QFrontendStepMetaData) t.qInstance.getProcess("authentikEditPolicy").getStep("details");
|
||||
assertThat(details.getComponents()).anyMatch(c -> c.getType() == QComponentType.WIDGET && "authentikPolicyEditor".equals(c.getValues().get("widgetName")));
|
||||
assertThat(t.qInstance.getProcess("authentikEditPolicy").getTableName()).isEqualTo(t.config.applyTablePrefix(AuthentikTables.GROUP));
|
||||
assertThat(t.qInstance.getProcess("authentikEditPolicyRecord").getTableName()).isEqualTo("authentik_policy");
|
||||
|
||||
RunProcessInput input = new RunProcessInput();
|
||||
input.setProcessName("authentikEditPolicy");
|
||||
input.addValue("recordIds", groupPk);
|
||||
RunProcessOutput output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getValues().get("groupPk")).isEqualTo(groupPk);
|
||||
assertThat(output.getValues().get("expectedFingerprint")).isNotNull();
|
||||
|
||||
input.setProcessUUID(output.getProcessUUID());
|
||||
Map<String, Serializable> form = Map.of("reason", "editors read pages", AuthentikAdmin.POLICY_DOCUMENT, PAGE_READ_EDIT);
|
||||
form.forEach(input::addValue);
|
||||
input.setStartAfterStep("details");
|
||||
output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getException()).isEmpty();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<ProcessSummaryLine> review = (List<ProcessSummaryLine>) output.getValues().get(StreamedETLWithFrontendProcess.FIELD_VALIDATION_SUMMARY);
|
||||
assertThat(review).anyMatch(l -> l.getStatus() == Status.OK && l.getMessage().contains("policy will be saved"));
|
||||
assertThat(review).anyMatch(l -> l.getMessage().contains("Adds: cms_page.edit, cms_page.read"));
|
||||
assertThat(t.changes()).as("review is a dry run").isEmpty();
|
||||
|
||||
input.setStartAfterStep("review");
|
||||
output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getException()).isEmpty();
|
||||
assertThat(PolicyParser.parse(t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").get("qqq.io/policy"), PolicyFormat.DEFAULT))
|
||||
.containsExactlyInAnyOrder("cms_page.read", "cms_page.edit");
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
// the same action from the policy record (its group) //
|
||||
////////////////////////////////////////////////////////
|
||||
RunProcessInput again = new RunProcessInput();
|
||||
again.setProcessName("authentikEditPolicyRecord");
|
||||
again.addValue("recordIds", String.valueOf(policyRows().get(0).getValue("id")));
|
||||
RunProcessOutput prepared = new RunProcessAction().execute(again);
|
||||
assertThat(prepared.getValues().get("groupPk")).isEqualTo(groupPk);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The widget: catalog plus the group's live document; a change made in
|
||||
** Authentik after the last QQQ save is flagged; invalid stored documents are
|
||||
** reported.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void widgetData() throws Exception
|
||||
{
|
||||
String groupPk = t.authentik.pk("kof-website-analysts");
|
||||
PolicyEditorWidget.Data empty = PolicyEditorWidget.load(t.config, groupPk);
|
||||
assertThat(empty.getType()).isEqualTo("AUTHENTIK_POLICY_EDITOR");
|
||||
assertThat(empty.getSpec()).isEqualTo("qqq-iam");
|
||||
assertThat(empty.getDocument()).isNull();
|
||||
assertThat(empty.getGroupLabel()).isEqualTo("kof-website-analysts");
|
||||
assertThat(empty.getOutputFieldName()).isEqualTo("policyDocument");
|
||||
assertThat(new JSONObject(Map.of("c", empty.getCatalog())).toString()).contains("\"cms_page\"").contains("\"publishPage\"");
|
||||
|
||||
save("kof-website-analysts", PAGE_READ_EDIT);
|
||||
PolicyEditorWidget.Data saved = PolicyEditorWidget.load(t.config, groupPk);
|
||||
assertThat(saved.getDocument()).contains("\"cms_page\"");
|
||||
assertThat(saved.getChangedInAuthentik()).isFalse();
|
||||
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("qqq.io/policy", PAGE_READ_EDIT.replace("\"edit\"", "\"insert\""));
|
||||
t.admin().getUtil().getRuntime().invalidateCache();
|
||||
assertThat(PolicyEditorWidget.load(t.config, groupPk).getChangedInAuthentik()).isTrue();
|
||||
|
||||
t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes").put("qqq.io/policy", "garbage");
|
||||
t.admin().getUtil().getRuntime().invalidateCache();
|
||||
PolicyEditorWidget.Data broken = PolicyEditorWidget.load(t.config, groupPk);
|
||||
assertThat(broken.getDocumentProblem()).contains("not a JSON object");
|
||||
assertThat(broken.getDocument()).isNull();
|
||||
|
||||
assertThat(PolicyEditorWidget.load(t.config, null).getGroupLabel()).isNull();
|
||||
assertThatThrownBy(() -> PolicyEditorWidget.load(t.config, "../x")).hasMessageContaining("Not a group id");
|
||||
|
||||
RenderWidgetInput input = new RenderWidgetInput();
|
||||
input.setWidgetMetaData(t.qInstance.getWidget("authentikPolicyEditor"));
|
||||
input.setQueryParams(new java.util.HashMap<>(Map.of("groupPk", groupPk)));
|
||||
RenderWidgetOutput output = new RenderWidgetAction().execute(input);
|
||||
assertThat(output.getWidgetData().getType()).isEqualTo("AUTHENTIK_POLICY_EDITOR");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.app;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikTestSupport;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminTestSupport;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Identity app: nav with only the main tables, child lists on the parents,
|
||||
** the local tables, the single home, and the guarantee that nothing but the
|
||||
** admin service changes Authentik.
|
||||
*******************************************************************************/
|
||||
class AuthentikAppTest
|
||||
{
|
||||
/*******************************************************************************
|
||||
** The nav lists only the main tables; memberships, sessions, tokens, events,
|
||||
** bindings, roles and blueprints are reached from their parents.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void navHasOnlyMainTablesAndParentsHaveChildLists() throws QException
|
||||
{
|
||||
AdminTestSupport t = AdminTestSupport.create();
|
||||
QAppMetaData app = t.qInstance.getApp("authentikAdmin");
|
||||
|
||||
assertThat(app.getChildren()).extracting(c -> c.getName())
|
||||
.containsExactly("authentik_user", "authentik_invitation", "authentik_group", "authentik_application", "authentik_approval_request", "authentik_admin_action");
|
||||
assertThat(app.getSections()).extracting(s -> s.getLabel()).containsExactly("People", "Access", "Activity");
|
||||
assertThat(app.getWidgets()).containsExactly("authentikHome", "authentikDriftReport");
|
||||
|
||||
for(String subTable : List.of("authentik_group_member", "authentik_session", "authentik_token", "authentik_event", "authentik_policy_binding", "authentik_role", "authentik_blueprint"))
|
||||
{
|
||||
assertThat(t.qInstance.getTable(subTable)).as(subTable).isNotNull();
|
||||
assertThat(app.getChildren()).extracting(c -> c.getName()).doesNotContain(subTable);
|
||||
}
|
||||
|
||||
QTableMetaData user = t.qInstance.getTable("authentik_user");
|
||||
assertThat(user.getSections()).extracting(s -> s.getName()).contains("identity", "access", "memberships", "sessions", "tokens", "events");
|
||||
assertThat(t.qInstance.getTable("authentik_group").getSections()).extracting(s -> s.getName()).contains("details", "permissions", "members");
|
||||
assertThat(t.qInstance.getJoin("authentik_user_sessions").getRightTable()).isEqualTo("authentik_session");
|
||||
assertThat(t.qInstance.getWidget("authentik_user_memberships")).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The local tables are standard visible tables on the host's backend, written
|
||||
** only by the qbit; with no local backend there are none (read-only app).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void localTables() throws QException
|
||||
{
|
||||
AdminTestSupport t = AdminTestSupport.create();
|
||||
for(String name : List.of("authentik_admin_action", "authentik_approval_request"))
|
||||
{
|
||||
QTableMetaData table = t.qInstance.getTable(name);
|
||||
assertThat(table.getBackendName()).isEqualTo(AdminTestSupport.LOCAL);
|
||||
assertThat(table.isCapabilityEnabled(t.qInstance.getBackend(AdminTestSupport.LOCAL), Capability.TABLE_INSERT)).isFalse();
|
||||
assertThat(table.isCapabilityEnabled(t.qInstance.getBackend(AdminTestSupport.LOCAL), Capability.TABLE_UPDATE)).isFalse();
|
||||
assertThat(table.isCapabilityEnabled(t.qInstance.getBackend(AdminTestSupport.LOCAL), Capability.TABLE_DELETE)).isFalse();
|
||||
assertThat(table.isCapabilityEnabled(t.qInstance.getBackend(AdminTestSupport.LOCAL), Capability.TABLE_QUERY)).isTrue();
|
||||
}
|
||||
assertThat(t.qInstance.getTable("authentik_admin_action").getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.audit.read");
|
||||
assertThat(t.qInstance.getTable("authentik_approval_request").getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.approve");
|
||||
assertThat(t.qInstance.getPossibleValueSource(AuthentikLocalTables.PVS_ACTION_STATUS)).isNotNull();
|
||||
|
||||
QInstance readOnly = AuthentikTestSupport.produce(AuthentikTestSupport.unitConfig());
|
||||
assertThat(readOnly.getTable("authentik_admin_action")).isNull();
|
||||
assertThat(readOnly.getProcesses()).isEmpty();
|
||||
assertThat(readOnly.getApp("authentikAdmin").getChildren()).extracting(c -> c.getName()).containsExactly("authentik_user", "authentik_group", "authentik_application");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read-only tables carry no key field for tokens and no insert capability.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void tokenTableNeverHasAKey() throws QException
|
||||
{
|
||||
AdminTestSupport t = AdminTestSupport.create();
|
||||
QTableMetaData token = t.qInstance.getTable("authentik_token");
|
||||
assertThat(token.getFields().keySet()).doesNotContain("key", "token", "secret");
|
||||
assertThat(token.getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.audit.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The home renders every card, escapes values, and shows honest states.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void homeRenders() throws Exception
|
||||
{
|
||||
AdminTestSupport t = AdminTestSupport.create();
|
||||
t.config.withBootstrapOperatorSubjects("<b>boot</b>");
|
||||
com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface widget = t.qInstance.getWidget("authentikHome");
|
||||
assertThat(widget.getPermissionRules().getPermissionBaseName()).isEqualTo("authentik.users.read");
|
||||
|
||||
RenderWidgetInput input = new RenderWidgetInput();
|
||||
input.setWidgetMetaData(widget);
|
||||
RenderWidgetOutput output = ((AbstractWidgetRenderer) new AuthentikHomeWidget.Renderer()).render(input);
|
||||
String html = ((RawHTML) output.getWidgetData()).getHtml();
|
||||
|
||||
assertThat(html).contains("Needs attention", "People", "Groups and permissions", "Recent changes", "Connection");
|
||||
assertThat(html).contains("Active</dt><dd style=\"margin:0;\">4<");
|
||||
assertThat(html).contains("Inactive</dt><dd style=\"margin:0;\">1<");
|
||||
assertThat(html).contains("Service accounts</dt><dd style=\"margin:0;\">2<");
|
||||
assertThat(html).contains("bootstrapOperatorSubjects is still set");
|
||||
assertThat(html).contains("No changes have been made from here yet.");
|
||||
assertThat(html).contains("href=\"/app/authentik_user\"").contains("href=\"/app/authentik_group\"");
|
||||
assertThat(html).doesNotContain("<b>boot</b>");
|
||||
assertThat(html).doesNotContain(AuthentikTestSupport.TEST_TOKEN);
|
||||
|
||||
t.loginAs(AuthentikTestSupport.OPERATOR, IdentityPermission.USERS_READ);
|
||||
String withoutAudit = ((RawHTML) new AuthentikHomeWidget.Renderer().render(input).getWidgetData()).getHtml();
|
||||
assertThat(withoutAudit).contains("needs the authentik.audit.read permission");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Nothing but AuthentikAdmin may send a change to Authentik: the util's
|
||||
** write method is only called from there (the guard's authorization is the
|
||||
** required argument; this keeps the call sites to one class).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void onlyTheAdminServiceWrites() throws IOException
|
||||
{
|
||||
Path root = Path.of("src/main/java/com/kingsrook/qbits/authentik");
|
||||
try(Stream<Path> files = Files.walk(root))
|
||||
{
|
||||
List<Path> callers = files.filter(p -> p.toString().endsWith(".java")).filter(p ->
|
||||
{
|
||||
try
|
||||
{
|
||||
return (Files.readString(p).contains("util.write(") || Files.readString(p).contains(".write(auth"));
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
throw (new IllegalStateException(e));
|
||||
}
|
||||
}).toList();
|
||||
assertThat(callers).extracting(p -> p.getFileName().toString()).containsExactly("AuthentikAdmin.java");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -339,7 +339,7 @@ class AuthentikActionUtilTest
|
||||
assertThat(identityAdmins.getValueString("permissions")).isEqualTo("authentik.*");
|
||||
assertThat(identityAdmins.getValueString("appAccess")).isEqualTo("kof22-website-prod");
|
||||
assertThat(identityAdmins.getValueBoolean("isSuperuser")).isFalse();
|
||||
assertThat(param(FixtureActionUtil.REQUESTS.get(0), "include_users", null)).isEqualTo("false");
|
||||
assertThat(param(FixtureActionUtil.REQUESTS.get(0), "include_users", null)).isEqualTo("true");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ public class FixtureActionUtil extends AuthentikActionUtil
|
||||
/** Body served for the group-graph sweep (GET /core/groups/?include_users=false&include_parents=false...). */
|
||||
public static String groupGraphBody = EMPTY_PAGE;
|
||||
|
||||
/** When set, serves group sweeps (include_parents=false) instead of groupGraphBody. */
|
||||
public static Function<HttpRequestBase, QHttpResponse> groupGraphHandler = null;
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -53,6 +56,7 @@ public class FixtureActionUtil extends AuthentikActionUtil
|
||||
REQUESTS.clear();
|
||||
handler = r -> response(404, "{\"detail\":\"Not found.\"}");
|
||||
groupGraphBody = EMPTY_PAGE;
|
||||
groupGraphHandler = null;
|
||||
AuthentikActionUtil.resetVersionCheck();
|
||||
}
|
||||
|
||||
@@ -71,7 +75,7 @@ public class FixtureActionUtil extends AuthentikActionUtil
|
||||
}
|
||||
if(request.getURI().getPath().endsWith("/core/groups/") && String.valueOf(request.getURI().getRawQuery()).contains("include_parents=false"))
|
||||
{
|
||||
return (response(200, groupGraphBody));
|
||||
return (groupGraphHandler != null ? groupGraphHandler.apply(request) : response(200, groupGraphBody));
|
||||
}
|
||||
return (handler.apply(request));
|
||||
}
|
||||
|
||||
@@ -200,6 +200,30 @@ public final class AuthentikTestStack
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run a command in the Authentik server container (for example `ak shell
|
||||
** -c ...`), for setup the API cannot do (creating MFA devices). Returns stdout;
|
||||
** throws when the command fails.
|
||||
*******************************************************************************/
|
||||
public String execInServer(String... command)
|
||||
{
|
||||
try
|
||||
{
|
||||
org.testcontainers.containers.Container.ExecResult result = server.execInContainer(command);
|
||||
if(result.getExitCode() != 0)
|
||||
{
|
||||
throw (new IllegalStateException("Command failed (" + result.getExitCode() + "): " + result.getStderr()));
|
||||
}
|
||||
return (result.getStdout());
|
||||
}
|
||||
catch(java.io.IOException | InterruptedException e)
|
||||
{
|
||||
throw (new IllegalStateException(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Host root, e.g. http://localhost:32768 (the qbit's baseUrl).
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.contract;
|
||||
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.RequiresDockerCondition;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyGenerator;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyParser;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyPermissions;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Pins the scope-mapping example of docs/POLICY-FORMAT.md on Authentik
|
||||
** 2026.8.3: the blueprint applies, and the mapping (run through Authentik's
|
||||
** property-mapping test endpoint) emits a claim that the qbit's parser turns
|
||||
** into the union of the user's groups' policies, including inherited parents.
|
||||
*******************************************************************************/
|
||||
@ExtendWith(RequiresDockerCondition.class)
|
||||
@Order(46)
|
||||
class PolicyClaimMappingIT
|
||||
{
|
||||
private static TestApi admin;
|
||||
private static String mappingPk;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeAll
|
||||
static void beforeAll() throws Exception
|
||||
{
|
||||
AuthentikTestStack stack = AuthentikTestStack.get();
|
||||
admin = stack.admin();
|
||||
try(InputStream in = PolicyClaimMappingIT.class.getResourceAsStream("/blueprints/qqq-policy-claim.yaml"))
|
||||
{
|
||||
stack.createContentBlueprint("qqq-policy-claim", new String(in.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
mappingPk = admin.first("/propertymappings/provider/scope/?name=qqq-policy-claim").getString("pk");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run the mapping for a user; the claim as Authentik would put it in a token.
|
||||
*******************************************************************************/
|
||||
private static JSONObject claimsFor(int userPk)
|
||||
{
|
||||
TestApi.Response response = admin.post("/propertymappings/all/" + mappingPk + "/test/", new JSONObject().put("user", userPk));
|
||||
assertThat(response.status()).as(response.body()).isEqualTo(200);
|
||||
JSONObject result = response.json();
|
||||
assertThat(result.getBoolean("successful")).as(result.toString()).isTrue();
|
||||
return (new JSONObject(result.getString("result")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A group with a canonical policy for these permissions.
|
||||
*******************************************************************************/
|
||||
private static String group(String name, String parentPk, Object policy) throws Exception
|
||||
{
|
||||
JSONObject group = new JSONObject().put("name", name).put("attributes", new JSONObject().put("qqq.io/policy", policy));
|
||||
if(parentPk != null)
|
||||
{
|
||||
group.put("parents", new JSONArray().put(parentPk));
|
||||
}
|
||||
admin.post("/core/groups/", group);
|
||||
return (admin.groupPk(name));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static int user(String username, String groupPk)
|
||||
{
|
||||
admin.post("/core/users/", new JSONObject().put("username", username).put("name", username).put("type", "internal").put("path", "users"));
|
||||
int pk = admin.userPk(username);
|
||||
if(groupPk != null)
|
||||
{
|
||||
admin.post("/core/groups/" + groupPk + "/add_user/", new JSONObject().put("pk", pk));
|
||||
}
|
||||
return (pk);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void claimIsTheUnionOfInheritedGroupPolicies() throws Exception
|
||||
{
|
||||
PolicyFormat format = PolicyFormat.DEFAULT;
|
||||
String parent = group("policy-parent", null, PolicyGenerator.toCompact(PolicyGenerator.generate(List.of("contentApp.hasAccess"), format)));
|
||||
String child = group("policy-child", parent, PolicyGenerator.toCompact(PolicyGenerator.generate(List.of("cms_page.read", "cms_page.edit"), format)));
|
||||
group("policy-object", null, PolicyGenerator.generate(List.of("objectAttr.read"), format));
|
||||
group("policy-other-spec", null, PolicyGenerator.toCompact(PolicyGenerator.generate(List.of("ignored.read"), new PolicyFormat("other", "1.0.0", "x", "y"))));
|
||||
|
||||
int member = user("policy.member", child);
|
||||
admin.post("/core/groups/" + admin.groupPk("policy-object") + "/add_user/", new JSONObject().put("pk", member));
|
||||
admin.post("/core/groups/" + admin.groupPk("policy-other-spec") + "/add_user/", new JSONObject().put("pk", member));
|
||||
|
||||
JSONObject claims = claimsFor(member);
|
||||
assertThat(claims.has("qqq_policy")).isTrue();
|
||||
assertThat(PolicyPermissions.fromClaims(claims, format))
|
||||
.as("parent (inherited), child, an object-valued attribute; another spec is skipped")
|
||||
.containsExactlyInAnyOrder("contentApp.hasAccess", "cms_page.read", "cms_page.edit", "objectAttr.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** No policies: the claim is still a valid, empty document.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void userWithoutPoliciesGetsAnEmptyDocument() throws Exception
|
||||
{
|
||||
JSONObject claims = claimsFor(user("policy.nobody", null));
|
||||
assertThat(PolicyParser.parseStrict(claims.get("qqq_policy"), PolicyFormat.DEFAULT).permissions()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.contract;
|
||||
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitProducer;
|
||||
import com.kingsrook.qbits.authentik.RequiresDockerCondition;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminAction;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminRequest;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikAdmin;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QUser;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The qbit's WRITE path against a real Authentik 2026.8.3 (DESIGN.md section
|
||||
** 10 contract tests a, f and the phase 2/3 actions), as the service account
|
||||
** holding the phase 2/3 role permissions (granted additively here and removed
|
||||
** again): create user + groups + the recovery email arriving in Mailpit,
|
||||
** membership, permission attributes (merged into the current attributes),
|
||||
** deactivation, app-password revocation that spares API tokens, the guard
|
||||
** refusing superuser groups and protected accounts before Authentik is
|
||||
** called, and the audit event naming the human operator.
|
||||
*******************************************************************************/
|
||||
@ExtendWith(RequiresDockerCondition.class)
|
||||
@Order(70)
|
||||
class QbitWriteContractIT
|
||||
{
|
||||
private static final String OPERATOR_EMAIL = "wr.operator@example.test";
|
||||
|
||||
/** The operator's own policy: they may grant read and edit on wr_page. */
|
||||
private static final String WR_POLICY = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\",\"edit\"],\"Resource\":[\"wr_page\"]}]}";
|
||||
|
||||
/** The phase 2/3 permissions of DESIGN.md section 5.1 (plus view_flow to resolve the invitation flow by slug). */
|
||||
private static final List<String> ROLE_PERMISSIONS = List.of(
|
||||
"authentik_core.add_user", "authentik_core.change_user", "authentik_core.reset_user_password",
|
||||
"authentik_core.add_group", "authentik_core.change_group", "authentik_core.add_user_to_group", "authentik_core.remove_user_from_group",
|
||||
"authentik_core.view_token", "authentik_core.delete_token", "authentik_core.delete_authenticatedsession",
|
||||
"authentik_stages_invitation.view_invitation", "authentik_stages_invitation.add_invitation", "authentik_stages_invitation.delete_invitation",
|
||||
"authentik_flows.view_flow",
|
||||
"authentik_stages_authenticator_totp.view_totpdevice", "authentik_stages_authenticator_totp.delete_totpdevice",
|
||||
"authentik_stages_authenticator_static.view_staticdevice", "authentik_stages_authenticator_static.delete_staticdevice",
|
||||
"authentik_stages_authenticator_webauthn.view_webauthndevice", "authentik_stages_authenticator_webauthn.delete_webauthndevice",
|
||||
"authentik_stages_authenticator_email.view_emaildevice", "authentik_stages_authenticator_email.delete_emaildevice",
|
||||
"authentik_stages_authenticator_sms.view_smsdevice", "authentik_stages_authenticator_sms.delete_smsdevice",
|
||||
"authentik_stages_authenticator_duo.view_duodevice", "authentik_stages_authenticator_duo.delete_duodevice");
|
||||
|
||||
private static AuthentikTestStack stack;
|
||||
private static TestApi admin;
|
||||
private static String roleUuid;
|
||||
|
||||
private QInstance qInstance;
|
||||
private AuthentikQBitConfig config;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Grant the role permissions, and create an operator who is an identity
|
||||
** administrator through a group (so the live subset rule has something to
|
||||
** resolve), plus the enrollment flow.
|
||||
*******************************************************************************/
|
||||
@BeforeAll
|
||||
static void beforeAll()
|
||||
{
|
||||
stack = AuthentikTestStack.get();
|
||||
admin = stack.admin();
|
||||
roleUuid = admin.first("/rbac/roles/?name=" + AuthentikTestStack.SERVICE_ACCOUNT).getString("pk");
|
||||
admin.post("/rbac/permissions/assigned_by_roles/" + roleUuid + "/assign/", new JSONObject().put("permissions", new JSONArray(ROLE_PERMISSIONS)));
|
||||
|
||||
admin.post("/core/groups/", new JSONObject().put("name", "wr-admins").put("attributes",
|
||||
new JSONObject().put("qqq.io/permissions", new JSONArray(List.of("authentik.*"))).put("qqq.io/app-access", new JSONArray(List.of(AuthentikTestStack.APP_SLUG)))
|
||||
.put("qqq.io/policy", WR_POLICY)));
|
||||
admin.post("/core/groups/", new JSONObject().put("name", "wr-readers").put("attributes",
|
||||
new JSONObject().put("qqq.io/permissions", new JSONArray(List.of("authentik.users.read")))));
|
||||
admin.post("/core/users/", new JSONObject().put("username", "wr.operator").put("name", "WR Operator").put("email", OPERATOR_EMAIL).put("type", "internal").put("path", "users"));
|
||||
admin.post("/core/groups/" + admin.groupPk("wr-admins") + "/add_user/", new JSONObject().put("pk", admin.userPk("wr.operator")));
|
||||
admin.post("/core/users/", new JSONObject().put("username", "wr.target").put("name", "WR Target").put("email", "wr.target@example.test").put("type", "internal").put("path", "users"));
|
||||
admin.post("/flows/instances/", new JSONObject().put("name", "wr enrollment").put("slug", "wr-enrollment").put("title", "Enroll").put("designation", "enrollment"));
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// recovery_email needs the brand to have a recovery flow ("No recovery flow //
|
||||
// set." otherwise): an owner prerequisite, documented in the checklist //
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
String brand = admin.get("/core/brands/").results().getJSONObject(0).getString("brand_uuid");
|
||||
String flow = admin.first("/flows/instances/?slug=kof22-recovery").getString("pk");
|
||||
admin.patch("/core/brands/" + brand + "/", new JSONObject().put("flow_recovery", flow));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remove the test-only grants again.
|
||||
*******************************************************************************/
|
||||
@AfterAll
|
||||
static void afterAll()
|
||||
{
|
||||
if(admin != null && roleUuid != null)
|
||||
{
|
||||
admin.patch("/rbac/permissions/assigned_by_roles/" + roleUuid + "/unassign/", new JSONObject().put("permissions", new JSONArray(ROLE_PERMISSIONS)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A fresh qbit instance (all write features, audit on the memory backend)
|
||||
** and the operator's session.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void beforeEach() throws QException
|
||||
{
|
||||
MemoryRecordStore.getInstance().reset();
|
||||
config = new AuthentikQBitConfig()
|
||||
.withBaseUrl(stack.baseUrl())
|
||||
.withApiToken(stack.serviceAccountToken())
|
||||
.withAppKey("kof22-admin")
|
||||
.withListCacheTtlSeconds(0)
|
||||
.withGroupCacheTtlSeconds(0)
|
||||
.withBulkPacingMillis(0)
|
||||
.withLocalBackendName("memory")
|
||||
.withRecoveryEmailStage("kof22-recovery-email")
|
||||
.withInvitationFlow("wr-enrollment")
|
||||
.withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES));
|
||||
|
||||
qInstance = new QInstance();
|
||||
qInstance.withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK));
|
||||
qInstance.addBackend(new QBackendMetaData().withName("memory").withBackendType(MemoryBackendModule.class));
|
||||
qInstance.addTable(new com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData().withName("wr_page").withBackendName("memory").withPrimaryKeyField("id")
|
||||
.withField(new com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData("id", com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType.INTEGER))
|
||||
.withPermissionRules(new com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules()
|
||||
.withLevel(com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS)));
|
||||
new AuthentikQBitProducer().withQBitConfig(config).produce(qInstance);
|
||||
|
||||
Set<String> permissions = new HashSet<>();
|
||||
for(IdentityPermission permission : IdentityPermission.values())
|
||||
{
|
||||
permissions.add(permission.getSessionPermission());
|
||||
}
|
||||
QSession session = new QSession();
|
||||
session.setUser(new QUser().withIdReference(OPERATOR_EMAIL).withFullName("WR Operator"));
|
||||
session.setPermissions(permissions);
|
||||
QContext.init(qInstance, session);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void afterEach()
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AuthentikAdmin.AdminResult run(AdminRequest request) throws QException
|
||||
{
|
||||
return (new AuthentikAdmin(AuthentikActionUtil.forBackend(config.getApiBackendName())).execute(request));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** (a) Create user -> add to group -> recovery email arrives in Mailpit; no
|
||||
** password is set; the operator's identity is on the user and in Authentik's
|
||||
** event log.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createUserSendsRecoveryEmailAndAuditsInAuthentik() throws Exception
|
||||
{
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.CREATE_USER, "", "contract test").with("username", "wr.created").with("name", "WR Created")
|
||||
.with("email", "wr.created@example.test").with("groups", "wr-readers"));
|
||||
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject user = admin.first("/core/users/?username=wr.created&include_groups=true");
|
||||
assertThat(user.getString("email")).isEqualTo("wr.created@example.test");
|
||||
assertThat(user.getString("path")).isEqualTo("users");
|
||||
assertThat(user.getJSONObject("attributes").getString("qqq.io/created-by")).isEqualTo(OPERATOR_EMAIL);
|
||||
assertThat(user.getJSONArray("groups_obj").getJSONObject(0).getString("name")).isEqualTo("wr-readers");
|
||||
|
||||
AuthentikTestStack.waitFor(Duration.ofSeconds(60), "the recovery email in Mailpit", () -> mailpitHas("wr.created@example.test"));
|
||||
|
||||
AuthentikTestStack.waitFor(Duration.ofSeconds(30), "the audit event naming the operator", () ->
|
||||
{
|
||||
for(Object event : admin.get("/events/events/?search=" + TestApi.encode(OPERATOR_EMAIL) + "&ordering=-created").results())
|
||||
{
|
||||
JSONObject context = ((JSONObject) event).optJSONObject("context");
|
||||
if(((JSONObject) event).getString("action").startsWith("custom_") && context != null && "CREATE_USER".equals(context.optString("action")))
|
||||
{
|
||||
return (OPERATOR_EMAIL.equals(context.optString("operator")) && "contract test".equals(context.optString("reason")));
|
||||
}
|
||||
}
|
||||
return (false);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Memberships both ways, with the subset rule using the operator's live
|
||||
** groups (wr-admins holds authentik.*, so adding to wr-readers is allowed).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void addAndRemoveMember() throws Exception
|
||||
{
|
||||
int target = admin.userPk("wr.target");
|
||||
String group = admin.groupPk("wr-readers");
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.ADD_MEMBER, group + ":" + target, "contract test")).ok()).isTrue();
|
||||
assertThat(memberNames("wr-readers")).contains("wr.target");
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.REMOVE_MEMBER, group + ":" + target, "contract test")).ok()).isTrue();
|
||||
assertThat(memberNames("wr-readers")).doesNotContain("wr.target");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The guard refuses a superuser group and a protected account BEFORE
|
||||
** Authentik is called (Authentik itself would refuse the first, and allow the
|
||||
** second: contract test (b) and the lockout findings).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void guardRefusesBeforeAuthentikIsCalled() throws Exception
|
||||
{
|
||||
int target = admin.userPk("wr.target");
|
||||
String superuser = admin.groupPk(AuthentikTestStack.SUPERUSER_GROUP);
|
||||
|
||||
AuthentikAdmin.AdminResult toSuperuser = run(AdminRequest.of(AdminAction.ADD_MEMBER, superuser + ":" + target, "contract test"));
|
||||
assertThat(toSuperuser.ok()).isFalse();
|
||||
assertThat(toSuperuser.message()).containsIgnoringCase("superuser");
|
||||
|
||||
AuthentikAdmin.AdminResult breakGlass = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, String.valueOf(admin.userPk(AuthentikTestStack.BREAK_GLASS)), "contract test")
|
||||
.with("confirmText", AuthentikTestStack.BREAK_GLASS));
|
||||
assertThat(breakGlass.ok()).isFalse();
|
||||
assertThat(breakGlass.message()).containsIgnoringCase("protected");
|
||||
assertThat(admin.get("/core/users/" + admin.userPk(AuthentikTestStack.BREAK_GLASS) + "/").json().getBoolean("is_active")).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Editing permissions merges only the two qqq.io keys into the group's
|
||||
** CURRENT attributes, so something set in the Authentik UI survives.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editPermissionsKeepsOtherAttributes() throws Exception
|
||||
{
|
||||
admin.post("/core/groups/", new JSONObject().put("name", "wr-merge").put("attributes", new JSONObject().put("owner-note", "set in the Authentik UI")));
|
||||
String pk = admin.groupPk("wr-merge");
|
||||
|
||||
config.withTwoPersonApproval(false);
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_PERMISSIONS, pk, "contract test")
|
||||
.with("permissions", "authentik.users.read").with("appAccess", AuthentikTestStack.APP_SLUG));
|
||||
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject attributes = admin.get("/core/groups/" + pk + "/").json().getJSONObject("attributes");
|
||||
assertThat(attributes.getString("owner-note")).isEqualTo("set in the Authentik UI");
|
||||
assertThat(attributes.getJSONArray("qqq.io/permissions").toList()).containsExactly("authentik.users.read");
|
||||
assertThat(attributes.getJSONArray("qqq.io/app-access").toList()).containsExactly(AuthentikTestStack.APP_SLUG);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Save a policy on a real Authentik: the canonical compact string lands in
|
||||
** the group's attributes next to the others, the qbit reads it back, and a
|
||||
** grant the operator does not hold is refused.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void savePolicy() throws Exception
|
||||
{
|
||||
admin.post("/core/groups/", new JSONObject().put("name", "wr-policy").put("attributes", new JSONObject().put("owner-note", "set in the Authentik UI")));
|
||||
String pk = admin.groupPk("wr-policy");
|
||||
String document = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\",\"delete\"],\"Resource\":[\"wr_page\"]}]}";
|
||||
|
||||
AuthentikAdmin.AdminResult escalation = run(AdminRequest.of(AdminAction.SAVE_POLICY, pk, "contract test").with(AuthentikAdmin.POLICY_DOCUMENT, document));
|
||||
assertThat(escalation.ok()).isFalse();
|
||||
assertThat(escalation.message()).contains("wr_page.delete");
|
||||
|
||||
String allowed = document.replace(",\"delete\"", "");
|
||||
AuthentikAdmin.AdminResult saved = run(AdminRequest.of(AdminAction.SAVE_POLICY, pk, "contract test").with(AuthentikAdmin.POLICY_DOCUMENT, allowed));
|
||||
assertThat(saved.ok()).as(saved.message()).isTrue();
|
||||
|
||||
JSONObject attributes = admin.get("/core/groups/" + pk + "/").json().getJSONObject("attributes");
|
||||
assertThat(attributes.getString("owner-note")).isEqualTo("set in the Authentik UI");
|
||||
assertThat(attributes.getString("qqq.io/policy")).isEqualTo("{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"wr_page\"]}]}");
|
||||
assertThat(AuthentikActionUtil.forBackend(config.getApiBackendName()).groupGraph().byPk(pk).policyPermissions()).containsExactly("wr_page.read");
|
||||
|
||||
AuthentikAdmin.AdminResult cleared = run(AdminRequest.of(AdminAction.SAVE_POLICY, pk, "contract test").with(AuthentikAdmin.POLICY_DOCUMENT, ""));
|
||||
assertThat(cleared.ok()).as(cleared.message()).isTrue();
|
||||
assertThat(admin.get("/core/groups/" + pk + "/").json().getJSONObject("attributes").has("qqq.io/policy")).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Group create and edit (parents), and the superuser parent refused by the
|
||||
** guard.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createAndEditGroup() throws Exception
|
||||
{
|
||||
AuthentikAdmin.AdminResult created = run(AdminRequest.of(AdminAction.CREATE_GROUP, "", "contract test").with("name", "wr-child").with("parents", "wr-readers"));
|
||||
assertThat(created.ok()).as(created.message()).isTrue();
|
||||
JSONObject group = admin.get("/core/groups/" + admin.groupPk("wr-child") + "/").json();
|
||||
assertThat(group.getJSONArray("parents").getString(0)).isEqualTo(admin.groupPk("wr-readers"));
|
||||
assertThat(group.getBoolean("is_superuser")).isFalse();
|
||||
|
||||
AuthentikAdmin.AdminResult renamed = run(AdminRequest.of(AdminAction.EDIT_GROUP, admin.groupPk("wr-child"), "contract test").with("name", "wr-child-renamed"));
|
||||
assertThat(renamed.ok()).as(renamed.message()).isTrue();
|
||||
assertThat(admin.groupPk("wr-child-renamed")).isEqualTo(admin.groupPk("wr-child-renamed"));
|
||||
|
||||
AuthentikAdmin.AdminResult superuserParent = run(AdminRequest.of(AdminAction.EDIT_GROUP, admin.groupPk("wr-child-renamed"), "contract test").with("parents", AuthentikTestStack.SUPERUSER_GROUP));
|
||||
assertThat(superuserParent.ok()).isFalse();
|
||||
assertThat(superuserParent.message()).containsIgnoringCase("superuser");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** (f) Deactivate: the user is inactive; app passwords go when asked, API
|
||||
** tokens never do. Reactivate restores.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void deactivateRevokesOnlyAppPasswords() throws Exception
|
||||
{
|
||||
admin.post("/core/users/", new JSONObject().put("username", "wr.deact").put("name", "WR Deact").put("email", "wr.deact@example.test").put("type", "internal").put("path", "users"));
|
||||
int pk = admin.userPk("wr.deact");
|
||||
admin.post("/core/tokens/", new JSONObject().put("identifier", "wr-deact-app").put("intent", "app_password").put("user", pk).put("expiring", false));
|
||||
admin.post("/core/tokens/", new JSONObject().put("identifier", "wr-deact-api").put("intent", "api").put("user", pk).put("expiring", false));
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.DEACTIVATE_USER, String.valueOf(pk), "contract test").with("confirmText", "wr.deact").with("revokeAppPasswords", true));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(admin.get("/core/users/" + pk + "/").json().getBoolean("is_active")).isFalse();
|
||||
assertThat(admin.get("/core/tokens/?identifier=wr-deact-app").results().length()).isZero();
|
||||
assertThat(admin.get("/core/tokens/?identifier=wr-deact-api").results().length()).isEqualTo(1);
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.REACTIVATE_USER, String.valueOf(pk), "contract test")).ok()).isTrue();
|
||||
assertThat(admin.get("/core/users/" + pk + "/").json().getBoolean("is_active")).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Edit user and the password-reset email (Authentik's own email; the link is
|
||||
** never shown to the operator).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editUserAndPasswordReset() throws Exception
|
||||
{
|
||||
int pk = admin.userPk("wr.target");
|
||||
AuthentikAdmin.AdminResult edit = run(AdminRequest.of(AdminAction.EDIT_USER, String.valueOf(pk), "contract test").with("name", "WR Target Renamed")
|
||||
.with("email", "wr.target@example.test").with("path", "users"));
|
||||
assertThat(edit.ok()).as(edit.message()).isTrue();
|
||||
assertThat(admin.get("/core/users/" + pk + "/").json().getString("name")).isEqualTo("WR Target Renamed");
|
||||
|
||||
AuthentikAdmin.AdminResult reset = run(AdminRequest.of(AdminAction.SEND_RECOVERY_EMAIL, String.valueOf(pk), "contract test"));
|
||||
assertThat(reset.ok()).as(reset.message()).isTrue();
|
||||
assertThat(reset.message()).doesNotContain("http");
|
||||
AuthentikTestStack.waitFor(Duration.ofSeconds(60), "the reset email in Mailpit", () -> mailpitHas("wr.target@example.test"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Invitations: create (with its email through the enrollment flow's slug
|
||||
** resolved by the qbit) and cancel.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void inviteAndCancel() throws Exception
|
||||
{
|
||||
AuthentikAdmin.AdminResult invite = run(AdminRequest.of(AdminAction.INVITE_USER, "", "contract test").with("email", "wr.invited@example.test"));
|
||||
assertThat(invite.ok()).as(invite.message()).isTrue();
|
||||
|
||||
JSONArray invitations = admin.get("/stages/invitation/invitations/").results();
|
||||
String pk = null;
|
||||
for(int i = 0; i < invitations.length(); i++)
|
||||
{
|
||||
if("wr.invited@example.test".equals(invitations.getJSONObject(i).getJSONObject("fixed_data").optString("email")))
|
||||
{
|
||||
pk = invitations.getJSONObject(i).getString("pk");
|
||||
}
|
||||
}
|
||||
assertThat(pk).isNotNull();
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.CANCEL_INVITATION, pk, "contract test")).ok()).isTrue();
|
||||
assertThat(admin.get("/stages/invitation/invitations/" + pk + "/").status()).isEqualTo(404);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Reset MFA: the device list is a bare array (not a paged object) whose type
|
||||
** strings map to the delete endpoints; both device kinds are removed and a
|
||||
** second reset finds nothing to do. (Devices are created in the server
|
||||
** container because the admin API cannot create them for another user.)
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void resetMfaRemovesEveryDevice() throws Exception
|
||||
{
|
||||
admin.post("/core/users/", new JSONObject().put("username", "wr.mfa").put("name", "WR MFA").put("email", "wr.mfa@example.test").put("type", "internal").put("path", "users"));
|
||||
int pk = admin.userPk("wr.mfa");
|
||||
stack.execInServer("ak", "shell", "-c",
|
||||
"from authentik.core.models import User; from authentik.stages.authenticator_totp.models import TOTPDevice; "
|
||||
+ "from authentik.stages.authenticator_static.models import StaticDevice; u = User.objects.get(username='wr.mfa'); "
|
||||
+ "TOTPDevice.objects.create(user=u, name='wr-totp', confirmed=True); StaticDevice.objects.create(user=u, name='wr-static', confirmed=True)");
|
||||
JSONArray before = new JSONArray(admin.get("/authenticators/admin/all/?user=" + pk).body());
|
||||
assertThat(before.length()).isEqualTo(2);
|
||||
for(int i = 0; i < before.length(); i++)
|
||||
{
|
||||
assertThat(AuthentikAdmin.devicePath(before.getJSONObject(i))).as(before.getJSONObject(i).toString()).startsWith("/authenticators/admin/");
|
||||
}
|
||||
|
||||
AuthentikAdmin.AdminResult untyped = run(AdminRequest.of(AdminAction.RESET_MFA, String.valueOf(pk), "contract test"));
|
||||
assertThat(untyped.ok()).isFalse();
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.RESET_MFA, String.valueOf(pk), "contract test").with("confirmText", "wr.mfa"));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
assertThat(new JSONArray(admin.get("/authenticators/admin/all/?user=" + pk).body()).length()).isZero();
|
||||
assertThat(run(AdminRequest.of(AdminAction.RESET_MFA, String.valueOf(pk), "contract test").with("confirmText", "wr.mfa")).noChange()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private List<String> memberNames(String groupName)
|
||||
{
|
||||
JSONArray users = admin.get("/core/groups/" + admin.groupPk(groupName) + "/?include_users=true").json().getJSONArray("users_obj");
|
||||
java.util.ArrayList<String> rs = new java.util.ArrayList<>();
|
||||
for(int i = 0; i < users.length(); i++)
|
||||
{
|
||||
rs.add(users.getJSONObject(i).getString("username"));
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether Mailpit holds a message addressed to this address.
|
||||
*******************************************************************************/
|
||||
private boolean mailpitHas(String address)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpResponse<String> response = HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(stack.mailpitRoot() + "/api/v1/messages")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
JSONArray messages = new JSONObject(response.body()).optJSONArray("messages");
|
||||
for(int i = 0; messages != null && i < messages.length(); i++)
|
||||
{
|
||||
JSONArray to = messages.getJSONObject(i).optJSONArray("To");
|
||||
for(int j = 0; to != null && j < to.length(); j++)
|
||||
{
|
||||
if(address.equalsIgnoreCase(to.getJSONObject(j).optString("Address")))
|
||||
{
|
||||
return (true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+114
-3
@@ -55,7 +55,7 @@ class AuthentikGroupPermissionMapperTest
|
||||
void beforeEach() throws QException
|
||||
{
|
||||
FixtureActionUtil.reset();
|
||||
config = AuthentikTestSupport.unitConfig().withGroupCacheTtlSeconds(0).withBootstrapOperators("Boot@Example.Test");
|
||||
config = AuthentikTestSupport.unitConfig().withGroupCacheTtlSeconds(0).withBootstrapOperatorSubjects("opaque-sub-123, 42");
|
||||
qInstance = AuthentikTestSupport.produce(config);
|
||||
AuthentikTestSupport.useActionUtil(qInstance, config, FixtureActionUtil.class);
|
||||
QContext.init(qInstance, new QSession());
|
||||
@@ -88,10 +88,121 @@ class AuthentikGroupPermissionMapperTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static Map<String, Object> subjectContext(String sub, String email, boolean verified)
|
||||
{
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put(AuthentikGroupPermissionMapper.CLAIMS_CONTEXT_KEY,
|
||||
new JSONObject().put("sub", sub).put("email", email).put("email_verified", verified).put("groups", new JSONArray()));
|
||||
return (context);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Serve /core/users/?email= with these users (everything else as before).
|
||||
*******************************************************************************/
|
||||
private static void usersWithEmail(JSONObject... users)
|
||||
{
|
||||
java.util.function.Function<org.apache.http.client.methods.HttpRequestBase, com.kingsrook.qqq.backend.module.api.actions.QHttpResponse> previous = FixtureActionUtil.handler;
|
||||
FixtureActionUtil.handler = request ->
|
||||
{
|
||||
if(request.getURI().getPath().endsWith("/core/users/") && String.valueOf(request.getURI().getRawQuery()).contains("email="))
|
||||
{
|
||||
return (FixtureActionUtil.response(200, new JSONObject().put("pagination", new JSONObject().put("count", users.length).put("current", 1).put("total_pages", 1))
|
||||
.put("results", new JSONArray(users)).toString()));
|
||||
}
|
||||
return (previous.apply(request));
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static JSONObject user(int pk, String email)
|
||||
{
|
||||
return (new JSONObject().put("pk", pk).put("uuid", "uuid-" + pk).put("email", email).put("is_active", true).put("username", "u" + pk));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Bootstrap operators are keyed on immutable ids, never on an email: a
|
||||
** spoofed email (duplicate, or a different user) is denied, an unverified
|
||||
** email is denied, a matching sub or a verified unique user is granted.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void bootstrapIsNotEmailBased()
|
||||
{
|
||||
AuthentikGroupPermissionMapper mapper = new AuthentikGroupPermissionMapper();
|
||||
String grant = IdentityPermission.MEMBERSHIPS_MANAGE.getSessionPermission();
|
||||
|
||||
// the attacker set their email to the owner's: two users share it, sub differs
|
||||
usersWithEmail(user(42, "owner@example.test"), user(99, "owner@example.test"));
|
||||
QSession duplicate = new QSession();
|
||||
mapper.customizeSession(qInstance, duplicate, subjectContext("attacker-sub", "owner@example.test", true));
|
||||
assertThat(duplicate.getPermissions()).doesNotContain(grant);
|
||||
|
||||
// only the attacker has that email, but their pk is not a configured subject
|
||||
usersWithEmail(user(99, "owner@example.test"));
|
||||
QSession other = new QSession();
|
||||
mapper.customizeSession(qInstance, other, subjectContext("attacker-sub", "owner@example.test", true));
|
||||
assertThat(other.getPermissions()).doesNotContain(grant);
|
||||
|
||||
// the right user, but the token's email is not verified
|
||||
usersWithEmail(user(42, "owner@example.test"));
|
||||
QSession unverified = new QSession();
|
||||
mapper.customizeSession(qInstance, unverified, subjectContext("some-sub", "owner@example.test", false));
|
||||
assertThat(unverified.getPermissions()).doesNotContain(grant);
|
||||
|
||||
// an email-looking sub never counts, even if it equals a configured value
|
||||
QSession emailSub = new QSession();
|
||||
mapper.customizeSession(qInstance, emailSub, subjectContext("owner@example.test", "x@example.test", false));
|
||||
assertThat(emailSub.getPermissions()).doesNotContain(grant);
|
||||
|
||||
// verified email, exactly one active user, pk is a configured subject
|
||||
QSession good = new QSession();
|
||||
mapper.customizeSession(qInstance, good, subjectContext("some-sub", "owner@example.test", true));
|
||||
assertThat(good.getPermissions()).contains(grant);
|
||||
|
||||
// the Authentik lookup failing denies
|
||||
FixtureActionUtil.handler = request -> FixtureActionUtil.response(500, "boom");
|
||||
QSession down = new QSession();
|
||||
mapper.customizeSession(qInstance, down, subjectContext("some-sub", "owner@example.test", true));
|
||||
assertThat(down.getPermissions()).doesNotContain(grant);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Inherited authentik.* through a child group; existing permissions kept.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void policyClaimIsAdded()
|
||||
{
|
||||
String policy = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"cms_page\"]}]}";
|
||||
Map<String, Object> ctx = context("someone@example.test", new JSONArray());
|
||||
ctx.put("idToken", new JSONObject().put("qqq_policy", policy));
|
||||
QSession session = new QSession();
|
||||
new AuthentikGroupPermissionMapper().customizeSession(qInstance, session, ctx);
|
||||
assertThat(session.getPermissions()).contains("cms_page.read");
|
||||
|
||||
ctx.put("idToken", new JSONObject().put("qqq_policy", policy.replace("Allow", "Deny")));
|
||||
QSession denied = new QSession();
|
||||
new AuthentikGroupPermissionMapper().customizeSession(qInstance, denied, ctx);
|
||||
assertThat(denied.getPermissions()).doesNotContain("cms_page.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void groupsBecomePermissions()
|
||||
{
|
||||
QSession session = new QSession();
|
||||
@@ -120,7 +231,7 @@ class AuthentikGroupPermissionMapperTest
|
||||
assertThat(admin.getPermissions()).contains("adminEsb.hasAccess").doesNotContain(IdentityPermission.USERS_READ.getSessionPermission());
|
||||
|
||||
QSession boot = new QSession();
|
||||
mapper.customizeSession(qInstance, boot, context("boot@example.test", new JSONArray()));
|
||||
mapper.customizeSession(qInstance, boot, subjectContext("opaque-sub-123", "boot@example.test", false));
|
||||
assertThat(boot.getPermissions()).contains(IdentityPermission.MEMBERSHIPS_MANAGE.getSessionPermission());
|
||||
|
||||
QSession none = new QSession();
|
||||
@@ -151,7 +262,7 @@ class AuthentikGroupPermissionMapperTest
|
||||
return ("nope");
|
||||
}
|
||||
};
|
||||
assertThat(wrongBackend.resolve(qInstance, List.of("phase1-child-of-identity-admins"), "x@example.test")).isEmpty();
|
||||
assertThat(wrongBackend.resolve(qInstance, List.of("phase1-child-of-identity-admins"), "s", "x@example.test", false)).isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.authentik.policy.PolicyParserTest.document;
|
||||
import static com.kingsrook.qbits.authentik.policy.PolicyParserTest.statement;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Unit tests for AuthentikPolicyClaimMapper and PolicyPermissions.
|
||||
*******************************************************************************/
|
||||
class AuthentikPolicyClaimMapperTest
|
||||
{
|
||||
private static final String READ_PAGE = document(statement("Allow", List.of("read"), List.of("cms_page"))).toString();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static QSession run(AuthentikPolicyClaimMapper mapper, Map<String, Object> context)
|
||||
{
|
||||
QSession session = new QSession();
|
||||
session.setPermissions(Set.of("existing.hasAccess"));
|
||||
mapper.customizeSession(null, session, context);
|
||||
return (session);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The claim as a string (the scope mapping's json.dumps) in the ID token.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void stringClaimInIdToken()
|
||||
{
|
||||
QSession session = run(new AuthentikPolicyClaimMapper(), Map.of("idToken", new JSONObject().put("qqq_policy", READ_PAGE)));
|
||||
assertThat(session.getPermissions()).containsExactlyInAnyOrder("existing.hasAccess", "cms_page.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An object claim in the access token (session resume: no ID token).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void objectClaimInAccessToken()
|
||||
{
|
||||
QSession session = run(new AuthentikPolicyClaimMapper(), Map.of("jwtPayloadJsonObject", new JSONObject().put("qqq_policy", new JSONObject(READ_PAGE))));
|
||||
assertThat(session.getPermissions()).contains("cms_page.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The ID token wins when both carry the claim; the access token is used when
|
||||
** only it has the claim.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void idTokenPreferred()
|
||||
{
|
||||
String other = document(statement("Allow", List.of("edit"), List.of("other"))).toString();
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put("idToken", new JSONObject().put("qqq_policy", READ_PAGE));
|
||||
context.put("jwtPayloadJsonObject", new JSONObject().put("qqq_policy", other));
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), context).getPermissions()).contains("cms_page.read").doesNotContain("other.edit");
|
||||
|
||||
context.put("idToken", new JSONObject().put("email", "a@example.test"));
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), context).getPermissions()).contains("other.edit");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Missing or invalid claims add nothing and keep what the session had.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void failsClosed()
|
||||
{
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), Map.of()).getPermissions()).containsExactly("existing.hasAccess");
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), null).getPermissions()).containsExactly("existing.hasAccess");
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), Map.of("idToken", new JSONObject().put("qqq_policy", "{}"))).getPermissions()).containsExactly("existing.hasAccess");
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), Map.of("idToken", new JSONObject().put("qqq_policy", "garbage"))).getPermissions()).containsExactly("existing.hasAccess");
|
||||
assertThat(run(new AuthentikPolicyClaimMapper(), Map.of("idToken", "not claims")).getPermissions()).containsExactly("existing.hasAccess");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A host's own names (spec, claim).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void customFormat()
|
||||
{
|
||||
PolicyFormat custom = new PolicyFormat("acme-iam", "1.0.0", "policies", "policies");
|
||||
String doc = new JSONObject(READ_PAGE).put("PolicySpec", "acme-iam").toString();
|
||||
|
||||
QSession session = run(new AuthentikPolicyClaimMapper().withFormat(custom), Map.of("idToken", Map.of("policies", doc)));
|
||||
assertThat(session.getPermissions()).contains("cms_page.read");
|
||||
assertThat(new AuthentikPolicyClaimMapper().withFormat(null).getFormat()).isEqualTo(PolicyFormat.DEFAULT);
|
||||
|
||||
assertThat(PolicyPermissions.fromClaims(new JSONObject().put("policies", doc), custom)).containsExactly("cms_page.read");
|
||||
assertThat(PolicyPermissions.fromClaims(null, custom)).isEmpty();
|
||||
assertThat(PolicyPermissions.claimsWithPolicy(null, null)).isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The security-key hook runs before permissions, with the claims, even when
|
||||
** the token has no policy claim.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void securityKeyHook()
|
||||
{
|
||||
List<String> calls = new ArrayList<>();
|
||||
AuthentikPolicyClaimMapper mapper = new AuthentikPolicyClaimMapper()
|
||||
{
|
||||
@Override
|
||||
protected void applySecurityKeys(QSession qSession, JSONObject claims)
|
||||
{
|
||||
calls.add(claims.optString("tenant") + ":" + qSession.getPermissions().contains("cms_page.read"));
|
||||
}
|
||||
};
|
||||
run(mapper, Map.of("idToken", new JSONObject().put("tenant", "t1").put("qqq_policy", READ_PAGE)));
|
||||
run(mapper, Map.of("jwtPayloadJsonObject", new JSONObject().put("tenant", "t2")));
|
||||
assertThat(calls).containsExactly("t1:false", "t2:false");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.reporting.QReportMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Unit tests for PolicyCatalog: the editor's enumeration of what a policy can
|
||||
** grant in a QInstance, grouped by app.
|
||||
*******************************************************************************/
|
||||
class PolicyCatalogTest
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static QPermissionRules rules(PermissionLevel level)
|
||||
{
|
||||
return (new QPermissionRules().withLevel(level));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static QTableMetaData table(String name, String label, PermissionLevel level)
|
||||
{
|
||||
return (new QTableMetaData().withName(name).withLabel(label).withBackendName("memory").withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER)).withPermissionRules(rules(level)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An instance with every kind of object and permission shape.
|
||||
*******************************************************************************/
|
||||
static QInstance instance()
|
||||
{
|
||||
QInstance instance = new QInstance();
|
||||
instance.addBackend(new QBackendMetaData().withName("memory").withBackendType(MemoryBackendModule.class));
|
||||
|
||||
QTableMetaData page = table("cms_page", "Pages", PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS);
|
||||
QTableMetaData audit = table("cms_audit", "Audit", PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS).withoutCapabilities(Capability.TABLE_INSERT, Capability.TABLE_UPDATE, Capability.TABLE_DELETE);
|
||||
QTableMetaData legacy = table("legacy", "Legacy", PermissionLevel.READ_WRITE_PERMISSIONS);
|
||||
QTableMetaData gate = table("gate", "Gate", PermissionLevel.HAS_ACCESS_PERMISSION);
|
||||
QTableMetaData shared1 = table("shared_one", "Shared One", PermissionLevel.HAS_ACCESS_PERMISSION);
|
||||
shared1.getPermissionRules().setPermissionBaseName("shared_base");
|
||||
QTableMetaData shared2 = table("shared_two", "Shared Two", PermissionLevel.HAS_ACCESS_PERMISSION);
|
||||
shared2.getPermissionRules().setPermissionBaseName("shared_base");
|
||||
QTableMetaData open = table("open_table", "Open", PermissionLevel.NOT_PROTECTED);
|
||||
QTableMetaData dotted = table("dotted", "Dotted", PermissionLevel.HAS_ACCESS_PERMISSION);
|
||||
dotted.getPermissionRules().setPermissionBaseName("cms.publish");
|
||||
QTableMetaData orphan = table("orphan", "Orphan", PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS);
|
||||
for(QTableMetaData t : List.of(page, audit, legacy, gate, shared1, shared2, open, dotted, orphan))
|
||||
{
|
||||
instance.addTable(t);
|
||||
}
|
||||
|
||||
instance.addProcess(new QProcessMetaData().withName("publishPage").withLabel("Publish").withTableName("cms_page").withIsHidden(true)
|
||||
.withPermissionRules(rules(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addProcess(new QProcessMetaData().withName("loose").withLabel("Loose").withPermissionRules(rules(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addReport(new QReportMetaData().withName("pageReport").withLabel("Page Report").withPermissionRules(rules(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addWidget(new QWidgetMetaData().withName("pageStats").withLabel("Page Stats").withPermissionRules(rules(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addWidget(new QWidgetMetaData().withName("openWidget").withLabel("Open Widget").withPermissionRules(rules(PermissionLevel.NOT_PROTECTED)));
|
||||
|
||||
instance.addApp(new QAppMetaData().withName("content").withLabel("Content").withSortOrder(1)
|
||||
.withChild(page).withChild(audit).withChild(legacy).withChild(gate).withChild(shared1).withChild(shared2).withChild(open).withChild(dotted)
|
||||
.withChild(instance.getReport("pageReport")).withWidgets(List.of("pageStats"))
|
||||
.withPermissionRules(rules(PermissionLevel.HAS_ACCESS_PERMISSION)));
|
||||
instance.addApp(new QAppMetaData().withName("emptyApp").withLabel("Empty").withSortOrder(2).withPermissionRules(rules(PermissionLevel.NOT_PROTECTED)));
|
||||
return (instance);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void groupsByAppWithTheActionsQqqChecks()
|
||||
{
|
||||
PolicyCatalog catalog = PolicyCatalog.of(instance());
|
||||
|
||||
assertThat(catalog.getGroups()).extracting(PolicyCatalog.Group::label).containsExactly("Content", "Other");
|
||||
PolicyCatalog.Group content = catalog.getGroups().get(0);
|
||||
assertThat(content.resources()).extracting(PolicyCatalog.Resource::name)
|
||||
.containsExactly("content", "cms_audit", "gate", "legacy", "cms_page", "shared_base", "publishPage", "pageReport", "pageStats");
|
||||
|
||||
assertThat(catalog.get("content").actions()).containsExactly(PolicyAction.HAS_ACCESS);
|
||||
assertThat(catalog.get("cms_page").actions()).containsExactly(PolicyAction.READ, PolicyAction.INSERT, PolicyAction.EDIT, PolicyAction.DELETE);
|
||||
assertThat(catalog.get("cms_audit").actions()).as("capabilities limit the actions").containsExactly(PolicyAction.READ);
|
||||
assertThat(catalog.get("legacy").actions()).containsExactly(PolicyAction.READ);
|
||||
assertThat(catalog.get("legacy").note()).contains("write permission");
|
||||
assertThat(catalog.get("gate").actions()).containsExactly(PolicyAction.HAS_ACCESS);
|
||||
assertThat(catalog.get("publishPage").kind()).isEqualTo(PolicyCatalog.Kind.PROCESS);
|
||||
assertThat(catalog.get("publishPage").label()).as("a hidden record action, with its table").isEqualTo("Publish (Pages action)");
|
||||
assertThat(catalog.get("shared_base").label()).as("one entry per base name").isEqualTo("Shared One / Shared Two");
|
||||
|
||||
assertThat(catalog.getGroups().get(1).resources()).extracting(PolicyCatalog.Resource::name).containsExactly("orphan", "loose");
|
||||
assertThat(catalog.get("open_table")).as("not protected: nothing to grant").isNull();
|
||||
assertThat(catalog.get("openWidget")).isNull();
|
||||
assertThat(catalog.get("emptyApp")).isNull();
|
||||
assertThat(catalog.get("cms.publish")).as("a dotted base name cannot be a resource").isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void permissionNamesAndUnknowns()
|
||||
{
|
||||
PolicyCatalog catalog = PolicyCatalog.of(instance());
|
||||
assertThat(catalog.permissionNames()).contains("cms_page.read", "cms_page.delete", "content.hasAccess", "publishPage.hasAccess", "pageReport.hasAccess")
|
||||
.doesNotContain("cms_page.hasAccess", "cms_audit.edit", "open_table.read");
|
||||
assertThat(catalog.unknownPermissions(Set.of("cms_page.read", "cms_page.hasAccess", "gone.read"))).containsExactly("cms_page.hasAccess", "gone.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void json()
|
||||
{
|
||||
JSONArray json = PolicyCatalog.of(instance()).toJson();
|
||||
JSONObject content = json.getJSONObject(0);
|
||||
assertThat(content.getString("app")).isEqualTo("content");
|
||||
assertThat(content.getString("label")).isEqualTo("Content");
|
||||
JSONObject legacy = content.getJSONArray("resources").getJSONObject(3);
|
||||
assertThat(legacy.getString("name")).isEqualTo("legacy");
|
||||
assertThat(legacy.getString("kind")).isEqualTo("TABLE");
|
||||
assertThat(legacy.getJSONArray("actions").toList()).containsExactly("read");
|
||||
assertThat(legacy.has("note")).isTrue();
|
||||
assertThat(json.getJSONObject(1).isNull("app")).isTrue();
|
||||
assertThat(PolicyCatalog.of(new QInstance()).getGroups()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Unit tests for PolicyGenerator: canonical form and the round trip.
|
||||
*******************************************************************************/
|
||||
class PolicyGeneratorTest
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void canonicalForm() throws Exception
|
||||
{
|
||||
JSONObject doc = PolicyGenerator.generate(List.of("cms_page.edit", "contentApp.hasAccess", "cms_page.read", "cms_media.read"), PolicyFormat.DEFAULT);
|
||||
|
||||
assertThat(PolicyGenerator.toCompact(doc)).isEqualTo("{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":[\"hasAccess\"],\"Resource\":[\"contentApp\"]},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"cms_media\",\"cms_page\"]},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":[\"edit\"],\"Resource\":[\"cms_page\"]}]}");
|
||||
|
||||
assertThat(PolicyGenerator.toPretty(doc)).isEqualTo("""
|
||||
{
|
||||
"PolicySpec": "qqq-iam",
|
||||
"PolicyVersion": "1.0.0",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["hasAccess"],
|
||||
"Resource": [
|
||||
"contentApp"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["read"],
|
||||
"Resource": [
|
||||
"cms_media",
|
||||
"cms_page"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["edit"],
|
||||
"Resource": [
|
||||
"cms_page"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void emptyDocument() throws Exception
|
||||
{
|
||||
JSONObject doc = PolicyGenerator.generate(List.of(), PolicyFormat.DEFAULT);
|
||||
assertThat(PolicyGenerator.toCompact(doc)).isEqualTo("{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[]}\n".trim());
|
||||
assertThat(PolicyGenerator.toPretty(doc)).isEqualTo("{\n \"PolicySpec\": \"qqq-iam\",\n \"PolicyVersion\": \"1.0.0\",\n \"Statement\": []\n}\n");
|
||||
assertThat(PolicyParser.parseStrict(PolicyGenerator.toPretty(doc), PolicyFormat.DEFAULT).permissions()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** parse(generate(x)) == x for many random permission sets, in both forms,
|
||||
** and generate(parse(doc)) is stable (canonical).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void roundTripRandomSets() throws Exception
|
||||
{
|
||||
Random random = new Random(20261013);
|
||||
List<String> resources = List.of("a", "B_2", "cms_page", "contentApp", "x9", "authentik_user", "publishPage");
|
||||
for(int run = 0; run < 500; run++)
|
||||
{
|
||||
Set<String> permissions = new TreeSet<>();
|
||||
for(String resource : resources)
|
||||
{
|
||||
for(PolicyAction action : PolicyAction.values())
|
||||
{
|
||||
if(random.nextInt(3) == 0)
|
||||
{
|
||||
permissions.add(action.permission(resource));
|
||||
}
|
||||
}
|
||||
}
|
||||
JSONObject doc = PolicyGenerator.generate(permissions, PolicyFormat.DEFAULT);
|
||||
assertThat(PolicyParser.parseStrict(PolicyGenerator.toCompact(doc), PolicyFormat.DEFAULT).permissions()).isEqualTo(permissions);
|
||||
assertThat(PolicyParser.parseStrict(PolicyGenerator.toPretty(doc), PolicyFormat.DEFAULT).permissions()).isEqualTo(permissions);
|
||||
assertThat(PolicyGenerator.toCompact(PolicyGenerator.canonical(PolicyGenerator.toPretty(doc), PolicyFormat.DEFAULT))).isEqualTo(PolicyGenerator.toCompact(doc));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A hand-written document with "*" and repeated statements becomes the
|
||||
** canonical one with the same grants.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void canonicalizesHandWrittenDocuments() throws Exception
|
||||
{
|
||||
String hand = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":[\"*\"],\"Resource\":[\"b\"]},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":[\"read\",\"read\"],\"Resource\":[\"a\",\"b\"]}]}";
|
||||
JSONObject canonical = PolicyGenerator.canonical(hand, PolicyFormat.DEFAULT);
|
||||
assertThat(PolicyParser.parse(canonical, PolicyFormat.DEFAULT)).isEqualTo(PolicyParser.parse(hand, PolicyFormat.DEFAULT));
|
||||
assertThat(PolicyGenerator.toCompact(canonical)).doesNotContain("\"*\"");
|
||||
assertThat(canonical.getJSONArray("Statement").length()).isEqualTo(5);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void rejectsWhatCannotRoundTrip()
|
||||
{
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(List.of("noaction"), PolicyFormat.DEFAULT)).isInstanceOf(PolicyParseException.class).hasMessageContaining("{resource}.{action}");
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(List.of("a."), PolicyFormat.DEFAULT)).isInstanceOf(PolicyParseException.class);
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(List.of(".read"), PolicyFormat.DEFAULT)).isInstanceOf(PolicyParseException.class);
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(List.of("a.write"), PolicyFormat.DEFAULT)).hasMessageContaining("unknown action \"write\"");
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(List.of("authentik.users.read"), PolicyFormat.DEFAULT)).hasMessageContaining("[A-Za-z0-9_]+");
|
||||
assertThatThrownBy(() -> PolicyGenerator.generate(java.util.Arrays.asList((String) null), PolicyFormat.DEFAULT)).isInstanceOf(PolicyParseException.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The generator writes the host's spec and version.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void customFormat() throws Exception
|
||||
{
|
||||
PolicyFormat custom = new PolicyFormat("acme-iam", "1.0.0", "policies", "policies");
|
||||
JSONObject doc = PolicyGenerator.generate(List.of("order.read"), custom);
|
||||
assertThat(doc.getString("PolicySpec")).isEqualTo("acme-iam");
|
||||
assertThat(PolicyParser.parse(PolicyGenerator.toCompact(doc), custom)).containsExactly("order.read");
|
||||
assertThat(PolicyGenerator.generate(List.of("order.read"), null).getString("PolicySpec")).isEqualTo("qqq-iam");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.authentik.permissions.EffectivePermissionResolver;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.authentik.policy.PolicyParserTest.document;
|
||||
import static com.kingsrook.qbits.authentik.policy.PolicyParserTest.statement;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Group policies in the group graph and the effective-permission resolver:
|
||||
** inherited from parents, fail closed per group, checked against the catalog.
|
||||
*******************************************************************************/
|
||||
class PolicyGraphTest
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static JSONObject group(String pk, List<String> parents, Object policy, String attribute)
|
||||
{
|
||||
JSONObject attributes = new JSONObject();
|
||||
if(policy != null)
|
||||
{
|
||||
attributes.put(attribute, policy);
|
||||
}
|
||||
return (new JSONObject().put("pk", pk).put("name", pk).put("is_superuser", false).put("parents", new JSONArray(parents)).put("attributes", attributes).put("users", new JSONArray()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void policiesAreInheritedAndFailClosedPerGroup()
|
||||
{
|
||||
String parentPolicy = document(statement("Allow", List.of("hasAccess"), List.of("contentApp"))).toString();
|
||||
JSONObject childPolicy = document(statement("Allow", List.of("read", "edit"), List.of("cms_page")));
|
||||
String broken = "{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"read\"],\"Resource\":[\"x\"]}]}";
|
||||
|
||||
GroupGraph graph = GroupGraph.fromGroups(List.of(
|
||||
group("parent", List.of(), parentPolicy, "qqq.io/policy"),
|
||||
group("child", List.of("parent"), childPolicy, "qqq.io/policy"),
|
||||
group("broken", List.of("parent"), broken, "qqq.io/policy"),
|
||||
group("empty", List.of(), "", "qqq.io/policy")));
|
||||
|
||||
assertThat(graph.byPk("child").policyPermissions()).containsExactlyInAnyOrder("cms_page.read", "cms_page.edit");
|
||||
assertThat(graph.byPk("broken").policyPermissions()).isEmpty();
|
||||
assertThat(graph.byPk("broken").malformed()).anyMatch(m -> m.startsWith("qqq.io/policy: ") && m.contains("Deny"));
|
||||
assertThat(graph.byPk("empty").malformed()).isEmpty();
|
||||
|
||||
EffectivePermissionResolver resolver = new EffectivePermissionResolver(graph, null);
|
||||
EffectivePermissionResolver.Resolution child = resolver.resolveGroups(List.of("child"));
|
||||
assertThat(child.sessionPermissions()).containsExactlyInAnyOrder("contentApp.hasAccess", "cms_page.read", "cms_page.edit");
|
||||
assertThat(child.grantedBy().get("contentApp.hasAccess")).containsExactly("parent");
|
||||
|
||||
assertThat(resolver.resolveGroups(List.of("broken")).sessionPermissions()).as("the broken group grants nothing; its parent still does").containsExactly("contentApp.hasAccess");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Grants outside the app's permission catalog are reported, not granted.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void catalogFiltersPolicyGrants()
|
||||
{
|
||||
GroupGraph graph = GroupGraph.fromGroups(List.of(group("g", List.of(), document(statement("Allow", List.of("read"), List.of("cms_page", "gone_table"))).toString(), "qqq.io/policy")));
|
||||
EffectivePermissionResolver.Resolution resolution = new EffectivePermissionResolver(graph, List.of("cms_page.read")).resolveGroups(List.of("g"));
|
||||
assertThat(resolution.sessionPermissions()).containsExactly("cms_page.read");
|
||||
assertThat(resolution.unknown()).containsExactly("gone_table.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A host's own attribute and spec.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void customFormat()
|
||||
{
|
||||
PolicyFormat custom = new PolicyFormat("acme-iam", "1.0.0", "policies", "policies");
|
||||
String doc = document(statement("Allow", List.of("read"), List.of("order"))).put("PolicySpec", "acme-iam").toString();
|
||||
GroupGraph graph = GroupGraph.fromGroups(List.of(group("g", List.of(), doc, "policies")), custom);
|
||||
assertThat(graph.byPk("g").policyPermissions()).containsExactly("order.read");
|
||||
assertThat(GroupGraph.fromGroups(List.of(group("g", List.of(), doc, "policies"))).byPk("g").policyPermissions()).as("default attribute is qqq.io/policy").isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.policy;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Unit tests for PolicyParser: the format and every fail-closed case.
|
||||
*******************************************************************************/
|
||||
class PolicyParserTest
|
||||
{
|
||||
private static final PolicyFormat FORMAT = PolicyFormat.DEFAULT;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A statement.
|
||||
*******************************************************************************/
|
||||
static JSONObject statement(String effect, List<String> actions, List<String> resources)
|
||||
{
|
||||
return (new JSONObject().put("Effect", effect).put("Action", new JSONArray(actions)).put("Resource", new JSONArray(resources)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A document with the default spec and version.
|
||||
*******************************************************************************/
|
||||
static JSONObject document(JSONObject... statements)
|
||||
{
|
||||
return (new JSONObject().put("PolicySpec", "qqq-iam").put("PolicyVersion", "1.0.0").put("Statement", new JSONArray(List.of(statements))));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void allowStatementsGrantResourceDotAction()
|
||||
{
|
||||
JSONObject doc = document(
|
||||
statement("Allow", List.of("hasAccess"), List.of("contentApp", "publishPage")),
|
||||
statement("Allow", List.of("read", "edit"), List.of("cms_page")));
|
||||
|
||||
assertThat(PolicyParser.parse(doc, FORMAT)).containsExactlyInAnyOrder(
|
||||
"contentApp.hasAccess", "publishPage.hasAccess", "cms_page.read", "cms_page.edit");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void wildcardActionIsAllFive()
|
||||
{
|
||||
assertThat(PolicyParser.parse(document(statement("Allow", List.of("*"), List.of("cms_page"))), FORMAT)).containsExactlyInAnyOrder(
|
||||
"cms_page.hasAccess", "cms_page.read", "cms_page.insert", "cms_page.edit", "cms_page.delete");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** String (as stored in an attribute or claim), JSONObject and Map all parse.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void acceptsStringObjectAndMap()
|
||||
{
|
||||
JSONObject doc = document(statement("Allow", List.of("read"), List.of("a")));
|
||||
assertThat(PolicyParser.parse(doc.toString(), FORMAT)).containsExactly("a.read");
|
||||
assertThat(PolicyParser.parse(doc, FORMAT)).containsExactly("a.read");
|
||||
assertThat(PolicyParser.parse(doc.toMap(), FORMAT)).containsExactly("a.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void emptyOrMissingStatementGrantsNothingWithoutError() throws Exception
|
||||
{
|
||||
assertThat(PolicyParser.parseStrict(document(), FORMAT).permissions()).isEmpty();
|
||||
assertThat(PolicyParser.parseStrict(new JSONObject().put("PolicySpec", "qqq-iam").put("PolicyVersion", "1.0.0"), FORMAT).permissions()).isEmpty();
|
||||
assertThat(PolicyParser.parseStrict(document(statement("Allow", List.of(), List.of("a"))), FORMAT).permissions()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every malformed document grants nothing (fail closed), and parseStrict
|
||||
** names the problem.
|
||||
*******************************************************************************/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"",
|
||||
" ",
|
||||
"not json",
|
||||
"[]",
|
||||
"{\"PolicyVersion\":\"1.0.0\",\"Statement\":[]}",
|
||||
"{\"PolicySpec\":\"other-spec\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"Statement\":[]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"2.0.0\",\"Statement\":[]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":{}}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[\"x\"]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"read\"],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"allow\",\"Action\":[\"read\"],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Action\":[\"read\"],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"read\",\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":\"a\"}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"write\"],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"Read\"],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[1],\"Resource\":[\"a\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"*\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"authentik.users\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"\"]}]}",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"read\"],\"Resource\":[\"cms_*\"]}]}",
|
||||
})
|
||||
void malformedDocumentsFailClosed(String text)
|
||||
{
|
||||
assertThat(PolicyParser.parse(text, FORMAT)).isEmpty();
|
||||
assertThatThrownBy(() -> PolicyParser.parseStrict(text, FORMAT)).isInstanceOf(PolicyParseException.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One bad statement voids the whole document (no partial credit).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void oneBadStatementVoidsAll()
|
||||
{
|
||||
JSONObject doc = document(
|
||||
statement("Allow", List.of("read"), List.of("good")),
|
||||
statement("Deny", List.of("read"), List.of("other")));
|
||||
assertThat(PolicyParser.parse(doc, FORMAT)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void nullAndOtherTypesGrantNothing()
|
||||
{
|
||||
assertThat(PolicyParser.parse(null, FORMAT)).isEmpty();
|
||||
assertThat(PolicyParser.parse(JSONObject.NULL, FORMAT)).isEmpty();
|
||||
assertThat(PolicyParser.parse(42, FORMAT)).isEmpty();
|
||||
assertThat(PolicyParser.parse(new JSONArray(), FORMAT)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A host keeps its own spec name and version.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void customSpecName()
|
||||
{
|
||||
PolicyFormat custom = new PolicyFormat("acme-iam", "2.1.0", "policies", "policies");
|
||||
JSONObject doc = new JSONObject().put("PolicySpec", "acme-iam").put("PolicyVersion", "2.1.0")
|
||||
.put("Statement", new JSONArray().put(statement("Allow", List.of("read"), List.of("order"))));
|
||||
|
||||
assertThat(PolicyParser.parse(doc, custom)).containsExactly("order.read");
|
||||
assertThat(PolicyParser.parse(doc, FORMAT)).as("the default spec rejects another spec").isEmpty();
|
||||
assertThat(PolicyParser.parse(doc, null)).as("null format means the default").isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void messagesNameTheProblem()
|
||||
{
|
||||
assertThatThrownBy(() -> PolicyParser.parseStrict(Map.of("PolicySpec", "x"), FORMAT)).hasMessageContaining("PolicySpec must be \"qqq-iam\"");
|
||||
assertThatThrownBy(() -> PolicyParser.parseStrict(document(statement("Allow", List.of("write"), List.of("a"))), FORMAT)).hasMessageContaining("unknown action \"write\"");
|
||||
assertThatThrownBy(() -> PolicyParser.parseStrict(document(statement("Deny", List.of("read"), List.of("a"))), FORMAT)).hasMessageContaining("Deny is not supported");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void formatProblems()
|
||||
{
|
||||
assertThat(PolicyFormat.DEFAULT.problem()).isNull();
|
||||
assertThat(new PolicyFormat("bad spec", "1.0.0", "a", "c").problem()).contains("policySpec");
|
||||
assertThat(new PolicyFormat("s", "1.0", "a", "c").problem()).contains("policyVersion");
|
||||
assertThat(new PolicyFormat("s", "1.0.0", " ", "c").problem()).contains("policyAttribute");
|
||||
assertThat(new PolicyFormat("s", "1.0.0", "a", "bad claim").problem()).contains("policyClaim");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.authentik.processes;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.admin.AdminTestSupport;
|
||||
import com.kingsrook.qbits.authentik.admin.AuthentikLocalTables;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikTables;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The record and table actions run as standard streamed-ETL processes through
|
||||
** QQQ's own RunProcessAction: a details screen, a Review step (the dry run,
|
||||
** with refused targets and why) and a Result step, and none is in the nav.
|
||||
*******************************************************************************/
|
||||
class AuthentikProcessesTest
|
||||
{
|
||||
private AdminTestSupport t;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws QException
|
||||
{
|
||||
t = AdminTestSupport.create();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a run produced: the Review lines and the Result lines.
|
||||
*******************************************************************************/
|
||||
private record Outcome(List<ProcessSummaryLine> review, List<ProcessSummaryLine> result)
|
||||
{
|
||||
/*******************************************************************************
|
||||
** All messages of a list, for readable assertions.
|
||||
*******************************************************************************/
|
||||
static List<String> messages(List<ProcessSummaryLine> lines)
|
||||
{
|
||||
return (lines.stream().map(l -> l.getCount() + " " + l.getMessage()).toList());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run a process as the frontend would: start (collecting the first screen),
|
||||
** submit the details with a full validation, review, execute.
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Outcome run(String processName, String table, String key, List<? extends Serializable> keys, Map<String, Serializable> form, boolean execute) throws QException
|
||||
{
|
||||
RunProcessInput input = new RunProcessInput();
|
||||
input.setProcessName(processName);
|
||||
if(keys != null)
|
||||
{
|
||||
input.addValue("recordIds", keys.stream().map(String::valueOf).collect(java.util.stream.Collectors.joining(",")));
|
||||
}
|
||||
RunProcessOutput output = new RunProcessAction().execute(input);
|
||||
input.setProcessUUID(output.getProcessUUID());
|
||||
form.forEach(input::addValue);
|
||||
input.setStartAfterStep(t.qInstance.getProcess(processName).getStepList().stream().filter(s -> s.getName().equals("details")).findFirst().isPresent() ? "details" : null);
|
||||
output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getException()).isEmpty();
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// the process defaults to full validation, so the Review screen already //
|
||||
// holds the dry-run lines for every target //
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
List<ProcessSummaryLine> review = (List<ProcessSummaryLine>) output.getValues().get(StreamedETLWithFrontendProcess.FIELD_VALIDATION_SUMMARY);
|
||||
assertThat(output.getProcessState().getNextStepName()).contains("review");
|
||||
if(!execute)
|
||||
{
|
||||
return (new Outcome(review, List.of()));
|
||||
}
|
||||
|
||||
input.setStartAfterStep("review");
|
||||
output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getException()).isEmpty();
|
||||
return (new Outcome(review, (List<ProcessSummaryLine>) output.getValues().get(StreamedETLWithFrontendProcess.FIELD_PROCESS_SUMMARY)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Which processes exist depends on the features; they are table or record
|
||||
** actions (bound to a table, hidden from the nav by not being in an app).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void processesFollowFeaturesAndAreNeverInTheNav() throws QException
|
||||
{
|
||||
assertThat(t.qInstance.getProcesses().keySet()).contains("authentikCreateUser", "authentikInviteUser", "authentikEditUser", "authentikDeactivateUser",
|
||||
"authentikReactivateUser", "authentikAddToGroup", "authentikRemoveFromGroup", "authentikSendPasswordReset", "authentikResetMfa", "authentikRevokeAppPasswords",
|
||||
"authentikRevokeSessions", "authentikCreateGroup", "authentikEditGroup", "authentikEditPermissions", "authentikAddMembers", "authentikRemoveMembers",
|
||||
"authentikCancelInvitation", "authentikApprove", "authentikReject");
|
||||
|
||||
for(QProcessMetaData process : t.qInstance.getProcesses().values())
|
||||
{
|
||||
assertThat(process.getTableName()).as(process.getName()).isNotBlank();
|
||||
assertThat(t.qInstance.getApp("authentikAdmin").getChildren()).extracting(c -> c.getName()).doesNotContain(process.getName());
|
||||
}
|
||||
assertThat(t.qInstance.getProcess("authentikCreateUser").getMaxInputRecords()).isEqualTo(0);
|
||||
assertThat(t.qInstance.getProcess("authentikEditUser").getMaxInputRecords()).isEqualTo(1);
|
||||
assertThat(t.qInstance.getProcess("authentikAddToGroup").getMinInputRecords()).isEqualTo(1);
|
||||
|
||||
AdminTestSupport readOnly = AdminTestSupport.create(java.util.EnumSet.of(AuthentikFeature.READ, AuthentikFeature.MEMBERSHIP));
|
||||
assertThat(readOnly.qInstance.getProcesses().keySet()).contains("authentikAddToGroup", "authentikAddMembers").doesNotContain("authentikCreateUser", "authentikEditPermissions", "authentikApprove");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Add To Group: the Review is a dry run (nothing sent), refused people are
|
||||
** listed with the reason, the Result applies the rest.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void addToGroupReviewThenResult() throws QException
|
||||
{
|
||||
Map<String, Serializable> form = Map.of("group", t.authentik.pk("kof-website-publishers"), "reason", "onboarding");
|
||||
|
||||
Outcome review = run("authentikAddToGroup", t.config.applyTablePrefix(AuthentikTables.USER), "pk", List.of(3, 4, 7), form, false);
|
||||
assertThat(Outcome.messages(review.review())).anyMatch(m -> m.contains("membership will be added") || m.contains("memberships will be added"));
|
||||
assertThat(review.review()).anyMatch(l -> l.getStatus() == Status.ERROR && l.getMessage().toLowerCase().contains("protected"));
|
||||
assertThat(t.writes()).as("review is a dry run").isEmpty();
|
||||
assertThat(review.review().stream().filter(l -> l.getStatus() == Status.ERROR).flatMap(l -> l.getBulletsOfText().stream())).anyMatch(b -> b.contains("breakglass"));
|
||||
|
||||
Outcome result = run("authentikAddToGroup", t.config.applyTablePrefix(AuthentikTables.USER), "pk", List.of(3, 4, 7), form, true);
|
||||
assertThat(result.result()).anyMatch(l -> l.getStatus() == Status.OK && l.getCount() == 2);
|
||||
assertThat(result.result()).anyMatch(l -> l.getStatus() == Status.ERROR);
|
||||
assertThat(t.authentik.groupNamesOf(3)).contains("kof-website-publishers");
|
||||
assertThat(t.authentik.groupNamesOf(7)).contains("kof-website-publishers");
|
||||
assertThat(t.authentik.groupNamesOf(4)).doesNotContain("kof-website-publishers");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Create User is a table action with no records: the form carries the data.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void createUserIsATableAction() throws QException
|
||||
{
|
||||
Map<String, Serializable> form = Map.of("username", "newbie", "name", "New Bie", "email", "newbie@example.test", "reason", "new hire", "groups", "", "sendRecovery", true);
|
||||
Outcome outcome = run("authentikCreateUser", t.config.applyTablePrefix(AuthentikTables.USER), null, null, form, true);
|
||||
|
||||
assertThat(Outcome.messages(outcome.review())).anyMatch(m -> m.contains("user will be created"));
|
||||
assertThat(Outcome.messages(outcome.result())).anyMatch(m -> m.contains("user was created"));
|
||||
assertThat(t.authentik.users.values()).anyMatch(u -> u.getString("username").equals("newbie"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Edit Permissions fills its form from the group (prepare step) and sends the
|
||||
** stale-check fingerprint back with it.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editPermissionsPrefillsTheForm() throws QException
|
||||
{
|
||||
RunProcessInput input = new RunProcessInput();
|
||||
input.setProcessName("authentikEditPermissions");
|
||||
input.addValue("recordIds", t.authentik.pk("kof-website-analysts"));
|
||||
RunProcessOutput output = new RunProcessAction().execute(input);
|
||||
|
||||
assertThat(output.getValues().get("permissions")).isEqualTo("kof22.analytics.hasAccess");
|
||||
assertThat(String.valueOf(output.getValues().get("expectedFingerprint"))).hasSize(16);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A change that needs a second person shows as a warning in Review and is
|
||||
** queued by the Result; Approve then applies it.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void approvalFlowThroughProcesses() throws QException
|
||||
{
|
||||
Map<String, Serializable> form = Map.of("permissions", "cms.publish.hasAccess\nauthentik.users.read", "appAccess", "kof22-website-prod", "reason", "grant");
|
||||
String table = t.config.applyTablePrefix(AuthentikTables.GROUP);
|
||||
Outcome outcome = run("authentikEditPermissions", table, "pk", List.of(t.authentik.pk("kof-website-publishers")), form, true);
|
||||
|
||||
assertThat(outcome.review()).anyMatch(l -> l.getStatus() == Status.WARNING && l.getMessage().contains("second person"));
|
||||
assertThat(outcome.result()).anyMatch(l -> l.getStatus() == Status.WARNING);
|
||||
assertThat(t.writes()).isEmpty();
|
||||
|
||||
t.loginAs("second@example.test", com.kingsrook.qbits.authentik.security.IdentityPermission.values());
|
||||
String approvalTable = t.config.applyTablePrefix(AuthentikLocalTables.APPROVAL_REQUEST);
|
||||
Outcome approved = run("authentikApprove", approvalTable, "id", List.of(1), Map.of(), true);
|
||||
assertThat(approved.result()).anyMatch(l -> l.getStatus() == Status.OK);
|
||||
assertThat(t.authentik.groupByName("kof-website-publishers").getJSONObject("attributes").getJSONArray("qqq.io/permissions").toList()).contains("authentik.users.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** More than 25 people in one run needs the count typed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void bulkAboveTwentyFiveNeedsTypedCount() throws QException
|
||||
{
|
||||
for(int pk = 200; pk < 230; pk++)
|
||||
{
|
||||
t.authentik.user(pk, "bulk" + pk, "bulk" + pk + "@example.test", "internal", true);
|
||||
}
|
||||
List<Integer> keys = new java.util.ArrayList<>();
|
||||
for(int pk = 200; pk < 230; pk++)
|
||||
{
|
||||
keys.add(pk);
|
||||
}
|
||||
|
||||
Map<String, Serializable> untyped = Map.of("group", t.authentik.pk("kof-website-publishers"), "reason", "bulk");
|
||||
Outcome review = run("authentikAddToGroup", t.config.applyTablePrefix(AuthentikTables.USER), "pk", keys, untyped, false);
|
||||
assertThat(review.review()).anyMatch(l -> l.getStatus() == Status.ERROR && l.getMessage().contains("type 30"));
|
||||
assertThat(t.writes()).isEmpty();
|
||||
|
||||
Map<String, Serializable> typed = Map.of("group", t.authentik.pk("kof-website-publishers"), "reason", "bulk", "confirmText", "30");
|
||||
Outcome result = run("authentikAddToGroup", t.config.applyTablePrefix(AuthentikTables.USER), "pk", keys, typed, true);
|
||||
assertThat(result.result()).anyMatch(l -> l.getStatus() == Status.OK && l.getCount() == 30);
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Records carry their table name (the Next UI rejects a record without one),
|
||||
** and the drift report understands undashed group pks in events.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void recordsCarryTheirTableName() throws QException
|
||||
{
|
||||
var input = new com.kingsrook.qqq.backend.core.model.actions.tables.get.GetInput(t.config.applyTablePrefix(AuthentikTables.USER));
|
||||
input.setPrimaryKey(3);
|
||||
assertThat(new com.kingsrook.qqq.backend.core.actions.tables.GetAction().execute(input).getRecord().getTableName()).isEqualTo("authentik_user");
|
||||
assertThat(com.kingsrook.qbits.authentik.drift.AuthentikDriftReport.class.getDeclaredMethods()).anyMatch(m -> m.getName().equals("dashed"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
# yaml-language-server: $schema=https://goauthentik.io/blueprints/schema.json
|
||||
#
|
||||
# Example: put the merged group policies into the sign-in token (POLICY-FORMAT.md,
|
||||
# "Getting policies into the token"). The contract test PolicyClaimMappingIT loads
|
||||
# this file and runs the mapping through Authentik's property-mapping test
|
||||
# endpoint, so the example in the docs is pinned to a real Authentik.
|
||||
#
|
||||
# Keep spec, version, attribute and the claim name equal to the qbit config
|
||||
# (policySpec, policyVersion, policyAttribute, policyClaim). Add the mapping to
|
||||
# your OAuth2 provider's property_mappings.
|
||||
version: 1
|
||||
metadata:
|
||||
name: qqq-policy-claim
|
||||
labels:
|
||||
blueprints.goauthentik.io/description: "QQQ policy claim (qbit-authentik example)"
|
||||
entries:
|
||||
- model: authentik_providers_oauth2.scopemapping
|
||||
id: qqq-policy-claim-mapping
|
||||
state: present
|
||||
identifiers:
|
||||
name: qqq-policy-claim
|
||||
attrs:
|
||||
name: qqq-policy-claim
|
||||
# "profile" is requested by every QQQ sign-in, so no client change is needed.
|
||||
scope_name: profile
|
||||
description: "QQQ policies of all the user's groups, including inherited parents"
|
||||
expression: |
|
||||
import json
|
||||
|
||||
spec = "qqq-iam"
|
||||
version = "1.0.0"
|
||||
attribute = "qqq.io/policy"
|
||||
|
||||
statements = []
|
||||
for group in request.user.all_groups():
|
||||
raw = (group.attributes or {}).get(attribute)
|
||||
if raw is None or raw == "":
|
||||
continue
|
||||
try:
|
||||
document = json.loads(raw) if isinstance(raw, str) else raw
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not isinstance(document, dict):
|
||||
continue
|
||||
if document.get("PolicySpec") != spec or document.get("PolicyVersion") != version:
|
||||
continue
|
||||
found = document.get("Statement")
|
||||
if isinstance(found, list):
|
||||
statements.extend(found)
|
||||
|
||||
return {"qqq_policy": json.dumps({"PolicySpec": spec, "PolicyVersion": version, "Statement": statements})}
|
||||
Reference in new issue
Block a user