Skip to content

Modern Docker Management, Designed for Everyone

feat: use DHI images for base docker image (#2499)

wrycub73eb4c5877a
diff --git a/.github/workflows/hadolint.yml b/.github/workflows/hadolint.yml
index e95053f0f..cf12349b3 100644
--- a/.github/workflows/hadolint.yml
+++ b/.github/workflows/hadolint.yml
@@ -10,12 +10,12 @@ name: Hadolint
on:
push:
- branches: [ "main" ]
+ branches: ["main"]
pull_request:
# The branches below must be a subset of the branches above
- branches: [ "main" ]
+ branches: ["main"]
schedule:
- - cron: '24 19 * * 2'
+ - cron: "24 19 * * 2"
permissions:
contents: read
@@ -28,6 +28,16 @@ jobs:
contents: read # for actions/checkout to fetch code
security-events: write # for github/codeql-action/upload-sarif to upload SARIF results
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: manager
+ dockerfile: ./docker/Dockerfile
+ output: hadolint-results-manager.sarif
+ - name: agent
+ dockerfile: ./docker/Dockerfile-agent
+ output: hadolint-results-agent.sarif
steps:
- name: Checkout code
uses: actions/checkout@v6
@@ -35,13 +45,14 @@ jobs:
- name: Run hadolint
uses: hadolint/hadolint-action@2332a7b74a6de0dda2e2221d575162eba76ba5e5
with:
- dockerfile: ./docker/Dockerfile
+ dockerfile: ${{ matrix.dockerfile }}
format: sarif
- output-file: hadolint-results.sarif
+ output-file: ${{ matrix.output }}
no-fail: true
- name: Upload analysis results to GitHub
uses: github/codeql-action/[email protected]
with:
- sarif_file: hadolint-results.sarif
+ sarif_file: ${{ matrix.output }}
+ category: hadolint-${{ matrix.name }}
wait-for-processing: true
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 6734c1cb0..8a403ccfd 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -570,11 +570,6 @@ func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs [
}
func (s *ImageService) ListImagesPaginated(ctx context.Context, params pagination.QueryParams) ([]imagetypes.Summary, pagination.Response, error) {
- dockerClient, err := s.dockerService.GetClient(ctx)
- if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)
- }
-
var (
dockerImages []image.Summary
containers []container.Summary
@@ -586,22 +581,22 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
// Fetch Docker images
g.Go(func() error {
var err error
- imageList, err := dockerClient.ImageList(groupCtx, client.ImageListOptions{})
+ imageList, err := s.dockerService.listImagesInternal(groupCtx)
if err != nil {
return fmt.Errorf("failed to list Docker images: %w", err)
}
- dockerImages = imageList.Items
+ dockerImages = imageList
return nil
})
// Fetch containers to determine usage
g.Go(func() error {
var err error
- containerList, err := dockerClient.ContainerList(groupCtx, client.ContainerListOptions{All: true})
+ containerList, err := s.dockerService.listContainersInternal(groupCtx)
if err != nil {
return fmt.Errorf("failed to list containers: %w", err)
}
- containers = containerList.Items
+ containers = containerList
return nil
})
@@ -744,18 +739,13 @@ func convertLabels(labels map[string]string) map[string]any {
}
func (s *ImageService) GetTotalImageSize(ctx context.Context) (int64, error) {
- dockerClient, err := s.dockerService.GetClient(ctx)
- if err != nil {
- return 0, fmt.Errorf("failed to connect to Docker: %w", err)
- }
-
- imageList, err := dockerClient.ImageList(ctx, client.ImageListOptions{})
+ images, err := s.dockerService.listImagesInternal(ctx)
if err != nil {
return 0, fmt.Errorf("failed to list images: %w", err)
}
var total int64
- for _, img := range imageList.Items {
+ for _, img := range images {
total += img.Size
}
diff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.go
index 1fa81b518..d0315dbf7 100644
--- a/backend/pkg/libarcane/startup/runtime_identity.go
+++ b/backend/pkg/libarcane/startup/runtime_identity.go
@@ -17,6 +17,8 @@ const (
defaultDatabaseURL = "file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate"
defaultDockerConfigDir = "/app/data/.docker"
defaultDockerSocketPath = "/var/run/docker.sock"
+ defaultRuntimeUID = 65532
+ defaultRuntimeGID = 65532
mountInfoPath = "/proc/self/mountinfo"
)
@@ -65,8 +67,7 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConf
runtimeUID := req.UID
runtimeGID := req.GID
- // Avoid re-execing forever when the requested runtime identity is already active,
- // including explicit root requests such as PUID=0/PGID=0.
+ // Avoid re-execing forever when the requested runtime identity is already active.
if os.Geteuid() == runtimeUID && os.Getegid() == runtimeGID {
if err := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID); err != nil {
return err
@@ -108,11 +109,11 @@ func loadRuntimeIdentityRequestInternal(cfg *RuntimeIdentityConfig) (runtimeIden
pgid := strings.TrimSpace(cfg.PGID)
if puid == "" && pgid == "" {
- return runtimeIdentityRequest{}, "", nil
+ return defaultRuntimeIdentityRequestInternal(cfg.DockerHost), "", nil
}
if puid == "" || pgid == "" {
- return runtimeIdentityRequest{}, "PUID and PGID must both be set to enable non-root mode; continuing with default runtime user", nil
+ return defaultRuntimeIdentityRequestInternal(cfg.DockerHost), "PUID and PGID must both be set to override the default non-root runtime user; continuing with the default non-root runtime user", nil
}
uid, credentialUID, err := parseRuntimeIdentityValueInternal(puid, "PUID")
@@ -135,6 +136,17 @@ func loadRuntimeIdentityRequestInternal(cfg *RuntimeIdentityConfig) (runtimeIden
}, "", nil
}
+func defaultRuntimeIdentityRequestInternal(dockerHost string) runtimeIdentityRequest {
+ return runtimeIdentityRequest{
+ Enabled: true,
+ UID: defaultRuntimeUID,
+ GID: defaultRuntimeGID,
+ CredentialUID: uint32(defaultRuntimeUID),
+ CredentialGID: uint32(defaultRuntimeGID),
+ DockerHost: dockerHost,
+ }
+}
+
func runtimeDockerConfigDirInternal(cfg *RuntimeIdentityConfig) string {
if cfg == nil {
cfg = &RuntimeIdentityConfig{}
@@ -257,6 +269,9 @@ func prepareWritablePathsWithRootsInternal(uid int, gid int, mountpoints map[str
for _, entry := range entries {
entryPath := filepath.Join(dataDirectory, entry.Name())
if _, mounted := mountpoints[entryPath]; mounted {
+ if err := os.Lchown(entryPath, uid, gid); err != nil {
+ return fmt.Errorf("chown mounted %s: %w", entryPath, err)
+ }
continue
}
if projectsDir != "" && filepath.Clean(entryPath) == projectsDir {
@@ -271,6 +286,9 @@ func prepareWritablePathsWithRootsInternal(uid int, gid int, mountpoints map[str
}
if _, mounted := mountpoints[buildsDirectory]; mounted {
+ if err := os.Lchown(buildsDirectory, uid, gid); err != nil {
+ return fmt.Errorf("chown mounted builds directory: %w", err)
+ }
return nil
}
diff --git a/backend/pkg/libarcane/startup/runtime_identity_test.go b/backend/pkg/libarcane/startup/runtime_identity_test.go
index 8b26d43ca..cf64b7e24 100644
--- a/backend/pkg/libarcane/startup/runtime_identity_test.go
+++ b/backend/pkg/libarcane/startup/runtime_identity_test.go
@@ -11,18 +11,29 @@ import (
)
func TestLoadRuntimeIdentityRequest(t *testing.T) {
- t.Run("disabled when unset", func(t *testing.T) {
- req, warning, err := loadRuntimeIdentityRequestInternal(&RuntimeIdentityConfig{})
+ t.Run("enabled with default non-root runtime when unset", func(t *testing.T) {
+ req, warning, err := loadRuntimeIdentityRequestInternal(&RuntimeIdentityConfig{
+ DockerHost: "unix:///tmp/docker.sock",
+ })
require.NoError(t, err)
require.Empty(t, warning)
- require.False(t, req.Enabled)
+ require.True(t, req.Enabled)
+ require.Equal(t, defaultRuntimeUID, req.UID)
+ require.Equal(t, defaultRuntimeGID, req.GID)
+ require.Equal(t, uint32(defaultRuntimeUID), req.CredentialUID)
+ require.Equal(t, uint32(defaultRuntimeGID), req.CredentialGID)
+ require.Equal(t, "unix:///tmp/docker.sock", req.DockerHost)
})
t.Run("warning when partial config", func(t *testing.T) {
req, warning, err := loadRuntimeIdentityRequestInternal(&RuntimeIdentityConfig{PUID: "1001"})
require.NoError(t, err)
require.Contains(t, warning, "PUID and PGID must both be set")
- require.False(t, req.Enabled)
+ require.True(t, req.Enabled)
+ require.Equal(t, defaultRuntimeUID, req.UID)
+ require.Equal(t, defaultRuntimeGID, req.GID)
+ require.Equal(t, uint32(defaultRuntimeUID), req.CredentialUID)
+ require.Equal(t, uint32(defaultRuntimeGID), req.CredentialGID)
})
t.Run("error when invalid numeric value", func(t *testing.T) {
@@ -75,12 +86,14 @@ func TestRuntimeDockerConfigDir(t *testing.T) {
require.Equal(t, "/custom/docker-config", dir)
})
- t.Run("root default runtime leaves runtime identity disabled", func(t *testing.T) {
+ t.Run("default runtime uses non-root identity", func(t *testing.T) {
req, warning, err := loadRuntimeIdentityRequestInternal(&RuntimeIdentityConfig{})
require.NoError(t, err)
require.Empty(t, warning)
- require.False(t, req.Enabled)
+ require.True(t, req.Enabled)
+ require.Equal(t, defaultRuntimeUID, req.UID)
+ require.Equal(t, defaultRuntimeGID, req.GID)
})
}
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 1cd2b0efa..388dc8fea 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -1,5 +1,6 @@
# syntax=docker/dockerfile:1
ARG BUILD_TAGS=""
+ARG ARCANE_RUNTIME_BASE_IMAGE=ghcr.io/getarcaneapp/base:trixie
# Stage 1: Build Frontend
FROM --platform=$BUILDPLATFORM node:25-trixie-slim AS frontend-builder
@@ -64,16 +65,13 @@ RUN --mount=type=cache,target=/root/.cache/go-build \
-o /build/arcane \
./cmd/main.go
-# Stage 3: Production Image
-FROM debian:trixie-slim AS runner
+# Stage 3: Hardened Production Image
+FROM ${ARCANE_RUNTIME_BASE_IMAGE} AS runner-hardened
+
ARG TARGETARCH
ARG VERSION
ARG REVISION
-RUN apt-get update \
- && apt-get install -y --no-install-recommends ca-certificates curl tzdata tar gzip libdrm2 \
- && apt-get clean && rm -rf /var/lib/apt/lists/*
-
ENV GIN_MODE=release
ENV PORT=3552
ENV ENVIRONMENT=production
@@ -86,7 +84,10 @@ ENV NVIDIA_VISIBLE_DEVICES=all \
WORKDIR /app
-RUN mkdir -p /app/data /builds
+
+USER 0:0
+RUN mkdir -p /app/data /builds \
+ && chown -R 65532:65532 /app /builds
COPY --from=backend-builder /build/arcane .
EXPOSE 3552
VOLUME ["/app/data"]
diff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agent
index 247ef84ab..7e3422b65 100644
--- a/docker/Dockerfile-agent
+++ b/docker/Dockerfile-agent
@@ -1,6 +1,7 @@
# syntax=docker/dockerfile:1
ARG VERSION="dev"
ARG REVISION="unknown"
+ARG ARCANE_RUNTIME_BASE_IMAGE=ghcr.io/getarcaneapp/base:trixie
FROM --platform=$BUILDPLATFORM golang:1.26.4-trixie AS agent-builder
ARG TARGETARCH
@@ -43,14 +44,13 @@ RUN --mount=type=cache,target=/root/.cache/go-build \
-o /out/arcane-agent \
./cmd/main.go
-FROM debian:trixie-slim AS agent
+FROM ${ARCANE_RUNTIME_BASE_IMAGE} AS agent
ARG TARGETARCH
-RUN apt-get update \
- && apt-get install -y --no-install-recommends ca-certificates curl tzdata tar gzip libdrm2 \
- && apt-get clean && rm -rf /var/lib/apt/lists/*
WORKDIR /app
-RUN mkdir -p /app/data
+USER 0:0
+RUN mkdir -p /app/data \
+ && chown -R 65532:65532 /app
COPY --from=agent-builder /out/arcane-agent ./arcane-agent
@@ -74,4 +74,4 @@ VOLUME ["/app/data"]
LABEL com.getarcaneapp.arcane.agent="true"
-CMD ["./arcane-agent"]
\ No newline at end of file
+CMD ["./arcane-agent"]
diff --git a/docker/examples/compose.basic.yaml b/docker/examples/compose.basic.yaml
index 46dc9ab2f..180ffe739 100644
--- a/docker/examples/compose.basic.yaml
+++ b/docker/examples/compose.basic.yaml
@@ -7,11 +7,12 @@ services:
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- arcane-data:/app/data
- - /host/path/to/projects:/app/data/projects
+ - /host/path/to/projects:/host/path/to/projects
- /host/path/to/builds:/builds
environment:
- ENCRYPTION_KEY=replace_me_with_a_random_32_char_value
- JWT_SECRET=replace_me_with_a_random_32_char_value
+ - PROJECTS_DIRECTORY=/host/path/to/projects
# Optional: run Arcane as a specific host UID/GID instead of the default runtime user.
# When using the mounted Docker socket, Arcane will map the socket group automatically.
# - PUID=1000
@@ -25,8 +26,10 @@ services:
healthcheck:
test:
[
- "CMD-SHELL",
- "curl -fsS http://localhost:3552/api/health >/dev/null || exit 1",
+ "CMD",
+ "curl",
+ "-fsS",
+ "http://localhost:3552/api/health",
]
interval: 10s
timeout: 3s
diff --git a/docker/examples/compose.proxy.yaml b/docker/examples/compose.proxy.yaml
index de8c8ff35..f192cd663 100644
--- a/docker/examples/compose.proxy.yaml
+++ b/docker/examples/compose.proxy.yaml
@@ -59,8 +59,10 @@ services:
healthcheck:
test:
[
- "CMD-SHELL",
- "curl -fsS http://localhost:3552/api/health >/dev/null || exit 1",
+ "CMD",
+ "curl",
+ "-fsS",
+ "http://localhost:3552/api/health",
]
interval: 10s
timeout: 3s
diff --git a/tests/setup/compose-postgres.yaml b/tests/setup/compose-postgres.yaml
index a5c7503d1..678a52872 100644
--- a/tests/setup/compose-postgres.yaml
+++ b/tests/setup/compose-postgres.yaml
@@ -15,12 +15,13 @@ services:
arcane:
image: arcane:playwright-tests
- user: root
ports:
- '3001:3552'
environment:
- ENVIRONMENT=testing
- APP_ENV=test
+ - PUID=65532
+ - PGID=65532
- DATABASE_URL=postgres://arcane:arcane_test_password@postgres:5432/arcane_test?sslmode=disable
- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt
- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
diff --git a/tests/setup/compose-proxy.yaml b/tests/setup/compose-proxy.yaml
index dfdcfba1e..ed18bf0ec 100644
--- a/tests/setup/compose-proxy.yaml
+++ b/tests/setup/compose-proxy.yaml
@@ -32,12 +32,13 @@ services:
arcane:
image: arcane:playwright-tests
- user: root
ports:
- '3002:3552'
environment:
- ENVIRONMENT=testing
- APP_ENV=test
+ - PUID=65532
+ - PGID=65532
- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt
- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
- ADMIN_STATIC_API_KEY=${E2E_ADMIN_STATIC_API_KEY:-}
diff --git a/tests/setup/compose.yaml b/tests/setup/compose.yaml
index 53e193c6a..88c94d3bf 100644
--- a/tests/setup/compose.yaml
+++ b/tests/setup/compose.yaml
@@ -1,12 +1,13 @@
services:
arcane:
image: arcane:playwright-tests
- user: root
ports:
- '3000:3552'
environment:
- ENVIRONMENT=testing
- APP_ENV=test
+ - PUID=65532
+ - PGID=65532
- ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt
- JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
- ADMIN_STATIC_API_KEY=${E2E_ADMIN_STATIC_API_KEY:-}
diff --git a/tests/setup/global-setup.ts b/tests/setup/global-setup.ts
index 6cad033e1..a21b8ec21 100644
--- a/tests/setup/global-setup.ts
+++ b/tests/setup/global-setup.ts
@@ -1,4 +1,4 @@
-import { execSync } from 'child_process';
+import { execFileSync, execSync } from 'child_process';
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
@@ -6,6 +6,36 @@ import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+function ensureProjectsDirIsContainerWritable(projectsDir: string) {
+ fs.mkdirSync(projectsDir, { recursive: true });
+
+ try {
+ fs.accessSync(projectsDir, fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
+ fs.chmodSync(projectsDir, 0o777);
+ return;
+ } catch (error) {
+ console.warn(
+ 'Projects directory is not writable by the test runner, fixing permissions:',
+ error
+ );
+ }
+
+ execFileSync(
+ 'docker',
+ [
+ 'run',
+ '--rm',
+ '-v',
+ `${projectsDir}:/projects`,
+ 'alpine',
+ 'sh',
+ '-c',
+ 'chmod -R 777 /projects'
+ ],
+ { stdio: 'inherit' }
+ );
+}
+
async function globalSetup() {
console.log('\nStarting global setup...');
@@ -13,6 +43,12 @@ async function globalSetup() {
? path.resolve(__dirname, '..', process.env.COMPOSE_FILE)
: path.resolve(__dirname, 'compose.yaml');
+ // This directory is bind-mounted into Arcane at /app/data/projects. Create it
+ // before `docker compose up` so Docker does not create it as root, and make it
+ // writable for the hardened non-root runtime user (65532).
+ const projectsDir = path.resolve(__dirname, 'projects');
+ ensureProjectsDirIsContainerWritable(projectsDir);
+
try {
console.log('Building and starting Docker containers...');
execSync(`docker compose -f ${composeFile} up -d --build`, { stdio: 'inherit' });
@@ -46,12 +82,6 @@ async function globalSetup() {
throw new Error(`Server at ${baseURL} did not become ready in time.`);
}
- // 3. Ensure the projects directory exists
- const projectsDir = path.resolve(__dirname, 'projects');
- if (!fs.existsSync(projectsDir)) {
- fs.mkdirSync(projectsDir, { recursive: true });
- }
-
console.log('Global setup complete.\n');
}
diff --git a/tests/setup/project.data.ts b/tests/setup/project.data.ts
index 7a91e4860..c5ec82aa7 100644
--- a/tests/setup/project.data.ts
+++ b/tests/setup/project.data.ts
@@ -6,24 +6,19 @@ export const TEST_COMPOSE_YAML = `configs:
Used for testing purposes.
services:
- redis:
- image: redis:latest
+ nginx:
+ image: ghcr.io/linuxserver/nginx:latest
container_name: \${CONTAINER_NAME}
configs:
- source: some_content
- target: /etc/some_content.txt
- command: /bin/sh -c 'cat /etc/some_content.txt && redis-server'
- ports:
- - "8081:81"
- - "6379:6379"
- - "6378:6378"
+ target: /config/test-content.txt
volumes:
- - redis_data:/data
+ - nginx_data:/config
volumes:
- redis_data:
+ nginx_data:
driver: local
`;
-export const TEST_ENV_FILE = `CONTAINER_NAME=test-redis-container
+export const TEST_ENV_FILE = `CONTAINER_NAME=test-nginx-container
`;
diff --git a/tests/spec/docker-runtime-identity.spec.ts b/tests/spec/docker-runtime-identity.spec.ts
index 7de110915..821465500 100644
--- a/tests/spec/docker-runtime-identity.spec.ts
+++ b/tests/spec/docker-runtime-identity.spec.ts
@@ -31,6 +31,15 @@ function dockerExecAsUser(container: string, user: string, command: string) {
return docker(['exec', '-u', user, container, 'sh', '-lc', command]);
}
+type ProcessStatus = {
+ gid: string;
+ groups: string;
+ name: string;
+ pid: string;
+ ppid: string;
+ uid: string;
+};
+
function dockerStatus(container: string) {
return docker(['inspect', '-f', '{{.State.Status}}', container]);
}
@@ -132,28 +141,44 @@ async function waitForFile(container: string, filePath: string) {
.toBe('present');
}
+function parseStatusBlock(status: string): ProcessStatus {
+ const fields = new Map<string, string>();
+
+ for (const line of status.split('\n')) {
+ const [key, ...valueParts] = line.split(':');
+ if (!key || valueParts.length === 0) continue;
+ fields.set(key, valueParts.join(':').trim());
+ }
+
+ return {
+ gid: fields.get('Gid') ?? '',
+ groups: fields.get('Groups') ?? '',
+ name: fields.get('Name') ?? '',
+ pid: fields.get('Pid') ?? '',
+ ppid: fields.get('PPid') ?? '',
+ uid: fields.get('Uid') ?? ''
+ };
+}
+
function pidOneStatus(container: string) {
- return dockerExec(container, "grep -E '^(Uid|Gid|Groups):' /proc/1/status");
+ return parseStatusBlock(dockerExec(container, 'cat /proc/1/status'));
}
function arcaneProcessStatuses(container: string) {
- return dockerExec(
+ const output = dockerExec(
container,
[
'for f in /proc/[0-9]*/status; do',
- ' name=$(awk \'/^Name:/ {print $2}\' "$f");',
- ' [ "$name" = "arcane" ] || continue;',
- ' pid=$(awk \'/^Pid:/ {print $2}\' "$f");',
- ' ppid=$(awk \'/^PPid:/ {print $2}\' "$f");',
- ' uid=$(awk \'/^Uid:/ {print $2}\' "$f");',
- ' gid=$(awk \'/^Gid:/ {print $2}\' "$f");',
- ' groups=$(awk \'/^Groups:/ {for (i = 2; i <= NF; i++) printf("%s%s", $i, (i < NF ? "," : ""));}\' "$f");',
- ' echo "$pid:$ppid:$uid:$gid:$groups";',
+ ' printf "%s\\n" "---ARCANE-PROCESS-STATUS---";',
+ ' cat "$f";',
'done'
].join(' ')
- )
- .split('\n')
- .filter(Boolean);
+ );
+
+ return output
+ .split('---ARCANE-PROCESS-STATUS---')
+ .map((block) => parseStatusBlock(block))
+ .filter((status) => status.name === 'arcane');
}
function defaultRunArgs(name: string, dataDir: string) {
@@ -178,7 +203,7 @@ function defaultRunArgs(name: string, dataDir: string) {
test.describe.serial('Docker runtime identity', () => {
test.setTimeout(240_000);
- test('keeps default root runtime behavior when PUID and PGID are unset', async () => {
+ test('uses the default non-root runtime when PUID and PGID are unset', async () => {
const containerName = uniqueName('arcane-default');
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-'));
@@ -194,8 +219,19 @@ test.describe.serial('Docker runtime identity', () => {
await waitForFile(containerName, '/app/data/arcane.db');
const status = pidOneStatus(containerName);
- expect(status).toContain('Uid:\t0\t0\t0\t0');
- expect(status).toContain('Gid:\t0\t0\t0\t0');
+ expect(status.uid).toBe('0\t0\t0\t0');
+ expect(status.gid).toBe('0\t0\t0\t0');
+
+ const processStatuses = arcaneProcessStatuses(containerName);
+ expect(
+ processStatuses.some(
+ (status) =>
+ status.pid !== '1' &&
+ status.ppid === '1' &&
+ status.uid.startsWith('65532\t') &&
+ status.gid.startsWith('65532\t')
+ )
+ ).toBe(true);
} finally {
cleanupContainer(containerName);
cleanupDir(dataDir);
@@ -242,8 +278,20 @@ test.describe.serial('Docker runtime identity', () => {
expect(projectsStat).toBe(baselineProjectsStat);
const processStatuses = arcaneProcessStatuses(containerName);
- expect(processStatuses.some((status) => status.startsWith('1:0:0:0:'))).toBe(true);
- expect(processStatuses.some((status) => /^(?!1:)\d+:1:1001:1001:/.test(status))).toBe(true);
+ expect(
+ processStatuses.some(
+ (status) => status.pid === '1' && status.ppid === '0' && status.uid.startsWith('0\t')
+ )
+ ).toBe(true);
+ expect(
+ processStatuses.some(
+ (status) =>
+ status.pid !== '1' &&
+ status.ppid === '1' &&
+ status.uid.startsWith('1001\t') &&
+ status.gid.startsWith('1001\t')
+ )
+ ).toBe(true);
const dockerConfigStat = dockerExecAsUser(
containerName,
@@ -259,6 +307,66 @@ test.describe.serial('Docker runtime identity', () => {
}
});
+ test('default non-root runtime prepares mounted writable roots', async () => {
+ const containerName = uniqueName('arcane-default-nonroot');
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-data-'));
+ const projectsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-projects-'));
+ const buildsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-builds-'));
+
+ try {
+ dockerRunContainer([
+ ...defaultRunArgs(containerName, dataDir),
+ '-v',
+ '/var/run/docker.sock:/var/run/docker.sock',
+ '-v',
+ `${projectsDir}:/app/data/projects`,
+ '-v',
+ `${buildsDir}:/builds`,
+ IMAGE
+ ]);
+
+ await waitForHealth(containerName);
+ await waitForFile(containerName, '/app/data/arcane.db');
+
+ const processStatuses = arcaneProcessStatuses(containerName);
+ expect(
+ processStatuses.some(
+ (status) =>
+ status.pid !== '1' &&
+ status.ppid === '1' &&
+ status.uid.startsWith('65532\t') &&
+ status.gid.startsWith('65532\t')
+ )
+ ).toBe(true);
+
+ const dataStat = dockerExecAsUser(
+ containerName,
+ '65532:65532',
+ "stat -c '%u:%g' /app/data/arcane.db"
+ );
+ expect(dataStat).toBe('65532:65532');
+
+ const projectWrite = dockerExecAsUser(
+ containerName,
+ '65532:65532',
+ "touch /app/data/projects/runtime-write && stat -c '%u:%g' /app/data/projects/runtime-write"
+ );
+ expect(projectWrite).toBe('65532:65532');
+
+ const buildsWrite = dockerExecAsUser(
+ containerName,
+ '65532:65532',
+ "touch /builds/runtime-write && stat -c '%u:%g' /builds/runtime-write"
+ );
+ expect(buildsWrite).toBe('65532:65532');
+ } finally {
+ cleanupContainer(containerName);
+ cleanupDir(dataDir);
+ cleanupDir(projectsDir);
+ cleanupDir(buildsDir);
+ }
+ });
+
test('supports tcp docker host mode without a mounted Unix socket', async () => {
const networkName = uniqueName('arcane-proxy-net');
const proxyName = uniqueName('arcane-proxy');
@@ -323,8 +431,20 @@ test.describe.serial('Docker runtime identity', () => {
expect(dbStat).toBe('1001:1001');
const processStatuses = arcaneProcessStatuses(containerName);
- expect(processStatuses.some((status) => status.startsWith('1:0:0:0:'))).toBe(true);
- expect(processStatuses.some((status) => /^(?!1:)\d+:1:1001:1001:/.test(status))).toBe(true);
+ expect(
+ processStatuses.some(
+ (status) => status.pid === '1' && status.ppid === '0' && status.uid.startsWith('0\t')
+ )
+ ).toBe(true);
+ expect(
+ processStatuses.some(
+ (status) =>
+ status.pid !== '1' &&
+ status.ppid === '1' &&
+ status.uid.startsWith('1001\t') &&
+ status.gid.startsWith('1001\t')
+ )
+ ).toBe(true);
} finally {
cleanupContainer(containerName);
cleanupContainer(proxyName);
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index 5ec567c63..c206664e7 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -1,4 +1,4 @@
-import { test, expect, type Locator, type Page } from '@playwright/test';
+import { test, expect, type Locator, type Page, type Response } from '@playwright/test';
import { fetchProjectCountsWithRetry, fetchProjectsWithRetry } from '../utils/fetch.util';
import { Project, ProjectStatusCounts } from 'types/project.type';
import { TEST_COMPOSE_YAML, TEST_ENV_FILE } from '../setup/project.data';
@@ -25,7 +25,7 @@ async function setCodeMirrorValue(page: Page, editor: Locator, text: string) {
await expect(content).toBeVisible();
await content.click({ position: { x: 10, y: 10 } });
await content.press('ControlOrMeta+A');
- await page.keyboard.type(text, { delay: 0 });
+ await page.keyboard.insertText(text);
}
async function getCodeMirrorValue(editor: Locator) {
@@ -122,8 +122,20 @@ function getProjectIdFromPageUrl(url: string): string {
return url.split('/projects/')[1]?.split(/[?#]/)[0] ?? '';
}
+async function expectProjectCreateResponse(responsePromise: Promise<Response>) {
+ const response = await responsePromise;
+ if (response.ok()) {
+ return response;
+ }
+
+ const body = await response.text().catch(() => '<unreadable response body>');
+ throw new Error(
+ `Create project request failed with ${response.status()} ${response.statusText()}: ${body}`
+ );
+}
+
async function createProjectViaUI(page: Page, projectName: string) {
- const containerName = `test-redis-container-${Date.now()}`;
+ const containerName = `test-nginx-container-${Date.now()}`;
const envFile = TEST_ENV_FILE.replace(/CONTAINER_NAME=.*/m, `CONTAINER_NAME=${containerName}`);
await page.goto(ROUTES.newProject);
@@ -141,12 +153,23 @@ async function createProjectViaUI(page: Page, projectName: string) {
await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);
await setCodeMirrorValue(page, envEditor, envFile);
+ await expect
+ .poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {
+ message: 'Expected compose editor to contain the exact test compose fixture before creation'
+ })
+ .toBe(TEST_COMPOSE_YAML.trimEnd());
const createButton = page
.getByRole('button', { name: 'Create Project' })
.locator('[data-slot="arcane-button"]');
await expect(createButton).toBeEnabled();
+ const createResponsePromise = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ /\/api\/environments\/[^/]+\/projects$/.test(getPathname(response.url()))
+ );
await createButton.click();
+ await expectProjectCreateResponse(createResponsePromise);
await page.waitForURL(/\/projects\/(?!new$).+/, { timeout: 10000 });
await expect(page.getByRole('button', { name: projectName })).toBeVisible();
@@ -544,7 +567,7 @@ test.describe('New Compose Project Page', () => {
test('should create a new project successfully', async ({ page }) => {
const projectName = `test-project-${Date.now()}`;
- const containerName = `test-redis-container-${Date.now()}`;
+ const containerName = `test-nginx-container-${Date.now()}`;
const envFile = TEST_ENV_FILE.replace(/CONTAINER_NAME=.*/m, `CONTAINER_NAME=${containerName}`);
let createdProjectId: string | null = null;
let projectPullRequestCount = 0;
@@ -556,12 +579,17 @@ test.describe('New Compose Project Page', () => {
const composeEditor = page.locator('.cm-editor:visible').first();
await expect(composeEditor).toBeVisible();
await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);
- await expect(composeEditor).toContainText(/redis/i);
+ await expect(composeEditor).toContainText(/nginx/i);
+ await expect
+ .poll(async () => (await getCodeMirrorValue(composeEditor)).trimEnd(), {
+ message: 'Expected compose editor to contain the exact test compose fixture before creation'
+ })
+ .toBe(TEST_COMPOSE_YAML.trimEnd());
const envEditor = page.locator('.cm-editor:visible').nth(1);
await expect(envEditor).toBeVisible();
await setCodeMirrorValue(page, envEditor, envFile);
- await expect(envEditor).toContainText(/redis/i);
+ await expect(envEditor).toContainText(/nginx/i);
await page.route('/api/environments/*/projects', async (route) => {
if (route.request().method() === 'POST') {
@@ -570,7 +598,7 @@ test.describe('New Compose Project Page', () => {
try {
const parsed = JSON.parse(responseBody);
- createdProjectId = parsed.id;
+ createdProjectId = parsed.data?.id ?? parsed.id;
} catch {
// Keep existing createdProjectId value if parsing fails
}
@@ -588,7 +616,13 @@ test.describe('New Compose Project Page', () => {
const createButton = page
.getByRole('button', { name: 'Create Project' })
.locator('[data-slot="arcane-button"]');
+ const createResponsePromise = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ /\/api\/environments\/[^/]+\/projects$/.test(getPathname(response.url()))
+ );
await createButton.click();
+ await expectProjectCreateResponse(createResponsePromise);
await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });
@@ -604,7 +638,7 @@ test.describe('New Compose Project Page', () => {
await page.waitForLoadState('networkidle');
const serviceTable = page.getByRole('table');
- const serviceNameWhenStopped = serviceTable.getByText('redis', {
+ const serviceNameWhenStopped = serviceTable.getByText('nginx', {
exact: true
});
const emptyServicesState = page.getByText(/No services found for this project/i);
@@ -630,7 +664,7 @@ test.describe('New Compose Project Page', () => {
await page.waitForLoadState('networkidle');
expect(projectPullRequestCount).toBe(0);
- await expect(page.getByText('Running', { exact: true })).toBeVisible({
+ await expect(page.getByText('Running', { exact: true }).first()).toBeVisible({
timeout: 20000
});
await expect(page.getByRole('button', { name: 'Down', exact: true })).toBeVisible();
@@ -784,50 +818,19 @@ test.describe('New Compose Project Page', () => {
test('should destroy the project and remove files from disk', async ({ page }) => {
const projectName = `test-destroy-${Date.now()}`;
+ let projectId = '';
- // 1. Create the project first
- await page.getByRole('button', { name: 'My New Project' }).click();
- await page.getByRole('textbox', { name: 'My New Project' }).fill(projectName);
- await page.getByRole('textbox', { name: 'My New Project' }).press('Enter');
-
- const composeEditor = page.locator('.cm-editor:visible').first();
- await expect(composeEditor).toBeVisible();
- await setCodeMirrorValue(page, composeEditor, TEST_COMPOSE_YAML);
-
- const createButton = page
- .locator('button[data-slot="arcane-button"]')
- .filter({ hasText: 'Create Project' });
- await createButton.click();
-
- await page.waitForURL(/\/projects\/.+/, { timeout: 10000 });
- await expect(page.getByRole('button', { name: projectName })).toBeVisible();
-
- // 2. Destroy the project
- const destroyButton = page.getByRole('button', {
- name: 'Destroy',
- exact: true
- });
- await expect(destroyButton).toBeVisible();
- await destroyButton.click();
-
- // 3. Handle the confirmation dialog
- const dialog = page.getByRole('dialog');
- await expect(dialog).toBeVisible();
-
- // Check "Remove project files"
- const removeFilesCheckbox = dialog.getByLabel(/Remove project files/i);
- await removeFilesCheckbox.check();
-
- // Click "Destroy" in the dialog
- const confirmDestroyButton = dialog.getByRole('button', {
- name: 'Destroy',
- exact: true
- });
- await confirmDestroyButton.click();
+ try {
+ projectId = await createProjectViaUI(page, projectName);
+ await destroyCurrentProjectViaUI(page);
+ projectId = '';
- // 4. Verify redirection and project removal
- await page.waitForURL(ROUTES.page, { timeout: 10000 });
- await expect(page.getByRole('link', { name: projectName })).not.toBeVisible();
+ await expect(page.getByRole('link', { name: projectName })).not.toBeVisible();
+ } finally {
+ if (projectId) {
+ await destroyProjectByIdViaAPI(page, projectId);
+ }
+ }
});
});