Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af970d32db
|
||
|
|
a5a74af0e2 | ||
|
|
a79f2d2d4b
|
||
|
|
a2fbb2516e | ||
|
|
9751296d6c | ||
|
|
93d3afa869 |
No files matched your search
@@ -4,6 +4,17 @@ All notable changes to this project are documented here. Format: [Keep a Changel
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added (policy cut-over, DESIGN.md section 12.8)
|
||||
- `AuthentikHostPermissionSource` SPI (today's access) and config `mapperEnabled`, `cutoverGuardGroups`, `mapperOverride`, `staticGroupPermissions`.
|
||||
- **Enforcement status**: banner widget `authentikPolicyEnforcement` (first on group and policy records and on the Edit Policy step) and a "Policies at sign-in" row in the home's Connection card: OFF, ACTIVE, OVERRIDDEN or BLOCKED.
|
||||
- **Compare Access** widget `authentikCompareAccess` on the app home (`authentik.admin`, read only): per active person, today vs the mapper, with added, removed and unchanged, and the guard result.
|
||||
- **Cut-over guard**: while a member of a guarded group would lose a permission (and no override), the mapper grants today's access plus the static fallback and bootstrap subjects instead of the policies.
|
||||
- **Generate Policy From Current Access** group action: the expressible part of today's access (joined with the current policy) becomes the policy, named permissions go to `qqq.io/permissions`, the rest is listed; Review shows the document and diff.
|
||||
|
||||
### Added (full user and group CRUD, phase 5c: DESIGN.md section 12.5)
|
||||
- **Edit User** also changes the username (validated, unique) and the other attributes (a JSON object; reserved `qqq.io/` and `goauthentik.io/` keys are kept and cannot be set; blank leaves them as they are; editing attributes needs `authentik.audit.read`, which is also what shows them on the form). **Edit Group** edits other attributes the same way.
|
||||
- **Delete User** and **Delete Group** record actions behind the new `DELETE` feature (off by default; needs Authentik's `delete_user` / `delete_group`). Typed confirmation; never yourself, a protected account, a superuser group or the last identity administrator; a group must have no members and no child groups first; the group's `authentik_policy` row goes with it. Deactivate stays the default for people.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -51,7 +51,7 @@ CI=true ./mvnw verify # + contract ITs: Authentik 2026.8.3 server+worker, Post
|
||||
- `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.
|
||||
- The service account must never be a superuser and never hold `enable_group_superuser`, token-key or impersonate permissions; `delete_user`/`delete_group` only when the host turns the `DELETE` feature on.
|
||||
|
||||
## Code Style
|
||||
|
||||
|
||||
@@ -8,8 +8,9 @@ Design: [`docs/DESIGN.md`](docs/DESIGN.md) (the approved spec, QRun-IO/qqq#1065)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **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). |
|
||||
| **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. Edit covers username, name, email, path and other attributes. Delete is a separate, explicit action behind the `DELETE` feature (off by default); deactivate stays the default. |
|
||||
| **Groups and permissions** | Create, edit (parents, other attributes) and delete groups, 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). |
|
||||
| **Policies** | IAM-style policy documents on groups (`qqq.io/policy`, format in [docs/POLICY-FORMAT.md](docs/POLICY-FORMAT.md)), edited with a matrix of the app's apps, tables, processes and reports and a live JSON preview (Next UI widget `AUTHENTIK_POLICY_EDITOR`). At sign-in they become QQQ permissions through `AuthentikGroupPermissionMapper`, or through the token claim with `AuthentikPolicyClaimMapper`. Parsing fails closed. |
|
||||
| **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. |
|
||||
@@ -23,7 +24,7 @@ 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
|
||||
.withFeatures(EnumSet.of(READ, USERS, GROUPS, MEMBERSHIP, CREDENTIALS, SESSIONS))
|
||||
.withFeatures(EnumSet.of(READ, USERS, GROUPS, MEMBERSHIP, CREDENTIALS, SESSIONS, POLICIES)) // + DELETE for delete actions
|
||||
.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
|
||||
@@ -38,10 +39,10 @@ Read-only is the default (`features` = `READ`). `readOnly=true` is a hard kill s
|
||||
| | |
|
||||
|---|---|
|
||||
| API backend | `authentikApi` |
|
||||
| Main tables (nav) | `authentik_user`, `authentik_invitation`, `authentik_group`, `authentik_application`, `authentik_approval_request`, `authentik_admin_action` |
|
||||
| Main tables (nav) | `authentik_user`, `authentik_invitation`, `authentik_group`, `authentik_policy` (with `POLICIES`), `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 |
|
||||
| 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; with `POLICIES`: Edit Policy (on groups and policies); with `DELETE`: Delete User, Delete Group |
|
||||
|
||||
### Permissions
|
||||
|
||||
@@ -54,6 +55,7 @@ QQQ permissions, held as `<name>.hasAccess`, granted through the group attribute
|
||||
| `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.policies.manage` | edit a group's policy (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 |
|
||||
@@ -65,9 +67,9 @@ QQQ permissions, held as `<name>.hasAccess`, granted through the group attribute
|
||||
|
||||
### Authentik side
|
||||
|
||||
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.
|
||||
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 or impersonate permissions, and holds delete permissions only when the `DELETE` feature is on. [`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.
|
||||
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. Saving a policy uses `change_group`. The `DELETE` feature also needs `delete_user` and `delete_group`. The contract tests grant exactly this list.
|
||||
|
||||
## Adopting in another app
|
||||
|
||||
|
||||
@@ -1178,6 +1178,54 @@ Deactivate stays the default for people, and *Delete User* says so in its help t
|
||||
|
||||
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.8 Cut-over: making policies take effect safely
|
||||
|
||||
Saved policies do nothing until the host signs people in through the qbit mapper. The qbit makes that state visible, helps seed policies from today's access, and refuses to switch over in a way that would lock administrators out.
|
||||
|
||||
**Host SPI.** `AuthentikHostPermissionSource` returns what a user (or a group's members) gets *today* from the host, typically a hard-coded grant such as "admins get `adminPermissions()`". The host sets it with `withHostPermissionSource(...)`.
|
||||
|
||||
**Config.**
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `mapperEnabled` | `false` | The host's own switch (kof22: `AUTHENTIK_QBIT_MAPPER`). Off means "policies are saved but not enforced". A host that calls the mapper without setting it is treated as on. |
|
||||
| `cutoverGuardGroups` | none | Groups whose members must lose no permission at the cut-over (kof22: `kof22-admins`) |
|
||||
| `mapperOverride` | `false` | The owner's explicit override of a failing guard |
|
||||
| `staticGroupPermissions` | none | Permissions always granted to a group's members (the floor), e.g. today's admin grant |
|
||||
|
||||
**Status** (`AccessComparison.state`, cached 60 s):
|
||||
- `OFF`: the mapper is not in use.
|
||||
- `ACTIVE`: the guard passed, or nothing is guarded.
|
||||
- `OVERRIDDEN`: the owner overrode a failing guard.
|
||||
- `BLOCKED`: the guard failed or could not reach Authentik.
|
||||
|
||||
The status is shown in three places:
|
||||
- the *Policy enforcement* banner, first on group and policy records and on the Edit Policy step. When off it reads "Policies are saved but NOT enforced at sign-in on this instance (mapper off)".
|
||||
- the home's Connection card ("Policies at sign-in")
|
||||
- **Compare Access**
|
||||
|
||||
**Compare Access** is a read-only `TABLE` widget on the app home (`authentik.admin`). For every active person it compares two sets:
|
||||
- **today**: the host source
|
||||
- **with the mapper**: the person's groups' policies and `qqq.io/permissions` including ancestors, the static fallback of their direct groups, and all `authentik.*` for a bootstrap subject
|
||||
|
||||
It shows what is added and removed, and the unchanged count. Guarded people are marked, and the footer says whether the guard passes.
|
||||
|
||||
**Guard.** While the status is `BLOCKED`, the mapper does not apply policies. A sign-in gets:
|
||||
- today's access from the host source
|
||||
- the static fallbacks
|
||||
- the bootstrap subjects
|
||||
|
||||
So switching the mapper on can never take access away from a guarded admin until Compare Access shows no removal for them, or the owner sets `mapperOverride`. The static fallback and the bootstrap subject (the owner's immutable Authentik pk) stay in force in every state, so a lockout is impossible.
|
||||
|
||||
**Generate Policy From Current Access** is a record action on groups that saves a policy. It takes what the group's members get today (`groupPermissions`):
|
||||
- Permissions a policy can express are joined with the group's current policy, so nothing is removed, and become the document.
|
||||
- Named permissions the app defines but a policy cannot express (dotted names, `write`) are merged into `qqq.io/permissions`.
|
||||
- Anything else is listed as skipped.
|
||||
|
||||
Review shows the generated document, the diff and the subset rule before anything is saved. For the subset rule, the operator's own access today (host source plus static fallback) counts.
|
||||
|
||||
**Rollback** is one switch: set the host flag off (kof22: `AUTHENTIK_QBIT_MAPPER=false`). Sign-in returns to the host's own grant immediately. Saved policies stay in Authentik and in `authentik_policy`, unused.
|
||||
|
||||
### 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.
|
||||
|
||||
+3
-3
@@ -11,14 +11,14 @@ The Authentik qbit's progress through DESIGN.md section 11, with links. Updated
|
||||
| 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 |
|
||||
| 5. Policies and full CRUD (DESIGN.md section 12) | 5a policy model (#14), 5b policy editor (#15), 5c user and group CRUD additions; the Next UI widget is a separate qqq-frontend-next PR |
|
||||
|
||||
### 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 |
|
||||
| People | Create, invite, edit (username, name, email, path, other attributes), deactivate, reactivate, delete (feature `DELETE`), password reset email, reset MFA, revoke app passwords, revoke sessions, cancel invitations |
|
||||
| Groups | Create, edit (parents, other attributes), delete (feature `DELETE`), add and remove members (bulk), edit permissions and app access, edit the group policy (feature `POLICIES`) |
|
||||
| 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 |
|
||||
|
||||
@@ -46,11 +46,11 @@ 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.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES);
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES, AuthentikFeature.DELETE);
|
||||
|
||||
/** 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);
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES, AuthentikFeature.DELETE);
|
||||
|
||||
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}");
|
||||
@@ -90,6 +90,12 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
private String policyAttribute = PolicyFormat.DEFAULT_ATTRIBUTE;
|
||||
private String policyClaim = PolicyFormat.DEFAULT_CLAIM;
|
||||
private Boolean policyTwoPersonApproval = false;
|
||||
private Boolean mapperEnabled = false;
|
||||
private Boolean mapperOverride = false;
|
||||
private List<String> cutoverGuardGroups = new ArrayList<>();
|
||||
private java.util.Map<String, List<String>> staticGroupPermissions = new java.util.LinkedHashMap<>();
|
||||
@JsonIgnore
|
||||
private com.kingsrook.qbits.authentik.permissions.AuthentikHostPermissionSource hostPermissionSource;
|
||||
|
||||
|
||||
|
||||
@@ -179,6 +185,11 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
errors.add("features USERS and CREDENTIALS need recoveryEmailStage");
|
||||
}
|
||||
|
||||
if(requested.contains(AuthentikFeature.DELETE) && !requested.contains(AuthentikFeature.USERS) && !requested.contains(AuthentikFeature.GROUPS))
|
||||
{
|
||||
errors.add("feature DELETE needs USERS or GROUPS");
|
||||
}
|
||||
|
||||
if(requested.contains(AuthentikFeature.POLICIES) && !requested.contains(AuthentikFeature.GROUPS))
|
||||
{
|
||||
errors.add("feature POLICIES needs GROUPS");
|
||||
@@ -1238,4 +1249,111 @@ public class AuthentikQBitConfig implements QBitConfig
|
||||
return (new PolicyFormat(policySpec, policyVersion, policyAttribute, policyClaim));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for mapperEnabled: whether the host uses the qbit mapper for sign-in permissions (its own flag, e.g. AUTHENTIK_QBIT_MAPPER); false shows "policies are not enforced" everywhere.
|
||||
*******************************************************************************/
|
||||
public Boolean getMapperEnabled()
|
||||
{
|
||||
return (this.mapperEnabled);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for mapperEnabled
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withMapperEnabled(Boolean mapperEnabled)
|
||||
{
|
||||
this.mapperEnabled = mapperEnabled;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for mapperOverride: activate the mapper even when the cut-over guard finds removed permissions (explicit owner override).
|
||||
*******************************************************************************/
|
||||
public Boolean getMapperOverride()
|
||||
{
|
||||
return (this.mapperOverride);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for mapperOverride
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withMapperOverride(Boolean mapperOverride)
|
||||
{
|
||||
this.mapperOverride = mapperOverride;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for cutoverGuardGroups: groups whose members must lose no permission at the cut-over (DESIGN.md section 12.8).
|
||||
*******************************************************************************/
|
||||
public List<String> getCutoverGuardGroups()
|
||||
{
|
||||
return (this.cutoverGuardGroups);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for cutoverGuardGroups
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withCutoverGuardGroups(List<String> cutoverGuardGroups)
|
||||
{
|
||||
this.cutoverGuardGroups = cutoverGuardGroups;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for staticGroupPermissions: permissions always granted to members of a group (the mapper floor, e.g. today's admin grant), so a cut-over cannot lock admins out.
|
||||
*******************************************************************************/
|
||||
public java.util.Map<String, List<String>> getStaticGroupPermissions()
|
||||
{
|
||||
return (this.staticGroupPermissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for staticGroupPermissions
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withStaticGroupPermissions(java.util.Map<String, List<String>> staticGroupPermissions)
|
||||
{
|
||||
this.staticGroupPermissions = staticGroupPermissions;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for hostPermissionSource: the host's current (pre-policy)
|
||||
** permission source, or null (DESIGN.md section 12.8).
|
||||
*******************************************************************************/
|
||||
@JsonIgnore
|
||||
public com.kingsrook.qbits.authentik.permissions.AuthentikHostPermissionSource getHostPermissionSource()
|
||||
{
|
||||
return (this.hostPermissionSource);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for hostPermissionSource
|
||||
*******************************************************************************/
|
||||
public AuthentikQBitConfig withHostPermissionSource(com.kingsrook.qbits.authentik.permissions.AuthentikHostPermissionSource hostPermissionSource)
|
||||
{
|
||||
this.hostPermissionSource = hostPermissionSource;
|
||||
return (this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
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.AccessComparison;
|
||||
import com.kingsrook.qbits.authentik.permissions.GroupGraph;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyCatalog;
|
||||
import com.kingsrook.qbits.authentik.security.AuthentikGuard;
|
||||
@@ -47,6 +48,8 @@ public class AuthentikRuntime
|
||||
private final Memoization<String, GroupGraph> groupGraphCache;
|
||||
private volatile java.util.Set<String> permissionCatalog;
|
||||
private volatile PolicyCatalog policyCatalog;
|
||||
private volatile AccessComparison.State mapperState;
|
||||
private volatile boolean mapperInvoked;
|
||||
private final Map<String, AuthentikTableSpec> specsByTableName = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
@@ -233,4 +236,48 @@ public class AuthentikRuntime
|
||||
return (responseCache);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The cached mapper state (DESIGN.md section 12.8), or null.
|
||||
*******************************************************************************/
|
||||
public AccessComparison.State getMapperState()
|
||||
{
|
||||
return (mapperState);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cache a mapper state.
|
||||
*******************************************************************************/
|
||||
public void setMapperState(AccessComparison.State mapperState)
|
||||
{
|
||||
this.mapperState = mapperState;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the host has run the qbit mapper at sign-in (counts as "enabled"
|
||||
** for hosts that call the mapper without setting mapperEnabled).
|
||||
*******************************************************************************/
|
||||
public boolean isMapperInvoked()
|
||||
{
|
||||
return (mapperInvoked);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Record that the mapper ran.
|
||||
*******************************************************************************/
|
||||
public void markMapperInvoked()
|
||||
{
|
||||
if(!mapperInvoked)
|
||||
{
|
||||
mapperInvoked = true;
|
||||
mapperState = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ public enum AdminAction
|
||||
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),
|
||||
DELETE_USER("Delete user", "user", IdentityPermission.USERS_MANAGE, AuthentikFeature.DELETE, Confirmation.TYPED),
|
||||
DELETE_GROUP("Delete group", "group", IdentityPermission.GROUPS_MANAGE, AuthentikFeature.DELETE, Confirmation.TYPED),
|
||||
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),
|
||||
|
||||
@@ -93,6 +93,12 @@ public class AuthentikAdmin
|
||||
/** Process value / request parameter that carries a submitted policy document. */
|
||||
public static final String POLICY_DOCUMENT = "policyDocument";
|
||||
|
||||
/** Request parameter: named permissions (one per line) to merge into qqq.io/permissions with a policy save. */
|
||||
public static final String EXTRA_PERMISSIONS = "extraPermissions";
|
||||
|
||||
/** Request parameter with the non-reserved attributes (JSON object text) of Edit User and Edit Group. */
|
||||
public static final String OTHER_ATTRIBUTES = "otherAttributes";
|
||||
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
|
||||
private static final Pattern USERNAME = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._@+-]{0,149}");
|
||||
private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+\\.[^@\\s]+");
|
||||
@@ -207,6 +213,21 @@ public class AuthentikAdmin
|
||||
EffectivePermissionResolver.Resolution resolution = resolver().resolveGroups(groupPks);
|
||||
permissions.addAll(resolution.sessionPermissions());
|
||||
appAccess.addAll(resolution.appAccess());
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// what the operator holds today through the host (and the static //
|
||||
// fallback) counts for the subset rule too (DESIGN.md 12.8) //
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
List<String> groupNames = new ArrayList<>();
|
||||
for(int i = 0; groups != null && i < groups.length(); i++)
|
||||
{
|
||||
groupNames.add(groups.getJSONObject(i).optString("name"));
|
||||
}
|
||||
permissions.addAll(com.kingsrook.qbits.authentik.permissions.AccessComparison.staticPermissions(config, groupNames));
|
||||
if(config.getHostPermissionSource() != null)
|
||||
{
|
||||
permissions.addAll(config.getHostPermissionSource().userPermissions(email, groupNames));
|
||||
}
|
||||
}
|
||||
else if(QContext.getQSession() != null && QContext.getQSession().getPermissions() != null)
|
||||
{
|
||||
@@ -261,6 +282,8 @@ public class AuthentikAdmin
|
||||
case EDIT_GROUP -> planEditGroup(plan, request);
|
||||
case EDIT_PERMISSIONS -> planEditPermissions(plan, request);
|
||||
case SAVE_POLICY -> planSavePolicy(plan, request);
|
||||
case DELETE_USER -> planDeleteUser(plan, request);
|
||||
case DELETE_GROUP -> planDeleteGroup(plan, request);
|
||||
case SEND_RECOVERY_EMAIL -> planRecovery(plan, request);
|
||||
case RESET_MFA -> planResetMfa(plan, request);
|
||||
case REVOKE_APP_PASSWORDS -> planAppPasswords(plan, request);
|
||||
@@ -665,6 +688,23 @@ public class AuthentikAdmin
|
||||
{
|
||||
return (plan);
|
||||
}
|
||||
String username = request.params().containsKey("username") && StringUtils.hasContent(request.str("username")) ? request.str("username") : user.optString("username");
|
||||
if(!username.equals(user.optString("username")))
|
||||
{
|
||||
if(!USERNAME.matcher(username).matches())
|
||||
{
|
||||
return (plan.refuse("A username is letters, digits and . _ @ + - (up to 150)."));
|
||||
}
|
||||
if(findUserByUsername(username) != null)
|
||||
{
|
||||
return (plan.refuse("Another user already has the username " + username + "."));
|
||||
}
|
||||
}
|
||||
String attributesProblem = otherAttributesProblem(request, user.optJSONObject("attributes"));
|
||||
if(attributesProblem != null)
|
||||
{
|
||||
return (plan.refuse(attributesProblem));
|
||||
}
|
||||
String name = request.params().containsKey("name") ? request.str("name") : user.optString("name");
|
||||
String email = request.params().containsKey("email") ? request.str("email") : user.optString("email");
|
||||
String path = request.params().containsKey("path") ? request.str("path") : user.optString("path");
|
||||
@@ -694,8 +734,14 @@ public class AuthentikAdmin
|
||||
return (plan.refuse("This user was changed (for example in the Authentik admin UI) since you opened it. Review it again."));
|
||||
}
|
||||
|
||||
String before = user.optString("name") + " <" + user.optString("email") + ">, " + user.optString("path");
|
||||
String after = name + " <" + email + ">, " + path;
|
||||
String before = user.optString("username") + ": " + user.optString("name") + " <" + user.optString("email") + ">, " + user.optString("path");
|
||||
String after = username + ": " + name + " <" + email + ">, " + path;
|
||||
String keys = changedAttributeKeys(request, user.optJSONObject("attributes"));
|
||||
if(keys != null)
|
||||
{
|
||||
before = before + "; attributes";
|
||||
after = after + "; attributes (" + keys + ")";
|
||||
}
|
||||
if(before.equals(after))
|
||||
{
|
||||
return (plan.noChange("Nothing to change."));
|
||||
@@ -932,7 +978,13 @@ public class AuthentikAdmin
|
||||
{
|
||||
return (plan.refuse("This group was changed (for example in the Authentik admin UI) since you opened it. Review it again."));
|
||||
}
|
||||
if(newName.equals(group.optString("name")) && new LinkedHashSet<>(newParents).equals(new LinkedHashSet<>(currentParents)))
|
||||
String attributesProblem = otherAttributesProblem(request, group.optJSONObject("attributes"));
|
||||
if(attributesProblem != null)
|
||||
{
|
||||
return (plan.refuse(attributesProblem));
|
||||
}
|
||||
String keys = changedAttributeKeys(request, group.optJSONObject("attributes"));
|
||||
if(newName.equals(group.optString("name")) && new LinkedHashSet<>(newParents).equals(new LinkedHashSet<>(currentParents)) && keys == null)
|
||||
{
|
||||
return (plan.noChange("Nothing to change."));
|
||||
}
|
||||
@@ -949,7 +1001,8 @@ public class AuthentikAdmin
|
||||
}
|
||||
|
||||
plan.getRequest().params().put("resolvedParentPks", String.join(",", newParents));
|
||||
return (plan.withChange(group.optString("name") + ", parents " + names(currentParents), newName + ", parents " + names(newParents)));
|
||||
return (plan.withChange(group.optString("name") + ", parents " + names(currentParents) + (keys == null ? "" : "; attributes"),
|
||||
newName + ", parents " + names(newParents) + (keys == null ? "" : "; attributes (" + keys + ")")));
|
||||
}
|
||||
|
||||
|
||||
@@ -1024,8 +1077,16 @@ public class AuthentikAdmin
|
||||
{
|
||||
return (plan);
|
||||
}
|
||||
if(StringUtils.hasContent(request.str("generateProblem")))
|
||||
{
|
||||
return (plan.refuse(request.str("generateProblem")));
|
||||
}
|
||||
PolicyFormat format = config.getPolicyFormat();
|
||||
|
||||
List<String> oldNamed = nonNull(AuthentikJson.stringList(group.optJSONObject("attributes"), AuthentikJson.ATTR_PERMISSIONS));
|
||||
Set<String> extrasNew = new TreeSet<>(AuthentikSafety.parseList(request.str(EXTRA_PERMISSIONS)));
|
||||
extrasNew.removeAll(oldNamed);
|
||||
|
||||
Set<String> newPermissions;
|
||||
JSONObject canonical;
|
||||
try
|
||||
@@ -1071,18 +1132,35 @@ public class AuthentikAdmin
|
||||
return (plan.refuse("These are not permissions of this app: " + String.join(", ", unknownNew) + ". Pick them in the editor."));
|
||||
}
|
||||
|
||||
if(added.isEmpty() && removed.isEmpty() && storedProblem == null)
|
||||
if(added.isEmpty() && removed.isEmpty() && storedProblem == null && extrasNew.isEmpty())
|
||||
{
|
||||
return (plan.noChange("Nothing to change."));
|
||||
}
|
||||
|
||||
Set<String> missing = AuthentikSafety.missing(added, operator().permissions());
|
||||
Set<String> needed = new TreeSet<>(added);
|
||||
for(String extra : extrasNew)
|
||||
{
|
||||
needed.addAll(resolver().expand(extra));
|
||||
}
|
||||
Set<String> missing = AuthentikSafety.missing(needed, operator().permissions());
|
||||
if(!missing.isEmpty())
|
||||
{
|
||||
return (plan.refuse("You cannot grant permissions you do not hold yourself: " + String.join(", ", missing)));
|
||||
}
|
||||
|
||||
plan.withChange(policySummary(oldPermissions), policySummary(newPermissions));
|
||||
if(request.bool("generated"))
|
||||
{
|
||||
plan.getNotes().add("Generated from current access: " + PolicyGenerator.toCompact(canonical));
|
||||
if(StringUtils.hasContent(request.str("skippedPermissions")))
|
||||
{
|
||||
plan.getNotes().add("Skipped (this app does not define them): " + request.str("skippedPermissions").replace("\n", ", "));
|
||||
}
|
||||
}
|
||||
if(!extrasNew.isEmpty())
|
||||
{
|
||||
plan.getNotes().add("Also added to qqq.io/permissions (not expressible as a policy): " + abbreviate(extrasNew));
|
||||
}
|
||||
if(!added.isEmpty())
|
||||
{
|
||||
plan.getNotes().add("Adds: " + abbreviate(added));
|
||||
@@ -1113,6 +1191,290 @@ public class AuthentikAdmin
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fill a Save Policy request from what members of the group get TODAY from
|
||||
** the host (DESIGN.md section 12.8): the policy-expressible permissions
|
||||
** (joined with the group's current policy, so nothing is removed) become
|
||||
** the document; named permissions this app defines but a policy cannot
|
||||
** express go to qqq.io/permissions; the rest are listed as skipped.
|
||||
*******************************************************************************/
|
||||
public AdminRequest withGeneratedPolicy(AdminRequest request) throws QException
|
||||
{
|
||||
request.with("generated", true);
|
||||
if(config.getHostPermissionSource() == null)
|
||||
{
|
||||
return (request.with("generateProblem", "This app has no host permission source, so there is no current access to generate from."));
|
||||
}
|
||||
JSONObject group = util.getApiJsonOrNull("/core/groups/" + safeKey(request.targetKey()) + "/?include_users=false&include_parents=false&include_children=false");
|
||||
if(group == null)
|
||||
{
|
||||
return (request.with("generateProblem", "That group no longer exists."));
|
||||
}
|
||||
PolicyFormat format = config.getPolicyFormat();
|
||||
Set<String> policy = new TreeSet<>();
|
||||
Object stored = group.optJSONObject("attributes") == null ? null : group.getJSONObject("attributes").opt(format.attribute());
|
||||
policy.addAll(PolicyParser.parse(stored, format));
|
||||
|
||||
Set<String> expressible = runtime.getPolicyCatalog().permissionNames();
|
||||
Set<String> extras = new TreeSet<>();
|
||||
Set<String> skipped = new TreeSet<>();
|
||||
for(String permission : config.getHostPermissionSource().groupPermissions(group.optString("name")))
|
||||
{
|
||||
if(expressible.contains(permission))
|
||||
{
|
||||
policy.add(permission);
|
||||
}
|
||||
else if(!resolver().expand(permission).isEmpty())
|
||||
{
|
||||
extras.add(permission);
|
||||
}
|
||||
else
|
||||
{
|
||||
skipped.add(permission);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
request.with(POLICY_DOCUMENT, PolicyGenerator.toCompact(PolicyGenerator.generate(policy, format)));
|
||||
}
|
||||
catch(PolicyParseException e)
|
||||
{
|
||||
return (request.with("generateProblem", "The current access cannot be written as a policy: " + e.getMessage()));
|
||||
}
|
||||
return (request.with(EXTRA_PERMISSIONS, String.join("\n", extras)).with("skippedPermissions", String.join("\n", skipped)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Delete a person (DESIGN.md section 12.5): explicit, typed, never yourself,
|
||||
** a protected account or the last identity administrator.
|
||||
*******************************************************************************/
|
||||
private AdminPlan planDeleteUser(AdminPlan plan, AdminRequest request) throws QException
|
||||
{
|
||||
JSONObject user = targetUser(plan, request.targetKey(), false);
|
||||
if(user == null)
|
||||
{
|
||||
return (plan);
|
||||
}
|
||||
String typed = typedProblem(request, user.optString("username"));
|
||||
if(typed != null)
|
||||
{
|
||||
return (plan.refuse(typed));
|
||||
}
|
||||
Set<Integer> before = adminsNow();
|
||||
if(before.contains(user.optInt("pk")))
|
||||
{
|
||||
List<AuthentikSafety.UserFacts> changed = new ArrayList<>();
|
||||
for(AuthentikSafety.UserFacts facts : userFacts())
|
||||
{
|
||||
if(facts.pk() != user.optInt("pk"))
|
||||
{
|
||||
changed.add(facts);
|
||||
}
|
||||
}
|
||||
if(AuthentikSafety.removesLastAdmin(before, AuthentikSafety.qualifyingAdmins(membersGraph(), new EffectivePermissionResolver(membersGraph(), runtime.getPermissionCatalog()), changed)))
|
||||
{
|
||||
return (plan.refuse("This is the last active person who can manage memberships and permissions. Add another administrator first."));
|
||||
}
|
||||
}
|
||||
plan.getNotes().add("Deleting cannot be undone. Deactivate User keeps the account and its history.");
|
||||
return (plan.withChange(user.optString("username") + " <" + user.optString("email") + ">", "deleted"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Delete a group (DESIGN.md section 12.5): explicit, typed, and only when it
|
||||
** has no members and no child groups (remove them first, so nobody loses
|
||||
** access by surprise).
|
||||
*******************************************************************************/
|
||||
private AdminPlan planDeleteGroup(AdminPlan plan, AdminRequest request) throws QException
|
||||
{
|
||||
JSONObject group = targetGroup(plan, request.targetKey());
|
||||
if(group == null)
|
||||
{
|
||||
return (plan);
|
||||
}
|
||||
String name = group.optString("name");
|
||||
if(!request.str("confirmText").equals(name) && !request.bool("approved"))
|
||||
{
|
||||
return (plan.refuse("Type the group name (" + name + ") to confirm."));
|
||||
}
|
||||
JSONArray users = group.optJSONArray("users");
|
||||
if(users != null && !users.isEmpty())
|
||||
{
|
||||
return (plan.refuse("The group has " + users.length() + " member(s). Remove them first."));
|
||||
}
|
||||
List<String> children = new ArrayList<>();
|
||||
for(GroupGraph.Node node : graph().nodes())
|
||||
{
|
||||
if(node.parentPks().contains(request.targetKey()))
|
||||
{
|
||||
children.add(node.name());
|
||||
}
|
||||
}
|
||||
if(!children.isEmpty())
|
||||
{
|
||||
return (plan.refuse("The group has child groups (" + String.join(", ", children) + "). Change their parents first."));
|
||||
}
|
||||
plan.getNotes().add("Deleting cannot be undone. Its permissions, app access and policy go with it.");
|
||||
return (plan.withChange(name, "deleted"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Why the submitted other-attributes JSON cannot be applied, or null. It must
|
||||
** be a JSON object without reserved keys (qqq.io/ and goauthentik.io/ are
|
||||
** set elsewhere), and editing attributes needs authentik.audit.read
|
||||
** (attributes are sensitive, DESIGN.md section 5.3).
|
||||
*******************************************************************************/
|
||||
private String otherAttributesProblem(AdminRequest request, JSONObject current) throws QException
|
||||
{
|
||||
if(!StringUtils.hasContent(request.str(OTHER_ATTRIBUTES)))
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
try
|
||||
{
|
||||
JSONObject submitted = parseOtherAttributes(request.str(OTHER_ATTRIBUTES));
|
||||
for(String key : submitted.keySet())
|
||||
{
|
||||
if(isReservedAttribute(key))
|
||||
{
|
||||
return ("The attribute " + key + " is reserved; it is set by Edit Permissions, Edit Policy or Authentik itself.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(QUserFacingException e)
|
||||
{
|
||||
return (e.getMessage());
|
||||
}
|
||||
if(changedAttributeKeys(request, current) != null && !operator().permissions().contains(IdentityPermission.AUDIT_READ.getSessionPermission()) && !operator().bootstrap())
|
||||
{
|
||||
return ("Editing attributes needs " + IdentityPermission.AUDIT_READ.getShortName() + ".");
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The keys whose values the submitted attributes change (added, changed or
|
||||
** removed), or null for no change. Blank means "leave them as they are"
|
||||
** ({} removes them all). A null current compares against nothing.
|
||||
*******************************************************************************/
|
||||
private static String changedAttributeKeys(AdminRequest request, JSONObject current) throws QUserFacingException
|
||||
{
|
||||
if(!StringUtils.hasContent(request.str(OTHER_ATTRIBUTES)))
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
JSONObject submitted = parseOtherAttributes(request.str(OTHER_ATTRIBUTES));
|
||||
JSONObject others = otherAttributes(current);
|
||||
Set<String> changed = new TreeSet<>();
|
||||
for(String key : submitted.keySet())
|
||||
{
|
||||
if(!others.has(key) || !String.valueOf(others.get(key)).equals(String.valueOf(submitted.get(key))))
|
||||
{
|
||||
changed.add(key);
|
||||
}
|
||||
}
|
||||
for(String key : others.keySet())
|
||||
{
|
||||
if(!submitted.has(key))
|
||||
{
|
||||
changed.add(key);
|
||||
}
|
||||
}
|
||||
return (changed.isEmpty() ? null : String.join(", ", changed));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The current attributes with the non-reserved part replaced by the
|
||||
** submitted object (reserved keys are kept as they are).
|
||||
*******************************************************************************/
|
||||
static JSONObject mergeOtherAttributes(JSONObject current, String submittedText) throws QUserFacingException
|
||||
{
|
||||
JSONObject rs = new JSONObject();
|
||||
if(current != null)
|
||||
{
|
||||
for(String key : current.keySet())
|
||||
{
|
||||
if(isReservedAttribute(key))
|
||||
{
|
||||
rs.put(key, current.get(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
JSONObject submitted = parseOtherAttributes(submittedText);
|
||||
for(String key : submitted.keySet())
|
||||
{
|
||||
if(!isReservedAttribute(key))
|
||||
{
|
||||
rs.put(key, submitted.get(key));
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The non-reserved attributes, as shown on Edit User and Edit Group.
|
||||
*******************************************************************************/
|
||||
public static JSONObject otherAttributes(JSONObject attributes)
|
||||
{
|
||||
JSONObject rs = new JSONObject();
|
||||
if(attributes != null)
|
||||
{
|
||||
for(String key : attributes.keySet())
|
||||
{
|
||||
if(!isReservedAttribute(key))
|
||||
{
|
||||
rs.put(key, attributes.get(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Keys QQQ manages elsewhere (qqq.io/) or Authentik owns (goauthentik.io/).
|
||||
*******************************************************************************/
|
||||
static boolean isReservedAttribute(String key)
|
||||
{
|
||||
return (key.startsWith(AuthentikJson.QQQ_ATTRIBUTE_PREFIX) || key.startsWith("goauthentik.io/"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A submitted attributes text as a JSON object (blank means none).
|
||||
*******************************************************************************/
|
||||
private static JSONObject parseOtherAttributes(String text) throws QUserFacingException
|
||||
{
|
||||
if(!StringUtils.hasContent(text))
|
||||
{
|
||||
return (new JSONObject());
|
||||
}
|
||||
try
|
||||
{
|
||||
return (new JSONObject(text));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw (new QUserFacingException("Other attributes must be a JSON object, e.g. {\"department\": \"sales\"}."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** "n permission(s): a, b, ..." for the audit before/after.
|
||||
*******************************************************************************/
|
||||
@@ -1489,13 +1851,18 @@ public class AuthentikAdmin
|
||||
case EDIT_USER:
|
||||
{
|
||||
JSONObject body = new JSONObject();
|
||||
for(String key : List.of("name", "email", "path"))
|
||||
for(String key : List.of("username", "name", "email", "path"))
|
||||
{
|
||||
if(request.params().containsKey(key))
|
||||
if(request.params().containsKey(key) && (!key.equals("username") || StringUtils.hasContent(request.str(key))))
|
||||
{
|
||||
body.put(key, request.str(key));
|
||||
}
|
||||
}
|
||||
if(changedAttributeKeys(request, null) != null)
|
||||
{
|
||||
JSONObject fresh = util.getObject(AuthentikTables.get(AuthentikTables.USER), request.targetKey());
|
||||
body.put("attributes", mergeOtherAttributes(fresh == null ? null : fresh.optJSONObject("attributes"), request.str(OTHER_ATTRIBUTES)));
|
||||
}
|
||||
util.write(auth, "PATCH", "/core/users/" + safeKey(request.targetKey()) + "/", body);
|
||||
return ("User updated.");
|
||||
}
|
||||
@@ -1545,6 +1912,12 @@ public class AuthentikAdmin
|
||||
{
|
||||
body.put("name", request.str("name"));
|
||||
}
|
||||
if(changedAttributeKeys(request, null) != null)
|
||||
{
|
||||
runtime.invalidateCache();
|
||||
JSONObject fresh = util.getApiJsonOrNull("/core/groups/" + safeKey(request.targetKey()) + "/?include_users=false&include_parents=false&include_children=false");
|
||||
body.put("attributes", mergeOtherAttributes(fresh == null ? null : fresh.optJSONObject("attributes"), request.str(OTHER_ATTRIBUTES)));
|
||||
}
|
||||
if(request.params().containsKey("resolvedParentPks"))
|
||||
{
|
||||
JSONArray parents = new JSONArray();
|
||||
@@ -1578,6 +1951,22 @@ public class AuthentikAdmin
|
||||
}
|
||||
case SAVE_POLICY:
|
||||
return (performSavePolicy(plan, auth));
|
||||
case DELETE_USER:
|
||||
util.write(auth, "DELETE", "/core/users/" + safeKey(request.targetKey()) + "/", null);
|
||||
return ("User deleted in Authentik.");
|
||||
case DELETE_GROUP:
|
||||
{
|
||||
util.write(auth, "DELETE", "/core/groups/" + safeKey(request.targetKey()) + "/", null);
|
||||
try
|
||||
{
|
||||
PolicyStore.delete(config, request.targetKey());
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("The group was deleted but its policy record could not be removed", logPair("group", request.targetKey()), logPair("error", e.getMessage()));
|
||||
}
|
||||
return ("Group deleted in Authentik.");
|
||||
}
|
||||
case SEND_RECOVERY_EMAIL:
|
||||
sendRecovery(auth, request.targetKey());
|
||||
return ("Password reset email sent by Authentik.");
|
||||
@@ -1638,6 +2027,13 @@ public class AuthentikAdmin
|
||||
}
|
||||
JSONObject attributes = fresh.optJSONObject("attributes") == null ? new JSONObject() : new JSONObject(fresh.getJSONObject("attributes").toString());
|
||||
String compact = PolicyGenerator.toCompact(canonical);
|
||||
List<String> extras = AuthentikSafety.parseList(request.str(EXTRA_PERMISSIONS));
|
||||
if(!extras.isEmpty())
|
||||
{
|
||||
Set<String> named = new java.util.LinkedHashSet<>(nonNull(AuthentikJson.stringList(attributes, AuthentikJson.ATTR_PERMISSIONS)));
|
||||
named.addAll(extras);
|
||||
putList(attributes, AuthentikJson.ATTR_PERMISSIONS, new ArrayList<>(named));
|
||||
}
|
||||
if(permissions.isEmpty())
|
||||
{
|
||||
attributes.remove(format.attribute());
|
||||
|
||||
@@ -212,6 +212,22 @@ public final class AuthentikHomeView
|
||||
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");
|
||||
if(data.getConfig().hasFeature(com.kingsrook.qbits.authentik.AuthentikFeature.POLICIES))
|
||||
{
|
||||
String state;
|
||||
try
|
||||
{
|
||||
com.kingsrook.qbits.authentik.permissions.AccessComparison.State mapper = com.kingsrook.qbits.authentik.permissions.AccessComparison.state(
|
||||
com.kingsrook.qbits.authentik.AuthentikRuntime.forBackend(data.getConfig().getApiBackendName()),
|
||||
com.kingsrook.qbits.authentik.client.AuthentikActionUtil.forBackend(data.getConfig().getApiBackendName()));
|
||||
state = (mapper.enforced() ? "Enforced. " : "Not enforced. ") + mapper.message();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
state = "Unknown (" + e.getMessage() + ")";
|
||||
}
|
||||
row(html, "Policies at sign-in", state);
|
||||
}
|
||||
html.append("</dl>");
|
||||
close(html);
|
||||
}
|
||||
|
||||
@@ -86,10 +86,22 @@ public final class AuthentikRelations
|
||||
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");
|
||||
enforcement(qInstance, config, groupSections);
|
||||
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);
|
||||
|
||||
String policyTable = config.applyTablePrefix(AuthentikLocalTables.POLICY);
|
||||
if(qInstance.getTable(policyTable) != null)
|
||||
{
|
||||
List<QFieldSection> policySections = new ArrayList<>();
|
||||
enforcement(qInstance, config, policySections);
|
||||
policySections.add(new QFieldSection("policy", "Policy", new QIcon("policy"), Tier.T1,
|
||||
List.of("groupName", "statementCount", "permissionCount", "savedBy", "savedDate", "policyJson")));
|
||||
policySections.add(new QFieldSection("system", "System", new QIcon("settings"), Tier.T3, List.of("id", "groupPk", "authentikFingerprint", "createDate", "modifyDate")));
|
||||
applySections(qInstance, policyTable, policySections);
|
||||
}
|
||||
|
||||
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")));
|
||||
@@ -99,6 +111,20 @@ public final class AuthentikRelations
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policy enforcement banner as the first section (when produced).
|
||||
*******************************************************************************/
|
||||
private static void enforcement(QInstance qInstance, AuthentikQBitConfig config, List<QFieldSection> sections)
|
||||
{
|
||||
String widget = config.applyPrefix(com.kingsrook.qbits.authentik.policy.PolicyCutoverWidgets.ENFORCEMENT);
|
||||
if(qInstance.getWidget(widget) != null)
|
||||
{
|
||||
sections.add(0, new QFieldSection("enforcement", new QIcon("verified_user"), Tier.T2).withLabel("Policy enforcement").withWidgetName(widget));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One join plus its child-list widget and the section that shows it.
|
||||
*******************************************************************************/
|
||||
|
||||
+2
-1
@@ -74,7 +74,8 @@ public class AuthentikAppMetaDataProducer extends QBitComponentMetaDataProducer<
|
||||
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)))
|
||||
for(String widgetName : List.of(config.applyPrefix(AuthentikHomeWidgetProducer.NAME), config.applyPrefix(AuthentikDriftReportWidgetProducer.NAME),
|
||||
config.applyPrefix(com.kingsrook.qbits.authentik.policy.PolicyCutoverWidgets.COMPARE)))
|
||||
{
|
||||
if(produced.get(QWidgetMetaData.class, widgetName) != null)
|
||||
{
|
||||
|
||||
+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.PolicyCutoverWidgets;
|
||||
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;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compare Access (DESIGN.md section 12.8): today's access against what the policies would grant, per active person. Read only.
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyCompareWidgetProducer 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(PolicyCutoverWidgets.COMPARE))
|
||||
.withLabel("Compare Access")
|
||||
.withType(WidgetType.TABLE.getType())
|
||||
.withGridColumns(12)
|
||||
.withIsCard(true)
|
||||
.withCodeReference(new QCodeReference(PolicyCutoverWidgets.CompareRenderer.class))
|
||||
.withPermissionRules(IdentityPermission.ADMIN.rules())
|
||||
.withDefaultValue(PolicyCutoverWidgets.BACKEND_NAME_KEY, config.getApiBackendName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the tables, before the app.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (470);
|
||||
}
|
||||
}
|
||||
+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.PolicyCutoverWidgets;
|
||||
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 policy enforcement banner (DESIGN.md section 12.8): whether saved policies take effect at sign-in on this instance.
|
||||
*******************************************************************************/
|
||||
public class AuthentikPolicyEnforcementWidgetProducer 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(PolicyCutoverWidgets.ENFORCEMENT))
|
||||
.withLabel("Policy Enforcement")
|
||||
.withType(WidgetType.HTML.getType())
|
||||
.withGridColumns(12)
|
||||
.withIsCard(false)
|
||||
.withCodeReference(new QCodeReference(PolicyCutoverWidgets.EnforcementRenderer.class))
|
||||
.withPermissionRules(IdentityPermission.USERS_READ.rules())
|
||||
.withDefaultValue(PolicyCutoverWidgets.BACKEND_NAME_KEY, config.getApiBackendName()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** After the tables, before the app.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public int getSortOrder()
|
||||
{
|
||||
return (465);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
/*
|
||||
* 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.permissions;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qbits.authentik.AuthentikQBitConfig;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import org.json.JSONObject;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The cut-over from a host's current permission source to Authentik group
|
||||
** policies (DESIGN.md section 12.8): for every active person, what they get
|
||||
** today (the host source) against what the mapper would grant (their groups'
|
||||
** policies and permissions, the static fallback and bootstrap subjects), and
|
||||
** the guard that keeps the mapper inactive while a member of a guarded group
|
||||
** would lose a permission.
|
||||
*******************************************************************************/
|
||||
public final class AccessComparison
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AccessComparison.class);
|
||||
|
||||
/** How long a computed mapper state is reused (sign-ins read it). */
|
||||
public static final Duration STATE_TTL = Duration.ofSeconds(60);
|
||||
|
||||
/** Banner shown wherever policies are edited while they are not enforced. */
|
||||
public static final String NOT_ENFORCED = "Policies are saved but NOT enforced at sign-in on this instance (mapper off).";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One person.
|
||||
*******************************************************************************/
|
||||
public record Row(int pk, String username, String email, List<String> groups, Set<String> before, Set<String> after,
|
||||
Set<String> added, Set<String> removed, boolean guarded)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the mapper is enforcing policies, and why not.
|
||||
*******************************************************************************/
|
||||
public enum Status
|
||||
{
|
||||
/** The host does not use the mapper: policies are saved, not enforced. */
|
||||
OFF,
|
||||
/** Enforced; the guard passed (or there is nothing to guard). */
|
||||
ACTIVE,
|
||||
/** Enforced because the owner overrode a failing guard. */
|
||||
OVERRIDDEN,
|
||||
/** Not enforced: the guard failed (or could not run); sign-in uses the host source. */
|
||||
BLOCKED
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A mapper state with a plain message.
|
||||
*******************************************************************************/
|
||||
public record State(Status status, String message, Instant checkedAt)
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Whether sign-in permissions come from the policies.
|
||||
*******************************************************************************/
|
||||
public boolean enforced()
|
||||
{
|
||||
return (status == Status.ACTIVE || status == Status.OVERRIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private AccessComparison()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compare every active person (internal and external users).
|
||||
*******************************************************************************/
|
||||
public static List<Row> run(AuthentikQBitConfig config, AuthentikActionUtil util, Collection<String> catalog) throws QException
|
||||
{
|
||||
GroupGraph graph = util.groupGraphWithMembers();
|
||||
EffectivePermissionResolver resolver = new EffectivePermissionResolver(graph, catalog);
|
||||
AuthentikHostPermissionSource source = config.getHostPermissionSource();
|
||||
List<Row> rows = new ArrayList<>();
|
||||
for(JSONObject user : util.allUsers())
|
||||
{
|
||||
String type = user.optString("type");
|
||||
if(!user.optBoolean("is_active", true) || !("internal".equals(type) || "external".equals(type)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int pk = user.optInt("pk");
|
||||
List<String> groupPks = graph.groupsOfUser(pk);
|
||||
List<String> names = new ArrayList<>();
|
||||
for(String groupPk : groupPks)
|
||||
{
|
||||
names.add(graph.byPk(groupPk).name());
|
||||
}
|
||||
String email = user.optString("email", null);
|
||||
Set<String> before = new TreeSet<>(source == null ? Set.of() : source.userPermissions(email, names));
|
||||
Set<String> after = mapperPermissions(config, resolver, groupPks, names, String.valueOf(pk), user.optString("uuid"));
|
||||
Set<String> added = new TreeSet<>(after);
|
||||
added.removeAll(before);
|
||||
Set<String> removed = new TreeSet<>(before);
|
||||
removed.removeAll(after);
|
||||
boolean guarded = names.stream().anyMatch(n -> config.getCutoverGuardGroups() != null && config.getCutoverGuardGroups().contains(n));
|
||||
rows.add(new Row(pk, user.optString("username"), email, names, before, after, added, removed, guarded));
|
||||
}
|
||||
return (rows);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What the mapper grants for a person's direct groups: the groups' (and
|
||||
** ancestors') qqq.io/permissions and policies, the static fallback of the
|
||||
** direct groups, and every authentik.* permission for a bootstrap subject.
|
||||
*******************************************************************************/
|
||||
public static Set<String> mapperPermissions(AuthentikQBitConfig config, EffectivePermissionResolver resolver, Collection<String> groupPks, Collection<String> directGroupNames,
|
||||
String userPk, String userUuid)
|
||||
{
|
||||
Set<String> rs = new TreeSet<>(resolver.resolveGroups(groupPks).sessionPermissions());
|
||||
rs.addAll(staticPermissions(config, directGroupNames));
|
||||
Set<String> subjects = config.getResolvedBootstrapSubjects();
|
||||
if(subjects.contains(userPk) || (userUuid != null && !userUuid.isEmpty() && subjects.contains(userUuid)))
|
||||
{
|
||||
for(IdentityPermission permission : IdentityPermission.values())
|
||||
{
|
||||
rs.add(permission.getSessionPermission());
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The static fallback permissions of some direct groups.
|
||||
*******************************************************************************/
|
||||
public static Set<String> staticPermissions(AuthentikQBitConfig config, Collection<String> directGroupNames)
|
||||
{
|
||||
Set<String> rs = new TreeSet<>();
|
||||
if(config.getStaticGroupPermissions() != null)
|
||||
{
|
||||
for(String name : directGroupNames)
|
||||
{
|
||||
rs.addAll(config.getStaticGroupPermissions().getOrDefault(name, List.of()));
|
||||
}
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The people in guarded groups who would lose a permission (the guard fails
|
||||
** when this is not empty).
|
||||
*******************************************************************************/
|
||||
public static List<Row> guardFailures(List<Row> rows)
|
||||
{
|
||||
return (rows.stream().filter(r -> r.guarded() && !r.removed().isEmpty()).toList());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The mapper state of a backend (cached for STATE_TTL; sign-ins read it).
|
||||
*******************************************************************************/
|
||||
public static State state(AuthentikRuntime runtime, AuthentikActionUtil util)
|
||||
{
|
||||
State cached = runtime.getMapperState();
|
||||
if(cached != null && cached.checkedAt().plus(STATE_TTL).isAfter(Instant.now()))
|
||||
{
|
||||
return (cached);
|
||||
}
|
||||
State state = compute(runtime, util);
|
||||
runtime.setMapperState(state);
|
||||
return (state);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compute the mapper state now.
|
||||
*******************************************************************************/
|
||||
static State compute(AuthentikRuntime runtime, AuthentikActionUtil util)
|
||||
{
|
||||
AuthentikQBitConfig config = runtime.getConfig();
|
||||
if(!Boolean.TRUE.equals(config.getMapperEnabled()) && !runtime.isMapperInvoked())
|
||||
{
|
||||
return (new State(Status.OFF, NOT_ENFORCED, Instant.now()));
|
||||
}
|
||||
if(config.getCutoverGuardGroups() == null || config.getCutoverGuardGroups().isEmpty())
|
||||
{
|
||||
return (new State(Status.ACTIVE, "Policies are enforced at sign-in.", Instant.now()));
|
||||
}
|
||||
if(Boolean.TRUE.equals(config.getMapperOverride()))
|
||||
{
|
||||
return (new State(Status.OVERRIDDEN, "Policies are enforced at sign-in; the cut-over guard is overridden by the owner.", Instant.now()));
|
||||
}
|
||||
try
|
||||
{
|
||||
List<Row> failures = guardFailures(run(config, util, runtime.getPermissionCatalog()));
|
||||
if(failures.isEmpty())
|
||||
{
|
||||
return (new State(Status.ACTIVE, "Policies are enforced at sign-in; the cut-over guard passed (no member of "
|
||||
+ String.join(", ", config.getCutoverGuardGroups()) + " loses a permission).", Instant.now()));
|
||||
}
|
||||
List<String> names = failures.stream().map(Row::username).limit(5).toList();
|
||||
return (new State(Status.BLOCKED, "Policies are saved but NOT enforced at sign-in: the cut-over guard found " + failures.size() + " member(s) of "
|
||||
+ String.join(", ", config.getCutoverGuardGroups()) + " who would lose permissions (" + String.join(", ", names)
|
||||
+ "). Sign-in keeps today's access until the policies cover it, or the owner overrides the guard.", Instant.now()));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOG.warn("The cut-over guard could not run; the mapper stays inactive", logPair("error", e.getMessage()));
|
||||
return (new State(Status.BLOCKED, "Policies are saved but NOT enforced at sign-in: the cut-over guard could not check Authentik ("
|
||||
+ e.getMessage() + "). Sign-in keeps today's access.", Instant.now()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -117,6 +117,49 @@ public class AuthentikGroupPermissionMapper implements QAuthenticationModuleCust
|
||||
AuthentikRuntime runtime = runtime();
|
||||
PolicyFormat format = runtime == null ? PolicyFormat.DEFAULT : runtime.getConfig().getPolicyFormat();
|
||||
permissions.addAll(PolicyPermissions.fromClaims(PolicyPermissions.claimsWithPolicy(context, format), format));
|
||||
|
||||
if(runtime != null)
|
||||
{
|
||||
permissions.addAll(AccessComparison.staticPermissions(runtime.getConfig(), groups));
|
||||
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// the cut-over guard (DESIGN.md section 12.8): while it blocks, the //
|
||||
// session gets today's access from the host plus the floor (static //
|
||||
// fallbacks, bootstrap subjects), never the policies alone //
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
runtime.markMapperInvoked();
|
||||
AccessComparison.State state;
|
||||
try
|
||||
{
|
||||
state = AccessComparison.state(runtime, client(qInstance));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
state = new AccessComparison.State(AccessComparison.Status.BLOCKED, "The cut-over guard could not run", java.time.Instant.now());
|
||||
}
|
||||
if(!state.enforced())
|
||||
{
|
||||
Set<String> floor = new TreeSet<>(AccessComparison.staticPermissions(runtime.getConfig(), groups));
|
||||
for(String group : groups)
|
||||
{
|
||||
floor.addAll(staticGroupPermissions.getOrDefault(group, List.of()));
|
||||
}
|
||||
if(!runtime.getConfig().getResolvedBootstrapSubjects().isEmpty() && isBootstrap(qInstance, runtime, sub, email, verified))
|
||||
{
|
||||
for(IdentityPermission permission : IdentityPermission.values())
|
||||
{
|
||||
floor.add(permission.getSessionPermission());
|
||||
}
|
||||
}
|
||||
AuthentikHostPermissionSource source = runtime.getConfig().getHostPermissionSource();
|
||||
if(source != null)
|
||||
{
|
||||
floor.addAll(source.userPermissions(email, groups));
|
||||
}
|
||||
LOG.warn("Policies are not enforced at this sign-in; granting today's access", logPair("reason", state.message()));
|
||||
permissions = floor;
|
||||
}
|
||||
}
|
||||
if(qSession.getPermissions() != null)
|
||||
{
|
||||
permissions.addAll(qSession.getPermissions());
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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.permissions;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** SPI: the permissions a host grants TODAY, before Authentik group policies
|
||||
** take over (DESIGN.md section 12.8). Typically a hard-coded grant such as
|
||||
** "members of the admins group get adminPermissions()". The qbit uses it to
|
||||
** - generate a group's policy from current access,
|
||||
** - compare current access with what the mapper would grant, and
|
||||
** - fall back to it while the cut-over guard keeps the mapper inactive.
|
||||
*******************************************************************************/
|
||||
public interface AuthentikHostPermissionSource
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** The QQQ session permissions a user gets today.
|
||||
**
|
||||
** @param email the user's email (may be null)
|
||||
** @param groupNames the user's direct Authentik group names
|
||||
*******************************************************************************/
|
||||
Set<String> userPermissions(String email, Collection<String> groupNames);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permissions members of a group get today because of that group. The
|
||||
** default asks for a user in only that group.
|
||||
*******************************************************************************/
|
||||
default Set<String> groupPermissions(String groupName)
|
||||
{
|
||||
return (userPermissions(null, List.of(groupName)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* 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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.permissions.AccessComparison;
|
||||
import com.kingsrook.qbits.authentik.security.AuthentikGuard;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
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.dashboard.widgets.TableData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The cut-over widgets (DESIGN.md section 12.8): the enforcement banner shown
|
||||
** on group and policy screens and on Edit Policy, and the Compare Access
|
||||
** report (read only).
|
||||
*******************************************************************************/
|
||||
public final class PolicyCutoverWidgets
|
||||
{
|
||||
/** Widget default value naming the qbit's API backend. */
|
||||
public static final String BACKEND_NAME_KEY = "backendName";
|
||||
|
||||
/** Short name of the banner widget. */
|
||||
public static final String ENFORCEMENT = "policyEnforcement";
|
||||
|
||||
/** Short name of the report widget. */
|
||||
public static final String COMPARE = "compareAccess";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private PolicyCutoverWidgets()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The mapper state for a widget's backend.
|
||||
*******************************************************************************/
|
||||
static AccessComparison.State state(RenderWidgetInput input) throws QException
|
||||
{
|
||||
String backendName = String.valueOf(((QWidgetMetaData) input.getWidgetMetaData()).getDefaultValues().get(BACKEND_NAME_KEY));
|
||||
return (AccessComparison.state(AuthentikRuntime.forBackend(backendName), AuthentikActionUtil.forBackend(backendName)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The banner as HTML (also used by the home's health card).
|
||||
*******************************************************************************/
|
||||
public static String bannerHtml(AccessComparison.State state)
|
||||
{
|
||||
String style = state.enforced()
|
||||
? "border:1px solid #16a34a;background:rgba(22,163,74,.10);"
|
||||
: "border:1px solid #d97706;background:rgba(217,119,6,.12);";
|
||||
return ("<div role=\"status\" data-qqq-id=\"authentik-policy-enforcement\" data-status=\"" + state.status().name() + "\" style=\"" + style
|
||||
+ "border-radius:.375rem;padding:.5rem .75rem;font-size:.875rem;line-height:1.4;color:inherit;\"><strong>"
|
||||
+ (state.enforced() ? "Enforced. " : "Not enforced. ") + "</strong>" + escape(state.message()) + "</div>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static String escape(String text)
|
||||
{
|
||||
return (text == null ? "" : text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The enforcement banner (authentik.users.read).
|
||||
*******************************************************************************/
|
||||
public static class EnforcementRenderer extends AbstractWidgetRenderer
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
|
||||
{
|
||||
return (new RenderWidgetOutput(new RawHTML(null, bannerHtml(state(input)))));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compare Access (authentik.admin): every active person's access today
|
||||
** against what the mapper would grant. Read only.
|
||||
*******************************************************************************/
|
||||
public static class CompareRenderer extends AbstractWidgetRenderer
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
|
||||
{
|
||||
if(!AuthentikGuard.has(QContext.getQSession(), IdentityPermission.ADMIN))
|
||||
{
|
||||
throw (new QPermissionDeniedException("You do not have permission to compare access."));
|
||||
}
|
||||
String backendName = String.valueOf(((QWidgetMetaData) input.getWidgetMetaData()).getDefaultValues().get(BACKEND_NAME_KEY));
|
||||
AuthentikRuntime runtime = AuthentikRuntime.forBackend(backendName);
|
||||
List<AccessComparison.Row> rows = AccessComparison.run(runtime.getConfig(), AuthentikActionUtil.forBackend(backendName), runtime.getPermissionCatalog());
|
||||
|
||||
List<Map<String, Object>> data = new ArrayList<>();
|
||||
int removedPeople = 0;
|
||||
for(AccessComparison.Row row : rows)
|
||||
{
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("user", escape(row.username()) + (row.guarded() ? " (guarded)" : ""));
|
||||
map.put("groups", escape(String.join(", ", row.groups())));
|
||||
map.put("added", row.added().isEmpty() ? "-" : escape(String.join(", ", row.added())));
|
||||
map.put("removed", row.removed().isEmpty() ? "-" : escape(String.join(", ", row.removed())));
|
||||
map.put("unchanged", row.before().size() - row.removed().size());
|
||||
data.add(map);
|
||||
if(!row.removed().isEmpty())
|
||||
{
|
||||
removedPeople++;
|
||||
}
|
||||
}
|
||||
List<TableData.Column> columns = List.of(
|
||||
new TableData.Column("html", "User", "user", "15%", "left"),
|
||||
new TableData.Column("html", "Groups", "groups", "20%", "left"),
|
||||
new TableData.Column("html", "Added", "added", "27%", "left"),
|
||||
new TableData.Column("html", "Removed", "removed", "28%", "left"),
|
||||
new TableData.Column("default", "Unchanged", "unchanged", "10%", "right"));
|
||||
List<AccessComparison.Row> failures = AccessComparison.guardFailures(rows);
|
||||
String summary = rows.size() + " active people; " + removedPeople + " would lose permissions; guard "
|
||||
+ (runtime.getConfig().getCutoverGuardGroups().isEmpty() ? "not configured" : failures.isEmpty() ? "passes" : "FAILS for " + failures.size())
|
||||
+ (runtime.getConfig().getHostPermissionSource() == null ? ". No host permission source is configured, so today's access is shown as empty." : ".");
|
||||
TableData table = new TableData("Compare Access (today vs policies)", columns, data)
|
||||
.withRowsPerPage(25)
|
||||
.withNoRowsFoundHTML("No active people.");
|
||||
table.setFooterHTML("<p style=\"font-size:.875rem;\">" + escape(summary) + "</p>");
|
||||
return (new RenderWidgetOutput(table));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,11 +25,13 @@ 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.DeleteAction;
|
||||
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.delete.DeleteInput;
|
||||
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;
|
||||
@@ -111,6 +113,23 @@ public final class PolicyStore
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Remove the row of a deleted group (no-op without one).
|
||||
*******************************************************************************/
|
||||
public static void delete(AuthentikQBitConfig config, String groupPk) throws QException
|
||||
{
|
||||
QRecord existing = find(config, groupPk);
|
||||
if(existing != null)
|
||||
{
|
||||
DeleteInput deleteInput = new DeleteInput();
|
||||
deleteInput.setTableName(config.applyTablePrefix(AuthentikLocalTables.POLICY));
|
||||
deleteInput.setPrimaryKeys(List.of(existing.getValue("id")));
|
||||
new DeleteAction().execute(deleteInput);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Insert or update the row of a group after a save to Authentik.
|
||||
**
|
||||
|
||||
@@ -150,14 +150,20 @@ public final class AuthentikProcesses
|
||||
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."));
|
||||
QFieldMetaData otherAttributes = new QFieldMetaData(AuthentikAdmin.OTHER_ATTRIBUTES, QFieldType.TEXT).withLabel("Other attributes (JSON; leave blank to keep them)");
|
||||
defs.add(new Def("editUser", "Edit User", AdminAction.EDIT_USER, Kind.USERS, users, "edit", true, List.of(
|
||||
new QFieldMetaData("username", QFieldType.STRING).withLabel("Username"),
|
||||
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."));
|
||||
otherAttributes,
|
||||
hidden("expectedFingerprint"), reason), "Change a person's username, name, email, path or other attributes. "
|
||||
+ "Attributes starting with qqq.io/ or goauthentik.io/ are set elsewhere; editing attributes needs authentik.audit.read."));
|
||||
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("deleteUser", "Delete User", AdminAction.DELETE_USER, Kind.USERS, users, "delete_forever", false, List.of(typed, reason),
|
||||
"Deletes the account in Authentik permanently. To keep the account and its history, use Deactivate User instead."));
|
||||
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),
|
||||
@@ -181,7 +187,11 @@ public final class AuthentikProcesses
|
||||
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."));
|
||||
otherAttributes,
|
||||
hidden("expectedFingerprint"), reason), "Rename a group, change its parents or its other attributes."));
|
||||
defs.add(new Def("deleteGroup", "Delete Group", AdminAction.DELETE_GROUP, Kind.GROUPS, groups, "delete_forever", false, List.of(
|
||||
new QFieldMetaData("confirmText", QFieldType.STRING).withLabel("Type the group name to confirm").withIsRequired(true), reason),
|
||||
"Deletes the group in Authentik permanently, with its permissions, app access and policy. Remove its members and child groups first."));
|
||||
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)"),
|
||||
@@ -191,6 +201,9 @@ public final class AuthentikProcesses
|
||||
+ "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("generatePolicy", "Generate Policy From Current Access", AdminAction.SAVE_POLICY, Kind.GROUPS, groups, "auto_fix_high", false, List.of(reason),
|
||||
"Builds this group's policy from what its members get today from the app (joined with its current policy, so nothing is removed). "
|
||||
+ "Review shows the generated document and what changes before anything is saved."));
|
||||
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),
|
||||
@@ -204,6 +217,8 @@ public final class AuthentikProcesses
|
||||
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()));
|
||||
defs.removeIf(def -> (def.action() == AdminAction.DELETE_USER && !config.hasFeature(com.kingsrook.qbits.authentik.AuthentikFeature.USERS))
|
||||
|| (def.action() == AdminAction.DELETE_GROUP && !config.hasFeature(com.kingsrook.qbits.authentik.AuthentikFeature.GROUPS)));
|
||||
if(!config.hasFeature(com.kingsrook.qbits.authentik.AuthentikFeature.GROUPS) || !config.getTwoPersonApproval())
|
||||
{
|
||||
defs.removeIf(def -> def.kind() == Kind.APPROVALS);
|
||||
@@ -284,7 +299,7 @@ public final class AuthentikProcesses
|
||||
{
|
||||
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);
|
||||
|| def.action() == AdminAction.SAVE_POLICY || def.action() == AdminAction.DELETE_USER || def.action() == AdminAction.DELETE_GROUP ? 1 : AuthentikAdmin.MAX_BULK);
|
||||
}
|
||||
default ->
|
||||
{
|
||||
@@ -299,6 +314,10 @@ public final class AuthentikProcesses
|
||||
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(com.kingsrook.qbits.authentik.policy.PolicyCutoverWidgets.ENFORCEMENT)));
|
||||
}
|
||||
if(def.action() == AdminAction.SAVE_POLICY && !def.key().equals("generatePolicy"))
|
||||
{
|
||||
details.withComponent(new QFrontendComponentMetaData().withType(QComponentType.WIDGET).withValue("widgetName", config.applyPrefix(PolicyEditorWidget.NAME)));
|
||||
}
|
||||
@@ -352,6 +371,8 @@ public final class AuthentikProcesses
|
||||
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 DELETE_USER -> w("user will be deleted", "users will be deleted", "user was deleted", "users were deleted");
|
||||
case DELETE_GROUP -> w("group will be deleted", "groups will be deleted", "group was deleted", "groups were deleted");
|
||||
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");
|
||||
@@ -421,7 +442,11 @@ public final class AuthentikProcesses
|
||||
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 GROUPS, INVITATIONS ->
|
||||
{
|
||||
AdminRequest request = withParams(AdminRequest.of(def.action(), String.valueOf(record.getValue("pk") != null ? record.getValue("pk") : record.getValue("uuid")), reason), def, input);
|
||||
rs.add("generatePolicy".equals(def.key()) ? admin.withGeneratedPolicy(request) : request);
|
||||
}
|
||||
case POLICIES -> rs.add(withParams(AdminRequest.of(def.action(), record.getValueString("groupPk"), reason), def, input));
|
||||
default ->
|
||||
{
|
||||
@@ -441,7 +466,7 @@ public final class AuthentikProcesses
|
||||
// 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)
|
||||
if(def.action() == AdminAction.SAVE_POLICY && !"generatePolicy".equals(def.key()) && input.getValue(AuthentikAdmin.POLICY_DOCUMENT) != null)
|
||||
{
|
||||
request.with(AuthentikAdmin.POLICY_DOCUMENT, input.getValueString(AuthentikAdmin.POLICY_DOCUMENT));
|
||||
}
|
||||
@@ -494,6 +519,18 @@ public final class AuthentikProcesses
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Attributes are sensitive (DESIGN.md section 5.3): they are shown on the
|
||||
** edit forms only with authentik.audit.read; left blank, they are unchanged.
|
||||
*******************************************************************************/
|
||||
static boolean canSeeAttributes()
|
||||
{
|
||||
return (QContext.getQSession() != null && QContext.getQSession().getPermissions() != null
|
||||
&& QContext.getQSession().getPermissions().contains(IdentityPermission.AUDIT_READ.getSessionPermission()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The details screen is filled from the selected record (edit actions).
|
||||
*******************************************************************************/
|
||||
@@ -529,6 +566,11 @@ public final class AuthentikProcesses
|
||||
JSONObject user = admin.getUtil().getObject(AuthentikTables.get(AuthentikTables.USER), pk);
|
||||
if(user != null)
|
||||
{
|
||||
output.addValue("username", user.optString("username"));
|
||||
if(canSeeAttributes())
|
||||
{
|
||||
output.addValue(AuthentikAdmin.OTHER_ATTRIBUTES, AuthentikAdmin.otherAttributes(user.optJSONObject("attributes")).toString(2));
|
||||
}
|
||||
output.addValue("name", user.optString("name"));
|
||||
output.addValue("email", user.optString("email"));
|
||||
output.addValue("path", user.optString("path"));
|
||||
@@ -543,6 +585,10 @@ public final class AuthentikProcesses
|
||||
output.addValue("expectedFingerprint", AuthentikSafety.groupFingerprint(group));
|
||||
if(def.action() == AdminAction.EDIT_GROUP)
|
||||
{
|
||||
if(canSeeAttributes())
|
||||
{
|
||||
output.addValue(AuthentikAdmin.OTHER_ATTRIBUTES, AuthentikAdmin.otherAttributes(group.optJSONObject("attributes")).toString(2));
|
||||
}
|
||||
output.addValue("name", group.optString("name"));
|
||||
JSONArray parents = group.optJSONArray("parents_obj");
|
||||
List<String> names = new ArrayList<>();
|
||||
|
||||
@@ -297,6 +297,29 @@ public class FakeAuthentik
|
||||
user.put("last_updated", "2026-10-12T01:00:00Z");
|
||||
return (ok(200, render(user)));
|
||||
}
|
||||
if(path.matches("/core/users/[0-9]+/") && method.equals("DELETE"))
|
||||
{
|
||||
int pk = Integer.parseInt(path.split("/")[3]);
|
||||
users.remove(pk);
|
||||
for(JSONObject group : groups.values())
|
||||
{
|
||||
JSONArray kept = new JSONArray();
|
||||
for(int i = 0; i < group.getJSONArray("users").length(); i++)
|
||||
{
|
||||
if(group.getJSONArray("users").getInt(i) != pk)
|
||||
{
|
||||
kept.put(group.getJSONArray("users").getInt(i));
|
||||
}
|
||||
}
|
||||
group.put("users", kept);
|
||||
}
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.matches("/core/groups/[^/]+/") && method.equals("DELETE"))
|
||||
{
|
||||
groups.remove(path.split("/")[3]);
|
||||
return (ok(204, null));
|
||||
}
|
||||
if(path.matches("/core/groups/[^/]+/") && method.equals("PATCH"))
|
||||
{
|
||||
JSONObject group = groups.get(path.split("/")[3]);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
* 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.Collection;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qbits.authentik.AuthentikFeature;
|
||||
import com.kingsrook.qbits.authentik.AuthentikRuntime;
|
||||
import com.kingsrook.qbits.authentik.client.AuthentikActionUtil;
|
||||
import com.kingsrook.qbits.authentik.permissions.AccessComparison;
|
||||
import com.kingsrook.qbits.authentik.permissions.AuthentikGroupPermissionMapper;
|
||||
import com.kingsrook.qbits.authentik.permissions.AuthentikHostPermissionSource;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyCutoverWidgets;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyFormat;
|
||||
import com.kingsrook.qbits.authentik.policy.PolicyParser;
|
||||
import com.kingsrook.qqq.backend.core.actions.dashboard.RenderWidgetAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
|
||||
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.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
|
||||
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.TableData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
|
||||
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;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The cut-over to policies (DESIGN.md section 12.8): enforcement status, the
|
||||
** compare report, the guard (and its fallback to today's access), and
|
||||
** Generate Policy From Current Access.
|
||||
*******************************************************************************/
|
||||
class PolicyCutoverTest
|
||||
{
|
||||
/** Today's grant: publishers read pages and publish; analysts see analytics. */
|
||||
static final AuthentikHostPermissionSource SOURCE = new AuthentikHostPermissionSource()
|
||||
{
|
||||
@Override
|
||||
public Set<String> userPermissions(String email, Collection<String> groupNames)
|
||||
{
|
||||
Set<String> rs = new TreeSet<>();
|
||||
if(groupNames.contains("kof-website-publishers") || groupNames.contains("identity-admins"))
|
||||
{
|
||||
rs.addAll(List.of("cms_page.read", "cms_page.edit", "cms.publish.hasAccess", "nothing.here.hasAccess"));
|
||||
}
|
||||
if(groupNames.contains("kof-website-analysts") || groupNames.contains("identity-admins"))
|
||||
{
|
||||
rs.addAll(List.of("kof22.analytics.hasAccess", "nothing.here.hasAccess"));
|
||||
}
|
||||
return (rs);
|
||||
}
|
||||
};
|
||||
|
||||
private AdminTestSupport t;
|
||||
private AuthentikRuntime runtime;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws Exception
|
||||
{
|
||||
t = AdminTestSupport.create(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP, AuthentikFeature.POLICIES));
|
||||
t.config.withHostPermissionSource(SOURCE).withCutoverGuardGroups(List.of("kof-website-publishers"));
|
||||
runtime = AuthentikRuntime.forBackend(t.config.getApiBackendName());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AccessComparison.State state() throws Exception
|
||||
{
|
||||
runtime.setMapperState(null);
|
||||
return (AccessComparison.state(runtime, AuthentikActionUtil.forBackend(t.config.getApiBackendName())));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** OFF until the host turns the mapper on; then the guard decides; the
|
||||
** owner can override.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void statusAndGuard() throws Exception
|
||||
{
|
||||
assertThat(state().status()).isEqualTo(AccessComparison.Status.OFF);
|
||||
assertThat(state().message()).isEqualTo("Policies are saved but NOT enforced at sign-in on this instance (mapper off).");
|
||||
|
||||
t.config.withMapperEnabled(true);
|
||||
AccessComparison.State blocked = state();
|
||||
assertThat(blocked.status()).isEqualTo(AccessComparison.Status.BLOCKED);
|
||||
assertThat(blocked.message()).contains("1 member(s) of kof-website-publishers").contains("operator");
|
||||
|
||||
t.config.withMapperOverride(true);
|
||||
assertThat(state().status()).isEqualTo(AccessComparison.Status.OVERRIDDEN);
|
||||
t.config.withMapperOverride(false);
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// the static fallback for the guarded group covers today's grant //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
t.config.withStaticGroupPermissions(Map.of("identity-admins", List.copyOf(SOURCE.userPermissions(null, List.of("identity-admins")))));
|
||||
assertThat(state().status()).isEqualTo(AccessComparison.Status.ACTIVE);
|
||||
assertThat(state().enforced()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compare Access: today against the mapper, per active person.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void compareReport() throws Exception
|
||||
{
|
||||
List<AccessComparison.Row> rows = AccessComparison.run(t.config, AuthentikActionUtil.forBackend(t.config.getApiBackendName()), runtime.getPermissionCatalog());
|
||||
AccessComparison.Row operator = rows.stream().filter(r -> r.username().equals("operator")).findFirst().orElseThrow();
|
||||
assertThat(operator.guarded()).isTrue();
|
||||
assertThat(operator.removed()).contains("cms_page.read", "cms_page.edit", "kof22.analytics.hasAccess").doesNotContain("cms.publish.hasAccess");
|
||||
assertThat(operator.added()).contains("authentik.users.read.hasAccess");
|
||||
assertThat(rows).noneMatch(r -> r.username().equals("dormant") || r.username().equals("svc-publisher"));
|
||||
assertThat(AccessComparison.guardFailures(rows)).extracting(AccessComparison.Row::username).containsExactly("operator");
|
||||
|
||||
RenderWidgetInput input = new RenderWidgetInput();
|
||||
input.setWidgetMetaData(t.qInstance.getWidget("authentikCompareAccess"));
|
||||
TableData table = (TableData) new RenderWidgetAction().execute(input).getWidgetData();
|
||||
assertThat(table.getRows()).anyMatch(r -> String.valueOf(r.get("user")).equals("operator (guarded)") && String.valueOf(r.get("removed")).contains("cms_page.edit"));
|
||||
assertThat(table.getFooterHTML()).contains("guard FAILS for 1");
|
||||
assertThat(t.qInstance.getApp("authentikAdmin").getWidgets()).contains("authentikCompareAccess");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The banner widget, on the group and policy screens and the Edit Policy
|
||||
** step, and the home's health row.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void enforcementBanner() throws Exception
|
||||
{
|
||||
RenderWidgetInput input = new RenderWidgetInput();
|
||||
input.setWidgetMetaData(t.qInstance.getWidget("authentikPolicyEnforcement"));
|
||||
String html = ((RawHTML) new RenderWidgetAction().execute(input).getWidgetData()).getHtml();
|
||||
assertThat(html).contains("Not enforced.").contains("NOT enforced at sign-in on this instance (mapper off)").contains("data-status=\"OFF\"");
|
||||
|
||||
assertThat(t.qInstance.getTable("authentik_group").getSections()).anyMatch(s -> "authentikPolicyEnforcement".equals(s.getWidgetName()));
|
||||
assertThat(t.qInstance.getTable("authentik_policy").getSections().get(0).getWidgetName()).isEqualTo("authentikPolicyEnforcement");
|
||||
assertThat(PolicyCutoverWidgets.bannerHtml(new AccessComparison.State(AccessComparison.Status.ACTIVE, "ok <b>", java.time.Instant.now()))).contains("Enforced.").contains("ok <b>");
|
||||
|
||||
String home = com.kingsrook.qbits.authentik.app.AuthentikHomeView.render(com.kingsrook.qbits.authentik.app.AuthentikHomeData.load(t.config));
|
||||
assertThat(home).contains("Policies at sign-in").contains("mapper off");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** While the guard blocks, a sign-in through the mapper gets today's access
|
||||
** (and the floor); once it passes, the policies.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void mapperFallsBackWhileBlocked() throws Exception
|
||||
{
|
||||
t.config.withMapperEnabled(true);
|
||||
Map<String, Object> context = new HashMap<>();
|
||||
context.put(AuthentikGroupPermissionMapper.CLAIMS_CONTEXT_KEY, new JSONObject().put("email", "sam@example.test").put("groups", new JSONArray().put("kof-website-publishers")));
|
||||
|
||||
runtime.setMapperState(null);
|
||||
QSession blocked = new QSession();
|
||||
new AuthentikGroupPermissionMapper().customizeSession(t.qInstance, blocked, context);
|
||||
assertThat(blocked.getPermissions()).contains("cms_page.read", "cms_page.edit", "cms.publish.hasAccess");
|
||||
|
||||
t.config.withStaticGroupPermissions(Map.of("kof-website-publishers", List.of("cms_page.read", "cms_page.edit", "cms.publish.hasAccess")));
|
||||
t.config.withCutoverGuardGroups(List.of());
|
||||
t.authentik.groupByName("kof-website-publishers").getJSONObject("attributes").put("qqq.io/policy",
|
||||
"{\"PolicySpec\":\"qqq-iam\",\"PolicyVersion\":\"1.0.0\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"delete\"],\"Resource\":[\"cms_page\"]}]}");
|
||||
t.config.withStaticGroupPermissions(Map.of());
|
||||
runtime.invalidateCache();
|
||||
runtime.setMapperState(null);
|
||||
QSession active = new QSession();
|
||||
new AuthentikGroupPermissionMapper().customizeSession(t.qInstance, active, context);
|
||||
assertThat(active.getPermissions()).contains("cms_page.delete", "cms.publish.hasAccess").doesNotContain("cms_page.edit");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Generate Policy From Current Access: the expressible part becomes the
|
||||
** policy, named permissions go to qqq.io/permissions, unknown ones are
|
||||
** skipped; Review shows the document before anything is saved.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void generatePolicy() throws Exception
|
||||
{
|
||||
String analysts = t.authentik.pk("kof-website-analysts");
|
||||
RunProcessInput input = new RunProcessInput();
|
||||
input.setProcessName("authentikGeneratePolicy");
|
||||
input.addValue("recordIds", t.authentik.pk("kof-website-publishers"));
|
||||
RunProcessOutput output = new RunProcessAction().execute(input);
|
||||
input.setProcessUUID(output.getProcessUUID());
|
||||
input.addValue("reason", "seed from today's access");
|
||||
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.getMessage().contains("Generated from current access: {\"PolicySpec\":\"qqq-iam\""));
|
||||
assertThat(review).anyMatch(l -> l.getMessage().contains("Skipped (this app does not define them): nothing.here.hasAccess"));
|
||||
assertThat(t.changes()).isEmpty();
|
||||
|
||||
AuthentikAdmin.AdminResult result = t.admin().execute(t.admin().withGeneratedPolicy(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk("kof-website-publishers"), "seed")));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject attributes = t.authentik.groupByName("kof-website-publishers").getJSONObject("attributes");
|
||||
assertThat(PolicyParser.parse(attributes.get("qqq.io/policy"), PolicyFormat.DEFAULT)).containsExactlyInAnyOrder("cms_page.read", "cms_page.edit");
|
||||
assertThat(attributes.getJSONArray("qqq.io/permissions").toList()).contains("cms.publish.hasAccess");
|
||||
|
||||
assertThat(t.admin().execute(t.admin().withGeneratedPolicy(AdminRequest.of(AdminAction.SAVE_POLICY, t.authentik.pk("kof-website-publishers"), "again"))).noChange()).isTrue();
|
||||
|
||||
t.config.withHostPermissionSource(null);
|
||||
assertThat(t.admin().execute(t.admin().withGeneratedPolicy(AdminRequest.of(AdminAction.SAVE_POLICY, analysts, "x"))).message()).contains("no host permission source");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* 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.policy.PolicyStore;
|
||||
import com.kingsrook.qbits.authentik.security.IdentityPermission;
|
||||
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.RunProcessInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessOutput;
|
||||
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;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Full user and group CRUD (DESIGN.md section 12.5): username and attribute
|
||||
** edits, delete user and delete group, and their gating.
|
||||
*******************************************************************************/
|
||||
class UserGroupCrudTest
|
||||
{
|
||||
private AdminTestSupport t;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws QException
|
||||
{
|
||||
t = AdminTestSupport.create(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.POLICIES, AuthentikFeature.DELETE));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AuthentikAdmin.AdminResult run(AdminRequest request) throws QException
|
||||
{
|
||||
return (t.admin().execute(request));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Username changes are validated and unique.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editUsername() throws QException
|
||||
{
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "rename").with("username", "second")).message()).contains("already has the username");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "rename").with("username", "has space")).message()).contains("A username is");
|
||||
|
||||
AuthentikAdmin.AdminResult renamed = run(AdminRequest.of(AdminAction.EDIT_USER, "3", "rename").with("username", "samuel"));
|
||||
assertThat(renamed.ok()).as(renamed.message()).isTrue();
|
||||
assertThat(t.authentik.users.get(3).getString("username")).isEqualTo("samuel");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Other attributes replace the non-reserved part; reserved keys survive and
|
||||
** cannot be set; blank leaves them as they are; editing needs audit.read.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editUserAttributes() throws QException
|
||||
{
|
||||
t.authentik.users.get(3).put("attributes", new JSONObject().put("qqq.io/protected", false).put("goauthentik.io/user/token-expires", true).put("team", "web").put("old", 1));
|
||||
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_USER, "3", "update").with("otherAttributes", "{\"team\": \"ops\", \"desk\": 4}"));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject attributes = t.authentik.users.get(3).getJSONObject("attributes");
|
||||
assertThat(attributes.getString("team")).isEqualTo("ops");
|
||||
assertThat(attributes.getInt("desk")).isEqualTo(4);
|
||||
assertThat(attributes.has("old")).isFalse();
|
||||
assertThat(attributes.getBoolean("qqq.io/protected")).isFalse();
|
||||
assertThat(attributes.getBoolean("goauthentik.io/user/token-expires")).isTrue();
|
||||
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "update").with("otherAttributes", "{\"qqq.io/protected\": true}")).message()).contains("reserved");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "update").with("otherAttributes", "[1]")).message()).contains("JSON object");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "update").with("otherAttributes", "").with("name", "Sam B")).ok()).isTrue();
|
||||
assertThat(t.authentik.users.get(3).getJSONObject("attributes").getString("team")).as("blank keeps them").isEqualTo("ops");
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// an operator without authentik.audit.read: refused //
|
||||
///////////////////////////////////////////////////////
|
||||
t.authentik.groupByName("identity-admins").getJSONObject("attributes").put("qqq.io/permissions", new JSONArray(List.of(
|
||||
"authentik.users.read", "authentik.users.manage", "authentik.memberships.manage", "authentik.permissions.manage", "authentik.groups.manage")));
|
||||
t.admin().getUtil().getRuntime().invalidateCache();
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_USER, "3", "update").with("otherAttributes", "{\"team\": \"x\"}")).message()).contains("authentik.audit.read");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Group attributes the same way.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editGroupAttributes() throws QException
|
||||
{
|
||||
String pk = t.authentik.pk("kof-website-analysts");
|
||||
AuthentikAdmin.AdminResult result = run(AdminRequest.of(AdminAction.EDIT_GROUP, pk, "update").with("otherAttributes", "{\"owner\": \"data team\"}"));
|
||||
assertThat(result.ok()).as(result.message()).isTrue();
|
||||
JSONObject attributes = t.authentik.groupByName("kof-website-analysts").getJSONObject("attributes");
|
||||
assertThat(attributes.getString("owner")).isEqualTo("data team");
|
||||
assertThat(attributes.getJSONArray("qqq.io/permissions").toList()).containsExactly("kof22.analytics.hasAccess");
|
||||
assertThat(run(AdminRequest.of(AdminAction.EDIT_GROUP, pk, "update").with("otherAttributes", "{\"owner\": \"data team\"}")).noChange()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Delete user: typed confirmation, never protected accounts or yourself.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void deleteUser() throws QException
|
||||
{
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_USER, "3", "left")).message()).contains("Type the username (sam)");
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_USER, "4", "left").with("confirmText", "breakglass")).message()).contains("Protected");
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_USER, "1", "left").with("confirmText", "operator")).message()).contains("your own account");
|
||||
assertThat(t.changes()).isEmpty();
|
||||
|
||||
AuthentikAdmin.AdminResult deleted = run(AdminRequest.of(AdminAction.DELETE_USER, "3", "left the company").with("confirmText", "sam"));
|
||||
assertThat(deleted.ok()).as(deleted.message()).isTrue();
|
||||
assertThat(t.authentik.users).doesNotContainKey(3);
|
||||
assertThat(t.changes()).containsExactly("DELETE /core/users/3/");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Delete group: typed, and only empty groups without children; the policy
|
||||
** record goes with it.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void deleteGroup() throws Exception
|
||||
{
|
||||
String publishers = t.authentik.pk("kof-website-publishers");
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_GROUP, publishers, "cleanup").with("confirmText", "kof-website-publishers")).message()).contains("member(s)");
|
||||
|
||||
t.authentik.group("child-of-analysts", false, List.of(), List.of(), "kof-website-analysts");
|
||||
t.admin().getUtil().getRuntime().invalidateCache();
|
||||
String analysts = t.authentik.pk("kof-website-analysts");
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_GROUP, analysts, "cleanup")).message()).contains("Type the group name");
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_GROUP, analysts, "cleanup").with("confirmText", "kof-website-analysts")).message()).contains("child groups (child-of-analysts)");
|
||||
|
||||
String child = t.authentik.pk("child-of-analysts");
|
||||
PolicyStore.save(t.config, child, "child-of-analysts", new JSONObject().put("PolicySpec", "qqq-iam").put("PolicyVersion", "1.0.0").put("Statement", new JSONArray()), 0, "x", null);
|
||||
AuthentikAdmin.AdminResult deleted = run(AdminRequest.of(AdminAction.DELETE_GROUP, child, "cleanup").with("confirmText", "child-of-analysts"));
|
||||
assertThat(deleted.ok()).as(deleted.message()).isTrue();
|
||||
assertThat(t.authentik.groups).doesNotContainKey(child);
|
||||
assertThat(PolicyStore.find(t.config, child)).isNull();
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_GROUP, t.authentik.pk("authentik Admins"), "x").with("confirmText", "authentik Admins")).message()).contains("Superuser groups");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** DELETE is off by default: no processes, and the action is refused; the
|
||||
** permission is still required with it on.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void gating() throws QException
|
||||
{
|
||||
assertThat(t.qInstance.getProcess("authentikDeleteUser")).isNotNull();
|
||||
assertThat(t.qInstance.getProcess("authentikDeleteGroup").getMaxInputRecords()).isEqualTo(1);
|
||||
|
||||
AdminTestSupport off = AdminTestSupport.create();
|
||||
assertThat(off.qInstance.getProcess("authentikDeleteUser")).isNull();
|
||||
assertThat(off.qInstance.getProcess("authentikDeleteGroup")).isNull();
|
||||
assertThat(off.admin().execute(AdminRequest.of(AdminAction.DELETE_USER, "3", "x").with("confirmText", "sam")).ok()).isFalse();
|
||||
|
||||
t.loginAs(AuthentikTestSupport.OPERATOR, IdentityPermission.USERS_READ, IdentityPermission.GROUPS_MANAGE);
|
||||
assertThat(run(AdminRequest.of(AdminAction.DELETE_USER, "3", "x").with("confirmText", "sam")).ok()).isFalse();
|
||||
assertThat(t.authentik.users).containsKey(3);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Edit User prefills username and (with audit.read) other attributes.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void editUserPrefill() throws QException
|
||||
{
|
||||
t.authentik.users.get(3).put("attributes", new JSONObject().put("team", "web").put("qqq.io/x", 1));
|
||||
RunProcessInput input = new RunProcessInput();
|
||||
input.setProcessName("authentikEditUser");
|
||||
input.addValue("recordIds", "3");
|
||||
RunProcessOutput output = new RunProcessAction().execute(input);
|
||||
assertThat(output.getValues().get("username")).isEqualTo("sam");
|
||||
assertThat(new JSONObject(String.valueOf(output.getValues().get("otherAttributes"))).toMap()).containsOnlyKeys("team");
|
||||
|
||||
t.loginAs(AuthentikTestSupport.OPERATOR, IdentityPermission.USERS_READ, IdentityPermission.USERS_MANAGE);
|
||||
RunProcessInput limited = new RunProcessInput();
|
||||
limited.setProcessName("authentikEditUser");
|
||||
limited.addValue("recordIds", "3");
|
||||
assertThat(new RunProcessAction().execute(limited).getValues().get("otherAttributes")).isNull();
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ class QbitWriteContractIT
|
||||
|
||||
/** 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_user", "authentik_core.change_user", "authentik_core.reset_user_password", "authentik_core.delete_user", "authentik_core.delete_group",
|
||||
"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",
|
||||
@@ -166,7 +166,7 @@ class QbitWriteContractIT
|
||||
.withRecoveryEmailStage("kof22-recovery-email")
|
||||
.withInvitationFlow("wr-enrollment")
|
||||
.withFeatures(EnumSet.of(AuthentikFeature.READ, AuthentikFeature.USERS, AuthentikFeature.GROUPS, AuthentikFeature.MEMBERSHIP,
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES));
|
||||
AuthentikFeature.CREDENTIALS, AuthentikFeature.SESSIONS, AuthentikFeature.POLICIES, AuthentikFeature.DELETE));
|
||||
|
||||
qInstance = new QInstance();
|
||||
qInstance.withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK));
|
||||
@@ -345,6 +345,35 @@ class QbitWriteContractIT
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Delete user and delete group on a real Authentik (delete_user and
|
||||
** delete_group granted only for the DELETE feature); a group with members is
|
||||
** refused by the qbit before any call.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void deleteUserAndGroup() throws Exception
|
||||
{
|
||||
admin.post("/core/users/", new JSONObject().put("username", "wr.leaver").put("name", "WR Leaver").put("email", "wr.leaver@example.test").put("type", "internal").put("path", "users"));
|
||||
int leaver = admin.userPk("wr.leaver");
|
||||
admin.post("/core/groups/", new JSONObject().put("name", "wr-doomed"));
|
||||
String doomed = admin.groupPk("wr-doomed");
|
||||
admin.post("/core/groups/" + doomed + "/add_user/", new JSONObject().put("pk", leaver));
|
||||
|
||||
AuthentikAdmin.AdminResult notEmpty = run(AdminRequest.of(AdminAction.DELETE_GROUP, doomed, "contract test").with("confirmText", "wr-doomed"));
|
||||
assertThat(notEmpty.ok()).isFalse();
|
||||
assertThat(notEmpty.message()).contains("member(s)");
|
||||
|
||||
AuthentikAdmin.AdminResult user = run(AdminRequest.of(AdminAction.DELETE_USER, String.valueOf(leaver), "contract test").with("confirmText", "wr.leaver"));
|
||||
assertThat(user.ok()).as(user.message()).isTrue();
|
||||
assertThat(admin.get("/core/users/" + leaver + "/").status()).isEqualTo(404);
|
||||
|
||||
AuthentikAdmin.AdminResult group = run(AdminRequest.of(AdminAction.DELETE_GROUP, doomed, "contract test").with("confirmText", "wr-doomed"));
|
||||
assertThat(group.ok()).as(group.message()).isTrue();
|
||||
assertThat(admin.get("/core/groups/" + doomed + "/").status()).isEqualTo(404);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Group create and edit (parents), and the superuser parent refused by the
|
||||
** guard.
|
||||
|
||||
Reference in new issue
Block a user