Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(review): list and name service accounts and workload identities on approval steps (#21577)

zchpeter0c05a00d8076
diff --git a/backend/component/review/evaluator.go b/backend/component/review/evaluator.go
index 614ab0e870..e515d05037 100644
--- a/backend/component/review/evaluator.go
+++ b/backend/component/review/evaluator.go
@@ -1214,9 +1214,9 @@ func collectStatementTypes(celVarsList []map[string]any) []string {
return result
}
-// getApproversForRole retrieves the list of users who have the specified role
-// for the given project. It queries both project and workspace IAM policies.
-// Only returns END_USER type principals (excludes service accounts, system bots, etc).
+// getApproversForRole returns the people who hold the role in the project or
+// workspace IAM policy, for a notification to mention. A service account or
+// workload identity that holds the role can approve too, but has nobody to notify.
func getApproversForRole(ctx context.Context, stores *store.Store, projectID string, role string) ([]webhook.User, error) {
// Get project to determine workspace
project, err := stores.GetProjectByResourceID(ctx, projectID)
diff --git a/backend/component/review/workflow_test.go b/backend/component/review/workflow_test.go
index cac9a20fea..9040586c2b 100644
--- a/backend/component/review/workflow_test.go
+++ b/backend/component/review/workflow_test.go
@@ -1307,16 +1307,21 @@ func setupWorkflowStoreWithDB(ctx context.Context, t *testing.T) (*sql.DB, *stor
}
func createPendingDatabaseChangeApproval(ctx context.Context, t *testing.T, stores *store.Store, roles []string) (*store.PlanMessage, *store.IssueMessage) {
+ t.Helper()
+ return createPendingDatabaseChangeApprovalBy(ctx, t, stores, "[email protected]", roles)
+}
+
+func createPendingDatabaseChangeApprovalBy(ctx context.Context, t *testing.T, stores *store.Store, creator string, roles []string) (*store.PlanMessage, *store.IssueMessage) {
t.Helper()
plan, err := stores.CreatePlan(ctx, &store.PlanMessage{
ProjectID: "project-a",
Name: "change database",
Config: &storepb.PlanConfig{ApprovalInputVersion: 2},
+ }, creator)
require.NoError(t, err)
issue, err := stores.CreateIssue(ctx, &store.IssueMessage{
ProjectID: "project-a",
- CreatorEmail: "[email protected]",
+ CreatorEmail: creator,
Title: "change database",
Type: storepb.Issue_DATABASE_CHANGE,
PlanUID: &plan.UID,
@@ -1412,3 +1417,118 @@ func TestApproverRoleLookupFailureIsNotARefusal(t *testing.T) {
require.Equal(t, ReasonUnspecified, workflowErr.Reason,
"an outage must not be marked as a permission denial in the audit log")
}
+
+const serviceNowApproverRole = "roles/servicenow-approver"
+
+// bindApproverRole grants the role to one policy member, in the project policy
+// or the workspace policy.
+func bindApproverRole(ctx context.Context, t *testing.T, stores *store.Store, inProject bool, member string) {
+ t.Helper()
+ resourceType, resource := storepb.Policy_WORKSPACE, common.FormatWorkspace("default")
+ if inProject {
+ resourceType, resource = storepb.Policy_PROJECT, common.FormatProject("project-a")
+ }
+ _, err := stores.PatchIamPolicy(ctx, "default", resourceType, resource, func(policy *storepb.IamPolicy) error {
+ policy.Bindings = append(policy.Bindings, &storepb.Binding{
+ Role: serviceNowApproverRole,
+ Members: []string{member},
+ })
+ return nil
+ })
+ require.NoError(t, err)
+}
+
+func TestNonHumanPrincipalApprovesTheStepItsRoleHolds(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ actor *store.UserMessage
+ inProject bool
+ }{
+ {
+ name: "workspace service account bound in the workspace policy",
+ actor: &store.UserMessage{Email: "[email protected]", Type: storepb.PrincipalType_SERVICE_ACCOUNT},
+ },
+ {
+ name: "workspace service account bound in the project policy",
+ actor: &store.UserMessage{Email: "[email protected]", Type: storepb.PrincipalType_SERVICE_ACCOUNT},
+ inProject: true,
+ },
+ {
+ name: "project service account bound in the project policy",
+ actor: &store.UserMessage{Email: "[email protected]", Type: storepb.PrincipalType_SERVICE_ACCOUNT},
+ inProject: true,
+ },
+ {
+ name: "workload identity bound in the project policy",
+ actor: &store.UserMessage{Email: "[email protected]", Type: storepb.PrincipalType_WORKLOAD_IDENTITY},
+ inProject: true,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ ctx := context.Background()
+ stores := setupWorkflowStore(ctx, t)
+ bindApproverRole(ctx, t, stores, test.inProject, common.FormatPrincipalMember(test.actor.Email, test.actor.Type))
+ _, issue := createPendingDatabaseChangeApproval(ctx, t, stores, []string{serviceNowApproverRole})
+
+ result, err := NewWorkflow(stores).ReviewIssue(ctx, IssueInput{
+ Workspace: "default",
+ ProjectID: "project-a",
+ IssueUID: issue.UID,
+ Actor: test.actor,
+ Action: ActionApprove,
+ })
+ require.NoError(t, err)
+ require.True(t, result.Approved)
+ approvers := result.Issue.Payload.GetApproval().GetApprovers()
+ require.Len(t, approvers, 1)
+ require.True(t, proto.Equal(&storepb.IssuePayloadApproval_Approver{
+ Status: storepb.IssuePayloadApproval_Approver_APPROVED,
+ Principal: common.FormatUserEmail(test.actor.Email),
+ }, approvers[0]), "the approver is recorded as users/{email} whatever its type, like the issue creator")
+ })
+ }
+}
+
+func TestNonHumanApproverIsRefusedLikeAPerson(t *testing.T) {
+ serviceAccount := &store.UserMessage{Email: "[email protected]", Type: storepb.PrincipalType_SERVICE_ACCOUNT}
+
+ for _, test := range []struct {
+ name string
+ member string
+ creator string
+ wantReason ErrorReason
+ }{
+ {
+ name: "bound under the users/ prefix, which holds nothing for a service account",
+ member: common.FormatUserEmail(serviceAccount.Email),
+ creator: "[email protected]",
+ wantReason: ReasonApproverRoleRequired,
+ },
+ {
+ name: "created the issue it would approve",
+ member: common.FormatPrincipalMember(serviceAccount.Email, serviceAccount.Type),
+ creator: serviceAccount.Email,
+ wantReason: ReasonUnspecified,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ ctx := context.Background()
+ stores := setupWorkflowStore(ctx, t)
+ bindApproverRole(ctx, t, stores, true, test.member)
+ _, issue := createPendingDatabaseChangeApprovalBy(ctx, t, stores, test.creator, []string{serviceNowApproverRole})
+
+ _, err := NewWorkflow(stores).ReviewIssue(ctx, IssueInput{
+ Workspace: "default",
+ ProjectID: "project-a",
+ IssueUID: issue.UID,
+ Actor: serviceAccount,
+ Action: ActionApprove,
+ })
+
+ var workflowErr *Error
+ require.ErrorAs(t, err, &workflowErr)
+ require.Equal(t, ErrorPermissionDenied, workflowErr.Code)
+ require.Equal(t, test.wantReason, workflowErr.Reason)
+ })
+ }
+}
diff --git a/docs/design/approval-step-non-human-approvers.md b/docs/design/approval-step-non-human-approvers.md
new file mode 100644
index 0000000000..1c08914816
--- /dev/null
+++ b/docs/design/approval-step-non-human-approvers.md
@@ -0,0 +1,239 @@
+# Approval steps held by service accounts and workload identities
+
+Status: implemented in this PR · 2026-10-12
+
+A custom approval step whose role is held only by service accounts shows "No reviewers" on the
+plan page, and the code comment beside that string says the step can never be approved. Both are
+wrong: the backend already lets a service account or workload identity approve any step whose role
+it holds, and QVC's ServiceNow integration does exactly that. The review UI applies a display
+filter the authorization model does not have. **A principal that holds a step's role is an
+approver whatever its type: the review surfaces list it, name it, and attribute its decision the
+same way they do for a person. Notifications stay human-only.**
+
+## Problem
+
+QVC (2026-10-08) ends every change's approval flow with a custom role "ServiceNow Approver" held
+by two service accounts: a workspace account `bytebase-integration-service` bound at workspace and
+project level, and a project account `testdt` bound at project level. The plan page shows the step
+as "No reviewers", so the customer asked whether the flow is supported at all.
+
+Reproduced on a throwaway 3.24-dev instance with the same shape (Developer → Workspace DBA →
+ServiceNow Approver). What each surface showed before this change, from real screenshots in the PR
+body:
+
+| Surface | Before | Where |
+| --- | --- | --- |
+| Reviewer line under a pending or current step | "No reviewers" | `ReviewApprovalFlow.tsx` `NodeReviewers`; comment claims the step "can never be approved" (BYT-9711) |
+| Folded-pending popover row | avatars omitted silently | `PendingPopoverRow`, `candidates.length > 0` guard |
+| Header "Review in progress" popover | "No reviewers" | `PlanStatusAction.tsx` → `ReviewApprovalFlow compact` |
+| "Approved by …" after the SA approves via API | `Approved by bytebase-integration-service` (email local part, no title, no account-type mark) | `FlowNode` subtitle, `ApprovedPopoverRow`, `ChipAvatars`: `getUserByIdentifier` misses, `unknownUser(principal)` fills in |
+| Activity row for the approval comment | `bytebase-integration-service approved issue` | `IssueCommentActivity.tsx` `IssueCommentHeader`, same fallback |
+| Collapsed REVIEW summary | `Last approved by bytebase-integration-service` | `phaseSummary.ts`: local part for every principal, humans included |
+| Legacy issue page (grant issues) | approver hidden: "Approved by" followed by nothing; candidates filtered to humans | `IssueDetailApprovalFlow.tsx` `ApprovalUserText` returns null for non-`USER`; `useApprovalStep` filters `AccountType.USER` |
+
+The authorization side is consistent and needs no change. `canReview` in
+`backend/component/review/workflow.go` resolves roles through `GetUserFormattedRolesMap`, which
+matches `serviceAccounts/{email}` and `workloadIdentities/{email}` members directly. The three QVC
+binding shapes all pass. The approval is recorded as `users/<sa-email>`
+(`common.FormatUserEmail(actor.Email)`), the approval comment's creator is the SA email, the
+webhook actor is the SA's `UserMessage`, and the audit log names the actor
+`serviceAccounts/<sa-email>`.
+
+## Principle
+
+> Who may approve is decided by IAM, not by principal type. The UI explains that decision; it never
+> narrows it. A step with no human holder is still a step someone can act on, and the page must
+> say who.
+
+## Approver truth table
+
+One row per kind of role holder. Cells that change are marked →.
+
+| Principal | Can approve (backend) | Listed as reviewer | Mentioned in approval-requested notification | "Approved by" / activity attribution |
+| --- | --- | --- | --- | --- |
+| End user, direct or via group | yes | yes | yes | title |
+| Service account (workspace), bound at workspace IAM | yes | no → **yes, badge "Service Account"** | no (by design) | local part → **title + badge** |
+| Service account (workspace), bound at project IAM | yes | no → **yes** | no | local part → **title + badge** |
+| Service account (project `[email protected]`), bound at project IAM | yes | no → **yes** | no | local part → **title + badge** |
+| Workload identity, bound at either level | yes (`canReview` matches `workloadIdentities/`) | no → **yes, badge "Workload Identity"** | no | local part → **title + badge** |
+| Deleted service account or workload identity still bound | no (cannot authenticate) | filtered like a deleted user (`State.ACTIVE` check) | no | as recorded |
+
+Self-approval and last-plan-editor rules apply to every row by email: the backend compares
+`issue.CreatorEmail` and `plan.LastPlanEditor` with `actor.Email`, and SA emails cannot collide
+with human emails because `validateEndUserEmail` refuses the `service.bytebase.com` and
+`workload.bytebase.com` suffixes for people.
+
+## Decisions
+
+**D1 · The reviewer list is every principal holding the step's role.** Project IAM plus workspace
+IAM, with `serviceAccounts/` and `workloadIdentities/` names kept where `useApprovalCandidates`
+used to drop them. "No reviewers" then means what it says: no principal holds the role. A listed
+holder can still be barred by the self-approval or last-plan-editor rule, exactly as a person is
+today; the list answers who holds the role, not who may act right now. Groups are expanded as
+today, as people: the Groups page adds only `users/` members. A service account written into a
+group through the API can approve, because the backend matches the stored member string, but it is
+not listed; that case is left alone. Rejected: keep the human filter and reword to "No human
+reviewers". It still hides who can act, which is the question the customer asked.
+
+**D2 · Non-human principals resolve through their own services, never the user service.**
+`BatchGetUsers` and `GetUser` reject SA and WI emails (`validateEndUserEmail`), and one such name
+fails the whole batch. The candidate hook therefore splits IAM names by prefix: `users/` through
+`batchGetOrFetchUsers`, `serviceAccounts/` through `fetchServiceAccount`, `workloadIdentities/`
+through `fetchWorkloadIdentity`. A recorded approver or creator is `users/<email>` whatever its
+type (D5), so there the split is by email suffix, which `usePrincipal.ts` on the issue-detail page
+already does. It becomes the shared `hooks/usePrincipal.ts` and serves "Approved by", the approved
+chip avatars, the activity header and avatar, the header status, and the rejection banner. The plan
+page makes no failing user-service call today only because it never fetches approvers. The plan and
+issue lists do: they prefetch creators through `batchGetOrFetchUsers`, and a page holding one
+SA-created plan gets a 400 for the whole batch, people included. The user store's fetch entry
+points therefore skip non-human emails instead of sending them, which fixes every caller at once.
+Rejected: teach `BatchGetUsers` to return SAs. The split services are deliberate, and the Members
+page already lives with it.
+
+**D3 · The account-type mark is the existing `AccountTypeBadge`.** It derives the type from the
+email suffix, which the server enforces, so a person cannot carry a "Service Account" badge and an
+SA cannot shed it. That holds once the frontend applies the server's rule: `getAccountTypeByEmail`
+accepts any email that ends in the suffix, while `IsServiceAccountEmail` requires the suffix to be
+the whole domain or to follow a project label and a dot, so a person at `[email protected]`
+is a service account to the frontend alone. D2 routes fetches on this classifier, so it is
+tightened to the server's rule. The badge gains a `compact` form with the geometry of the "Current"
+badge (`px-1.5 py-0 text-xs`): it sits after the title and never shrinks, and the title truncates.
+The legacy issue page's sidebar is too narrow for both on one line, so there the badge sits
+beneath the name. The name identifies the principal and the mark only qualifies it, so the mark
+never outweighs the name: it is drawn in the neutral control colors, as the Users and Service
+Accounts pages already draw the account type, and at regular weight in the compact form, because
+the names in the step, the reviewer list and the sidebar are regular weight. Rejected: the accent
+pill the badge had on the Members page. Accent is for primary action and selected state, and in a
+dense review row it read as more important than the name. Rejected: a distinct robot avatar
+glyph. The Members page sets the precedent of initials avatar plus badge, and reviewers scan the
+badge text, not the avatar.
+
+**D4 · A candidate of any type carries the attribution name `users/<email>`.** `issue.creator` and
+`plan.lastPlanEditor` are `users/<email>` for every actor, SAs included. A service account or
+workload identity is therefore listed through the same `User` projection the Members page uses
+(`workloadIdentityToUser`, and a `serviceAccountToUser` twin), so `getApprovalEligibility`'s name
+comparison holds unchanged. Naming the candidate `serviceAccounts/<email>` would show an SA creator
+as eligible to approve its own plan when the backend refuses.
+
+**D5 · The stored approver principal stays `users/<email>`.** Switching `applyReviewAction` to
+`common.FormatPrincipalMember` was inventoried against every consumer: `issue_service_converter.go`
+passes the string through; `utils.FindNextPendingRole`, `FindRejectedRole` and
+`store/issue_approval_status.go` read only status and count; `approvalsEqual` and the staleness
+check in `ReviewIssue` compare whole protos; `store/principal.go` rewrites `users/<old>` →
+`users/<new>` when a user's email changes, which cannot happen to an SA (`UpdateServiceAccount`
+accepts only `title` and `service_key`); webhooks use the actor's `UserMessage`, not the stored
+string. Nothing needs the type in the string, because the email suffix already carries it. The
+codebase has two conventions and this field belongs to the first: attribution fields
+(`issue.creator`, `plan.creator`, `plan.last_plan_editor`, comment creators) are `users/<email>`
+for every actor, while policy members and the audit-log actor carry the typed prefix. A new format
+would need a backfill for every SA approval already stored (QVC's included) and dual-format
+readers forever, for no information gain.
+
+**D6 · Notifications are unchanged.** `getApproversForRole` keeps `END_USER` only and
+`webhook/manager.go` filters mentions to end users; a machine has no IM identity to mention. The
+UI's reviewer list and the notification's mention list are therefore different sets, and the
+comment on `getApproversForRole` says so.
+
+**D7 · The legacy issue page uses the same two hooks.** `IssueDetailApprovalFlow.tsx` still renders
+grant issues (create-database, access, role) and carried its own copy of the candidate pipeline.
+That copy is removed: `useApprovalCandidates` moves beside `approvalEligibility.ts` and both pages
+call it. `ApprovalUserText` adopts the principal hook, so a role-grant request approved by an SA
+no longer reads "Approved by" followed by a blank. It also stops hiding an approver who has since
+been deactivated: a decided step names whoever decided it.
+
+## States of the reviewer line
+
+| Role holders | Line | Popover |
+| --- | --- | --- |
+| Humans only | avatar stack + "N reviewers" (unchanged) | rows: title, email, ineligibility note |
+| Service accounts and workload identities only | avatar stack + "N reviewers" | rows carry the account-type badge |
+| Mixed | humans first, current user first, then by title | same |
+| Nobody | "No reviewers" | none |
+| Policy not loaded | nothing (unchanged) | none |
+| Holder record does not resolve | avatar from the email local part, badge still correct | row shows local part as title |
+
+The last row is rare. `GetServiceAccount` and `GetWorkloadIdentity` need `bb.serviceAccounts.get`
+/ `bb.workloadIdentities.get`, and every predefined workspace role carries both, Workspace Member
+included (`backend/store/predefined_roles.go`). It takes a workspace that replaces Workspace
+Member with a narrower custom role, or a binding that names an account that was never created.
+The badge never depends on the fetch because the suffix is in the name.
+
+## Risks
+
+**R1 · Showing machines as approvers makes an existing capability visible.** Nothing new becomes
+possible: an SA could already approve, and the audit log already records it. What changes is that a
+reviewer reading the page learns that a machine can close the step. That is the governed path
+(IAM binding, reviewed as code) and the shape Bytebase itself recommended when external approval
+was removed. The design does not add a project setting to forbid non-human approvers; a workspace
+that does not want them removes the binding.
+
+**R2 · Self-approval by the integration's own account.** An SA that creates the plan through the
+API and holds the approver role is refused by the backend unless the project allows self-approval,
+exactly as a person is. D4 keeps the UI's eligibility note in step; getting it wrong would only
+mislead, not grant.
+
+**R3 · Spoofing the badge.** Impossible by construction: the suffixes are reserved server-side for
+SA and WI records, and the badge reads the suffix.
+
+**R4 · Fetch noise and permission.** Resolving the recorded `users/<sa-email>` through the user
+store would add a failing request per plan view (D2). Fetching through the SA/WI services is
+permitted for every predefined workspace role. Where a custom role lacks the read permission the
+fetch fails silently and the row shows the local-part title. The SA and WI stores dedupe in-flight
+requests and cache successes, not failures, so such a viewer pays one silent request per holder
+per mount, never a loop; the user store treats a person it cannot resolve the same way. No
+negative cache is added for that case.
+
+**R5 · Stale bindings.** A deleted SA or WI stays in the IAM policy until an administrator removes
+the binding, and it can no longer authenticate. Its record still resolves: deletion is soft, and
+`GetServiceAccount` / `GetWorkloadIdentity` return it with `state: DELETED`. The hook applies the
+`State.ACTIVE` filter that already drops a deleted user, so the line never lists it. The hook does
+not branch on why a fetch failed, which the stores do not expose: a holder whose record does not
+resolve keeps its placeholder and stays listed, as a person does today through `unknownUser`.
+
+**R6 · Approval-flow width.** The "Approved by" subtitle is a fixed-height truncating line; the
+badge is `shrink-0` and the title truncates, so a long SA title never pushes the badge out of
+view. The reviewer popover widens from 240px to 288px so a title keeps room beside the badge;
+the vertical layout below 560px stacks the same row.
+
+**R7 · Existing stored data.** Every SA approval ever recorded is `users/<sa-email>` and renders
+correctly under D5 without migration. Customers on older versions keep seeing the local-part
+fallback until they upgrade; no data changes.
+
+## Scope
+
+| File | Change |
+| --- | --- |
+| `frontend/src/routes/project/useApprovalCandidates.ts` (moved from `plan-detail/components/review/`) | keep SA/WI names; resolve by prefix; list each as a `users/<email>` user; filter resolved records by state; people first |
+| `frontend/src/hooks/usePrincipal.ts` (moved from `issue-detail/components/`) | shared; `principalLabel` names a principal by title, or by its email until a record arrives |
+| `frontend/src/components/AccountTypeBadge.tsx` | `compact` form; neutral colors in place of accent, on every surface that uses it |
+| `frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.tsx` | badge in `CandidateRow`, `FlowNode` subtitle, `ApprovedPopoverRow`; chip avatars through the hook; popover width; the BYT-9711 comment |
+| `frontend/src/components/issue-activity/IssueCommentActivity.tsx` | `CommentCreator` and `ActivityUserIcon` take the principal and resolve it through the hook, badge after the name |
+| `PlanStatusAction.tsx`, `ReviewRejectionBanner.tsx`, `ReviewActivityTimeline.tsx` | whoever rejected or acted, through the hook |
+| `IssueDetailApprovalFlow.tsx`, `IssueDetailCommentList.tsx` | shared candidates hook in place of the local pipeline; approver identity with the badge beneath |
+| `frontend/src/stores/app/user.ts` | `batchGetOrFetchUsers` and `fetchUser` skip non-human emails instead of sending them to the user service |
+| `frontend/src/stores/app/serviceAccount.ts` | `serviceAccountToUser` |
+| `frontend/src/types/v1/user.ts` | `getAccountTypeByEmail` applies the server's domain-boundary rule |
+| `backend/component/review/evaluator.go` | comment on `getApproversForRole`: it returns the people to notify, not everyone who can approve |
+
+Tests:
+
+| File | Covers |
+| --- | --- |
+| `backend/component/review/workflow_test.go` | an SA approves via workspace IAM, via project IAM, and as a project SA; a WI via project IAM; each is recorded as `users/<email>`; an SA bound under `users/` and an SA that created the issue are refused |
+| `useApprovalCandidates.test.tsx` | SA-only role; people before machines; nobody; deleted SA dropped, unresolved SA kept; SA creator held to self-approval; SA bound as `user:` not listed |
+| `ReviewApprovalFlow.test.tsx` | SA-held step shows its reviewer; no holder says "No reviewers"; a step decided by an SA shows title and badge; a person without a record falls back to the email name, unmarked |
+| `IssueCommentActivity.test.tsx` | an SA's approval names it with the badge; a person's does not |
+| `AccountTypeBadge.test.tsx` | nothing for a person; the type named for an SA and a WI; neither form is drawn in accent |
+| `stores/app/user.test.ts` | a batch that contains an SA email still resolves the people in it and sends nothing for the SA; a lone SA is never asked of the user service |
+| `types/v1/user.test.ts` | the classifier against the server's rule, including `[email protected]` |
+| `tests/e2e/plan-detail/plan-detail-review.spec.ts` | in a browser: an SA-held step lists the account with its badge; after the SA approves through the API the step and the activity name it |
+
+## Not in this PR
+
+- Mentioning non-human approvers in IM notifications.
+- Fetching SA/WI records on the Members page so it shows titles instead of the local part.
+- Approver-type restrictions as a project setting.
+- Listing a service account that was added to a group through the API.
+- Showing an SA creator's title in the plan and issue lists; they keep the local-part fallback.
+- Stating the `users/{email}` convention in the `Approver.principal` proto comments: a comment-only
+ proto edit regenerates the API docs and can ride on a change that already touches those files.
diff --git a/frontend/src/components/AccountTypeBadge.test.tsx b/frontend/src/components/AccountTypeBadge.test.tsx
new file mode 100644
index 0000000000..749f884e8d
--- /dev/null
+++ b/frontend/src/components/AccountTypeBadge.test.tsx
@@ -0,0 +1,37 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { AccountTypeBadge } from "./AccountTypeBadge";
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe("AccountTypeBadge", () => {
+ test("marks nothing for a person", () => {
+ const { container } = render(<AccountTypeBadge email="[email protected]" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ test.each([
+ ["[email protected]", "settings.members.service-account"],
+ ["[email protected]", "settings.members.workload-identity"],
+ ])("names the account type of %s", (email, label) => {
+ render(<AccountTypeBadge email={email} />);
+ expect(screen.getByText(label)).toBeInTheDocument();
+ });
+
+ // The name beside it identifies the principal; the mark is secondary
+ // metadata, and accent is reserved for primary action and selected state.
+ test.each([
+ false,
+ true,
+ ])("never draws the mark in the accent role (compact: %s)", (compact) => {
+ render(
+ <AccountTypeBadge compact={compact} email="[email protected]" />
+ );
+ expect(
+ screen.getByText("settings.members.service-account").className
+ ).not.toMatch(/accent/);
+ });
+});
diff --git a/frontend/src/components/AccountTypeBadge.tsx b/frontend/src/components/AccountTypeBadge.tsx
index f5d420be2d..16c3753832 100644
--- a/frontend/src/components/AccountTypeBadge.tsx
+++ b/frontend/src/components/AccountTypeBadge.tsx
@@ -1,17 +1,42 @@
import { useTranslation } from "react-i18next";
import { Badge } from "@/components/ui/badge";
+import { cn } from "@/lib/utils";
import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
-/** Marks a service account or a workload identity; nothing for a person. */
-export function AccountTypeBadge({ email }: { email: string | undefined }) {
+/**
+ * Marks a service account or a workload identity; nothing for a person.
+ * Secondary metadata beside the name that identifies the principal, so it is
+ * never drawn in the accent role. `compact` fits a one-line row beside a name
+ * that truncates.
+ */
+export function AccountTypeBadge({
+ compact = false,
+ email,
+}: {
+ compact?: boolean;
+ email: string | undefined;
+}) {
const type = email ? getAccountTypeByEmail(email) : AccountType.USER;
- return type === AccountType.USER ? null : <AccountTypeLabel type={type} />;
+ return type === AccountType.USER ? null : (
+ <AccountTypeLabel compact={compact} type={type} />
+ );
}
-function AccountTypeLabel({ type }: { type: AccountType }) {
+function AccountTypeLabel({
+ compact,
+ type,
+}: {
+ compact: boolean;
+ type: AccountType;
+}) {
const { t } = useTranslation();
return (
- <Badge variant="secondary" className="text-xs">
+ <Badge
+ className={cn(
+ "text-xs",
+ compact && "shrink-0 whitespace-nowrap px-1.5 py-0 font-normal"
+ )}
+ >
{type === AccountType.SERVICE_ACCOUNT
? t("settings.members.service-account")
: t("settings.members.workload-identity")}
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
index 592491bcc7..b48ace6834 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
@@ -6,6 +6,7 @@ import { describe, expect, test, vi } from "vitest";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";
import { IssueStatus } from "@/types/proto-es/v1/common_pb";
import {
+ IssueComment_Approval_Status,
IssueComment_PlanUpdateSchema,
Issue_Type,
IssueComment_ReviewSubmissionSchema,
@@ -48,20 +49,22 @@ vi.mock("@/utils/iam/permission", async (importOriginal) => ({
}));
vi.mock("@/stores/app", () => ({
- useAppStore: (selector: (state: unknown) => unknown) =>
- selector({
- getUserByIdentifier: (identifier: string) =>
- identifier.includes("alice")
- ? {
- email: "[email protected]",
- title: "Alice",
- }
- : {
- name: "users/[email protected]",
- email: "[email protected]",
- title: "Submitter",
- },
- }),
+ useAppStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+// What usePrincipal resolves: two people and a service account.
+vi.mock("@/hooks/usePrincipal", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/usePrincipal")>()),
+ usePrincipal: (identifier?: string) => {
+ if (!identifier) return undefined;
+ if (identifier.includes("alice")) {
+ return { email: "[email protected]", title: "Alice" };
+ }
+ if (identifier.includes("service.bytebase.com")) {
+ return { email: "[email protected]", title: "Deploy bot" };
+ }
+ return { email: "[email protected]", title: "Submitter" };
+ },
}));
vi.mock("@/components/HumanizeTs", async () => ({
@@ -211,6 +214,52 @@ describe("IssueCommentRow", () => {
).toBeInTheDocument();
});
+ test("names the service account that approved and marks its account type", () => {
+ const comment = create(IssueCommentSchema, {
+ creator: "users/[email protected]",
+ event: {
+ case: "approval",
+ value: { status: IssueComment_Approval_Status.APPROVED },
+ },
+ });
+
+ render(
+ <IssueCommentRow
+ comment={comment}
+ isLast
+ issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
+ linkless
+ />
+ );
+
+ expect(screen.getByText("Deploy bot")).toBeInTheDocument();
+ expect(
+ screen.getByText("settings.members.service-account")
+ ).toBeInTheDocument();
+ });
+
+ test("a person's activity carries no account-type mark", () => {
+ const comment = create(IssueCommentSchema, {
+ creator: "users/[email protected]",
+ event: {
+ case: "approval",
+ value: { status: IssueComment_Approval_Status.APPROVED },
+ },
+ });
+
+ render(
+ <IssueCommentRow
+ comment={comment}
+ isLast
+ issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
+ linkless
+ />
+ );
+
+ expect(screen.getByText("Alice")).toBeInTheDocument();
+ expect(screen.queryByText(/settings\.members\./)).not.toBeInTheDocument();
+ });
+
test("renders Review Submission as a meaningful Issue Detail activity", () => {
expect(getIssueCommentType(reviewSubmission)).toBe(
IssueCommentType.REVIEW_SUBMISSION
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
index 0c5215446e..ae0347e084 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
@@ -9,6 +9,7 @@ import {
buildPlanRolloutRouteFromPlanName,
buildSpecDetailRouteFromPlanName,
} from "@/app/router/routeHelpers";
+import { AccountTypeBadge } from "@/components/AccountTypeBadge";
import { HumanizeTs } from "@/components/HumanizeTs";
import {
type ActivityIconSpec,
@@ -23,7 +24,7 @@ import { UserAvatar } from "@/components/UserAvatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
-import { useUserByIdentifier } from "@/hooks/useAppState";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import {
diffEntryKey,
diffPlanSpecsForEvent,
@@ -35,7 +36,7 @@ import {
getIssueCommentType,
IssueCommentType,
} from "@/stores/app/issueComment";
-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -43,7 +44,6 @@ import {
IssueComment_Approval_Status,
} from "@/types/proto-es/v1/issue_service_pb";
import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
-import type { User } from "@/types/proto-es/v1/user_service_pb";
import { extractPlanUID, getSpecDisplayInfo } from "@/utils";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
import {
@@ -204,11 +204,15 @@ export function ActivityRowShell({
);
}
-export function CommentCreator({ creator }: { creator: User }) {
+// Who acted, by `users/{email}`: a person, a service account, or a workload
+// identity, the last two marked as such.
+export function CommentCreator({ creator }: { creator: string }) {
+ const principal = usePrincipal(creator);
return (
- <span className="font-medium text-main">
- {creator.title || creator.email}
- </span>
+ <>
+ <span className="font-medium text-main">{principalLabel(principal)}</span>
+ <AccountTypeBadge compact email={principal?.email} />
+ </>
);
}
@@ -223,8 +227,6 @@ function IssueCommentHeader({
similarCount,
}: ActivityProps & { similarCount?: number }) {
const { t } = useTranslation();
- const creator =
- useUserByIdentifier(comment.creator) ?? unknownUser(comment.creator);
const createdTs = getTimeForPbTimestampProtoEs(comment.createTime);
const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime);
const isEdited =
@@ -233,7 +235,7 @@ function IssueCommentHeader({
return (
<>
- <CommentCreator creator={creator} />
+ <CommentCreator creator={comment.creator} />
<IssueCommentActionSentence
comment={comment}
issue={issue}
@@ -368,15 +370,15 @@ function IssueCommentActionIcon({ issue, plan, comment }: ActivityProps) {
// The avatar badge of a user-authored activity row.
export function ActivityUserIcon({ principal }: { principal: string }) {
- const user = useUserByIdentifier(principal) ?? unknownUser(principal);
+ const actor = usePrincipal(principal);
return (
<div className="relative pl-0.5">
<div className="flex size-7 items-center justify-center rounded-full bg-background ring-4 ring-background">
<UserAvatar
- colorSeed={user.email}
+ colorSeed={actor?.email}
className="font-medium"
size="sm"
- title={user.title || user.email}
+ title={principalLabel(actor)}
/>
</div>
</div>
diff --git a/frontend/src/routes/project/issue-detail/components/usePrincipal.test.tsx b/frontend/src/hooks/usePrincipal.test.tsx
similarity index 100%
rename from frontend/src/routes/project/issue-detail/components/usePrincipal.test.tsx
rename to frontend/src/hooks/usePrincipal.test.tsx
diff --git a/frontend/src/routes/project/issue-detail/components/usePrincipal.ts b/frontend/src/hooks/usePrincipal.ts
similarity index 90%
rename from frontend/src/routes/project/issue-detail/components/usePrincipal.ts
rename to frontend/src/hooks/usePrincipal.ts
index 425169b831..7a9bd3258a 100644
--- a/frontend/src/routes/project/issue-detail/components/usePrincipal.ts
+++ b/frontend/src/hooks/usePrincipal.ts
@@ -6,11 +6,15 @@ import { extractUserEmail } from "@/stores/modules/v1/common";
import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
import { ensureUserFullName } from "@/utils/v1/user";
-interface Principal {
+export interface Principal {
email: string;
title: string;
}
+/** A principal's title, or its email's local part until a record arrives. */
+export const principalLabel = (principal: Principal | undefined): string =>
+ principal ? principal.title || principal.email.split("@")[0] : "";
+
type AppState = ReturnType<typeof useAppStore.getState>;
// The user service refuses service accounts and workload identities, which
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailApprovalFlow.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailApprovalFlow.tsx
index fe6d2f4b7e..cefb3b1e45 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailApprovalFlow.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailApprovalFlow.tsx
@@ -7,26 +7,23 @@ import {
User,
X,
} from "lucide-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect } from "@/api";
+import { AccountTypeBadge } from "@/components/AccountTypeBadge";
import { FeatureBadge } from "@/components/FeatureBadge";
import { getAvatarColor, getInitials } from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { useCurrentUser } from "@/hooks/useAppState";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import { useProjectByName } from "@/hooks/useProjectByName";
import { displayRoleTitleFromList } from "@/lib/role";
import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
-import { ensureGroupIdentifier } from "@/stores/app/group";
import { projectNamePrefix, userNamePrefix } from "@/stores/modules/v1/common";
-import {
- ApprovalStatus,
- RiskLevel,
- State,
-} from "@/types/proto-es/v1/common_pb";
+import { ApprovalStatus, RiskLevel } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import {
Issue_Approver_Status,
@@ -34,29 +31,15 @@ import {
RetryIssueApprovalRequestSchema,
} from "@/types/proto-es/v1/issue_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import type { User as UserMessage } from "@/types/proto-es/v1/user_service_pb";
-import {
- AccountType,
- getAccountTypeByEmail,
- groupBindingPrefix,
-} from "@/types/v1/user";
import {
- ensureUserFullName,
- isBindingPolicyExpired,
- memberMapToRolesInProjectIAM,
-} from "@/utils";
-import {
- type ApprovalIneligibility,
- getApprovalEligibility,
-} from "../../approvalEligibility";
+ type ApprovalCandidate,
+ useApprovalCandidates,
+} from "../../useApprovalCandidates";
import { useIssueDetailContext } from "../context/IssueDetailContext";
type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";
-type PotentialApprover = {
- ineligibilities: ApprovalIneligibility[];
- user: UserMessage;
-};
+type PotentialApprover = Pick<ApprovalCandidate, "ineligibilities" | "user">;
export function IssueDetailApprovalFlow() {
const { t } = useTranslation();
@@ -246,8 +229,8 @@ function ApprovalStepItem({
<div className="text-sm font-medium text-main">{roleName}</div>
<div className="mt-1 text-sm text-control-light">
{status === "approved" && (
- <div className="flex flex-row items-center gap-1">
- <span className="text-xs">
+ <div className="flex flex-row flex-wrap items-start gap-x-1">
+ <span className="shrink-0 text-xs leading-5">
{t("custom-approval.issue-review.approved-by")}
</span>
{stepApprover?.principal && (
@@ -258,8 +241,8 @@ function ApprovalStepItem({
{status === "rejected" && (
<div className="flex flex-col gap-1">
- <div className="flex flex-row items-center gap-1">
- <span className="text-xs">
+ <div className="flex flex-row flex-wrap items-start gap-x-1">
+ <span className="shrink-0 text-xs leading-5">
{t("custom-approval.issue-review.rejected-by")}
</span>
{stepApprover?.principal && (
@@ -302,52 +285,36 @@ function ApprovalStepItem({
}
function ApprovalUserText({ candidate }: { candidate: string }) {
- const getOrFetchUserByIdentifier = useAppStore(
- (state) => state.getOrFetchUserByIdentifier
+ const principal = usePrincipal(candidate);
+ return (
+ <ApproverIdentity
+ email={principal?.email}
+ name={principalLabel(principal)}
+ />
);
- const [user, setUser] = useState<UserMessage>();
-
- useEffect(() => {
- let canceled = false;
-
- const load = async () => {
- const next = await getOrFetchUserByIdentifier({
- identifier: candidate,
- });
- if (canceled || !next) {
- return;
- }
- if (
- getAccountTypeByEmail(next.email) !== AccountType.USER ||
- next.state !== State.ACTIVE
- ) {
- setUser(undefined);
- return;
- }
- setUser(next);
- };
-
- void load();
-
- return () => {
- canceled = true;
- };
- }, [candidate, getOrFetchUserByIdentifier]);
-
- if (!user) {
- return null;
- }
+}
- const displayName = user.title || user.email.split("@")[0];
+// Avatar and name, with the account-type mark beneath the name: the sidebar is
+// too narrow to hold both on one line.
+function ApproverIdentity({
+ email,
+ name,
+}: {
+ email: string | undefined;
+ name: string;
+}) {
return (
- <span className="inline-flex items-center gap-1">
+ <span className="inline-flex min-w-0 max-w-full items-start gap-1.5">
<span
className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-xs font-medium text-accent-text"
- style={{ backgroundColor: getAvatarColor(displayName) }}
+ style={{ backgroundColor: getAvatarColor(name) }}
>
- {getInitials(displayName)}
+ {getInitials(name)}
+ </span>
+ <span className="flex min-w-0 flex-col items-start">
+ <span className="text-xs leading-5 text-control">{name}</span>
+ <AccountTypeBadge compact email={email} />
</span>
- <span className="text-xs text-control">{displayName}</span>
</span>
);
}
@@ -413,28 +380,23 @@ function ApprovalCandidateRow({
const { t } = useTranslation();
const currentUser = useCurrentUser();
const { user } = candidate;
- const displayName = user.title || user.email.split("@")[0];
const isCurrentUser = currentUser?.name === user.name;
return (
- <div className="inline-flex items-center gap-1.5">
- <span
- className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-xs font-medium text-accent-text"
- style={{ backgroundColor: getAvatarColor(displayName) }}
- >
- {getInitials(displayName)}
- </span>
- <span className="text-xs text-control">{displayName}</span>
+ <div className="inline-flex items-start gap-1.5">
+ <ApproverIdentity email={user.email} name={principalLabel(user)} />
{isCurrentUser && (
<span className="rounded-full bg-success/10 px-1.5 py-0.5 text-xs text-success">
{t("common.you")}
</span>
)}
{showEmail && (
- <span className="text-xs text-control-light">{user.email}</span>
+ <span className="text-xs leading-5 text-control-light">
+ {user.email}
+ </span>
)}
{candidate.ineligibilities.includes("last-plan-editor") && (
- <span className="text-xs text-warning">
+ <span className="text-xs leading-5 text-warning">
{t("plan.review.candidate-last-changed-plan")}
</span>
)}
@@ -523,23 +485,6 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
const currentUser = useCurrentUser();
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
- const batchGetOrFetchUsers = useAppStore(
- (state) => state.batchGetOrFetchUsers
- );
- const batchGetOrFetchGroups = useAppStore(
- (state) => state.batchGetOrFetchGroups
- );
- const groupsByName = useAppStore((state) => state.groupsByName);
- // Resolve groups from the app store cache the prefetch above populates.
- // Depending on `groupsByName` makes candidate computation recompute once
- // the prefetched groups arrive.
- const getGroupByIdentifier = useCallback(
- (identifier: string) => groupsByName[ensureGroupIdentifier(identifier)],
- [groupsByName]
- );
- const [potentialApprovers, setPotentialApprovers] = useState<
- PotentialApprover[]
- >([]);
const [reRequesting, setReRequesting] = useState(false);
const projectName = `${projectNamePrefix}${page.projectId}`;
const currentUserEmail = currentUser?.email ?? "";
@@ -583,122 +528,19 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
);
}, [currentUserEmail, issue.creator, stepApprover?.status]);
- // Subscribe directly to the Zustand project IAM cache so groupNames /
- // candidateEmails recompute the moment loadProjectIamPolicy() resolves.
- const projectIamPolicy = useAppStore(
- (state) => state.projectPoliciesByName[projectName]
- );
-
- const groupNames = useMemo(() => {
- if (!projectIamPolicy) return [];
- const names: string[] = [];
- for (const binding of projectIamPolicy.bindings) {
- if (binding.role !== step || isBindingPolicyExpired(binding)) {
- continue;
- }
- for (const member of binding.members) {
- if (member.startsWith(groupBindingPrefix)) {
- names.push(member);
- }
- }
- }
- return [...new Set(names)].sort();
- }, [projectIamPolicy, step]);
-
- useEffect(() => {
- void batchGetOrFetchGroups(groupNames).catch(() => undefined);
- }, [groupNames, batchGetOrFetchGroups]);
-
- const candidateEmails = useMemo(() => {
- if (!projectIamPolicy) return [];
- const memberMap = memberMapToRolesInProjectIAM(
- projectIamPolicy,
- step,
- getGroupByIdentifier
- );
- const candidates: string[] = [];
- for (const fullname of memberMap.keys()) {
- if (fullname.startsWith(userNamePrefix)) {
- candidates.push(fullname);
- }
- }
- return [...new Set(candidates)].sort();
- }, [projectIamPolicy, step, getGroupByIdentifier]);
-
- const isCurrentUserInCandidates = useMemo(() => {
- return candidateEmails.includes(`${userNamePrefix}${currentUserEmail}`);
- }, [candidateEmails, currentUserEmail]);
-
- const showSelfApprovalTip = useMemo(() => {
- return (
- status === "current" &&
- !project.allowSelfApproval &&
- issue.creator === `${userNamePrefix}${currentUserEmail}` &&
- isCurrentUserInCandidates
+ const { candidates: potentialApprovers, isCurrentUserRoleMember } =
+ useApprovalCandidates(
+ issue,
+ page.projectId,
+ status === "current" ? step : "",
+ page.plan?.lastPlanEditor ?? ""
);
- }, [
- currentUserEmail,
- isCurrentUserInCandidates,
- issue.creator,
- project.allowSelfApproval,
- status,
- ]);
-
- useEffect(() => {
- let canceled = false;
-
- const load = async () => {
- if (status !== "current" || candidateEmails.length === 0) {
- setPotentialApprovers([]);
- return;
- }
-
- const users = await batchGetOrFetchUsers(
- candidateEmails.map(ensureUserFullName)
- );
- if (canceled) {
- return;
- }
- const next = users
- .filter((user) => {
- return (
- user &&
- user.state === State.ACTIVE &&
- getAccountTypeByEmail(user.email) === AccountType.USER
- );
- })
- .sort((left, right) => {
- if (left.email === currentUserEmail) return -1;
- if (right.email === currentUserEmail) return 1;
- return left.title.localeCompare(right.title);
- })
- .map((user) => ({
- ineligibilities: getApprovalEligibility({
- actor: user.name,
- issueCreator: issue.creator,
- lastPlanEditor: page.plan?.lastPlanEditor ?? "",
- project,
- }).ineligibilities,
- user,
- }));
- setPotentialApprovers(next);
- };
-
- void load();
-
- return () => {
- canceled = true;
- };
- }, [
- batchGetOrFetchUsers,
- candidateEmails,
- currentUserEmail,
- issue.creator,
- page.plan?.lastPlanEditor,
- project,
- status,
- ]);
+ const showSelfApprovalTip =
+ status === "current" &&
+ !project.allowSelfApproval &&
+ issue.creator === `${userNamePrefix}${currentUserEmail}` &&
+ isCurrentUserRoleMember;
const handleReRequestReview = async () => {
if (reRequesting) {
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
index 369cd77d9f..ec37cc30ee 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
@@ -15,13 +15,14 @@ import { MarkdownEditor } from "@/components/MarkdownEditor";
import { UserAvatar } from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import { useProjectByName } from "@/hooks/useProjectByName";
import { collectPlanUpdateSpecs } from "@/lib/plan/diffPlanSpecs";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { isThreadReply } from "@/stores/app/issueComment";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import {
type IssueComment,
IssueSchema,
@@ -336,10 +337,7 @@ function IssueDescriptionCommentRow({
const projectName = `${projectNamePrefix}${page.projectId}`;
const project = useProjectByName(projectName);
void projectsByName;
- const creatorUser = useAppStore((state) =>
- state.getUserByIdentifier(page.issue?.creator || "")
- );
- const creator = creatorUser ?? unknownUser(page.issue?.creator || "");
+ const creator = usePrincipal(page.issue?.creator);
const [isEditing, setIsEditing] = useState(false);
const [editContent, setEditContent] = useState(page.issue?.description || "");
const [isSaving, setIsSaving] = useState(false);
@@ -407,7 +405,7 @@ function IssueDescriptionCommentRow({
<UserAvatar
className="h-7 w-7 text-xs font-medium"
size="sm"
- title={creator.title || creator.email}
+ title={principalLabel(creator)}
/>
<div className="absolute -bottom-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-control-bg ring-2 ring-background">
<Plus className="h-4 w-4 text-control" />
@@ -419,7 +417,7 @@ function IssueDescriptionCommentRow({
<div className="bg-control-bg/50 px-3 py-2">
<div className="flex items-center justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">
- <CommentCreator creator={creator} />
+ <CommentCreator creator={page.issue?.creator ?? ""} />
<span className="wrap-break-word min-w-0 text-control">
{t("activity.sentence.created-issue")}
</span>
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
index 720c939b14..7a2e297767 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
@@ -51,7 +51,7 @@ vi.mock("@/hooks/useAppState", () => ({
usePlanFeature: () => true,
}));
-vi.mock("./usePrincipal", () => ({
+vi.mock("@/hooks/usePrincipal", () => ({
usePrincipal: (identifier?: string) =>
identifier ? PRINCIPALS[identifier] : undefined,
}));
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
index 42f9143316..32404f5699 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
@@ -14,6 +14,7 @@ import {
TableRow,
} from "@/components/ui/table";
import { useEnvironmentList, usePlanFeature } from "@/hooks/useAppState";
+import { usePrincipal } from "@/hooks/usePrincipal";
import { directExecutionOf } from "@/lib/project-member/directExecution";
import { displayRoleTitleFromList } from "@/lib/role";
import { useAppStore } from "@/stores/app";
@@ -26,7 +27,6 @@ import {
} from "@/utils/issue/cel";
import { extractDatabaseResourceName } from "@/utils/v1/database";
import { useIssueDetailContext } from "../context/IssueDetailContext";
-import { usePrincipal } from "./usePrincipal";
export function IssueDetailRoleGrantDetails() {
const { t } = useTranslation();
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
index df1b786e3d..0808ca13ec 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
@@ -28,12 +28,12 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { useCurrentUser } from "@/hooks/useAppState";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import { displayRoleTitleFromList } from "@/lib/role";
import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { userNamePrefix } from "@/stores/modules/v1/common";
-import { unknownUser } from "@/types";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { RequestIssueRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
@@ -217,11 +217,7 @@ function ReviewGateRow({
const steps = useMemo(() => deriveSteps(issue), [issue]);
const rejectedStep = steps.find((step) => step.status === "rejected");
const currentStep = steps.find((step) => step.status === "current");
- const rejecter = useAppStore((state) =>
- rejectedStep?.approver
- ? state.getUserByIdentifier(rejectedStep.approver)
- : undefined
- );
+ const rejecter = usePrincipal(rejectedStep?.approver);
const approvedCount = steps.filter(
(step) => step.status === "approved"
).length;
@@ -233,7 +229,7 @@ function ReviewGateRow({
icon = <CircleX className="size-5 shrink-0 text-error" />;
title = t("plan.lifecycle.gate-review-rejected");
subtitle = t("plan.review.approval-flow.rejected-by", {
- user: (rejecter ?? unknownUser(rejectedStep?.approver ?? "")).title,
+ user: principalLabel(rejecter),
});
} else if (issue.approvalStatus === ApprovalStatus.APPROVED) {
icon = <CircleCheck className="size-5 shrink-0 text-success" />;
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
index 24ea7b6f61..40443659bd 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
@@ -7,11 +7,11 @@ import { useMemo } from "react";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";
+import { useApprovalCandidates } from "../../../useApprovalCandidates";
import type { PlanDetailPageState } from "../../shell/hooks/types";
import { getPlanCheckSummary } from "../../utils/phaseSummary";
import { isReleaseBackedPlan } from "../../utils/spec";
import { deriveSteps } from "../review/ReviewApprovalFlow";
-import { useApprovalCandidates } from "../review/useApprovalCandidates";
import {
type PlanLifecycleHeaderState,
resolvePlanLifecycleHeaderState,
diff --git a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
index f1a881ad18..4e6504057e 100644
--- a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
@@ -139,6 +139,15 @@ vi.mock("@/hooks/useAppState", () => ({
useCurrentUser: () => mocks.currentUser,
}));
+// No record has arrived for anyone: a principal is named from its email.
+vi.mock("@/hooks/usePrincipal", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/usePrincipal")>()),
+ usePrincipal: (identifier?: string) =>
+ identifier
+ ? { email: identifier.replace(/^users\//, ""), title: "" }
+ : undefined,
+}));
+
vi.mock("@/hooks/useProjectByName", () => ({
useProjectByName: () => ({
name: "projects/p1",
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
index 8a723a265d..edd56aa04f 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
@@ -94,6 +94,14 @@ vi.mock("@/hooks/useProjectByName", () => ({
useProjectByName: () => undefined,
}));
+vi.mock("@/hooks/usePrincipal", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/usePrincipal")>()),
+ usePrincipal: (identifier?: string) =>
+ identifier
+ ? { email: "[email protected]", title: "Submitter" }
+ : undefined,
+}));
+
vi.mock("@/stores/app", () => ({
useAppStore: Object.assign(
(selector: (state: unknown) => unknown) =>
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
index 90bba00a7a..93c02dd880 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
@@ -37,7 +37,7 @@ import {
isThreadRoot,
} from "@/stores/app/issueComment";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
@@ -309,7 +309,7 @@ function SyntheticHeader({
const { t } = useTranslation();
return (
<>
- <ActorName principal={source.creator} />
+ <CommentCreator creator={source.creator} />
{source.type === "plan-created" ? (
<span className="wrap-break-word min-w-0 text-control-light">
{t("plan.review.activity.created-this-plan")}
@@ -325,11 +325,6 @@ function SyntheticHeader({
);
}
-function ActorName({ principal }: { principal: string }) {
- const user = useAppStore((state) => state.getUserByIdentifier(principal));
- return <CommentCreator creator={user ?? unknownUser(principal)} />;
-}
-
// A comment-backed timeline row: delegates layout/icon/header to the shared
// IssueCommentRow and owns the inline edit affordance (matching the issue page).
function ReviewCommentRow({
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.test.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.test.tsx
index c9637d554a..345de6dc35 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.test.tsx
@@ -1,9 +1,12 @@
import type { ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
-import { describe, expect, test, vi } from "vitest";
+import { afterEach, describe, expect, test, vi } from "vitest";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ type Issue,
+ Issue_Approver_Status,
+} from "@/types/proto-es/v1/issue_service_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -22,27 +25,42 @@ vi.mock("react-i18next", () => ({
? `${key}:${JSON.stringify(params)}`
: key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
+const NO_CANDIDATES = {
+ canCurrentUserApprove: false,
+ candidates: [],
+ isCurrentUserReviewCandidate: false,
+ isCurrentUserRoleMember: false,
+} as ApprovalCandidates;
+
+const mocks: {
+ approvalCandidates: ApprovalCandidates;
+ projectPoliciesByName: Record<string, unknown>;
+ // What usePrincipal resolves, by `users/{email}`.
+ principals: Record<string, { email: string; title: string }>;
+} = {
+ approvalCandidates: NO_CANDIDATES,
+ projectPoliciesByName: {},
+ principals: {},
+};
+
vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
roleList: [],
- getUserByIdentifier: () => undefined,
- projectPoliciesByName: {},
+ projectPoliciesByName: mocks.projectPoliciesByName,
}),
}));
-const mocks: { approvalCandidates: ApprovalCandidates } = {
- approvalCandidates: {
- canCurrentUserApprove: false,
- candidates: [],
- isCurrentUserReviewCandidate: false,
- isCurrentUserRoleMember: false,
- } as ApprovalCandidates,
-};
+vi.mock("@/hooks/usePrincipal", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/hooks/usePrincipal")>()),
+ usePrincipal: (identifier?: string) =>
+ identifier ? mocks.principals[identifier] : undefined,
+}));
-vi.mock("./useApprovalCandidates", () => ({
+vi.mock("../../../useApprovalCandidates", () => ({
useApprovalCandidates: () => mocks.approvalCandidates,
}));
@@ -55,36 +73,26 @@ vi.mock("@/components/UserAvatar", () => ({
getInitials: (name: string) => name.slice(0, 2),
}));
-vi.mock("@/stores/modules/v1/common", () => ({
- projectNamePrefix: "projects/",
-}));
-
-vi.mock("@/types", () => ({
- unknownUser: (principal: string) => ({
- name: principal,
- email: principal,
- title: principal,
- }),
-}));
-
vi.mock("@/lib/role", () => ({
displayRoleTitleFromList: (role: string) => role,
}));
import { ReviewApprovalFlow } from "./ReviewApprovalFlow";
-import type { ApprovalCandidates } from "./useApprovalCandidates";
+import type { ApprovalCandidates } from "../../../useApprovalCandidates";
const makeIssue = ({
approvalStatus = ApprovalStatus.PENDING,
+ approvers = [],
roles = ["roles/PROJECT_OWNER"],
}: {
approvalStatus?: ApprovalStatus;
+ approvers?: { principal: string; status: Issue_Approver_Status }[];
roles?: string[];
} = {}): Issue =>
({
name: "projects/p1/issues/123",
approvalStatus,
- approvers: [],
+ approvers,
approvalTemplate: { flow: { roles }, title: "Test policy" },
riskLevel: 0,
}) as unknown as Issue;
@@ -99,6 +107,12 @@ const renderIntoContainer = (element: ReactElement) => {
};
};
+afterEach(() => {
+ mocks.approvalCandidates = NO_CANDIDATES;
+ mocks.projectPoliciesByName = {};
+ mocks.principals = {};
+});
+
describe("ReviewApprovalFlow", () => {
test("keeps the last plan editor visible with an ineligible reason", () => {
mocks.approvalCandidates = {
@@ -129,12 +143,6 @@ describe("ReviewApprovalFlow", () => {
"plan.review.candidate-last-changed-plan"
);
- mocks.approvalCandidates = {
- canCurrentUserApprove: false,
- candidates: [],
- isCurrentUserReviewCandidate: false,
- isCurrentUserRoleMember: false,
- } as ApprovalCandidates;
unmount();
});
@@ -196,4 +204,106 @@ describe("ReviewApprovalFlow", () => {
unmount();
});
+
+ test("a step whose role only a service account holds lists it as the reviewer", () => {
+ mocks.projectPoliciesByName = { "projects/p1": {} };
+ mocks.approvalCandidates = {
+ ...NO_CANDIDATES,
+ candidates: [
+ {
+ canApprove: true,
+ canReview: true,
+ ineligibilities: [],
+ user: {
+ email: "[email protected]",
+ name: "users/[email protected]",
+ title: "Deploy bot",
+ },
+ },
+ ],
+ } as unknown as ApprovalCandidates;
+ const { container, render, unmount } = renderIntoContainer(
+ <ReviewApprovalFlow issue={makeIssue()} />
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ 'plan.review.approval-flow.n-reviewers:{"count":1}'
+ );
+ expect(container.textContent).not.toContain(
+ "plan.review.approval-flow.no-reviewers"
+ );
+
+ unmount();
+ });
+
+ test("a step nobody holds the role for says so once the policy has loaded", () => {
+ mocks.projectPoliciesByName = { "projects/p1": {} };
+ const { container, render, unmount } = renderIntoContainer(
+ <ReviewApprovalFlow issue={makeIssue()} />
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ "plan.review.approval-flow.no-reviewers"
+ );
+
+ unmount();
+ });
+
+ test.each([
+ [Issue_Approver_Status.APPROVED, "plan.review.approval-flow.approved-by"],
+ [Issue_Approver_Status.REJECTED, "plan.review.approval-flow.rejected-by"],
+ ])("a step decided by a service account names it and marks its account type (%s)", (status, sentence) => {
+ mocks.principals["users/[email protected]"] = {
+ email: "[email protected]",
+ title: "Deploy bot",
+ };
+ const { container, render, unmount } = renderIntoContainer(
+ <ReviewApprovalFlow
+ issue={makeIssue({
+ approvers: [
+ { principal: "users/[email protected]", status },
+ ],
+ })}
+ />
+ );
+
+ render();
+
+ expect(container.textContent).toContain(`${sentence}:{"user":"Deploy bot"}`);
+ expect(container.textContent).toContain("settings.members.service-account");
+
+ unmount();
+ });
+
+ test("a step approved by a person whose record has not arrived falls back to the email name, unmarked", () => {
+ mocks.principals["users/[email protected]"] = {
+ email: "[email protected]",
+ title: "",
+ };
+ const { container, render, unmount } = renderIntoContainer(
+ <ReviewApprovalFlow
+ issue={makeIssue({
+ approvers: [
+ {
+ principal: "users/[email protected]",
+ status: Issue_Approver_Status.APPROVED,
+ },
+ ],
+ })}
+ />
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ 'plan.review.approval-flow.approved-by:{"user":"alex"}'
+ );
+ expect(container.textContent).not.toContain("settings.members.");
+
+ unmount();
+ });
});
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.tsx
index 3e55217944..25dcf65243 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewApprovalFlow.tsx
@@ -1,6 +1,7 @@
import { Check, User, X } from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { AccountTypeBadge } from "@/components/AccountTypeBadge";
import { getAvatarColor, getInitials } from "@/components/UserAvatar";
import { Badge } from "@/components/ui/badge";
import {
@@ -8,24 +9,23 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import { displayRoleTitleFromList } from "@/lib/role";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { unknownUser } from "@/types";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { Issue_Approver_Status } from "@/types/proto-es/v1/issue_service_pb";
-import type { User as UserProto } from "@/types/proto-es/v1/user_service_pb";
+import {
+ type ApprovalCandidate,
+ useApprovalCandidates,
+} from "../../../useApprovalCandidates";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import {
type ApprovalStepStatus,
computeApprovalFlowLayout,
} from "./approvalFlowLayout";
-import {
- type ApprovalCandidate,
- useApprovalCandidates,
-} from "./useApprovalCandidates";
export interface FlowStep {
index: number;
@@ -246,19 +246,17 @@ function FlowNode({
const { t } = useTranslation();
const page = usePlanDetailContext();
const roleList = useAppStore((state) => state.roleList);
- const approverUser = useAppStore((state) =>
- step.approver ? state.getUserByIdentifier(step.approver) : undefined
- );
+ const approver = usePrincipal(step.approver);
const roleName = displayRoleTitleFromList(step.role, roleList);
const subtitle =
step.status === "approved"
? t("plan.review.approval-flow.approved-by", {
- user: (approverUser ?? unknownUser(step.approver ?? "")).title,
+ user: principalLabel(approver),
})
: step.status === "rejected"
? t("plan.review.approval-flow.rejected-by", {
- user: (approverUser ?? unknownUser(step.approver ?? "")).title,
+ user: principalLabel(approver),
})
: undefined;
@@ -294,8 +292,9 @@ function FlowNode({
)}
</div>
{subtitle ? (
- <div className="mt-1 h-4 truncate text-xs leading-4 text-control-light">
- {subtitle}
+ <div className="mt-1 flex h-4 min-w-0 items-center gap-x-1.5 text-xs leading-4 text-control-light">
+ <span className="truncate">{subtitle}</span>
+ <AccountTypeBadge compact email={approver?.email} />
</div>
) : step.status === "current" || step.status === "pending" ? (
<NodeReviewers
@@ -337,9 +336,9 @@ function NodeReviewers({
page.plan?.lastPlanEditor ?? ""
);
if (candidates.length === 0) {
- // No eligible reviewers means this stage can never be approved — surface it
- // explicitly rather than rendering nothing (BYT-9711). Stay silent until the
- // policy resolves so it doesn't flash during load.
+ // No principal of any type holds this step's role — say so rather than
+ // render nothing (BYT-9711). Stay silent until the policy resolves so it
+ // doesn't flash during load.
if (!policyLoaded) return null;
return (
<div className="mt-1 flex h-4 items-center text-xs leading-4 text-control-placeholder">
@@ -372,7 +371,7 @@ function NodeReviewers({
<InitialsAvatar
className="-ml-1 size-5 text-xs ring-2 ring-background first:ml-0"
key={user.name}
- user={user}
+ name={principalLabel(user)}
/>
))}
{overflow > 0 && (
@@ -389,7 +388,7 @@ function NodeReviewers({
</div>
}
/>
- <PopoverContent align="start" className="w-60" side="bottom">
+ <PopoverContent align="start" className="w-72" side="bottom">
<div className="flex max-h-64 flex-col gap-y-2 overflow-y-auto">
{listed.map((candidate) => (
<CandidateRow candidate={candidate} key={candidate.user.name} />
@@ -419,10 +418,16 @@ function CandidateRow({ candidate }: { candidate: ApprovalCandidate }) {
const { user } = candidate;
return (
<div className="flex items-center gap-x-2">
- <InitialsAvatar className="size-6 text-xs" user={user} />
+ <InitialsAvatar
+ className="size-6 shrink-0 text-xs"
+ name={principalLabel(user)}
+ />
<div className="min-w-0">
- <div className="truncate text-sm text-main">
- {user.title || user.email.split("@")[0]}
+ <div className="flex items-center gap-x-1.5">
+ <span className="truncate text-sm text-main">
+ {principalLabel(user)}
+ </span>
+ <AccountTypeBadge compact email={user.email} />
</div>
<div className="truncate text-xs text-control-light">{user.email}</div>
{candidate.ineligibilities.includes("last-plan-editor") && (
@@ -473,10 +478,7 @@ function ApprovedChip({ steps }: { steps: FlowStep[] }) {
function ApprovedPopoverRow({ step }: { step: FlowStep }) {
const { t } = useTranslation();
const roleList = useAppStore((state) => state.roleList);
- const approverUser = useAppStore((state) =>
- step.approver ? state.getUserByIdentifier(step.approver) : undefined
- );
- const approver = approverUser ?? unknownUser(step.approver ?? "");
+ const approver = usePrincipal(step.approver);
const roleName = displayRoleTitleFromList(step.role, roleList);
return (
<div className="flex items-start gap-x-2">
@@ -486,12 +488,16 @@ function ApprovedPopoverRow({ step }: { step: FlowStep }) {
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-main">{roleName}</div>
<div className="mt-0.5 flex items-center gap-x-1 text-xs text-control-light">
- <InitialsAvatar className="size-5 shrink-0 text-xs" user={approver} />
+ <InitialsAvatar
+ className="size-5 shrink-0 text-xs"
+ name={principalLabel(approver)}
+ />
<span className="truncate">
{t("plan.review.approval-flow.approved-by", {
- user: approver.title,
+ user: principalLabel(approver),
})}
</span>
+ <AccountTypeBadge compact email={approver?.email} />
</div>
</div>
</div>
@@ -502,12 +508,11 @@ function ApprovedPopoverRow({ step }: { step: FlowStep }) {
// variant; the common geometry + color derivation lives here.
function InitialsAvatar({
className,
- user,
+ name,
}: {
className: string;
- user: UserProto;
+ name: string;
}) {
- const name = user.title || user.email.split("@")[0];
return (
<span
className={cn(
@@ -522,20 +527,34 @@ function InitialsAvatar({
}
function ChipAvatars({ principals }: { principals: string[] }) {
- const getUserByIdentifier = useAppStore((state) => state.getUserByIdentifier);
return (
<span className="flex items-center">
{principals.slice(0, 3).map((principal, i) => (
- <InitialsAvatar
+ <PrincipalAvatar
className="-ml-1 size-5 text-xs ring-1 ring-background first:ml-0"
key={`${principal}-${i}`}
- user={getUserByIdentifier(principal) ?? unknownUser(principal)}
+ principal={principal}
/>
))}
</span>
);
}
+function PrincipalAvatar({
+ className,
+ principal,
+}: {
+ className: string;
+ principal: string;
+}) {
+ return (
+ <InitialsAvatar
+ className={className}
+ name={principalLabel(usePrincipal(principal))}
+ />
+ );
+}
+
function PendingChip({ issue, steps }: { issue: Issue; steps: FlowStep[] }) {
const { t } = useTranslation();
return (
@@ -594,7 +613,7 @@ function PendingPopoverRow({ issue, step }: { issue: Issue; step: FlowStep }) {
<InitialsAvatar
className="-ml-1 size-5 text-xs ring-2 ring-background first:ml-0"
key={user.name}
- user={user}
+ name={principalLabel(user)}
/>
))}
{overflow > 0 && (
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewRejectionBanner.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewRejectionBanner.tsx
index bf55aaaaa7..6c857f6b9a 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewRejectionBanner.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewRejectionBanner.tsx
@@ -6,14 +6,14 @@ import { HumanizeTs } from "@/components/HumanizeTs";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
+import { principalLabel, usePrincipal } from "@/hooks/usePrincipal";
import { pushNotification } from "@/stores";
-import { useAppStore } from "@/stores/app";
import {
getIssueCommentType,
IssueCommentType,
} from "@/stores/app/issueComment";
import { userNamePrefix } from "@/stores/modules/v1/common";
-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
+import { getTimeForPbTimestampProtoEs } from "@/types";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -48,15 +48,12 @@ export function ReviewRejectionBanner({
const currentUser = useCurrentUser();
const [reRequesting, setReRequesting] = useState(false);
const rejection = useMemo(() => findLastRejection(comments), [comments]);
- const rejectorUser = useAppStore((state) =>
- rejection ? state.getUserByIdentifier(rejection.creator) : undefined
- );
+ const rejector = usePrincipal(rejection?.creator);
if (issue.approvalStatus !== ApprovalStatus.REJECTED || !rejection) {
return null;
}
- const rejector = rejectorUser ?? unknownUser(rejection.creator);
const isCreator =
issue.creator === `${userNamePrefix}${currentUser?.email ?? ""}`;
@@ -89,7 +86,9 @@ export function ReviewRejectionBanner({
title={
<span className="flex items-center gap-x-2 text-error">
<span>
- {t("plan.review.rejection.title", { user: rejector.title })}
+ {t("plan.review.rejection.title", {
+ user: principalLabel(rejector),
+ })}
</span>
{rejection.createTime && (
<>
diff --git a/frontend/src/routes/project/useApprovalCandidates.test.tsx b/frontend/src/routes/project/useApprovalCandidates.test.tsx
new file mode 100644
index 0000000000..7ebf959382
--- /dev/null
+++ b/frontend/src/routes/project/useApprovalCandidates.test.tsx
@@ -0,0 +1,232 @@
+import { create } from "@bufbuild/protobuf";
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ BindingSchema,
+ type IamPolicy,
+ IamPolicySchema,
+} from "@/types/proto-es/v1/iam_policy_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import { type User, UserSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ type AppStoreUtilBridge,
+ registerAppStoreUtilBridge,
+} from "@/utils/app-store-bridge";
+import { useApprovalCandidates } from "./useApprovalCandidates";
+
+const ROLE = "roles/servicenow-approver";
+const PROJECT = "projects/orders";
+const WORKSPACE_SA = "[email protected]";
+const PROJECT_SA = "[email protected]";
+const WORKLOAD_IDENTITY = "[email protected]";
+
+type Account = { name: string; email: string; title: string; state: State };
+
+const store = vi.hoisted(() => ({
+ projectPoliciesByName: {} as Record<string, unknown>,
+ groupsByName: {},
+ batchGetOrFetchGroups: vi.fn(async () => []),
+ batchGetOrFetchUsers: vi.fn(),
+ fetchServiceAccount: vi.fn(),
+ fetchWorkloadIdentity: vi.fn(),
+}));
+const session = vi.hoisted(() => ({
+ currentUserEmail: "",
+ project: { allowSelfApproval: false, allowLastPlanEditorApproval: true },
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) => selector(store),
+}));
+vi.mock("@/hooks/useAppState", () => ({
+ useCurrentUser: () => ({ email: session.currentUserEmail }),
+}));
+vi.mock("@/hooks/useProjectByName", () => ({
+ useProjectByName: () => session.project,
+}));
+
+const person = (email: string, title: string, state = State.ACTIVE): User =>
+ create(UserSchema, { name: `users/${email}`, email, title, state });
+
+const account = (email: string, title: string, state = State.ACTIVE) => ({
+ email,
+ title,
+ state,
+});
+
+const policy = (members: string[]): IamPolicy =>
+ create(IamPolicySchema, {
+ bindings: [create(BindingSchema, { role: ROLE, members })],
+ });
+
+// What each service knows; a name missing here does not resolve.
+let people: Record<string, User>;
+let serviceAccounts: Record<string, Omit<Account, "name">>;
+let workloadIdentities: Record<string, Omit<Account, "name">>;
+let workspaceHolders: string[];
+
+const issue = (creator = "users/[email protected]") =>
+ ({ creator }) as unknown as Issue;
+
+const candidatesOf = async (issueArg = issue(), role = ROLE) => {
+ const { result } = renderHook(() =>
+ useApprovalCandidates(issueArg, "orders", role, "")
+ );
+ return result;
+};
+
+beforeEach(() => {
+ people = {};
+ serviceAccounts = {};
+ workloadIdentities = {};
+ workspaceHolders = [];
+ session.currentUserEmail = "";
+ session.project = {
+ allowSelfApproval: false,
+ allowLastPlanEditorApproval: true,
+ };
+ store.projectPoliciesByName = {};
+ store.batchGetOrFetchUsers.mockReset();
+ // As the store answers: a name it cannot resolve comes back as a placeholder
+ // named from its email.
+ store.batchGetOrFetchUsers.mockImplementation(async (names: string[]) =>
+ names.map(
+ (name) =>
+ people[name] ??
+ person(name.slice("users/".length), name.slice(6).split("@")[0])
+ )
+ );
+ store.fetchServiceAccount.mockReset();
+ store.fetchServiceAccount.mockImplementation(
+ async (name: string) => serviceAccounts[name]
+ );
+ store.fetchWorkloadIdentity.mockReset();
+ store.fetchWorkloadIdentity.mockImplementation(
+ async (name: string) => workloadIdentities[name]
+ );
+ registerAppStoreUtilBridge({
+ getGroupByIdentifier: () => undefined,
+ workspaceRoleMapToUsers: () => new Map([[ROLE, new Set(workspaceHolders)]]),
+ } as unknown as AppStoreUtilBridge);
+});
+
+describe("useApprovalCandidates", () => {
+ test("a role held only by service accounts and a workload identity lists each of them", async () => {
+ workspaceHolders = [`serviceAccounts/${WORKSPACE_SA}`];
+ store.projectPoliciesByName[PROJECT] = policy([
+ `serviceAccount:${PROJECT_SA}`,
+ `workloadIdentity:${WORKLOAD_IDENTITY}`,
+ ]);
+ serviceAccounts[`serviceAccounts/${WORKSPACE_SA}`] = account(
+ WORKSPACE_SA,
+ "ServiceNow integration"
+ );
+ serviceAccounts[`serviceAccounts/${PROJECT_SA}`] = account(
+ PROJECT_SA,
+ "testdt"
+ );
+ workloadIdentities[`workloadIdentities/${WORKLOAD_IDENTITY}`] = account(
+ WORKLOAD_IDENTITY,
+ "Deploy pipeline"
+ );
+
+ const result = await candidatesOf();
+
+ await waitFor(() => expect(result.current.candidates).toHaveLength(3));
+ expect(
+ result.current.candidates.map(({ user }) => [user.title, user.email])
+ ).toEqual([
+ ["Deploy pipeline", WORKLOAD_IDENTITY],
+ ["ServiceNow integration", WORKSPACE_SA],
+ ["testdt", PROJECT_SA],
+ ]);
+ expect(store.batchGetOrFetchUsers).not.toHaveBeenCalledWith(
+ expect.arrayContaining([expect.stringContaining("service.bytebase.com")])
+ );
+ });
+
+ test("people come before service accounts, and the signed-in reviewer first", async () => {
+ session.currentUserEmail = "[email protected]";
+ store.projectPoliciesByName[PROJECT] = policy([
+ `serviceAccount:${PROJECT_SA}`,
+ ]);
+ people["users/[email protected]"] = person("[email protected]", "Zoe");
+ people["users/[email protected]"] = person("[email protected]", "Adam");
+ serviceAccounts[`serviceAccounts/${PROJECT_SA}`] = account(PROJECT_SA, "A");
+
+ const result = await candidatesOf();
+
+ await waitFor(() => expect(result.current.candidates).toHaveLength(3));
+ expect(result.current.candidates.map(({ user }) => user.title)).toEqual([
+ "Zoe",
+ "Adam",
+ "A",
+ ]);
+ expect(result.current.isCurrentUserRoleMember).toBe(true);
+ });
+
+ test("nobody holds the role: no candidates", async () => {
+ store.projectPoliciesByName[PROJECT] = policy([]);
+
+ const result = await candidatesOf();
+
+ await waitFor(() =>
+ expect(store.batchGetOrFetchGroups).toHaveBeenCalled()
+ );
+ expect(result.current.candidates).toEqual([]);
+ });
+
+ test("a deleted service account is not a candidate; one whose record does not resolve still is", async () => {
+ store.projectPoliciesByName[PROJECT] = policy([
+ `serviceAccount:${PROJECT_SA}`,
+ `serviceAccount:${WORKSPACE_SA}`,
+ ]);
+ serviceAccounts[`serviceAccounts/${PROJECT_SA}`] = account(
+ PROJECT_SA,
+ "testdt",
+ State.DELETED
+ );
+
+ const result = await candidatesOf();
+
+ await waitFor(() => expect(result.current.candidates).toHaveLength(1));
+ expect(result.current.candidates[0].user).toMatchObject({
+ email: WORKSPACE_SA,
+ title: "integration",
+ });
+ });
+
+ test("a service account that created the issue is held to the self-approval rule", async () => {
+ store.projectPoliciesByName[PROJECT] = policy([
+ `serviceAccount:${WORKSPACE_SA}`,
+ ]);
+ serviceAccounts[`serviceAccounts/${WORKSPACE_SA}`] = account(
+ WORKSPACE_SA,
+ "ServiceNow integration"
+ );
+
+ const result = await candidatesOf(issue(`users/${WORKSPACE_SA}`));
+
+ await waitFor(() => expect(result.current.candidates).toHaveLength(1));
+ expect(result.current.candidates[0]).toMatchObject({
+ canApprove: false,
+ ineligibilities: ["self-approval"],
+ });
+ });
+
+ test("a service account bound under user: holds nothing and is not listed", async () => {
+ store.projectPoliciesByName[PROJECT] = policy([
+ `user:${WORKSPACE_SA}`,
+ ]);
+ people["users/[email protected]"] = person("[email protected]", "Adam");
+
+ const result = await candidatesOf();
+
+ await waitFor(() => expect(result.current.candidates).toHaveLength(1));
+ expect(result.current.candidates[0].user.title).toBe("Adam");
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/review/useApprovalCandidates.ts b/frontend/src/routes/project/useApprovalCandidates.ts
similarity index 61%
rename from frontend/src/routes/project/plan-detail/components/review/useApprovalCandidates.ts
rename to frontend/src/routes/project/useApprovalCandidates.ts
index 13d104449a..9e753b6951 100644
--- a/frontend/src/routes/project/plan-detail/components/review/useApprovalCandidates.ts
+++ b/frontend/src/routes/project/useApprovalCandidates.ts
@@ -3,7 +3,20 @@ import { useCurrentUser } from "@/hooks/useAppState";
import { useProjectByName } from "@/hooks/useProjectByName";
import { useAppStore } from "@/stores/app";
import { ensureGroupIdentifier } from "@/stores/app/group";
-import { projectNamePrefix, userNamePrefix } from "@/stores/modules/v1/common";
+import {
+ extractServiceAccountId,
+ serviceAccountToUser,
+} from "@/stores/app/serviceAccount";
+import {
+ extractWorkloadIdentityId,
+ workloadIdentityToUser,
+} from "@/stores/app/workloadIdentity";
+import {
+ projectNamePrefix,
+ serviceAccountNamePrefix,
+ userNamePrefix,
+ workloadIdentityNamePrefix,
+} from "@/stores/modules/v1/common";
import { State } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import type { User } from "@/types/proto-es/v1/user_service_pb";
@@ -11,6 +24,7 @@ import {
AccountType,
getAccountTypeByEmail,
groupBindingPrefix,
+ unknownUser,
} from "@/types/v1/user";
import {
ensureUserFullName,
@@ -20,7 +34,7 @@ import {
import {
type ApprovalIneligibility,
getApprovalEligibility,
-} from "../../../approvalEligibility";
+} from "./approvalEligibility";
export interface ApprovalCandidate {
canApprove: boolean;
@@ -30,8 +44,9 @@ export interface ApprovalCandidate {
}
export interface ApprovalCandidates {
- // Active human users holding the role. They stay visible even when a project
- // policy means they cannot approve.
+ // Every active principal holding the role: people, service accounts and
+ // workload identities, each as a `users/{email}` User. They stay visible even
+ // when a project policy means they cannot approve.
candidates: ApprovalCandidate[];
// Role membership remains distinct from review and approval eligibility.
canCurrentUserApprove: boolean;
@@ -55,6 +70,10 @@ export function useApprovalCandidates(
const batchGetOrFetchUsers = useAppStore(
(state) => state.batchGetOrFetchUsers
);
+ const fetchServiceAccount = useAppStore((state) => state.fetchServiceAccount);
+ const fetchWorkloadIdentity = useAppStore(
+ (state) => state.fetchWorkloadIdentity
+ );
const batchGetOrFetchGroups = useAppStore(
(state) => state.batchGetOrFetchGroups
);
@@ -86,7 +105,7 @@ export function useApprovalCandidates(
void batchGetOrFetchGroups(names).catch(() => undefined);
}, [groupNamesKey, batchGetOrFetchGroups]);
- const candidateEmailsKey = useMemo(() => {
+ const holderNamesKey = useMemo(() => {
// An empty role would make memberMapToRolesInProjectIAM skip its role
// filter and return every project member — guard so callers that pass a
// placeholder role (e.g. when no step is current) get no candidates.
@@ -96,40 +115,58 @@ export function useApprovalCandidates(
role,
getGroupByIdentifier
);
- const names: string[] = [];
- for (const fullname of memberMap.keys()) {
- if (fullname.startsWith(userNamePrefix)) {
- names.push(fullname);
- }
- }
- return JSON.stringify([...new Set(names)].sort());
+ return JSON.stringify([...memberMap.keys()].sort());
}, [projectIamPolicy, role, getGroupByIdentifier]);
useEffect(() => {
let canceled = false;
const load = async () => {
- const emails = candidateEmailsKey
- ? (JSON.parse(candidateEmailsKey) as string[])
+ const names = holderNamesKey
+ ? (JSON.parse(holderNamesKey) as string[])
: [];
- if (emails.length === 0) {
- setUsers([]);
- return;
- }
- const nextUsers = await batchGetOrFetchUsers(
- emails.map(ensureUserFullName)
- );
+ const withPrefix = (prefix: string) =>
+ names.filter((name) => name.startsWith(prefix));
+ // Each kind of principal is served by its own service. A record that
+ // does not resolve keeps a placeholder named from its email.
+ const [people, serviceAccounts, workloadIdentities] = await Promise.all([
+ batchGetOrFetchUsers(withPrefix(userNamePrefix)),
+ Promise.all(
+ withPrefix(serviceAccountNamePrefix).map(async (name) => {
+ const serviceAccount = await fetchServiceAccount(name, true);
+ return serviceAccount
+ ? serviceAccountToUser(serviceAccount)
+ : unknownUser(ensureUserFullName(extractServiceAccountId(name)));
+ })
+ ),
+ Promise.all(
+ withPrefix(workloadIdentityNamePrefix).map(async (name) => {
+ const workloadIdentity = await fetchWorkloadIdentity(name, true);
+ return workloadIdentity
+ ? workloadIdentityToUser(workloadIdentity)
+ : unknownUser(
+ ensureUserFullName(extractWorkloadIdentityId(name))
+ );
+ })
+ ),
+ ]);
if (canceled) return;
+ const isPerson = (user: User) =>
+ getAccountTypeByEmail(user.email) === AccountType.USER;
setUsers(
- nextUsers
- .filter(
- (user) =>
- user &&
- user.state === State.ACTIVE &&
- getAccountTypeByEmail(user.email) === AccountType.USER
- )
+ [
+ // A machine's email bound as `user:` matches no policy member on the
+ // server, so it holds nothing.
+ ...people.filter(isPerson),
+ ...serviceAccounts,
+ ...workloadIdentities,
+ ]
+ .filter((user) => user.state === State.ACTIVE)
.sort((left, right) => {
if (left.email === currentUserEmail) return -1;
if (right.email === currentUserEmail) return 1;
+ if (isPerson(left) !== isPerson(right)) {
+ return isPerson(left) ? -1 : 1;
+ }
return left.title.localeCompare(right.title);
})
);
@@ -138,7 +175,13 @@ export function useApprovalCandidates(
return () => {
canceled = true;
};
- }, [batchGetOrFetchUsers, candidateEmailsKey, currentUserEmail]);
+ }, [
+ batchGetOrFetchUsers,
+ currentUserEmail,
+ fetchServiceAccount,
+ fetchWorkloadIdentity,
+ holderNamesKey,
+ ]);
const candidates = useMemo(
() =>
diff --git a/frontend/src/stores/app/serviceAccount.ts b/frontend/src/stores/app/serviceAccount.ts
index 46dd4fb3e9..65f8667a75 100644
--- a/frontend/src/stores/app/serviceAccount.ts
+++ b/frontend/src/stores/app/serviceAccount.ts
@@ -13,6 +13,7 @@ import {
UndeleteServiceAccountRequestSchema,
UpdateServiceAccountRequestSchema,
} from "@/types/proto-es/v1/service_account_service_pb";
+import { type User, UserSchema } from "@/types/proto-es/v1/user_service_pb";
import { celString } from "@/utils/v1/celLiteral";
import type {
AccountFilter,
@@ -34,6 +35,17 @@ export const ensureServiceAccountFullName = (identifier: string) => {
return `${serviceAccountNamePrefix}${id}`;
};
+// A service account as a `User`, for display. Named `users/{email}`, as creator
+// and approver fields name every actor.
+export const serviceAccountToUser = (sa: ServiceAccount): User => {
+ return createProto(UserSchema, {
+ name: `users/${sa.email}`,
+ email: sa.email,
+ title: sa.title,
+ state: sa.state,
+ });
+};
+
export const buildAccountListFilter = (params: AccountFilter) => {
const filter = [];
const search = params.query?.trim()?.toLowerCase();
diff --git a/frontend/src/stores/app/user.test.ts b/frontend/src/stores/app/user.test.ts
index 293f3b1523..0106830783 100644
--- a/frontend/src/stores/app/user.test.ts
+++ b/frontend/src/stores/app/user.test.ts
@@ -1,6 +1,16 @@
// @vitest-environment node
-import { describe, expect, test } from "vitest";
-import { buildUserFilter } from "./user";
+import { create } from "@bufbuild/protobuf";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";
+import { buildUserFilter, createUserSlice } from "./user";
+
+const mocks = vi.hoisted(() => ({
+ batchGetUsers: vi.fn(),
+ getUser: vi.fn(),
+}));
+vi.mock("@/api", () => ({
+ userServiceClientConnect: mocks,
+}));
const QUOTED = 'SELECT * FROM "users"';
const ESCAPED = 'SELECT * FROM \\"users\\"';
@@ -12,3 +22,67 @@ describe("buildUserFilter", () => {
expect(filter).toContain(ESCAPED.toLowerCase());
});
});
+
+describe("fetching users", () => {
+ const person = create(UserSchema, {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ title: "Alice",
+ });
+ const serviceAccount = "users/[email protected]";
+ const workloadIdentity = "users/[email protected]";
+
+ const createStore = () => {
+ const state: Record<string, unknown> = {};
+ const set = (updater: unknown) => {
+ Object.assign(
+ state,
+ typeof updater === "function" ? updater(state) : updater
+ );
+ };
+ Object.assign(
+ state,
+ createUserSlice(set as never, (() => state) as never, {} as never)
+ );
+ return state as ReturnType<typeof createUserSlice>;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("a batch that names a service account still resolves the people in it", async () => {
+ mocks.batchGetUsers.mockResolvedValue({ users: [person] });
+ const store = createStore();
+
+ const users = await store.batchGetOrFetchUsers([
+ person.name,
+ serviceAccount,
+ workloadIdentity,
+ ]);
+
+ expect(mocks.batchGetUsers).toHaveBeenCalledTimes(1);
+ expect(mocks.batchGetUsers.mock.calls[0][0].names).toEqual([person.name]);
+ expect(users.map((user) => user.title)).toEqual(["Alice", "deploy", "ci"]);
+ });
+
+ test("a batch of only service accounts sends nothing", async () => {
+ const store = createStore();
+
+ await store.batchGetOrFetchUsers([serviceAccount, workloadIdentity]);
+
+ expect(mocks.batchGetUsers).not.toHaveBeenCalled();
+ expect(mocks.getUser).not.toHaveBeenCalled();
+ });
+
+ test("a single service account is not asked of the user service", async () => {
+ const store = createStore();
+
+ expect(await store.fetchUser(serviceAccount)).toBeUndefined();
+ expect(
+ (await store.getOrFetchUserByIdentifier({ identifier: workloadIdentity }))
+ .email
+ ).toBe("[email protected]");
+ expect(mocks.getUser).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/stores/app/user.ts b/frontend/src/stores/app/user.ts
index 199c651765..eb1f0cc54f 100644
--- a/frontend/src/stores/app/user.ts
+++ b/frontend/src/stores/app/user.ts
@@ -6,7 +6,9 @@ import { silentContextKey } from "@/api/context-key";
import { userNamePrefix } from "@/lib/resourceName";
import { extractUserEmail } from "@/stores/modules/v1/common";
import {
+ AccountType,
allUsersUser,
+ getAccountTypeByEmail,
isValidProjectName,
isValidUserName,
unknownUser,
@@ -30,6 +32,12 @@ import { isMissingOrForbidden } from "./utils";
const UNKNOWN_PROJECT_NAME_LEGACY = "projects/-";
+// The user service refuses a service account's or workload identity's email,
+// and one refused name fails a whole batch. Creators and approvers carry such
+// emails under `users/`.
+const isServedByUserService = (name: string) =>
+ getAccountTypeByEmail(extractUserEmail(name)) === AccountType.USER;
+
export const buildUserFilter = (params: UserFilter) => {
const filter = [];
const search = params.query?.trim()?.toLowerCase();
@@ -82,6 +90,7 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {
const validName = ensureUserFullName(name);
const existing = get().usersByName[validName];
if (existing) return existing;
+ if (!isServedByUserService(validName)) return undefined;
const pending = get().userRequests[validName];
if (pending) return pending;
@@ -120,7 +129,11 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {
name.startsWith(userBindingPrefix))
);
const missing = validNames
- .filter((name) => get().getUserByIdentifier(name) === undefined)
+ .filter(
+ (name) =>
+ isServedByUserService(name) &&
+ get().getUserByIdentifier(name) === undefined
+ )
.map((name) => ensureUserFullName(name));
if (missing.length > 0) {
diff --git a/frontend/src/types/v1/user.test.ts b/frontend/src/types/v1/user.test.ts
new file mode 100644
index 0000000000..3cfc5361c6
--- /dev/null
+++ b/frontend/src/types/v1/user.test.ts
@@ -0,0 +1,22 @@
+// @vitest-environment node
+import { describe, expect, test } from "vitest";
+import { AccountType, getAccountTypeByEmail } from "./user";
+
+// The server's rule (IsServiceAccountEmail / IsWorkloadIdentityEmail): the
+// suffix is the whole domain, or follows a project label and a dot.
+describe("getAccountTypeByEmail", () => {
+ test.each([
+ ["[email protected]", AccountType.SERVICE_ACCOUNT],
+ ["[email protected]", AccountType.SERVICE_ACCOUNT],
+ ["[email protected]", AccountType.WORKLOAD_IDENTITY],
+ ["[email protected]", AccountType.WORKLOAD_IDENTITY],
+ ["[email protected]", AccountType.USER],
+ ["[email protected]", AccountType.USER],
+ ["[email protected]", AccountType.USER],
+ ["[email protected]", AccountType.USER],
+ ["service.bytebase.com", AccountType.USER],
+ ["", AccountType.USER],
+ ])("%s", (email, type) => {
+ expect(getAccountTypeByEmail(email)).toBe(type);
+ });
+});
diff --git a/frontend/src/types/v1/user.ts b/frontend/src/types/v1/user.ts
index a0b67e3ff5..291eed6178 100644
--- a/frontend/src/types/v1/user.ts
+++ b/frontend/src/types/v1/user.ts
@@ -109,11 +109,21 @@ export const getAccountTypeByFullname = (fullname: string): AccountType => {
return AccountType.USER;
};
+// Mirrors the server's IsServiceAccountEmail / IsWorkloadIdentityEmail: the
+// suffix is the whole domain, or follows a project label and a dot.
+const hasAccountDomain = (email: string, suffix: string) => {
+ const parts = email.split("@");
+ return (
+ email.endsWith(`@${suffix}`) ||
+ (parts.length === 2 && parts[1].endsWith(`.${suffix}`))
+ );
+};
+
export const getAccountTypeByEmail = (email: string): AccountType => {
- if (email.endsWith(serviceAccountSuffix)) {
+ if (hasAccountDomain(email, serviceAccountSuffix)) {
return AccountType.SERVICE_ACCOUNT;
}
- if (email.endsWith(workloadIdentitySuffix)) {
+ if (hasAccountDomain(email, workloadIdentitySuffix)) {
return AccountType.WORKLOAD_IDENTITY;
}
return AccountType.USER;
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.ts
index 52871e9325..9bcca8ccfa 100644
--- a/frontend/tests/e2e/framework/api-client.ts
+++ b/frontend/tests/e2e/framework/api-client.ts
@@ -475,8 +475,9 @@ export class BytebaseApiClient {
}
// Service Accounts
+ // `serviceKey` is returned only here; it is the account's login password.
async createServiceAccount(parent: string, serviceAccountId: string, title: string) {
- return this.request<{ name: string; email: string }>("POST",
+ return this.request<{ name: string; email: string; serviceKey: string }>("POST",
`/v1/${parent}/serviceAccounts?serviceAccountId=${serviceAccountId}`,
{ title });
}
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
index 460892aed8..7f8353511d 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
@@ -16,6 +16,8 @@
// - Comment composer: draft survives collapse, post appends + re-collapses (CUJ E)
// - Long-history timeline fold (torn separator + Show all) (CUJ J)
// - Non-candidate sees no Review action but can still comment (permission boundary)
+// - A step whose role only a service account holds lists it as the reviewer,
+// and names it once it approves through the API
// - BYT-9746 guard: "(edited)" marker shows in place after an inline edit
// - Inline comment threads: seeded thread in editor + timeline, gutter
// creation, reply / resolve / reopen, View in Statement (CUJ K)
@@ -48,7 +50,7 @@ import {
type BrowserContext,
} from "@playwright/test";
import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
+import { BytebaseApiClient, type IamPolicy } from "../framework/api-client";
import { signInBrowserAs } from "../framework/sign-in";
import { PlanDetailPage } from "./plan-detail.page";
import { seedReviewPlan, waitForApprovalStatus } from "./plan-helpers";
@@ -425,6 +427,107 @@ test.describe("Permission boundary: non-candidate cannot review but can comment"
});
});
+// An integration approves through the API as a service account that holds a
+// custom role (design doc: docs/design/approval-step-non-human-approvers.md).
+// The step used to read "No reviewers".
+test.describe("A step held only by a service account", () => {
+ test.describe.configure({ mode: "serial" });
+ const suffix = Date.now();
+ const role = `roles/e2e-integration-approver-${suffix}`;
+ const serviceAccountTitle = `E2E Integration ${suffix}`;
+ let serviceAccount: { email: string; serviceKey: string };
+ let originalProjectPolicy: IamPolicy;
+ let planId: string;
+ let issueName: string;
+
+ test.beforeAll(async () => {
+ await env.api.createRole(role.split("/")[1], "E2E Integration Approver", [
+ "bb.projects.get",
+ "bb.issues.get",
+ "bb.plans.get",
+ ]);
+ const { workspace } = await env.api.getActuatorInfo();
+ serviceAccount = await env.api.createServiceAccount(
+ workspace,
+ `e2e-integration-${suffix}`,
+ serviceAccountTitle,
+ );
+ originalProjectPolicy = await env.api.getProjectIamPolicy(env.project);
+ await env.api.appendProjectBinding(env.project, role, [
+ `serviceAccount:${serviceAccount.email}`,
+ ]);
+ await setupApproval({
+ source: "CHANGE_DATABASE",
+ condition: { expression: "true" },
+ template: {
+ flow: { roles: [role] },
+ title: "E2E Integration Approval",
+ description: "One step, held only by a service account",
+ },
+ });
+ const seeded = await seedReviewPlan(env, page, {
+ prefix: "E2E Review SA",
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_sa_${suffix} TEXT;`,
+ });
+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);
+ planId = seeded.planId;
+ issueName = seeded.issueName;
+ await goReview(planId);
+ });
+
+ test.afterAll(async () => {
+ const current = await env.api.getProjectIamPolicy(env.project);
+ await env.api
+ .setProjectIamPolicy(env.project, {
+ ...originalProjectPolicy,
+ etag: current.etag,
+ })
+ .catch(() => {});
+ await env.api.deleteServiceAccount(serviceAccount.email);
+ await env.api.deleteRole(role);
+ });
+
+ test("the step lists the service account as its reviewer, marked as one", async () => {
+ await expect(planPage.reviewBadge("Under review")).toBeVisible({
+ timeout: 15_000,
+ });
+ const reviewers = page.getByText("1 reviewer", { exact: true });
+ await expect(reviewers).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByText("No reviewers")).toHaveCount(0);
+ // The signed-in admin does not hold the role, so there is nothing to review.
+ await expect(planPage.reviewButton).not.toBeVisible();
+
+ await reviewers.hover();
+ await expect(page.getByText(serviceAccountTitle)).toBeVisible();
+ await expect(page.getByText(serviceAccount.email)).toBeVisible();
+ await expect(
+ page.getByText("Service Account", { exact: true }),
+ ).toBeVisible();
+ });
+
+ test("once it approves through the API, the step and the activity name it", async () => {
+ const integration = new BytebaseApiClient({ baseURL: env.baseURL });
+ await integration.login(serviceAccount.email, serviceAccount.serviceKey);
+ await integration.approveIssue(issueName);
+ await waitForApprovalStatus(env.api, issueName, ["APPROVED"]);
+
+ await goReview(planId);
+ await expect(planPage.reviewBadge("Approved")).toBeVisible({
+ timeout: 15_000,
+ });
+ await expect(
+ page.getByText(`Approved by ${serviceAccountTitle}`),
+ ).toBeVisible({ timeout: 15_000 });
+ // One mark beside the step, one beside the approval in the activity.
+ await expect(
+ page.getByText("Service Account", { exact: true }),
+ ).toHaveCount(2);
+ await expect(
+ page.getByText(serviceAccountTitle, { exact: true }),
+ ).toBeVisible();
+ });
+});
+
// Inline comment threads (design doc: Plan Review Comment and Thread UI/UX).
// A thread anchors to whole lines of the spec's saved sheet; it renders as a
// gutter marker + expanded card in the statement editor and as a card with