From 287acab6690ce42caefe4e80383f58d0b2038af8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Tue, 25 Aug 2026 13:58:06 +0100 Subject: [PATCH] fix(auth): hide the Docker build control from non-admins (#3034) Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 5 (1M context) --- .../agent/docker/handlers_auth_test.go | 36 ++++++++++ .../docker-build-card-permissions.test.tsx | 63 +++++++++++++++++ .../profile-edit/docker-sections.test.ts | 25 ++++++- .../settings/profile-edit/docker-sections.tsx | 70 ++++++++++++++----- .../docker-profile-persistence.spec.ts | 37 ++++++++++ apps/web/src/locales/en/executors.json | 1 + apps/web/src/locales/pseudo/executors.json | 1 + apps/web/src/locales/pt-pt/executors.json | 1 + apps/web/src/locales/zh-cn/executors.json | 1 + apps/web/src/locales/zh-hk/executors.json | 1 + apps/web/src/locales/zh-tw/executors.json | 1 + 11 files changed, 220 insertions(+), 17 deletions(-) create mode 100644 apps/web/components/settings/profile-edit/docker-build-card-permissions.test.tsx diff --git a/apps/backend/internal/agent/docker/handlers_auth_test.go b/apps/backend/internal/agent/docker/handlers_auth_test.go index 6a843f1cde..b9e074e617 100644 --- a/apps/backend/internal/agent/docker/handlers_auth_test.go +++ b/apps/backend/internal/agent/docker/handlers_auth_test.go @@ -486,3 +486,39 @@ func TestBuildWithoutAnyIdentityIsRejected(t *testing.T) { t.Fatalf("identity-free build reached Docker: %v", client.builtTags) } } + +// TestUnownedContainerIsDeniedOnStopAndRemove is the other half of the task +// fallback: a container that resolves through neither label must stay denied, +// so the fallback cannot be widened into a fail-open path. +func TestUnownedContainerIsDeniedOnStopAndRemove(t *testing.T) { + client, authorizer, titles := twoUserFixture() + client.containers = append(client.containers, ContainerInfo{ + ID: "ctr-unlabeled", Name: "stray", State: "running", + }) + // A container carrying Kandev's marker label but neither ownership label + // must be denied too, not just a wholly unlabeled one. + client.containers = append(client.containers, ContainerInfo{ + ID: "ctr-marker-only", Name: "marked", State: "running", + Labels: map[string]string{"kandev.managed": "true"}, + }) + router := dockerTestRouter(t, client, titles.provider(), authorizer, member("user-a")) + + for _, containerID := range []string{"ctr-unlabeled", "ctr-marker-only"} { + stop := do(router, http.MethodPost, "/api/v1/docker/containers/"+containerID+"/stop", "") + if stop.Code != http.StatusNotFound { + t.Fatalf("%s stop = %d, want 404; body = %s", containerID, stop.Code, stop.Body.String()) + } + remove := do(router, http.MethodDelete, "/api/v1/docker/containers/"+containerID, "") + if remove.Code != http.StatusNotFound { + t.Fatalf("%s remove = %d, want 404; body = %s", containerID, remove.Code, remove.Body.String()) + } + } + if len(client.stopped) != 0 || len(client.removed) != 0 { + t.Fatalf("unowned container reached Docker: stopped=%v removed=%v", client.stopped, client.removed) + } + + list := do(router, http.MethodGet, "/api/v1/docker/containers", "") + if strings.Contains(list.Body.String(), "ctr-unlabeled") || strings.Contains(list.Body.String(), "ctr-marker-only") { + t.Fatalf("unowned container leaked into listing: %s", list.Body.String()) + } +} diff --git a/apps/web/components/settings/profile-edit/docker-build-card-permissions.test.tsx b/apps/web/components/settings/profile-edit/docker-build-card-permissions.test.tsx new file mode 100644 index 0000000000..bcc05e7273 --- /dev/null +++ b/apps/web/components/settings/profile-edit/docker-build-card-permissions.test.tsx @@ -0,0 +1,63 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { DockerfileBuildCard } from "./docker-sections"; + +const roleMock: { value: string | undefined } = { value: undefined }; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: { auth: { user?: { role?: string } } }) => unknown) => + selector({ + auth: { user: roleMock.value === undefined ? undefined : { role: roleMock.value } }, + }), +})); + +// The Dockerfile editor is a CodeMirror surface with no bearing on the +// permission wiring under test. +vi.mock("./script-editor", () => ({ + ScriptEditor: () =>
, +})); + +const BUILD_BUTTON = /build image/i; +const ADMIN_ONLY_COPY = "Only administrators can build images."; + +function renderCard(role: string | undefined) { + roleMock.value = role; + render( + , + ); +} + +afterEach(() => { + cleanup(); + roleMock.value = undefined; +}); + +// canBuildDockerImage is unit-tested separately; these cover the hop from that +// decision into the rendered control, which a leaf-only test would miss. +describe("DockerfileBuildCard build permissions", () => { + it("disables the build button and explains why for a member", () => { + renderCard("member"); + + expect(screen.getByRole("button", { name: BUILD_BUTTON }).hasAttribute("disabled")).toBe(true); + expect(screen.getByText(ADMIN_ONLY_COPY)).not.toBeNull(); + }); + + it("leaves the build button usable for an admin", () => { + renderCard("admin"); + + expect(screen.getByRole("button", { name: BUILD_BUTTON }).hasAttribute("disabled")).toBe(false); + expect(screen.queryByText(ADMIN_ONLY_COPY)).toBeNull(); + }); + + it("leaves the build button usable when authentication is disabled", () => { + renderCard(undefined); + + expect(screen.getByRole("button", { name: BUILD_BUTTON }).hasAttribute("disabled")).toBe(false); + expect(screen.queryByText(ADMIN_ONLY_COPY)).toBeNull(); + }); +}); diff --git a/apps/web/components/settings/profile-edit/docker-sections.test.ts b/apps/web/components/settings/profile-edit/docker-sections.test.ts index 144d3e2a9c..3fd7fb627f 100644 --- a/apps/web/components/settings/profile-edit/docker-sections.test.ts +++ b/apps/web/components/settings/profile-edit/docker-sections.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { containerTaskLabel } from "./docker-sections"; +import { canBuildDockerImage, containerTaskLabel } from "./docker-sections"; import type { DockerContainer } from "@/lib/api/domains/settings-api"; const taskID = "task-abc123"; @@ -49,3 +49,26 @@ describe("containerTaskLabel", () => { expect(containerTaskLabel(container({ "kandev.task_title": " " }))).toBeNull(); }); }); + +describe("canBuildDockerImage", () => { + // POST /api/v1/docker/build is admin-gated on the backend, so a member must + // not be shown an enabled control that can only end in a 403. + it("denies members", () => { + expect(canBuildDockerImage("member")).toBe(false); + }); + + it("allows admins", () => { + expect(canBuildDockerImage("admin")).toBe(true); + }); + + // An undefined role means authentication is disabled (the synthetic + // single-user admin), which must behave exactly as before. + it("allows the single user when authentication is disabled", () => { + expect(canBuildDockerImage(undefined)).toBe(true); + }); + + it("denies an unrecognized role rather than defaulting open", () => { + expect(canBuildDockerImage("")).toBe(false); + expect(canBuildDockerImage("Admin")).toBe(false); + }); +}); diff --git a/apps/web/components/settings/profile-edit/docker-sections.tsx b/apps/web/components/settings/profile-edit/docker-sections.tsx index b452ec8079..0b44420988 100644 --- a/apps/web/components/settings/profile-edit/docker-sections.tsx +++ b/apps/web/components/settings/profile-edit/docker-sections.tsx @@ -19,6 +19,7 @@ import type { DockerContainer } from "@/lib/api/domains/settings-api"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/settings-card-header"; import { settingsActionClassName } from "@/components/settings/settings-control"; +import { useAppStore } from "@/components/state-provider"; import { useTranslation } from "react-i18next"; const DEFAULT_IMAGE_TAG = "kandev/multi-agent:latest"; @@ -170,6 +171,48 @@ type DockerfileBuildCardProps = { onBuildSuccess?: (result: DockerBuildSuccess) => void; }; +/** Build trigger plus its status badge, or the admin-only explanation. */ +function BuildActionRow({ + canBuild, + buildStatus, + disabled, + onBuild, +}: { + canBuild: boolean; + buildStatus: BuildStatus; + disabled: boolean; + onBuild: () => void; +}) { + const { t } = useTranslation(); + return ( +
+ + {canBuild ? ( + + ) : ( +

{t("executors:buildImageAdminOnly")}

+ )} +
+ ); +} + +/** + * Building an image is a host-level operation with no per-user resource, so the + * backend gates POST /api/v1/docker/build on the admin role. An undefined role + * means authentication is disabled (the synthetic single-user admin), which + * keeps the control enabled exactly as before. + */ +export function canBuildDockerImage(role: string | undefined): boolean { + return role === undefined || role === "admin"; +} + export function DockerfileBuildCard({ dockerfile, onDockerfileChange, @@ -182,13 +225,15 @@ export function DockerfileBuildCard({ const { t } = useTranslation(); const { buildStatus, buildLog, runBuild } = useBuildStream(onBuildSuccess); const logRef = useRef(null); + const role = useAppStore((state) => state.auth.user?.role); + const canBuild = canBuildDockerImage(role); useEffect(() => { if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; }, [buildLog]); const handleBuild = () => { - if (dockerfile.trim() && imageTag.trim()) void runBuild(dockerfile, imageTag); + if (canBuild && dockerfile.trim() && imageTag.trim()) void runBuild(dockerfile, imageTag); }; const canFillDefaults = !dockerfile.trim() || !imageTag.trim(); @@ -245,21 +290,14 @@ export function DockerfileBuildCard({ />
-
- - -
+ {buildLog && (
 {
       await apiClient.deleteExecutor(exec.id).catch(() => {});
     }
   });
+
+  /**
+   * POST /api/v1/docker/build is admin-gated on the backend, so a member must
+   * not be shown an enabled control that can only end in a 403. Auth is
+   * disabled in e2e, which leaves the role undefined and the button enabled,
+   * so the member identity is injected through the store bridge the same way
+   * the message-queue settings spec does.
+   */
+  test("member sees the build control disabled with an explanation", async ({ testPage }) => {
+    await testPage.goto("/settings/executors/new/local_docker");
+    await expect(testPage.locator("#profile-name")).toHaveValue("Docker", { timeout: 10_000 });
+    await testPage.getByRole("button", { name: "Use defaults" }).click();
+
+    const buildButton = testPage.getByRole("button", { name: "Build Image" });
+    await expect(buildButton).toBeEnabled();
+
+    await testPage.waitForFunction(() => Boolean(window.__KANDEV_E2E_STORE__));
+    await testPage.evaluate(() => {
+      const store = window.__KANDEV_E2E_STORE__;
+      if (!store) throw new Error("E2E store bridge is unavailable");
+      store.getState().setAuthState({
+        mode: "enabled",
+        authenticated: true,
+        user: {
+          id: "e2e-member",
+          email: "member@e2e.dev",
+          display_name: "E2E Member",
+          role: "member",
+          status: "active",
+        },
+        ssoProviders: [],
+      });
+    });
+
+    await expect(buildButton).toBeDisabled();
+    await expect(testPage.getByText("Only administrators can build images.")).toBeVisible();
+  });
 });
diff --git a/apps/web/src/locales/en/executors.json b/apps/web/src/locales/en/executors.json
index 01dbb2747b..142ddef5b0 100644
--- a/apps/web/src/locales/en/executors.json
+++ b/apps/web/src/locales/en/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "Build failed: {{message}}",
   "buildFailedWithStatus": "Build failed ({{status}}): {{text}}",
   "buildImage": "Build Image",
+  "buildImageAdminOnly": "Only administrators can build images.",
   "buildThisDockerImageBeforeCreating": "Build this Docker image before creating the profile.",
   "building": "Building...",
   "checking": "Checking...",
diff --git a/apps/web/src/locales/pseudo/executors.json b/apps/web/src/locales/pseudo/executors.json
index 408a5caaeb..4995d89ee0 100644
--- a/apps/web/src/locales/pseudo/executors.json
+++ b/apps/web/src/locales/pseudo/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "Ɓũĩĺď ƒàĩĺēď: {{message}}",
   "buildFailedWithStatus": "Ɓũĩĺď ƒàĩĺēď ({{status}}): {{text}}",
   "buildImage": "Ɓũĩĺď Ĩḿàĝē",
+  "buildImageAdminOnly": "Ōńĺŷ àďḿĩńĩśţŕàţōŕś ćàń ƀũĩĺď ĩḿàĝēś.",
   "buildThisDockerImageBeforeCreating": "Ɓũĩĺď ţĥĩś Ďōćķēŕ ĩḿàĝē ƀēƒōŕē ćŕēàţĩńĝ ţĥē ƥŕōƒĩĺē.",
   "building": "Ɓũĩĺďĩńĝ...",
   "checking": "Ćĥēćķĩńĝ...",
diff --git a/apps/web/src/locales/pt-pt/executors.json b/apps/web/src/locales/pt-pt/executors.json
index 515825d5b7..80568faf97 100644
--- a/apps/web/src/locales/pt-pt/executors.json
+++ b/apps/web/src/locales/pt-pt/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "A compilação falhou: {{message}}",
   "buildFailedWithStatus": "A compilação falhou ({{status}}): {{text}}",
   "buildImage": "Construir imagem",
+  "buildImageAdminOnly": "Apenas os administradores podem construir imagens.",
   "buildThisDockerImageBeforeCreating": "Construa esta imagem Docker antes de criar o perfil.",
   "building": "A construir...",
   "checking": "A verificar...",
diff --git a/apps/web/src/locales/zh-cn/executors.json b/apps/web/src/locales/zh-cn/executors.json
index de47b9a809..27f8ff556c 100644
--- a/apps/web/src/locales/zh-cn/executors.json
+++ b/apps/web/src/locales/zh-cn/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "构建失败:{{message}}",
   "buildFailedWithStatus": "构建失败({{status}}):{{text}}",
   "buildImage": "构建镜像",
+  "buildImageAdminOnly": "只有管理员可以构建镜像。",
   "buildThisDockerImageBeforeCreating": "创建配置前请先构建此 Docker 镜像。",
   "building": "正在构建…",
   "checking": "正在检查…",
diff --git a/apps/web/src/locales/zh-hk/executors.json b/apps/web/src/locales/zh-hk/executors.json
index ddd5480f65..68c579ba3a 100644
--- a/apps/web/src/locales/zh-hk/executors.json
+++ b/apps/web/src/locales/zh-hk/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "構建失敗:{{message}}",
   "buildFailedWithStatus": "構建失敗({{status}}):{{text}}",
   "buildImage": "構建鏡像",
+  "buildImageAdminOnly": "只有管理員可以構建鏡像。",
   "buildThisDockerImageBeforeCreating": "建立設定前請先構建此 Docker 鏡像。",
   "building": "正在構建…",
   "checking": "正在檢查…",
diff --git a/apps/web/src/locales/zh-tw/executors.json b/apps/web/src/locales/zh-tw/executors.json
index 901d0cf1fa..788948e4a2 100644
--- a/apps/web/src/locales/zh-tw/executors.json
+++ b/apps/web/src/locales/zh-tw/executors.json
@@ -17,6 +17,7 @@
   "buildFailedWithMessage": "構建失敗:{{message}}",
   "buildFailedWithStatus": "構建失敗({{status}}):{{text}}",
   "buildImage": "構建映象",
+  "buildImageAdminOnly": "只有管理員可以構建映象。",
   "buildThisDockerImageBeforeCreating": "建立設定前請先構建此 Docker 映象。",
   "building": "正在構建…",
   "checking": "正在檢查…",