Edit Authentik groups: rename and change members
Apps → Authentik gets a Groups section for administrators: the groups with member counts, and an Edit form to rename one and put users in and take them out. Members are changed one user at a time, never by replacing the list. Everything is checked first and nothing changes unless all of it may; service accounts, the token's own account and the last active administrator losing that are refused. Whether a group makes administrators is shown, not changed. Groups that decide roles in this app (Settings → Sign-in) are marked and ask first. Audited with who was put in and taken out. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3618cb3ae8
commit
6c5a5f0bd6
10 files changed
+794
-9
No files matched your search
+6
-1
@@ -529,7 +529,12 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
|||||||
**Users** on the same page lists the people (service accounts — what an outpost or an integration signs in with — are left out), searchable, with whether each is on, whether they are an administrator and when they last signed in, and lets an administrator **edit a user's name, email and groups** (the user name is shown but not changeable: it is how a person is known elsewhere, and renaming could make them a new person here; Authentik is sent only what differs, as a `PATCH`, and groups as what goes in and what comes out on top of the groups the user has *now*, so a membership somebody gave them meanwhile is kept; a user whose groups Authentik does not say can be renamed but not moved between groups), **switch a user off** (a `PATCH` of `is_active` and nothing else;
|
**Users** on the same page lists the people (service accounts — what an outpost or an integration signs in with — are left out), searchable, with whether each is on, whether they are an administrator and when they last signed in, and lets an administrator **edit a user's name, email and groups** (the user name is shown but not changeable: it is how a person is known elsewhere, and renaming could make them a new person here; Authentik is sent only what differs, as a `PATCH`, and groups as what goes in and what comes out on top of the groups the user has *now*, so a membership somebody gave them meanwhile is kept; a user whose groups Authentik does not say can be renamed but not moved between groups), **switch a user off** (a `PATCH` of `is_active` and nothing else;
|
||||||
they can no longer sign in, nothing of theirs is lost, *Switch on* brings it back) or **delete** one (a `DELETE`, for good: the user name has to be typed, and is checked again by the server against the user as Authentik has them now). **Refused, by the server, with the reason:** a service account, the account the token
|
they can no longer sign in, nothing of theirs is lost, *Switch on* brings it back) or **delete** one (a `DELETE`, for good: the user name has to be typed, and is checked again by the server against the user as Authentik has them now). **Refused, by the server, with the reason:** a service account, the account the token
|
||||||
itself belongs to, and the last active administrator (so nobody can be locked out, or the sign-in in front of everything else cut off — for an edit, only when it would take them out of every group that makes them one); do those in Authentik. Each is in the audit log (*who edited — which fields, never their new values — switched off / on / deleted which user*). Switching off or deleting someone in Authentik does not end a session they
|
itself belongs to, and the last active administrator (so nobody can be locked out, or the sign-in in front of everything else cut off — for an edit, only when it would take them out of every group that makes them one); do those in Authentik. Each is in the audit log (*who edited — which fields, never their new values — switched off / on / deleted which user*). Switching off or deleting someone in Authentik does not end a session they
|
||||||
already have in this app: end it under Users → *Signed in now*. Lists are read 200 at a time. Without it nothing about the page changes for anyone but an administrator, who sees where to add one. The calls (`GET /core/groups/`, `POST /core/users/`, `POST /core/users/{id}/recovery/`, `GET /core/users/`, `GET /core/users/{id}/`, `GET /core/users/me/`, `PATCH` (`is_active`, or `name`, `email` and `groups`) and `DELETE /core/users/{id}/`; asking for a link that lasts a day, which a version of
|
already have in this app: end it under Users → *Signed in now*. Lists are read 200 at a time.
|
||||||
|
**Groups** on the same page lists the groups with how many are in each and lets an administrator **rename** one and **put users in and take them out** (a `PATCH` of `name` and nothing else; `POST /core/groups/{id}/add_user/` and `remove_user/`, one user each,
|
||||||
|
so somebody who joined meanwhile is never dropped by a whole list replacing the members). Everything asked is checked first and **nothing is changed unless all of it may be**: a service account, the token's own account, the last active administrator
|
||||||
|
being taken out of the group that makes them one, and someone whose groups Authentik did not say (when taking them out of such a group) are refused with the reason. If Authentik fails part-way, the answer says how many of the changes had been made, and the audit log
|
||||||
|
(*who renamed which group, who was put in and taken out*) has what was done. Whether a group **makes its members administrators of Authentik** is shown and is **not** changed from here, and groups are not made or deleted here. A group whose name is one of the
|
||||||
|
*admin* or *operator* groups of **Settings → Sign-in** is marked *decides admins / operators here* and asks before it is saved: renaming it, or changing who is in it, changes people's roles in this app at their next sign-in. Without it nothing about the page changes for anyone but an administrator, who sees where to add one. The calls (`GET /core/groups/`, `POST /core/users/`, `POST /core/users/{id}/recovery/`, `GET /core/users/`, `GET /core/users/{id}/`, `GET /core/users/me/`, `PATCH` (`is_active`, or `name`, `email` and `groups`) and `DELETE /core/users/{id}/`, `GET /core/groups/{id}/`, `PATCH /core/groups/{id}/` and `POST /core/groups/{id}/add_user/` and `remove_user/`; asking for a link that lasts a day, which a version of
|
||||||
Authentik that does not take that sets for itself) are **not verified against a live Authentik**; the tests use a pretend one.
|
Authentik that does not take that sets for itself) are **not verified against a live Authentik**; the tests use a pretend one.
|
||||||
- **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the
|
- **What it does:** every **five minutes** Authentik is read and stored — its version (and whether a newer one is out), whether a **worker** is connected, each **outpost** (the proxy outpost that guards your apps, an LDAP one) with how many instances reported in during the last five minutes and whether they run the right version, the
|
||||||
**certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first.
|
**certificates** (those Authentik does not renew by itself) with their expiry, the **API tokens and app passwords** that expire, and how many **sign-ins failed** and **configuration errors** happened in the last day. **Apps → Authentik** shows it, with what runs out soonest first.
|
||||||
|
|||||||
@@ -572,7 +572,7 @@ quietly never made. The page shows the photo and video counts, what the library
|
|||||||
|
|
||||||
**Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is
|
**Authentik** (Apps → Authentik). Add an Authentik integration (its address and an API token) and the app watches the sign-in in front of everything else: it raises a **critical** alert when an **outpost** that guards applications stops reporting, and warns when a **certificate** or an **API token** is
|
||||||
about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md.
|
about to run out (the token it reads Authentik with included), when **no worker** is connected, and when **sign-ins are failing** or flows are misconfigured. The page lists the outposts, what runs out soonest and the failed sign-ins of the last day. See INTEGRATIONS.md and docs/MONITORING.md.
|
||||||
An administrator can also **make a user** from that page — with a second, optional token for it — and gets a **one-time recovery link** to send them, so they choose their own password; no password is ever set or seen here, and the link is shown once and not kept. The same page lists the users and lets an administrator **edit** one (name, email, groups), **switch one off** (and on again) or **delete** one (the user name has to be typed); service accounts, the account the token belongs to and the last active administrator are refused.
|
An administrator can also **make a user** from that page — with a second, optional token for it — and gets a **one-time recovery link** to send them, so they choose their own password; no password is ever set or seen here, and the link is shown once and not kept. The same page lists the users and lets an administrator **edit** one (name, email, groups), **switch one off** (and on again) or **delete** one (the user name has to be typed); service accounts, the account the token belongs to and the last active administrator are refused. **Groups** can be renamed and have users put in and taken out (never made or deleted, and whether a group makes administrators is not changed here); a group that decides roles in this app is marked and asks first.
|
||||||
|
|
||||||
**Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a
|
**Jellyfin** (Apps → Jellyfin). Add a Jellyfin integration (its address and an API key) and the app shows whether it is up, **who is streaming what** and whether it is being transcoded, the scheduled tasks that failed, and a chart of how many watched at once; it warns when Jellyfin **wants a restart**, a
|
||||||
**task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md.
|
**task failed** or **sign-ins are failing**. And when the Jellyfin runs on a server the app manages, **an update run asks first if people are watching**, and a patch plan **waits for them (up to two hours)** instead of restarting the machine in the middle of a film. See INTEGRATIONS.md and docs/MONITORING.md.
|
||||||
|
|||||||
@@ -163,7 +163,7 @@ even further, to admin only:
|
|||||||
- **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration.
|
- **Immich** (Apps → Immich): everyone signed in sees the counts, the disk and the job queues; adding one (its address and API key) is an administrator's job, like any integration.
|
||||||
- **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration.
|
- **Paperless-ngx** (Apps → Paperless): everyone signed in sees the counts, the system status and the names of the files that failed to import; adding one (its address and a superuser's token) is an administrator's job, like any integration.
|
||||||
- **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration.
|
- **Prometheus** (Monitoring → Prometheus): everyone signed in sees the targets, what is down and the alerts firing; adding one (its address, and a token if it needs one) is an administrator's job, like any integration.
|
||||||
- **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. **Making a user** there (and the groups to offer), **listing** the users and **editing, switching them off or on or deleting them** are an administrator's alone, and only for an Authentik that was given a token for it; each is written in the audit log (who made, edited (which fields, not the new values), switched off, switched on or deleted which user, and who made a recovery link), never the link.
|
- **Authentik** (Apps → Authentik): everyone signed in sees the outposts, what runs out and the failed-sign-in count (the names of tokens and certificates, not their values); adding one (its address and API token) is an administrator's job, like any integration. **Making a user** there (and the groups to offer), **listing** the users and **editing, switching them off or on or deleting them**, and **renaming groups and changing who is in them**, are an administrator's alone, and only for an Authentik that was given a token for it; each is written in the audit log (who made, edited (which fields, not the new values), switched off, switched on or deleted which user, who renamed which group and who was put in or taken out of it, and who made a recovery link), never the link.
|
||||||
- **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators).
|
- **Jellyfin** (Apps → Jellyfin): everyone signed in sees who is streaming and what is wrong; adding one (its address and API key) is an administrator's job, like any integration. Starting an update run on a server people are streaming from needs `startAnyway` — the update drawer asks (operators).
|
||||||
- **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them.
|
- **Media managers** (Apps → Media managers, for Sonarr, Radarr and Prowlarr): everyone signed in sees what each says is wrong, its queue, disks and indexers; adding one (its API key) is an administrator's job, like any integration. Nothing on the page changes anything in them.
|
||||||
- **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's.
|
- **App versions** (Operations → App versions): everyone signed in sees what each application runs against the newest release; switching the lookup of releases on and off, and the number of days after which a newer release is a warning, are an administrator's.
|
||||||
|
|||||||
@@ -42,6 +42,15 @@ export function extractGroups(sources: Record<string, unknown>[], claim: string)
|
|||||||
|
|
||||||
const norm = (s: string) => s.trim().toLowerCase();
|
const norm = (s: string) => s.trim().toLowerCase();
|
||||||
|
|
||||||
|
/** The role a group of this name decides in this app, if any: "admin" or "operator" when roles follow the groups and the name is one of the named ones (compared the way sign-in does); otherwise null. */
|
||||||
|
export function roleForGroupName(settings: Pick<SignInRoleSettings, "roleFromGroups" | "adminGroups" | "operatorGroups">, name: string): "admin" | "operator" | null {
|
||||||
|
if (!settings.roleFromGroups) return null;
|
||||||
|
const n = norm(name);
|
||||||
|
if (settings.adminGroups.some((g) => norm(g) === n)) return "admin";
|
||||||
|
if (settings.operatorGroups.some((g) => norm(g) === n)) return "operator";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/** The role these groups give: admin if any is an admin group, else operator if any is an operator group, else what `otherwise` says. */
|
/** The role these groups give: admin if any is an admin group, else operator if any is an operator group, else what `otherwise` says. */
|
||||||
export function roleFromGroups(settings: SignInRoleSettings, groups: string[], current: UserRole): UserRole {
|
export function roleFromGroups(settings: SignInRoleSettings, groups: string[], current: UserRole): UserRole {
|
||||||
const have = new Set(groups.map(norm));
|
const have = new Set(groups.map(norm));
|
||||||
|
|||||||
@@ -5,6 +5,10 @@
|
|||||||
* Making one takes three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the
|
* Making one takes three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the
|
||||||
* person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored.
|
* person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored.
|
||||||
*
|
*
|
||||||
|
* Looking after groups: the groups with who is in them (`GET /core/groups/`, one `GET /core/groups/{id}/`), renaming one (`PATCH` with only `name`) and putting a user in or taking one out
|
||||||
|
* (`POST /core/groups/{id}/add_user/` and `remove_user/`, one user each — never a whole list of members, so someone who joined meanwhile is not dropped). Whether a group makes its members
|
||||||
|
* administrators of Authentik (`is_superuser`) is shown and not changed from here.
|
||||||
|
*
|
||||||
* Looking after them: the users (`GET /core/users/`, one `GET /core/users/{pk}/`), who the token is (`GET /core/users/me/`), switching one off or on (`PATCH /core/users/{pk}/` with only `is_active`),
|
* Looking after them: the users (`GET /core/users/`, one `GET /core/users/{pk}/`), who the token is (`GET /core/users/me/`), switching one off or on (`PATCH /core/users/{pk}/` with only `is_active`),
|
||||||
* changing their name, email and groups (the same `PATCH`, with only what changed — never the user name, which is how a person is known elsewhere) and deleting one (`DELETE /core/users/{pk}/`). Service accounts — what an outpost or an integration signs in with — are not listed and are refused, and so are the account the token belongs to and the last
|
* changing their name, email and groups (the same `PATCH`, with only what changed — never the user name, which is how a person is known elsewhere) and deleting one (`DELETE /core/users/{pk}/`). Service accounts — what an outpost or an integration signs in with — are not listed and are refused, and so are the account the token belongs to and the last
|
||||||
* active administrator, so this cannot be used to lock everyone out or to cut off the sign-in in front of everything else.
|
* active administrator, so this cannot be used to lock everyone out or to cut off the sign-in in front of everything else.
|
||||||
@@ -95,6 +99,28 @@ export function parseRecoveryLink(raw: unknown): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A group with who is in it. */
|
||||||
|
export interface AuthentikGroupDetail extends AuthentikGroup {
|
||||||
|
/** User ids; null when Authentik did not say, which is not the same as none — and then they are not changed from here. */
|
||||||
|
members: number[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure: one group with its members; null when the answer is not a group. */
|
||||||
|
export function parseGroupDetail(raw: unknown): AuthentikGroupDetail | null {
|
||||||
|
const g = obj(raw);
|
||||||
|
const id = str(g.pk);
|
||||||
|
const name = str(g.name);
|
||||||
|
if (!id || !name || !UUID.test(id)) return null;
|
||||||
|
const members = Array.isArray(g.users) ? g.users.filter((u): u is number => typeof u === "number" && Number.isInteger(u) && u > 0) : null;
|
||||||
|
return { id, name, admin: g.is_superuser === true, members };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure: the groups of a `/core/groups/` page, by name, each with who is in it. */
|
||||||
|
export function parseGroupDetails(raw: unknown): AuthentikGroupDetail[] {
|
||||||
|
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : [];
|
||||||
|
return list.map(parseGroupDetail).filter((g): g is AuthentikGroupDetail => g !== null).sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}
|
||||||
|
|
||||||
/** A user as the list shows them. */
|
/** A user as the list shows them. */
|
||||||
export interface AuthentikUser {
|
export interface AuthentikUser {
|
||||||
pk: number;
|
pk: number;
|
||||||
@@ -181,6 +207,11 @@ export interface AuthentikUsersAdapter {
|
|||||||
updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser>;
|
updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser>;
|
||||||
deleteUser(pk: number): Promise<void>;
|
deleteUser(pk: number): Promise<void>;
|
||||||
listGroups(): Promise<AuthentikGroup[]>;
|
listGroups(): Promise<AuthentikGroup[]>;
|
||||||
|
listGroupDetails(): Promise<AuthentikGroupDetail[]>;
|
||||||
|
getGroup(id: string): Promise<AuthentikGroupDetail>;
|
||||||
|
renameGroup(id: string, name: string): Promise<AuthentikGroupDetail>;
|
||||||
|
addMember(id: string, userPk: number): Promise<void>;
|
||||||
|
removeMember(id: string, userPk: number): Promise<void>;
|
||||||
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
||||||
recoveryLink(pk: number): Promise<string>;
|
recoveryLink(pk: number): Promise<string>;
|
||||||
}
|
}
|
||||||
@@ -190,7 +221,7 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
const insecure = config.insecure === true;
|
const insecure = config.insecure === true;
|
||||||
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
|
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
|
||||||
|
|
||||||
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown): Promise<unknown> {
|
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown, emptyOk = method === "DELETE"): Promise<unknown> {
|
||||||
let res;
|
let res;
|
||||||
try {
|
try {
|
||||||
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
|
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
|
||||||
@@ -201,8 +232,8 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
if (res.status === 404) throw new AuthentikUserError("Authentik has no such thing there — a user that is gone, or an address that is not Authentik's", "missing");
|
if (res.status === 404) throw new AuthentikUserError("Authentik has no such thing there — a user that is gone, or an address that is not Authentik's", "missing");
|
||||||
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
|
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
|
||||||
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
|
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
|
||||||
// A delete is answered with nothing; everything else with JSON.
|
// A delete, and putting a user in or out of a group, are answered with nothing; everything else with JSON.
|
||||||
if (res.json === null && method !== "DELETE") throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
|
if (res.json === null && !emptyOk) throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
|
||||||
return res.json;
|
return res.json;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,8 +283,38 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
|
await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const groupId = (id: string) => {
|
||||||
|
if (!UUID.test(id)) throw new AuthentikUserError("That is not a group id", "invalid");
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function listGroupDetails(): Promise<AuthentikGroupDetail[]> {
|
||||||
|
return parseGroupDetails(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name&include_users=false`));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGroup(id: string): Promise<AuthentikGroupDetail> {
|
||||||
|
const group = parseGroupDetail(await call("GET", `/core/groups/${groupId(id)}/?include_users=false`));
|
||||||
|
if (!group) throw new AuthentikUserError("Authentik answered, but not with a group", "failed");
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renameGroup(id: string, name: string): Promise<AuthentikGroupDetail> {
|
||||||
|
// Only the name: a PATCH leaves out what it does not mention, so whether the group makes administrators, its members and its parent are as they were.
|
||||||
|
const group = parseGroupDetail(await call("PATCH", `/core/groups/${groupId(id)}/`, { name }));
|
||||||
|
if (!group) throw new AuthentikUserError("Authentik answered, but not with the group", "failed");
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addMember(id: string, userPk: number): Promise<void> {
|
||||||
|
await call("POST", `/core/groups/${groupId(id)}/add_user/`, { pk: wholeNumber(userPk) }, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeMember(id: string, userPk: number): Promise<void> {
|
||||||
|
await call("POST", `/core/groups/${groupId(id)}/remove_user/`, { pk: wholeNumber(userPk) }, true);
|
||||||
|
}
|
||||||
|
|
||||||
async function listGroups(): Promise<AuthentikGroup[]> {
|
async function listGroups(): Promise<AuthentikGroup[]> {
|
||||||
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
|
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name&include_users=false`));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser> {
|
async function createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser> {
|
||||||
@@ -272,5 +333,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
|||||||
return link;
|
return link;
|
||||||
}
|
}
|
||||||
|
|
||||||
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroups, createUser, recoveryLink });
|
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, renameGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,9 @@ import { requireAuth, requireRole } from "../auth/middleware.js";
|
|||||||
import { decryptSecret, encryptSecret } from "../crypto.js";
|
import { decryptSecret, encryptSecret } from "../crypto.js";
|
||||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||||
import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||||
|
import { roleForGroupName } from "../auth/groups.js";
|
||||||
import { recordAudit } from "../services/audit.js";
|
import { recordAudit } from "../services/audit.js";
|
||||||
|
import { getSettings } from "../services/settingsStore.js";
|
||||||
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
||||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
|
||||||
@@ -309,3 +311,115 @@ authentikRouter.patch("/:id/users/:pk", requireRole("admin"), asyncHandler(async
|
|||||||
sendFailure(res, err);
|
sendFailure(res, err);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const GROUP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The groups with who is in each, for the page that looks after them — and the people to name the members by (not the service accounts), and which one the token is. Every group says
|
||||||
|
* whether it decides somebody's role in this app (Settings → Sign-in), because changing its name or its members changes that at their next sign-in.
|
||||||
|
*/
|
||||||
|
authentikRouter.get("/:id/group-details", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||||
|
const target = await usersAdapterFor(req.params.id, res);
|
||||||
|
if (!target) return;
|
||||||
|
try {
|
||||||
|
const [groups, people, self, settings] = await Promise.all([target.adapter.listGroupDetails(), target.adapter.listUsers(), target.adapter.whoAmI(), getSettings()]);
|
||||||
|
res.json({
|
||||||
|
groups: groups.map((g) => ({ ...g, decidesRole: roleForGroupName(settings.signIn, g.name) })),
|
||||||
|
people: people.users.map((u) => ({ pk: u.pk, username: u.username, name: u.name, active: u.active })),
|
||||||
|
more: people.more,
|
||||||
|
self,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
sendFailure(res, err);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
const groupEditSchema = z
|
||||||
|
.object({
|
||||||
|
name: z.string().trim().min(1, "A group needs a name.").max(200).optional(),
|
||||||
|
// Members are changed by who goes in and who comes out, never by a whole list: somebody who joined meanwhile is not dropped.
|
||||||
|
membersAdd: z.array(z.number().int().positive()).max(25).default([]),
|
||||||
|
membersRemove: z.array(z.number().int().positive()).max(25).default([]),
|
||||||
|
})
|
||||||
|
.refine((d) => !d.membersAdd.some((m) => d.membersRemove.includes(m)), { message: "A user can't be both put in and taken out." });
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renames a group and/or puts users in it and takes them out. Everything is checked first, against Authentik as it is now, and nothing is changed if anything is refused — a service account, the
|
||||||
|
* account the token belongs to, someone whose groups Authentik did not say (when taking them out of a group that makes administrators), or the last active administrator losing that. Then the
|
||||||
|
* name, then the users one by one; if Authentik fails part-way the answer says how far it got and the audit log has what was done. Whether the group makes administrators is not changed here.
|
||||||
|
*/
|
||||||
|
authentikRouter.patch("/:id/groups/:gid", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||||
|
const parsed = groupEditSchema.safeParse(req.body);
|
||||||
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change.", details: parsed.error.flatten() });
|
||||||
|
const gid = req.params.gid;
|
||||||
|
if (!GROUP_ID.test(gid)) return res.status(400).json({ error: "invalid_group" });
|
||||||
|
const target = await usersAdapterFor(req.params.id, res);
|
||||||
|
if (!target) return;
|
||||||
|
const { adapter } = target;
|
||||||
|
const { name, membersAdd, membersRemove } = parsed.data;
|
||||||
|
try {
|
||||||
|
const group = await adapter.getGroup(gid);
|
||||||
|
const rename = name !== undefined && name !== group.name ? name : null;
|
||||||
|
let add: number[] = [];
|
||||||
|
let remove: number[] = [];
|
||||||
|
if (membersAdd.length > 0 || membersRemove.length > 0) {
|
||||||
|
if (group.members === null) return res.status(409).json({ error: "refused", message: "Authentik did not say who is in this group, so its members are not changed from here." });
|
||||||
|
add = membersAdd.filter((m) => !group.members!.includes(m));
|
||||||
|
remove = membersRemove.filter((m) => group.members!.includes(m));
|
||||||
|
}
|
||||||
|
if (rename === null && add.length === 0 && remove.length === 0) return res.json({ changed: [], added: 0, removed: 0 });
|
||||||
|
|
||||||
|
// Look at everyone first: nothing is changed unless all of it may be.
|
||||||
|
const people = new Map<number, AuthentikUser>();
|
||||||
|
for (const pk of [...add, ...remove]) {
|
||||||
|
const user = await adapter.getUser(pk);
|
||||||
|
people.set(pk, user);
|
||||||
|
let refusal: string | null;
|
||||||
|
if (remove.includes(pk) && group.admin && user.groups === null && !isServiceAccount(user)) refusal = "Authentik did not say which groups they are in, so they are not taken out of a group that makes administrators from here.";
|
||||||
|
else refusal = await judge(adapter, user, "edit", remove.includes(pk) && group.admin && user.groups ? user.groups.filter((g) => g !== gid) : undefined);
|
||||||
|
if (refusal) return res.status(409).json({ error: "refused", message: `${user.username}: ${refusal}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = (rename === null ? 0 : 1) + add.length + remove.length;
|
||||||
|
let done = 0;
|
||||||
|
const doneAdded: string[] = [];
|
||||||
|
const doneRemoved: string[] = [];
|
||||||
|
let failure: unknown = null;
|
||||||
|
try {
|
||||||
|
if (rename !== null) {
|
||||||
|
await adapter.renameGroup(gid, rename);
|
||||||
|
done += 1;
|
||||||
|
}
|
||||||
|
for (const pk of add) {
|
||||||
|
await adapter.addMember(gid, pk);
|
||||||
|
done += 1;
|
||||||
|
doneAdded.push(people.get(pk)!.username);
|
||||||
|
}
|
||||||
|
for (const pk of remove) {
|
||||||
|
await adapter.removeMember(gid, pk);
|
||||||
|
done += 1;
|
||||||
|
doneRemoved.push(people.get(pk)!.username);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
failure = err;
|
||||||
|
}
|
||||||
|
if (done > 0) {
|
||||||
|
await recordAudit({
|
||||||
|
actor: req.currentUser!,
|
||||||
|
category: "integration",
|
||||||
|
action: "update_authentik_group",
|
||||||
|
targetType: "authentik_group",
|
||||||
|
targetId: gid,
|
||||||
|
detail: { integrationId: target.id, integration: target.name, group: group.name, ...(rename !== null && done > 0 ? { renamedTo: rename } : {}), added: doneAdded, removed: doneRemoved },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (failure !== null) {
|
||||||
|
const kind = failure instanceof AuthentikUserError ? failure.kind : "failed";
|
||||||
|
const message = failure instanceof Error ? failure.message : String(failure);
|
||||||
|
return sendFailure(res, new AuthentikUserError(`${message} — ${done} of ${total} changes had been made`, kind));
|
||||||
|
}
|
||||||
|
res.json({ changed: [...(rename !== null ? ["name"] : []), ...(add.length + remove.length > 0 ? ["members"] : [])], added: add.length, removed: remove.length });
|
||||||
|
} catch (err) {
|
||||||
|
sendFailure(res, err);
|
||||||
|
}
|
||||||
|
}));
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
/**
|
||||||
|
* Looking after Authentik groups: reading them with who is in them, renaming one, putting users in and taking them out — and what is refused (service accounts, the account the token belongs
|
||||||
|
* to, the last active administrator losing that, a user whose groups Authentik did not say), that nothing is changed unless all of it may be, how far a failure got, who may, what is in the
|
||||||
|
* audit log, and which groups decide roles in this app.
|
||||||
|
*
|
||||||
|
* Run with: npm test --workspace server
|
||||||
|
*/
|
||||||
|
import { test, describe, before, after } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { createServer as createHttpServer, type Server } from "node:http";
|
||||||
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "hm-authentik-groups-"));
|
||||||
|
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||||
|
process.env.SESSION_DIR = join(dir, "sessions");
|
||||||
|
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||||
|
|
||||||
|
const express = (await import("express")).default;
|
||||||
|
const { db } = await import("../src/db/client.js");
|
||||||
|
const { users, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js");
|
||||||
|
const { runMigrations } = await import("../src/db/migrate.js");
|
||||||
|
const { encryptSecret } = await import("../src/crypto.js");
|
||||||
|
const usersApi = await import("../src/integrations/authentik/users.js");
|
||||||
|
const { roleForGroupName } = await import("../src/auth/groups.js");
|
||||||
|
const { updateSettings } = await import("../src/services/settingsStore.js");
|
||||||
|
const { authentikRouter } = await import("../src/routes/authentik.js");
|
||||||
|
|
||||||
|
await runMigrations();
|
||||||
|
|
||||||
|
const G_ADMIN = "22222222-2222-4222-8222-222222222222";
|
||||||
|
const G_FAMILY = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const G_OTHER = "44444444-4444-4444-8444-444444444444";
|
||||||
|
|
||||||
|
interface FakeGroup {
|
||||||
|
pk: string;
|
||||||
|
name: string;
|
||||||
|
is_superuser: boolean;
|
||||||
|
users: number[];
|
||||||
|
}
|
||||||
|
interface FakeUser {
|
||||||
|
pk: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
is_active: boolean;
|
||||||
|
is_superuser: boolean;
|
||||||
|
last_login: string | null;
|
||||||
|
type: string;
|
||||||
|
groups?: string[];
|
||||||
|
}
|
||||||
|
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", groups: [], ...extra });
|
||||||
|
|
||||||
|
describe("what Authentik's answers are read as", () => {
|
||||||
|
test("a group with who is in it: the ids of the users; none given is not the same as none", () => {
|
||||||
|
assert.deepEqual(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family", is_superuser: false, users: [3, 4, "x", 0, 1.5] }), { id: G_FAMILY, name: "Family", admin: false, members: [3, 4] });
|
||||||
|
assert.deepEqual(usersApi.parseGroupDetail({ pk: G_ADMIN, name: "admins", is_superuser: true, users: [] }), { id: G_ADMIN, name: "admins", admin: true, members: [] });
|
||||||
|
assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family" })!.members, null);
|
||||||
|
assert.equal(usersApi.parseGroupDetail({ pk: "nope", name: "x" }), null);
|
||||||
|
assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: " " }), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the list is by name", () => {
|
||||||
|
const list = usersApi.parseGroupDetails({ results: [{ pk: G_OTHER, name: "other", users: [] }, { pk: G_FAMILY, name: "Family", users: [] }, { pk: "x", name: "junk" }] });
|
||||||
|
assert.deepEqual(list.map((g) => g.name), ["Family", "other"]);
|
||||||
|
assert.deepEqual(usersApi.parseGroupDetails("nonsense"), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a group decides a role here when roles follow the groups and its name is one of the named ones — compared the way sign-in compares", () => {
|
||||||
|
const rules = { roleFromGroups: true, adminGroups: ["Homelab-Admins"], operatorGroups: [" ops "] };
|
||||||
|
assert.equal(roleForGroupName(rules, "homelab-admins"), "admin");
|
||||||
|
assert.equal(roleForGroupName(rules, "OPS"), "operator");
|
||||||
|
assert.equal(roleForGroupName(rules, "Family"), null);
|
||||||
|
assert.equal(roleForGroupName({ ...rules, roleFromGroups: false }, "homelab-admins"), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** An Authentik with groups and users that remembers what it was asked. */
|
||||||
|
interface Seen {
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
auth: string;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
const seen: Seen[] = [];
|
||||||
|
const freshGroups = (): FakeGroup[] => [
|
||||||
|
{ pk: G_ADMIN, name: "admins", is_superuser: true, users: [1, 2] },
|
||||||
|
{ pk: G_FAMILY, name: "Family", is_superuser: false, users: [3] },
|
||||||
|
{ pk: G_OTHER, name: "Other", is_superuser: false, users: [] },
|
||||||
|
];
|
||||||
|
const freshUsers = (): FakeUser[] => [
|
||||||
|
person(1, "akadmin", { is_superuser: true, groups: [G_ADMIN] }),
|
||||||
|
person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }),
|
||||||
|
person(3, "carol", { groups: [G_FAMILY] }),
|
||||||
|
person(4, "dave"),
|
||||||
|
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
|
||||||
|
];
|
||||||
|
let groupTable = freshGroups();
|
||||||
|
let userTable = freshUsers();
|
||||||
|
let meId = 1;
|
||||||
|
/** A user id whose put-in or take-out Authentik answers with an error. */
|
||||||
|
let failMemberPk = 0;
|
||||||
|
|
||||||
|
let fake: Server;
|
||||||
|
let fakeUrl = "";
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
fake = createHttpServer((req, res) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", (c) => (body += c));
|
||||||
|
req.on("end", () => {
|
||||||
|
const path = req.url ?? "";
|
||||||
|
seen.push({ method: req.method ?? "", path, auth: String(req.headers.authorization ?? ""), body });
|
||||||
|
const send = (status: number, json?: unknown) => {
|
||||||
|
if (json === undefined) {
|
||||||
|
res.writeHead(status);
|
||||||
|
return res.end();
|
||||||
|
}
|
||||||
|
res.writeHead(status, { "content-type": "application/json" });
|
||||||
|
res.end(JSON.stringify(json));
|
||||||
|
};
|
||||||
|
const url = new URL(path, "http://x");
|
||||||
|
if (req.method === "GET" && url.pathname === "/api/v3/core/groups/") return send(200, { results: groupTable });
|
||||||
|
const grp = /^\/api\/v3\/core\/groups\/([0-9a-f-]{36})\/(add_user\/|remove_user\/)?$/.exec(url.pathname);
|
||||||
|
if (grp) {
|
||||||
|
const group = groupTable.find((g) => g.pk === grp[1]);
|
||||||
|
if (!group) return send(404, { detail: "Not found." });
|
||||||
|
if (!grp[2] && req.method === "GET") return send(200, group);
|
||||||
|
if (!grp[2] && req.method === "PATCH") {
|
||||||
|
Object.assign(group, JSON.parse(body));
|
||||||
|
return send(200, group);
|
||||||
|
}
|
||||||
|
if (grp[2] && req.method === "POST") {
|
||||||
|
const pk = (JSON.parse(body) as { pk: number }).pk;
|
||||||
|
if (pk === failMemberPk) return send(500, { detail: "boom" });
|
||||||
|
const user = userTable.find((u) => u.pk === pk);
|
||||||
|
if (!user) return send(404, { detail: "Not found." });
|
||||||
|
if (grp[2] === "add_user/") {
|
||||||
|
if (!group.users.includes(pk)) group.users.push(pk);
|
||||||
|
if (user.groups && !user.groups.includes(group.pk)) user.groups.push(group.pk);
|
||||||
|
} else {
|
||||||
|
group.users = group.users.filter((u) => u !== pk);
|
||||||
|
if (user.groups) user.groups = user.groups.filter((g) => g !== group.pk);
|
||||||
|
}
|
||||||
|
user.is_superuser = (user.groups ?? []).some((g) => groupTable.find((x) => x.pk === g)?.is_superuser);
|
||||||
|
return send(204);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: userTable.find((u) => u.pk === meId) });
|
||||||
|
if (req.method === "GET" && url.pathname === "/api/v3/core/users/") {
|
||||||
|
let list = userTable;
|
||||||
|
if (url.searchParams.get("is_superuser") === "true") list = list.filter((u) => u.is_superuser);
|
||||||
|
if (url.searchParams.get("is_active") === "true") list = list.filter((u) => u.is_active);
|
||||||
|
return send(200, { pagination: { total_pages: 1 }, results: list });
|
||||||
|
}
|
||||||
|
const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname);
|
||||||
|
if (one && req.method === "GET") {
|
||||||
|
const user = userTable.find((u) => u.pk === Number(one[1]));
|
||||||
|
return user ? send(200, user) : send(404, { detail: "Not found." });
|
||||||
|
}
|
||||||
|
return send(200, { results: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
|
||||||
|
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
|
||||||
|
});
|
||||||
|
after(() => {
|
||||||
|
fake.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
groupTable = freshGroups();
|
||||||
|
userTable = freshUsers();
|
||||||
|
meId = 1;
|
||||||
|
failMemberPk = 0;
|
||||||
|
seen.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("the calls", () => {
|
||||||
|
const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" });
|
||||||
|
|
||||||
|
test("the groups are listed with their members, without the heavy user objects", async () => {
|
||||||
|
reset();
|
||||||
|
const list = await adapter().listGroupDetails();
|
||||||
|
assert.deepEqual(list.map((g) => [g.name, g.admin, g.members]), [["admins", true, [1, 2]], ["Family", false, [3]], ["Other", false, []]]);
|
||||||
|
assert.match(seen[0].path, /include_users=false/);
|
||||||
|
assert.equal(seen[0].auth, "Bearer write-tok");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renaming is a PATCH of the name and nothing else; a member goes in or out with a POST of that one user", async () => {
|
||||||
|
reset();
|
||||||
|
const renamed = await adapter().renameGroup(G_FAMILY, "Household");
|
||||||
|
assert.equal(renamed.name, "Household");
|
||||||
|
assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", `/api/v3/core/groups/${G_FAMILY}/`, JSON.stringify({ name: "Household" })]);
|
||||||
|
await adapter().addMember(G_FAMILY, 4);
|
||||||
|
await adapter().removeMember(G_FAMILY, 3);
|
||||||
|
assert.deepEqual(seen.slice(1).map((s) => [s.method, s.path, s.body]), [["POST", `/api/v3/core/groups/${G_FAMILY}/add_user/`, '{"pk":4}'], ["POST", `/api/v3/core/groups/${G_FAMILY}/remove_user/`, '{"pk":3}']]);
|
||||||
|
assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a group id that is not an id and a user id that is not a whole number are never put in the address", async () => {
|
||||||
|
reset();
|
||||||
|
for (const bad of ["../../x", "", "not-a-uuid", `${G_FAMILY}/../x`]) {
|
||||||
|
await assert.rejects(() => adapter().getGroup(bad), /not a group id/);
|
||||||
|
await assert.rejects(() => adapter().renameGroup(bad, "x"), /not a group id/);
|
||||||
|
await assert.rejects(() => adapter().addMember(bad, 1), /not a group id/);
|
||||||
|
}
|
||||||
|
for (const pk of [0, -2, 1.5, Number.NaN]) await assert.rejects(() => adapter().removeMember(G_FAMILY, pk), /not a user id/);
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the routes", () => {
|
||||||
|
let app: Server;
|
||||||
|
let base = "";
|
||||||
|
let id = 0;
|
||||||
|
let readOnly = 0;
|
||||||
|
|
||||||
|
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
|
||||||
|
const details = (sub = "admin") => fetch(`${base}/${id}/group-details`, { headers: as(sub) });
|
||||||
|
const change = (gid: string, body: unknown, sub = "admin") => fetch(`${base}/${id}/groups/${gid}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
|
||||||
|
const writes = () => seen.filter((s) => s.method !== "GET");
|
||||||
|
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
|
||||||
|
const refused = async (res: Response, pattern: RegExp) => {
|
||||||
|
assert.equal(res.status, 409);
|
||||||
|
assert.match(((await res.json()) as { message: string }).message, pattern);
|
||||||
|
};
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await db.insert(users).values([
|
||||||
|
{ oidcSub: "admin", name: "Alma", role: "admin" },
|
||||||
|
{ oidcSub: "operator", name: "Olle", role: "operator" },
|
||||||
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
||||||
|
]);
|
||||||
|
const cred = (await db.insert(integrationCredentials).values({ name: "authentik:Front door", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok", writeToken: "write-tok" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||||
|
const credRead = (await db.insert(integrationCredentials).values({ name: "authentik:Watched", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||||
|
const config = JSON.stringify({ url: fakeUrl });
|
||||||
|
id = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
|
||||||
|
readOnly = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credRead.id }).returning({ id: integrations.id }))[0].id;
|
||||||
|
await updateSettings({ signIn: { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["admins"], operatorGroups: ["family"], otherwise: "viewer" } });
|
||||||
|
const a = express();
|
||||||
|
a.use(express.json());
|
||||||
|
a.use((req, _res, next) => {
|
||||||
|
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
a.use("/api/authentik", authentikRouter);
|
||||||
|
app = await new Promise<Server>((resolve) => {
|
||||||
|
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||||
|
});
|
||||||
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/authentik`;
|
||||||
|
});
|
||||||
|
after(() => {
|
||||||
|
app.close();
|
||||||
|
try {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// Windows keeps the database file locked until the process exits.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("only an administrator sees the groups or changes them; nothing reaches Authentik for anyone else", async () => {
|
||||||
|
reset();
|
||||||
|
for (const sub of ["viewer", "operator"]) {
|
||||||
|
assert.equal((await details(sub)).status, 403, sub);
|
||||||
|
assert.equal((await change(G_FAMILY, { name: "x" }, sub)).status, 403, sub);
|
||||||
|
}
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the groups with their members and the people to name them by (not service accounts), which group decides a role here, and which user the token is", async () => {
|
||||||
|
reset();
|
||||||
|
const res = await details();
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const text = await res.text();
|
||||||
|
assert.equal(/write-tok|read-tok/.test(text), false);
|
||||||
|
const body = JSON.parse(text) as { groups: { name: string; admin: boolean; members: number[]; decidesRole: string | null }[]; people: { username: string }[]; self: number; more: boolean };
|
||||||
|
assert.deepEqual(body.groups.map((g) => [g.name, g.admin, g.members, g.decidesRole]), [["admins", true, [1, 2], "admin"], ["Family", false, [3], "operator"], ["Other", false, [], null]]);
|
||||||
|
assert.deepEqual(body.people.map((p) => p.username), ["akadmin", "bob", "carol", "dave"]);
|
||||||
|
assert.deepEqual([body.self, body.more], [1, false]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renaming and changing members: the name first, then each user, and the audit log says who was put in and taken out", async () => {
|
||||||
|
reset();
|
||||||
|
const res = await change(G_FAMILY, { name: "Household", membersAdd: [4], membersRemove: [3] });
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.deepEqual(await res.json(), { changed: ["name", "members"], added: 1, removed: 1 });
|
||||||
|
assert.deepEqual(writes().map((s) => `${s.method} ${s.path.replace(G_FAMILY, "G")} ${s.body}`), ["PATCH /api/v3/core/groups/G/ {\"name\":\"Household\"}", "POST /api/v3/core/groups/G/add_user/ {\"pk\":4}", "POST /api/v3/core/groups/G/remove_user/ {\"pk\":3}"]);
|
||||||
|
const [entry] = await audit("update_authentik_group");
|
||||||
|
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_group", G_FAMILY]);
|
||||||
|
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: id, integration: "Front door", group: "Family", renamedTo: "Household", added: ["dave"], removed: ["carol"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("members already in are not put in again, those not in are not taken out, and a change that changes nothing sends nothing and writes nothing", async () => {
|
||||||
|
reset();
|
||||||
|
const before = (await audit("update_authentik_group")).length;
|
||||||
|
const res = await change(G_FAMILY, { name: "Family", membersAdd: [3], membersRemove: [4] });
|
||||||
|
assert.deepEqual(await res.json(), { changed: [], added: 0, removed: 0 });
|
||||||
|
assert.deepEqual(writes(), []);
|
||||||
|
assert.equal((await audit("update_authentik_group")).length, before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("somebody who joined meanwhile is not dropped: members are put in and out one by one, never replaced", async () => {
|
||||||
|
reset();
|
||||||
|
groupTable.find((g) => g.pk === G_OTHER)!.users = [4]; // dave joined after the page was read
|
||||||
|
const res = await change(G_OTHER, { membersAdd: [3] });
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [4, 3]);
|
||||||
|
assert.deepEqual(writes().map((s) => s.path.split("/").slice(-2, -1)[0]), ["add_user"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("what is wrong with the change is said before Authentik is asked", async () => {
|
||||||
|
reset();
|
||||||
|
for (const bad of [{ name: "" }, { membersAdd: ["x"] }, { membersAdd: [1.5] }, { membersAdd: [0] }, { membersAdd: [4], membersRemove: [4] }, { membersAdd: Array.from({ length: 26 }, (_, i) => i + 1) }]) {
|
||||||
|
const res = await change(G_FAMILY, bad);
|
||||||
|
assert.equal(res.status, 400, JSON.stringify(bad));
|
||||||
|
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
|
||||||
|
}
|
||||||
|
assert.equal((await change("not-a-uuid", { name: "x" })).status, 400);
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a service account and the token's own account are refused, and nothing at all is changed — not even the name asked for in the same request", async () => {
|
||||||
|
reset();
|
||||||
|
await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [5] }), /ak-outpost-front: .*service account/);
|
||||||
|
await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [4, 1] }), /akadmin: .*token/);
|
||||||
|
await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*token/);
|
||||||
|
assert.deepEqual(writes(), []);
|
||||||
|
assert.equal(groupTable.find((g) => g.pk === G_FAMILY)!.name, "Family");
|
||||||
|
assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [3], "dave, checked before akadmin, was not put in either");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the last active administrator can't be taken out of the group that makes them one — unless they are in another such group, or another administrator is active", async () => {
|
||||||
|
reset();
|
||||||
|
meId = 3;
|
||||||
|
userTable.find((u) => u.pk === 2)!.is_active = false; // bob is off: akadmin is the only active administrator
|
||||||
|
await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*only active administrator/);
|
||||||
|
assert.deepEqual(writes(), []);
|
||||||
|
assert.equal((await change(G_ADMIN, { membersRemove: [2] })).status, 200, "bob is not an active administrator, so taking him out loses nothing");
|
||||||
|
// akadmin in a second administrators group: taking him out of the first leaves him an administrator.
|
||||||
|
groupTable.push({ pk: "55555555-5555-4555-8555-555555555555", name: "root", is_superuser: true, users: [1] });
|
||||||
|
userTable.find((u) => u.pk === 1)!.groups!.push("55555555-5555-4555-8555-555555555555");
|
||||||
|
assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200);
|
||||||
|
// And with another active administrator, one may come out of the only group.
|
||||||
|
reset();
|
||||||
|
meId = 3;
|
||||||
|
assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user whose groups Authentik did not say can be put in a group, but not taken out of one that makes administrators", async () => {
|
||||||
|
reset();
|
||||||
|
meId = 3;
|
||||||
|
delete userTable.find((u) => u.pk === 2)!.groups;
|
||||||
|
await refused(await change(G_ADMIN, { membersRemove: [2] }), /bob: .*did not say which groups/);
|
||||||
|
assert.equal((await change(G_FAMILY, { membersAdd: [4] })).status, 200);
|
||||||
|
assert.equal((await change(G_OTHER, { membersAdd: [2] })).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a group whose members Authentik did not say can be renamed but its members are not changed", async () => {
|
||||||
|
reset();
|
||||||
|
delete (groupTable.find((g) => g.pk === G_OTHER) as Partial<FakeGroup>).users;
|
||||||
|
await refused(await change(G_OTHER, { membersAdd: [4] }), /did not say who is in this group/);
|
||||||
|
assert.equal((await change(G_OTHER, { name: "Others" })).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a failure part-way says how far it got, and the audit log has what was done", async () => {
|
||||||
|
reset();
|
||||||
|
failMemberPk = 4;
|
||||||
|
const res = await change(G_OTHER, { name: "Others", membersAdd: [3, 4] });
|
||||||
|
assert.equal(res.status, 502);
|
||||||
|
assert.match(((await res.json()) as { message: string }).message, /boom|Authentik error/);
|
||||||
|
assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [3], "the name and carol were done; dave was not");
|
||||||
|
const entry = (await audit("update_authentik_group")).at(-1)!;
|
||||||
|
const detail = JSON.parse(entry.detail ?? "{}") as { renamedTo?: string; added: string[] };
|
||||||
|
assert.deepEqual([detail.renamedTo, detail.added], ["Others", ["carol"]]);
|
||||||
|
assert.match(((await (await change(G_OTHER, { membersAdd: [4] })).json()) as { message: string }).message, /0 of 1 changes had been made/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a group that is gone is not found; an Authentik with no token for managing users is not asked anything", async () => {
|
||||||
|
reset();
|
||||||
|
assert.equal((await change("99999999-9999-4999-8999-999999999999", { name: "x" })).status, 404);
|
||||||
|
seen.length = 0;
|
||||||
|
assert.equal((await fetch(`${base}/${readOnly}/group-details`, { headers: as("admin") })).status, 400);
|
||||||
|
assert.equal((await fetch(`${base}/${readOnly}/groups/${G_FAMILY}`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400);
|
||||||
|
assert.deepEqual(seen, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1764,6 +1764,21 @@ export interface AuthentikGroup {
|
|||||||
admin: boolean;
|
admin: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A group with who is in it, and the role it decides in this app, if any (Settings → Sign-in). */
|
||||||
|
export interface AuthentikGroupDetail extends AuthentikGroup {
|
||||||
|
/** User ids; null when Authentik did not say, and then they are not changed from here. */
|
||||||
|
members: number[] | null;
|
||||||
|
decidesRole: "admin" | "operator" | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A person to name a group's members by. */
|
||||||
|
export interface AuthentikGroupPerson {
|
||||||
|
pk: number;
|
||||||
|
username: string;
|
||||||
|
name: string;
|
||||||
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthentikNewUser {
|
export interface AuthentikNewUser {
|
||||||
username: string;
|
username: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -3428,6 +3443,8 @@ export const api = {
|
|||||||
createUser: (id: number, body: AuthentikNewUser) => request<AuthentikUserMade>(`/api/authentik/${id}/users`, { method: "POST", body: JSON.stringify(body) }),
|
createUser: (id: number, body: AuthentikNewUser) => request<AuthentikUserMade>(`/api/authentik/${id}/users`, { method: "POST", body: JSON.stringify(body) }),
|
||||||
users: (id: number, search = "") => request<{ users: AuthentikPerson[]; more: boolean; self: number | null }>(`/api/authentik/${id}/users${search.trim() ? `?search=${encodeURIComponent(search.trim())}` : ""}`),
|
users: (id: number, search = "") => request<{ users: AuthentikPerson[]; more: boolean; self: number | null }>(`/api/authentik/${id}/users${search.trim() ? `?search=${encodeURIComponent(search.trim())}` : ""}`),
|
||||||
setUserActive: (id: number, pk: number, active: boolean) => request<{ user: AuthentikPerson }>(`/api/authentik/${id}/users/${pk}/active`, { method: "POST", body: JSON.stringify({ active }) }),
|
setUserActive: (id: number, pk: number, active: boolean) => request<{ user: AuthentikPerson }>(`/api/authentik/${id}/users/${pk}/active`, { method: "POST", body: JSON.stringify({ active }) }),
|
||||||
|
groupDetails: (id: number) => request<{ groups: AuthentikGroupDetail[]; people: AuthentikGroupPerson[]; more: boolean; self: number | null }>(`/api/authentik/${id}/group-details`),
|
||||||
|
updateGroup: (id: number, gid: string, body: { name?: string; membersAdd?: number[]; membersRemove?: number[] }) => request<{ changed: string[]; added: number; removed: number }>(`/api/authentik/${id}/groups/${gid}`, { method: "PATCH", body: JSON.stringify(body) }),
|
||||||
updateUser: (id: number, pk: number, body: { name?: string; email?: string; groupsAdd?: string[]; groupsRemove?: string[] }) => request<{ user: AuthentikPerson; changed: string[] }>(`/api/authentik/${id}/users/${pk}`, { method: "PATCH", body: JSON.stringify(body) }),
|
updateUser: (id: number, pk: number, body: { name?: string; email?: string; groupsAdd?: string[]; groupsRemove?: string[] }) => request<{ user: AuthentikPerson; changed: string[] }>(`/api/authentik/${id}/users/${pk}`, { method: "PATCH", body: JSON.stringify(body) }),
|
||||||
deleteUser: (id: number, pk: number, username: string) => request<void>(`/api/authentik/${id}/users/${pk}`, { method: "DELETE", body: JSON.stringify({ username }) }),
|
deleteUser: (id: number, pk: number, username: string) => request<void>(`/api/authentik/${id}/users/${pk}`, { method: "DELETE", body: JSON.stringify({ username }) }),
|
||||||
removeWriteToken: (id: number) => request<void>(`/api/authentik/${id}/write-token`, { method: "DELETE" }),
|
removeWriteToken: (id: number) => request<void>(`/api/authentik/${id}/write-token`, { method: "DELETE" }),
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import { useState, type FormEvent } from "react";
|
||||||
|
import { api, type AuthentikGroupDetail, type AuthentikGroupPerson, type AuthentikInfo } from "../api/client";
|
||||||
|
import { ErrorNotice, SuccessNotice } from "./Notice";
|
||||||
|
import { confirmDialog } from "../utils/dialogs";
|
||||||
|
import { readableError } from "../utils/errors";
|
||||||
|
|
||||||
|
function EditGroup({ g, people, self, busy, onSave, onCancel }: { g: AuthentikGroupDetail; people: AuthentikGroupPerson[]; self: number | null; busy: boolean; onSave: (name: string, add: number[], remove: number[]) => void; onCancel: () => void }) {
|
||||||
|
const [name, setName] = useState(g.name);
|
||||||
|
const [members, setMembers] = useState<number[]>(g.members ?? []);
|
||||||
|
const [filter, setFilter] = useState("");
|
||||||
|
const canEditMembers = g.members !== null;
|
||||||
|
const shown = people.filter((p) => !filter.trim() || `${p.username} ${p.name}`.toLowerCase().includes(filter.trim().toLowerCase()));
|
||||||
|
// Members who are not in the list of people — service accounts, or beyond the first 200 — are not shown and are never taken out from here.
|
||||||
|
const hidden = (g.members ?? []).filter((m) => !people.some((p) => p.pk === m)).length;
|
||||||
|
|
||||||
|
const toggle = (pk: number) => setMembers((cur) => (cur.includes(pk) ? cur.filter((x) => x !== pk) : [...cur, pk]));
|
||||||
|
|
||||||
|
function submit(e: FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
const was = g.members ?? [];
|
||||||
|
const add = canEditMembers ? members.filter((m) => !was.includes(m)) : [];
|
||||||
|
const remove = canEditMembers ? was.filter((m) => !members.includes(m) && people.some((p) => p.pk === m)) : [];
|
||||||
|
if (name.trim() === g.name && add.length === 0 && remove.length === 0) return onCancel();
|
||||||
|
onSave(name.trim(), add, remove);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit} className="p-2">
|
||||||
|
{g.decidesRole && (
|
||||||
|
<div className="alert alert-warning py-2 small">
|
||||||
|
This group decides who is {g.decidesRole === "admin" ? "an administrator" : "an operator"} <em>here</em> (Settings → Sign-in). Renaming it, or changing who is in it, changes that at their next sign-in.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{g.admin && <div className="text-secondary small mb-2">Members of this group are administrators of Authentik. Whether a group is one is changed in Authentik, not here.</div>}
|
||||||
|
<label className="form-label" htmlFor={`ak-group-name-${g.id}`}>
|
||||||
|
Name
|
||||||
|
</label>
|
||||||
|
<input id={`ak-group-name-${g.id}`} className="form-control form-control-sm mb-3" style={{ maxWidth: 360 }} required maxLength={200} autoComplete="off" value={name} onChange={(e) => setName(e.target.value)} />
|
||||||
|
|
||||||
|
<div className="form-label">Members</div>
|
||||||
|
{!canEditMembers ? (
|
||||||
|
<div className="text-secondary small mb-3">Authentik did not say who is in this group, so only its name can be changed here.</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<input className="form-control form-control-sm mb-2" style={{ maxWidth: 360 }} placeholder="Find a user" aria-label="Find a user" value={filter} onChange={(e) => setFilter(e.target.value)} />
|
||||||
|
<div className="border rounded p-2 mb-1" style={{ maxHeight: 240, overflowY: "auto" }}>
|
||||||
|
{shown.length === 0 && <div className="text-secondary small">No user matches.</div>}
|
||||||
|
{shown.map((p) => (
|
||||||
|
<label key={p.pk} className="form-check">
|
||||||
|
<input type="checkbox" className="form-check-input" checked={members.includes(p.pk)} disabled={p.pk === self} onChange={() => toggle(p.pk)} />
|
||||||
|
<span className="form-check-label">
|
||||||
|
{p.username}
|
||||||
|
{p.name !== p.username && <span className="text-secondary"> — {p.name}</span>}
|
||||||
|
{!p.active && <span className="badge bg-secondary-lt text-secondary ms-2">off</span>}
|
||||||
|
{p.pk === self && <span className="text-secondary small ms-2">this token’s account — looked after in Authentik</span>}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{hidden > 0 && <div className="text-secondary small mb-2">{hidden} member{hidden === 1 ? " is" : "s are"} not shown (service accounts, or beyond the first 200 users) and are left as they are.</div>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="d-flex gap-2 mt-2">
|
||||||
|
<button type="submit" className="btn btn-sm btn-primary" disabled={busy}>
|
||||||
|
{busy ? "Saving…" : "Save"}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={onCancel} disabled={busy}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The groups of an Authentik, for an administrator to rename and to put users in and take them out of. Whether a group makes its members administrators is shown, not changed. A group that
|
||||||
|
* decides somebody's role in this app says so, and asks before it is changed.
|
||||||
|
*/
|
||||||
|
export default function AuthentikGroupList({ a }: { a: AuthentikInfo }) {
|
||||||
|
const [groups, setGroups] = useState<AuthentikGroupDetail[] | null>(null);
|
||||||
|
const [people, setPeople] = useState<AuthentikGroupPerson[]>([]);
|
||||||
|
const [self, setSelf] = useState<number | null>(null);
|
||||||
|
const [editing, setEditing] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | "list" | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
if (!a.canCreateUsers) return null;
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
setBusy("list");
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const r = await api.authentik.groupDetails(a.id);
|
||||||
|
setGroups(r.groups);
|
||||||
|
setPeople(r.people);
|
||||||
|
setSelf(r.self);
|
||||||
|
} catch (err) {
|
||||||
|
setError(readableError(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(g: AuthentikGroupDetail, name: string, add: number[], remove: number[]) {
|
||||||
|
if (g.decidesRole) {
|
||||||
|
const ok = await confirmDialog({
|
||||||
|
title: "Change a group that decides roles",
|
||||||
|
message: `"${g.name}" decides who is ${g.decidesRole === "admin" ? "an administrator" : "an operator"} in this app. Changing its name or its members changes people's roles here at their next sign-in. Go on?`,
|
||||||
|
confirmLabel: "Save",
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
setBusy(g.id);
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
try {
|
||||||
|
const r = await api.authentik.updateGroup(a.id, g.id, { name: name !== g.name ? name : undefined, membersAdd: add, membersRemove: remove });
|
||||||
|
setEditing(null);
|
||||||
|
setNotice(r.changed.length === 0 ? "Nothing was different." : `Saved "${name}"${r.added + r.removed > 0 ? ` — ${r.added} put in, ${r.removed} taken out` : ""}.`);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(readableError(err));
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-3">
|
||||||
|
<h4>Groups</h4>
|
||||||
|
<ErrorNotice error={error} />
|
||||||
|
<SuccessNotice notice={notice} />
|
||||||
|
{groups === null ? (
|
||||||
|
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void load()} disabled={busy !== null}>
|
||||||
|
{busy === "list" ? "Reading…" : "Show groups"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{groups.length === 0 ? (
|
||||||
|
<div className="text-secondary mb-2">There are no groups.</div>
|
||||||
|
) : (
|
||||||
|
<div className="table-responsive">
|
||||||
|
<table className="table table-vcenter table-sm">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Group</th>
|
||||||
|
<th className="text-end">Members</th>
|
||||||
|
<th className="text-end"> </th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{groups.map((g) =>
|
||||||
|
editing === g.id ? (
|
||||||
|
<tr key={g.id}>
|
||||||
|
<td colSpan={3}>
|
||||||
|
<EditGroup g={g} people={people} self={self} busy={busy === g.id} onSave={(name, add, remove) => void save(g, name, add, remove)} onCancel={() => setEditing(null)} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
<tr key={g.id}>
|
||||||
|
<td>
|
||||||
|
{g.name}
|
||||||
|
{g.admin && <span className="badge bg-yellow-lt text-yellow ms-2">administrators</span>}
|
||||||
|
{g.decidesRole && <span className="badge bg-blue-lt text-blue ms-1">decides {g.decidesRole === "admin" ? "admins" : "operators"} here</span>}
|
||||||
|
</td>
|
||||||
|
<td className="text-end text-secondary">{g.members === null ? "?" : g.members.length}</td>
|
||||||
|
<td className="text-end">
|
||||||
|
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy !== null} onClick={() => { setEditing(g.id); setNotice(null); }}>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<button type="button" className="btn btn-sm btn-link text-secondary px-0" onClick={() => { setGroups(null); setEditing(null); }}>
|
||||||
|
Hide groups
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { api, type AuthentikInfo, type CurrentUser } from "../api/client";
|
import { api, type AuthentikInfo, type CurrentUser } from "../api/client";
|
||||||
import AuthentikNewUser from "../components/AuthentikNewUser";
|
import AuthentikNewUser from "../components/AuthentikNewUser";
|
||||||
|
import AuthentikGroupList from "../components/AuthentikGroupList";
|
||||||
import AuthentikUserList from "../components/AuthentikUserList";
|
import AuthentikUserList from "../components/AuthentikUserList";
|
||||||
import EmptyState from "../components/EmptyState";
|
import EmptyState from "../components/EmptyState";
|
||||||
import TimeAgo from "../components/TimeAgo";
|
import TimeAgo from "../components/TimeAgo";
|
||||||
@@ -130,6 +131,7 @@ function Card({ a, isAdmin, onChanged }: { a: AuthentikInfo; isAdmin: boolean; o
|
|||||||
)}
|
)}
|
||||||
{isAdmin && a.enabled && <AuthentikNewUser a={a} onChanged={onChanged} />}
|
{isAdmin && a.enabled && <AuthentikNewUser a={a} onChanged={onChanged} />}
|
||||||
{isAdmin && a.enabled && <AuthentikUserList a={a} />}
|
{isAdmin && a.enabled && <AuthentikUserList a={a} />}
|
||||||
|
{isAdmin && a.enabled && <AuthentikGroupList a={a} />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -160,7 +162,7 @@ export default function Authentik({ user }: { user: CurrentUser }) {
|
|||||||
<h2 className="page-title">Authentik</h2>
|
<h2 className="page-title">Authentik</h2>
|
||||||
<p className="text-secondary">
|
<p className="text-secondary">
|
||||||
The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "}
|
The sign-in in front of everything else. It is read every few minutes with an API token (see <Link to="/integrations">Integrations</Link>). An <strong>outpost that goes quiet</strong> (the apps it guards stop letting anyone in), a <strong>certificate</strong> or an{" "}
|
||||||
<strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>.{user.role === "admin" && " An administrator can also make a user here, with a one-time link for them to choose a password, and switch users off or delete them."}
|
<strong>API token</strong> that is about to run out, <strong>no worker</strong> and a burst of <strong>failed sign-ins</strong> are alerts — see <Link to="/alerts">Alerts</Link>.{user.role === "admin" && " An administrator can also make a user here, with a one-time link for them to choose a password, and switch users off or delete them, and rename groups and change who is in them."}
|
||||||
</p>
|
</p>
|
||||||
<ErrorNotice error={error} />
|
<ErrorNotice error={error} />
|
||||||
{!data && !error && <BlockSkeleton lines={4} />}
|
{!data && !error && <BlockSkeleton lines={4} />}
|
||||||
|
|||||||
Reference in new issue
Block a user