Skip to content

Commit f205dfe

Browse files
authored
feat: service accounts settings pages (#3151)
* feat(service-accounts): add Service Accounts settings pages Settings → Service Accounts, gated on service-account:manage from /auth/whoami: a list to create and delete accounts, and an account page with its RoleBindings (read-only, for readers of roleBinding), a Tokens tab that reuses the personal token form, and a kubeconfig download through GET /kubeconfig?serviceAccount=, warning when the account holds neither kubernetes-proxy:read nor :write. RoleBindings get a serviceAccounts subject picker that takes exact names, without *. fetchPeopleWithRoles keeps only humans and federated users, so notification and playbook people pickers never offer a service account. Team members are added and removed through POST /teams/:id/members and DELETE /teams/:id/members/:personId, since /db/team_members writes now return 405, and the unused createPerson is removed. * fix(service-accounts): refresh the tokens tab with the page The page's Refresh button refetched only the account, so on the Tokens tab it never showed tokens issued or revoked elsewhere, such as through GET /kubeconfig from the CLI. It now invalidates every query under the account's key, the account and its tokens alike. * fix: restore fsevents in package-lock.json The security updates in #3060 dropped the node_modules/fsevents entry from the lock file while chokidar and jest-haste-map still list it as an optional dependency. npm 10 tolerates the gap, but newer npm fails npm ci with "Missing: fsevents@2.3.3 from lock file", which breaks the storybook job since it runs on the runner's default Node instead of Node 20. This restores the entry #3060 removed. * fix(service-accounts): drop Created By Service accounts don't record who created them, now or later, like GCP, AWS and Kubernetes service accounts, which keep only the creation time. The list column, the Overview row and the created_by field are removed, so the pages no longer show "Not recorded" for every account. Created stays, and Issued By stays on the Tokens tab since token issuers are recorded. * feat(role-bindings): filter role bindings by a subject they name The RoleBindings page filters by a person, team or service account, kept in the person, team or serviceAccount search param, so links and reloads keep it. PostgREST does the filtering with JSON containment on role_bindings.subjects, so a binding is listed when that field names the subject exactly: "*" and other ways a binding applies aren't expanded, which is for Check Access. On a filtered page, Create opens the RoleBinding form with the subject filled in. The service account page gets a Manage role bindings button to its filtered page, for callers who can read role bindings, and each binding in its Overview links to the filtered page with that binding open.
1 parent 73baadb commit f205dfe

26 files changed

Lines changed: 1476 additions & 162 deletions

‎package-lock.json‎

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/App.tsx‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import dynamic from "next/dynamic";
66
import React, { ReactNode, useEffect, useState, useMemo } from "react";
77
import { IconType } from "react-icons";
88
import { AiFillHeart } from "react-icons/ai";
9-
import { BsLink, BsToggles } from "react-icons/bs";
9+
import { BsLink, BsRobot, BsToggles } from "react-icons/bs";
1010
import { FaArchive, FaBell, FaPlug, FaTasks } from "react-icons/fa";
1111
import { HiUser } from "react-icons/hi";
1212
import { ImLifebuoy } from "react-icons/im";
@@ -321,6 +321,14 @@ const AgentsPage = dynamic(
321321
() => import("@flanksource-ui/components/Agents/AgentPage")
322322
);
323323

324+
const ServiceAccountsPage = dynamic(
325+
() => import("@flanksource-ui/components/ServiceAccounts/ServiceAccountsPage")
326+
);
327+
328+
const ServiceAccountPage = dynamic(
329+
() => import("@flanksource-ui/components/ServiceAccounts/ServiceAccountPage")
330+
);
331+
324332
const TokensPage = dynamic(
325333
() => import("@flanksource-ui/components/Tokens/TokensPage")
326334
);
@@ -501,6 +509,13 @@ const settingsNav: SettingsNavigationItems = {
501509
featureName: features.agents,
502510
resourceName: tables.agents
503511
},
512+
{
513+
name: "Service Accounts",
514+
href: "/settings/service-accounts",
515+
icon: BsRobot,
516+
featureName: features["settings.permissions"],
517+
resourceName: tables.service_accounts
518+
},
504519
{
505520
name: "Personal access tokens",
506521
href: "/settings/tokens",
@@ -973,6 +988,36 @@ export function IncidentManagerRoutes({ sidebar }: { sidebar: ReactNode }) {
973988
/>
974989
</Route>
975990

991+
<Route path="service-accounts">
992+
<Route
993+
index
994+
element={withAuthorizationAccessCheck(
995+
<ServiceAccountsPage />,
996+
tables.service_accounts,
997+
"read",
998+
true
999+
)}
1000+
/>
1001+
<Route
1002+
path=":name"
1003+
element={withAuthorizationAccessCheck(
1004+
<ServiceAccountPage tab="Overview" />,
1005+
tables.service_accounts,
1006+
"read",
1007+
true
1008+
)}
1009+
/>
1010+
<Route
1011+
path=":name/tokens"
1012+
element={withAuthorizationAccessCheck(
1013+
<ServiceAccountPage tab="Tokens" />,
1014+
tables.service_accounts,
1015+
"read",
1016+
true
1017+
)}
1018+
/>
1019+
</Route>
1020+
9761021
<Route path="tokens">
9771022
<Route
9781023
index

‎src/api/query-hooks/useRoleBindingsQuery.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2+
import { RoleBindingNamedSubject } from "../types/roleBindings";
23
import {
34
createRoleBinding,
45
getRoleBindings,
56
updateRoleBinding
67
} from "../services/roleBindings";
78

8-
export function useRoleBindingsQuery() {
9+
export function useRoleBindingsQuery(subject?: RoleBindingNamedSubject) {
910
return useQuery({
10-
queryKey: ["role-bindings"],
11-
queryFn: getRoleBindings
11+
queryKey: ["role-bindings", subject?.field, subject?.name],
12+
queryFn: () => getRoleBindings(subject)
1213
});
1314
}
1415

‎src/api/services/roleBindings.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,28 @@ import {
77
import {
88
RoleBindingDB,
99
RoleBindingDisplay,
10+
RoleBindingNamedSubject,
1011
RoleBindingSpec
1112
} from "../types/roleBindings";
1213
import { createRbacObject, updateRbacObject } from "./rbacResources";
1314

1415
// Role bindings are read through PostgREST, which can join their author.
15-
export async function getRoleBindings(): Promise<RoleBindingDisplay[]> {
16+
// With a subject, only the bindings whose subjects list it, by JSON containment on subjects.
17+
export async function getRoleBindings(
18+
subject?: RoleBindingNamedSubject
19+
): Promise<RoleBindingDisplay[]> {
1620
const response = await IncidentCommander.get<RoleBindingDisplay[]>(
1721
"/role_bindings",
1822
{
1923
params: {
2024
select: `*,created_by(${AVATAR_INFO})`,
2125
deleted_at: "is.null",
2226
namespace: `neq.${RBAC_ACCESS_TOKENS_NAMESPACE}`,
27+
...(subject
28+
? {
29+
subjects: `cs.${JSON.stringify({ [subject.field]: [subject.name] })}`
30+
}
31+
: {}),
2332
order: "namespace,name"
2433
}
2534
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { apiBase, IncidentCommander } from "../axios";
2+
import { RoleBindingDB } from "../types/roleBindings";
3+
import { TokenRole, TokenRoleBinding } from "./tokens";
4+
5+
type PersonInfo = {
6+
id: string;
7+
name: string;
8+
email?: string;
9+
avatar?: string;
10+
};
11+
12+
export type ServiceAccount = {
13+
id: string;
14+
name: string;
15+
created_at: string;
16+
};
17+
18+
export type ServiceAccountDetail = ServiceAccount & {
19+
/** What it holds of kubernetes-proxy:read and kubernetes-proxy:write */
20+
kubernetes_proxy?: Record<string, boolean>;
21+
/** Omitted unless the caller may read RoleBindings */
22+
role_bindings?: RoleBindingDB[];
23+
};
24+
25+
export type ServiceAccountToken = {
26+
id: string;
27+
name: string;
28+
created_at: string;
29+
expires_at?: string | null;
30+
auto_renew?: boolean;
31+
/** Whoever issued the token */
32+
issuer?: PersonInfo | null;
33+
role_bindings?: TokenRoleBinding[];
34+
};
35+
36+
export type CreateServiceAccountTokenRequest = {
37+
name: string;
38+
expiry: string;
39+
autoRenew: boolean;
40+
roles: TokenRole[];
41+
};
42+
43+
export type CreatedServiceAccountToken = {
44+
id: string;
45+
name: string;
46+
token: string;
47+
expires_at?: string;
48+
};
49+
50+
// Every route takes service-account:manage, and is refused to a request made with an access token
51+
export async function getServiceAccounts() {
52+
const { data } = await apiBase.get<ServiceAccount[]>("/service-accounts");
53+
return data ?? [];
54+
}
55+
56+
export async function getServiceAccount(name: string) {
57+
const { data } = await apiBase.get<ServiceAccountDetail>(
58+
`/service-accounts/${encodeURIComponent(name)}`
59+
);
60+
return data;
61+
}
62+
63+
export async function createServiceAccount(name: string) {
64+
const { data } = await apiBase.post<ServiceAccount>("/service-accounts", {
65+
name
66+
});
67+
return data;
68+
}
69+
70+
export async function deleteServiceAccount(name: string) {
71+
await apiBase.delete(`/service-accounts/${encodeURIComponent(name)}`);
72+
}
73+
74+
export async function getServiceAccountTokens(name: string) {
75+
const { data } = await apiBase.get<ServiceAccountToken[]>(
76+
`/service-accounts/${encodeURIComponent(name)}/tokens`
77+
);
78+
return data ?? [];
79+
}
80+
81+
export async function createServiceAccountToken(
82+
name: string,
83+
request: CreateServiceAccountTokenRequest
84+
) {
85+
const { data } = await apiBase.post<CreatedServiceAccountToken>(
86+
`/service-accounts/${encodeURIComponent(name)}/tokens`,
87+
request
88+
);
89+
return data;
90+
}
91+
92+
export async function revokeServiceAccountToken(name: string, id: string) {
93+
await apiBase.delete(
94+
`/service-accounts/${encodeURIComponent(name)}/tokens/${id}`
95+
);
96+
}
97+
98+
/** Issues a new token of the service account, bound to the kubernetes-proxy Role, and returns a kubeconfig that uses it. */
99+
export async function downloadServiceAccountKubeconfig(
100+
serviceAccount: string,
101+
options: { name?: string; expiry?: string; autoRenew?: boolean }
102+
) {
103+
const { data } = await apiBase.get<string>("/kubeconfig", {
104+
params: {
105+
serviceAccount,
106+
...(options.name ? { name: options.name } : {}),
107+
...(options.expiry ? { expiry: options.expiry } : {}),
108+
...(options.autoRenew ? { autoRenew: true } : {})
109+
}
110+
// The kubeconfig is YAML, which the default JSON parsing leaves as text, while an error's JSON body is still parsed
111+
});
112+
return data;
113+
}
114+
115+
/** Names of service accounts, which anyone with read on person may see. Used to pick RoleBinding subjects. */
116+
export async function getServiceAccountNames() {
117+
const { data } = await IncidentCommander.get<{ name: string }[]>("/people", {
118+
params: {
119+
select: "name",
120+
type: "eq.service_account",
121+
deleted_at: "is.null",
122+
order: "name.asc"
123+
}
124+
});
125+
return (data ?? []).map(({ name }) => name);
126+
}

‎src/api/services/teams.ts‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { IncidentCommander } from "../axios";
2-
import { resolvePostGrestRequestWithPagination } from "../resolve";
1+
import { apiBase, IncidentCommander } from "../axios";
32
import { Team, User } from "../types/users";
43

54
export const getTeam = async (id: string): Promise<Team | null> => {
@@ -36,22 +35,9 @@ export const getTeamMembers = async (
3635
return { data };
3736
};
3837

39-
export const addUserToTeam = (teamId: string, userIds: string[]) => {
40-
const payload = userIds.map((userId) => {
41-
return {
42-
team_id: teamId,
43-
person_id: userId
44-
};
45-
});
46-
return resolvePostGrestRequestWithPagination(
47-
IncidentCommander.post(`/team_members`, payload)
48-
);
49-
};
38+
// Members are written through /teams/:id/members, which only accepts people who can be team members; /db/team_members is read-only
39+
export const addUserToTeam = (teamId: string, personIds: string[]) =>
40+
apiBase.post(`/teams/${teamId}/members`, { personIds });
5041

51-
export const removeUserFromTeam = (teamId: string, userId: string) => {
52-
return resolvePostGrestRequestWithPagination(
53-
IncidentCommander.delete(
54-
`/team_members?team_id=eq.${teamId}&person_id=eq.${userId}`
55-
)
56-
);
57-
};
42+
export const removeUserFromTeam = (teamId: string, personId: string) =>
43+
apiBase.delete(`/teams/${teamId}/members/${personId}`);

‎src/api/services/users.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,7 @@ import {
1010
} from "../axios";
1111
import { resolvePostGrestRequestWithPagination } from "../resolve";
1212
import { VersionInfo } from "../types/common";
13-
import {
14-
NewUser,
15-
PeopleRoles,
16-
RegisteredUser,
17-
Team,
18-
User
19-
} from "../types/users";
13+
import { PeopleRoles, RegisteredUser, Team, User } from "../types/users";
2014

2115
export const getPerson = (id: string) =>
2216
resolvePostGrestRequestWithPagination<User[]>(
@@ -44,26 +38,33 @@ export const getPersonWithEmail = (email: string) =>
4438
IncidentCommander.get(`/people?email=eq.${email}`)
4539
);
4640

47-
export const createPerson = ({ name, email, avatar }: NewUser) =>
48-
resolvePostGrestRequestWithPagination<User>(
49-
IncidentCommander.post("/people", { name, email, avatar })
50-
);
51-
5241
export const fetchPeopleRoles = (personIds: string[]) =>
5342
resolvePostGrestRequestWithPagination<PeopleRoles[]>(
5443
IncidentCommander.get(`/people_roles?id=in.(${personIds.toString()})`)
5544
);
5645

57-
export const fetchPeopleWithRoles = (roles?: string[]) => {
46+
// Notification recipients and playbook people parameters accept humans and users of external identity providers.
47+
// people_roles has no type, so it's narrowed to the ids of people of those types.
48+
export const fetchPeopleWithRoles = async (roles?: string[]) => {
5849
let query = `/people_roles?order=name.asc`;
5950

6051
if (roles && roles.length > 0) {
6152
query += `&roles=cs.{${roles.join(",")}}`;
6253
}
6354

64-
return resolvePostGrestRequestWithPagination<PeopleRoles[]>(
65-
IncidentCommander.get(query)
66-
);
55+
const [peopleRoles, accepted] = await Promise.all([
56+
resolvePostGrestRequestWithPagination<PeopleRoles[]>(
57+
IncidentCommander.get(query)
58+
),
59+
IncidentCommander.get<{ id: string }[]>(
60+
`/people?select=id&deleted_at=is.null&or=(type.is.null,type.eq.federated)`
61+
)
62+
]);
63+
const acceptedIds = new Set(accepted.data.map(({ id }) => id));
64+
return {
65+
...peopleRoles,
66+
data: (peopleRoles.data ?? []).filter(({ id }) => acceptedIds.has(id))
67+
};
6768
};
6869

6970
export const getPeopleLastLogin = (personIds: string[]) => {

0 commit comments

Comments
 (0)