fix(auth): hide the Docker build control from non-admins (#3034)

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-08-25 13:58:06 +01:00
committed by GitHub
parent c59f1acb55
commit 287acab669
11 changed files with 220 additions and 17 deletions
@@ -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())
}
}
@@ -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: () => <div data-testid="script-editor" />,
}));
const BUILD_BUTTON = /build image/i;
const ADMIN_ONLY_COPY = "Only administrators can build images.";
function renderCard(role: string | undefined) {
roleMock.value = role;
render(
<DockerfileBuildCard
dockerfile="FROM scratch"
onDockerfileChange={vi.fn()}
imageTag="kandev/multi-agent:latest"
onImageTagChange={vi.fn()}
/>,
);
}
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();
});
});
@@ -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);
});
});
@@ -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 (
<div className="flex items-center gap-3">
<Button onClick={onBuild} disabled={disabled} className="cursor-pointer">
{buildStatus === "building" ? (
<IconLoader2 className="mr-1.5 h-4 w-4 animate-spin" />
) : (
<IconPlayerPlay className="mr-1.5 h-4 w-4" />
)}
{t("executors:buildImage")}
</Button>
{canBuild ? (
<BuildStatusBadge status={buildStatus} />
) : (
<p className="text-sm text-muted-foreground">{t("executors:buildImageAdminOnly")}</p>
)}
</div>
);
}
/**
* 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<HTMLPreElement>(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({
/>
</div>
</div>
<div className="flex items-center gap-3">
<Button
onClick={handleBuild}
disabled={buildStatus === "building" || !dockerfile.trim() || !imageTag.trim()}
className="cursor-pointer"
>
{buildStatus === "building" ? (
<IconLoader2 className="mr-1.5 h-4 w-4 animate-spin" />
) : (
<IconPlayerPlay className="mr-1.5 h-4 w-4" />
)}
{t("executors:buildImage")}
</Button>
<BuildStatusBadge status={buildStatus} />
</div>
<BuildActionRow
canBuild={canBuild}
buildStatus={buildStatus}
disabled={
!canBuild || buildStatus === "building" || !dockerfile.trim() || !imageTag.trim()
}
onBuild={handleBuild}
/>
{buildLog && (
<pre
ref={logRef}
@@ -204,4 +204,41 @@ test.describe("Docker executor profile persistence", () => {
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();
});
});
+1
View File
@@ -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...",
@@ -17,6 +17,7 @@
"buildFailedWithMessage": "Ɓũĩĺď ƒàĩĺēď: {{message}}",
"buildFailedWithStatus": "Ɓũĩĺď ƒàĩĺēď ({{status}}): {{text}}",
"buildImage": "Ɓũĩĺď Ĩḿàĝē",
"buildImageAdminOnly": "Ōńĺŷ àďḿĩńĩśţŕàţōŕś ćàń ƀũĩĺď ĩḿàĝēś.",
"buildThisDockerImageBeforeCreating": "Ɓũĩĺď ţĥĩś Ďōćķēŕ ĩḿàĝē ƀēƒōŕē ćŕēàţĩńĝ ţĥē ƥŕōƒĩĺē.",
"building": "Ɓũĩĺďĩńĝ...",
"checking": "Ćĥēćķĩńĝ...",
@@ -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...",
@@ -17,6 +17,7 @@
"buildFailedWithMessage": "构建失败:{{message}}",
"buildFailedWithStatus": "构建失败({{status}}):{{text}}",
"buildImage": "构建镜像",
"buildImageAdminOnly": "只有管理员可以构建镜像。",
"buildThisDockerImageBeforeCreating": "创建配置前请先构建此 Docker 镜像。",
"building": "正在构建…",
"checking": "正在检查…",
@@ -17,6 +17,7 @@
"buildFailedWithMessage": "構建失敗:{{message}}",
"buildFailedWithStatus": "構建失敗({{status}}):{{text}}",
"buildImage": "構建鏡像",
"buildImageAdminOnly": "只有管理員可以構建鏡像。",
"buildThisDockerImageBeforeCreating": "建立設定前請先構建此 Docker 鏡像。",
"building": "正在構建…",
"checking": "正在檢查…",
@@ -17,6 +17,7 @@
"buildFailedWithMessage": "構建失敗:{{message}}",
"buildFailedWithStatus": "構建失敗({{status}}):{{text}}",
"buildImage": "構建映象",
"buildImageAdminOnly": "只有管理員可以構建映象。",
"buildThisDockerImageBeforeCreating": "建立設定前請先構建此 Docker 映象。",
"building": "正在構建…",
"checking": "正在檢查…",