Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: PUID and PGID runtime identity for file ownership (#2151)
Giulio Savinibff53e013917
diff --git a/.env.example b/.env.exampleindex 53022a6a1..232f56126 100644--- a/.env.example+++ b/.env.example@@ -14,9 +14,12 @@ APP_URL=https://your-domain.com# TLS_CERT_FILE=/path/to/fullchain.pem# TLS_KEY_FILE=/path/to/privkey.pem-# User/Group IDs for file permissions (used by Docker)-PUID=1000-PGID=1000+# Optional runtime UID/GID for published Docker images.+# When both are set, Arcane will run as that UID/GID and files it writes under+# /app/data will be owned by that user inside the container.+# Leave both unset to keep the current default runtime behavior.+# PUID=1000+# PGID=1000# File and Directory Permissions (Octal)# Default: 0644 for files, 0755 for directoriesdiff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 616386c6c..1edab2e06 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -31,6 +31,9 @@ import (func Bootstrap(ctx context.Context) error {_ = godotenv.Load()+ if err := startup.ApplyRequestedRuntimeIdentity(ctx); err != nil {+ return fmt.Errorf("apply runtime identity: %w", err)+ }cfg := config.Load()SetupGinLogger(cfg)diff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.gonew file mode 100644index 000000000..4a58ada6b--- /dev/null+++ b/backend/pkg/libarcane/startup/runtime_identity.go@@ -0,0 +1,316 @@+package startup++import (+ "context"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "strconv"+ "strings"++ pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"+)++const (+ defaultDataDirectory = "/app/data"+ defaultBuildsDirectory = "/builds"+ defaultDatabaseURL = "file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate"+ defaultDockerSocketPath = "/var/run/docker.sock"+ mountInfoPath = "/proc/self/mountinfo"+)++type runtimeIdentityRequest struct {+ Enabled bool+ UID uint32+ GID uint32+}++// ApplyRequestedRuntimeIdentity switches the current process to the configured+// runtime UID/GID before the rest of the app initializes.+func ApplyRequestedRuntimeIdentity(ctx context.Context) error {+ req, warning, err := loadRuntimeIdentityRequestInternal(os.Getenv)+ if warning != "" {+ fmt.Fprintf(os.Stderr, "Runtime identity warning: %s\n", warning)+ }+ if err != nil || !req.Enabled {+ return err+ }++ runtimeUID := int(req.UID)+ runtimeGID := int(req.GID)++ // Avoid re-execing forever when the requested runtime identity is already active,+ // including explicit root requests such as PUID=0/PGID=0.+ if os.Geteuid() == runtimeUID && os.Getegid() == runtimeGID {+ return ensureSQLiteFilesExistInternal(os.Getenv("DATABASE_URL"))+ }++ if os.Geteuid() != 0 {+ fmt.Fprintf(os.Stderr, "Runtime identity warning: process is not root (euid=%d), cannot switch to PUID=%d PGID=%d; continuing as current user\n",+ os.Geteuid(), runtimeUID, runtimeGID)+ return ensureSQLiteFilesExistInternal(os.Getenv("DATABASE_URL"))+ }++ mountpoints, err := loadMountpointsInternal(mountInfoPath)+ if err != nil {+ return fmt.Errorf("load mountpoints: %w", err)+ }++ if err := prepareWritablePathsInternal(req, mountpoints); err != nil {+ return err+ }++ return reexecWithRuntimeIdentityInternal(ctx, req)+}++func loadRuntimeIdentityRequestInternal(getenv func(string) string) (runtimeIdentityRequest, string, error) {+ puid := strings.TrimSpace(getenv("PUID"))+ pgid := strings.TrimSpace(getenv("PGID"))++ if puid == "" && pgid == "" {+ return runtimeIdentityRequest{}, "", nil+ }++ if puid == "" || pgid == "" {+ return runtimeIdentityRequest{}, "PUID and PGID must both be set to enable non-root mode; continuing with default runtime user", nil+ }++ uid, err := parseRuntimeIdentityValueInternal(puid, "PUID")+ if err != nil {+ return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PUID %q: %w", puid, err)+ }++ gid, err := parseRuntimeIdentityValueInternal(pgid, "PGID")+ if err != nil {+ return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PGID %q: %w", pgid, err)+ }++ return runtimeIdentityRequest{+ Enabled: true,+ UID: uid,+ GID: gid,+ }, "", nil+}++func parseRuntimeIdentityValueInternal(raw string, key string) (uint32, error) {+ value, err := strconv.ParseUint(raw, 10, 32)+ if err != nil {+ return 0, fmt.Errorf("parse %s: %w", key, err)+ }++ return uint32(value), nil+}++func runtimeIdentitySupplementaryGroupsInternal(getenv func(string) string, resolveSocketGroup func(string) (uint32, bool)) []uint32 {+ socketPath, ok := dockerSocketPathInternal(getenv("DOCKER_HOST"))+ if !ok {+ return nil+ }++ socketGID, ok := resolveSocketGroup(socketPath)+ if !ok {+ return nil+ }++ return []uint32{socketGID}+}++func dockerSocketPathInternal(raw string) (string, bool) {+ value := strings.TrimSpace(raw)+ if value == "" {+ return defaultDockerSocketPath, true+ }++ parsed, err := url.Parse(value)+ if err != nil || parsed.Scheme != "unix" {+ return "", false+ }++ if parsed.Host != "" || parsed.Path != "" {+ socketPath := parsed.Host + parsed.Path+ if !strings.HasPrefix(socketPath, "/") {+ socketPath = "/" + socketPath+ }+ return filepath.Clean(socketPath), true+ }++ if parsed.Opaque == "" {+ return "", false+ }++ socketPath := strings.TrimPrefix(parsed.Opaque, "//")+ if !strings.HasPrefix(socketPath, "/") {+ socketPath = "/" + socketPath+ }++ return filepath.Clean(socketPath), true+}++func prepareWritablePathsInternal(req runtimeIdentityRequest, mountpoints map[string]struct{}) error {+ uid := int(req.UID)+ gid := int(req.GID)++ if err := os.MkdirAll(defaultDataDirectory, pkgutils.DirPerm); err != nil {+ return fmt.Errorf("create data directory: %w", err)+ }++ if err := os.Chown(defaultDataDirectory, uid, gid); err != nil {+ return fmt.Errorf("chown data directory: %w", err)+ }++ entries, err := os.ReadDir(defaultDataDirectory)+ if err != nil {+ return fmt.Errorf("read data directory: %w", err)+ }++ for _, entry := range entries {+ entryPath := filepath.Join(defaultDataDirectory, entry.Name())+ if _, mounted := mountpoints[entryPath]; mounted {+ continue+ }+ if err := chownRecursiveInternal(entryPath, uid, gid, mountpoints); err != nil {+ return fmt.Errorf("chown %s: %w", entryPath, err)+ }+ }++ if _, mounted := mountpoints[defaultBuildsDirectory]; mounted {+ return nil+ }++ if _, err := os.Stat(defaultBuildsDirectory); err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("stat builds directory: %w", err)+ }++ if err := chownRecursiveInternal(defaultBuildsDirectory, uid, gid, mountpoints); err != nil {+ return fmt.Errorf("chown builds directory: %w", err)+ }++ return nil+}++func ensureSQLiteFilesExistInternal(databaseURL string) error {+ sqlitePath, ok, err := sqliteDatabasePathInternal(databaseURL)+ if err != nil {+ return err+ }+ if !ok {+ return nil+ }++ // Ensure the parent directory exists before creating the file.+ // This covers the "already the right user" early-return path where+ // prepareWritablePathsInternal is not called.+ dir := filepath.Dir(sqlitePath)+ if dir != "" && dir != "." {+ if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil { //nolint:gosec // path is derived from the configured SQLite DSN, not user input+ return fmt.Errorf("create sqlite directory %s: %w", dir, err)+ }+ }++ file, err := os.OpenFile(sqlitePath, os.O_CREATE|os.O_RDWR, pkgutils.FilePerm) //nolint:gosec // path is derived from the configured SQLite DSN+ if err != nil {+ return fmt.Errorf("create sqlite file %s: %w", sqlitePath, err)+ }+ if err := file.Close(); err != nil {+ return fmt.Errorf("close sqlite file %s: %w", sqlitePath, err)+ }++ return nil+}++func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {+ value := strings.TrimSpace(databaseURL)+ if value == "" {+ value = defaultDatabaseURL+ }+ if !strings.HasPrefix(value, "file:") {+ return "", false, nil+ }++ parsed, err := url.Parse(value)+ if err != nil {+ return "", false, fmt.Errorf("parse sqlite database url: %w", err)+ }++ // For relative URLs like "file:data/arcane.db", url.Parse puts the path in+ // Opaque (without a leading slash). For absolute URLs like "file:/app/data/arcane.db",+ // Opaque is empty and Path contains the absolute path. Only strip the leading+ // slash from the opaque portion to preserve absolute paths.+ var pathPart string+ if parsed.Opaque != "" {+ pathPart = strings.TrimPrefix(parsed.Opaque, "/")+ } else {+ pathPart = parsed.Path+ }++ if pathPart == "" || strings.HasPrefix(pathPart, ":memory:") {+ return "", false, nil+ }++ return filepath.Clean(pathPart), true, nil+}++func chownRecursiveInternal(path string, uid int, gid int, mountpoints map[string]struct{}) error {+ return filepath.Walk(path, func(currentPath string, info os.FileInfo, err error) error {+ if err != nil {+ return err+ }+ // Skip any sub-tree that is a separate mountpoint.+ if currentPath != path {+ if _, mounted := mountpoints[filepath.Clean(currentPath)]; mounted {+ return filepath.SkipDir+ }+ }+ //nolint:gosec // currentPath comes from fixed container paths under /app/data or /builds+ return os.Lchown(currentPath, uid, gid)+ })+}++func loadMountpointsInternal(path string) (map[string]struct{}, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return map[string]struct{}{}, nil+ }+ return nil, err+ }+ return parseMountpointsInternal(string(data)), nil+}++func parseMountpointsInternal(data string) map[string]struct{} {+ mountpoints := make(map[string]struct{})++ for line := range strings.SplitSeq(data, "\n") {+ line = strings.TrimSpace(line)+ if line == "" {+ continue+ }++ fields := strings.Fields(line)+ if len(fields) < 5 {+ continue+ }++ mountpoint := filepath.Clean(unescapeMountInfoPathInternal(fields[4]))+ mountpoints[mountpoint] = struct{}{}+ }++ return mountpoints+}++// unescapeMountInfoPathInternal decodes the kernel's octal escape sequences+// used in /proc/self/mountinfo. The kernel only uses \040 (space), \011 (tab),+// \012 (newline), and \134 (backslash) — no other escape forms appear.+func unescapeMountInfoPathInternal(path string) string {+ replacer := strings.NewReplacer(+ `\040`, " ",+ `\011`, "\t",+ `\012`, "\n",+ `\134`, `\`,+ )+ return replacer.Replace(path)+}diff --git a/backend/pkg/libarcane/startup/runtime_identity_linux.go b/backend/pkg/libarcane/startup/runtime_identity_linux.gonew file mode 100644index 000000000..3c61f3b44--- /dev/null+++ b/backend/pkg/libarcane/startup/runtime_identity_linux.go@@ -0,0 +1,88 @@+//go:build linux++package startup++import (+ "context"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "os/signal"+ "syscall"+)++func reexecWithRuntimeIdentityInternal(ctx context.Context, req runtimeIdentityRequest) error {+ executable, err := os.Executable()+ if err != nil {+ return fmt.Errorf("resolve executable: %w", err)+ }++ groups := runtimeIdentitySupplementaryGroupsInternal(os.Getenv, resolveSocketGroupInternal)++ cmd := exec.CommandContext(ctx, executable, os.Args[1:]...) //nolint:gosec // re-executing our own binary with the same args under a different UID/GID+ cmd.Env = os.Environ()+ cmd.Stdin = os.Stdin+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr+ cmd.SysProcAttr = &syscall.SysProcAttr{+ Credential: &syscall.Credential{+ Uid: req.UID,+ Gid: req.GID,+ Groups: groups,+ },+ }++ if err := cmd.Start(); err != nil {+ return fmt.Errorf("start runtime identity child: %w", err)+ }++ sigCh := make(chan os.Signal, 2)+ signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)++ done := make(chan error, 1)+ go func() {+ done <- cmd.Wait()+ }()++ for {+ select {+ case sig := <-sigCh:+ if cmd.Process != nil {+ _ = cmd.Process.Signal(sig)+ }+ case err := <-done:+ signal.Stop(sigCh)+ if err == nil {+ os.Exit(0)+ }++ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {+ if status.Signaled() {+ os.Exit(128 + int(status.Signal()))+ }+ os.Exit(status.ExitStatus())+ }+ os.Exit(exitErr.ExitCode())+ }++ return fmt.Errorf("wait for runtime identity child: %w", err)+ }+ }+}++func resolveSocketGroupInternal(socketPath string) (uint32, bool) {+ info, err := os.Stat(socketPath)+ if err != nil {+ return 0, false+ }++ stat, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return 0, false+ }++ return stat.Gid, true+}diff --git a/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.gonew file mode 100644index 000000000..0f05c8931--- /dev/null+++ b/backend/pkg/libarcane/startup/runtime_identity_nonlinux.go@@ -0,0 +1,13 @@+//go:build !linux++package startup++import (+ "context"+ "fmt"+ "runtime"+)++func reexecWithRuntimeIdentityInternal(_ context.Context, req runtimeIdentityRequest) error {+ return fmt.Errorf("runtime identity switching is only supported on linux, current platform is %s", runtime.GOOS)+}diff --git a/backend/pkg/libarcane/startup/runtime_identity_test.go b/backend/pkg/libarcane/startup/runtime_identity_test.gonew file mode 100644index 000000000..e8248b1a4--- /dev/null+++ b/backend/pkg/libarcane/startup/runtime_identity_test.go@@ -0,0 +1,206 @@+package startup++import (+ "math"+ "path/filepath"+ "strconv"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestLoadRuntimeIdentityRequest(t *testing.T) {+ t.Run("disabled when unset", func(t *testing.T) {+ req, warning, err := loadRuntimeIdentityRequestInternal(func(string) string { return "" })+ require.NoError(t, err)+ require.Empty(t, warning)+ require.False(t, req.Enabled)+ })++ t.Run("warning when partial config", func(t *testing.T) {+ req, warning, err := loadRuntimeIdentityRequestInternal(func(key string) string {+ if key == "PUID" {+ return "1001"+ }+ return ""+ })+ require.NoError(t, err)+ require.Contains(t, warning, "PUID and PGID must both be set")+ require.False(t, req.Enabled)+ })++ t.Run("error when invalid numeric value", func(t *testing.T) {+ _, _, err := loadRuntimeIdentityRequestInternal(func(key string) string {+ if key == "PUID" {+ return "abc"+ }+ return "1001"+ })+ require.Error(t, err)+ require.Contains(t, err.Error(), "invalid PUID")+ })++ t.Run("error when value exceeds uint32", func(t *testing.T) {+ tooLarge := strconv.FormatUint(uint64(math.MaxUint32)+1, 10)++ _, _, err := loadRuntimeIdentityRequestInternal(func(key string) string {+ if key == "PUID" {+ return tooLarge+ }+ return "1001"+ })+ require.Error(t, err)+ require.Contains(t, err.Error(), "invalid PUID")+ })++ t.Run("enabled when both set", func(t *testing.T) {+ req, warning, err := loadRuntimeIdentityRequestInternal(func(key string) string {+ switch key {+ case "PUID":+ return "1001"+ case "PGID":+ return "2001"+ default:+ return ""+ }+ })+ require.NoError(t, err)+ require.Empty(t, warning)+ require.True(t, req.Enabled)+ require.Equal(t, uint32(1001), req.UID)+ require.Equal(t, uint32(2001), req.GID)+ })+}++func TestRuntimeIdentitySupplementaryGroups(t *testing.T) {+ t.Run("maps default docker socket group when docker host unset", func(t *testing.T) {+ groups := runtimeIdentitySupplementaryGroupsInternal(+ func(string) string { return "" },+ func(socketPath string) (uint32, bool) {+ require.Equal(t, defaultDockerSocketPath, socketPath)+ return 997, true+ },+ )++ require.Equal(t, []uint32{997}, groups)+ })++ t.Run("maps custom unix docker host socket group", func(t *testing.T) {+ groups := runtimeIdentitySupplementaryGroupsInternal(+ func(string) string { return "unix:///tmp/docker.sock" },+ func(socketPath string) (uint32, bool) {+ require.Equal(t, "/tmp/docker.sock", socketPath)+ return 998, true+ },+ )++ require.Equal(t, []uint32{998}, groups)+ })++ t.Run("skips non unix docker host", func(t *testing.T) {+ called := false++ groups := runtimeIdentitySupplementaryGroupsInternal(+ func(string) string { return "tcp://docker:2375" },+ func(string) (uint32, bool) {+ called = true+ return 0, false+ },+ )++ require.Nil(t, groups)+ require.False(t, called)+ })++ t.Run("skips socket group when socket lookup fails", func(t *testing.T) {+ groups := runtimeIdentitySupplementaryGroupsInternal(+ func(string) string { return "unix:///tmp/missing.sock" },+ func(string) (uint32, bool) { return 0, false },+ )++ require.Nil(t, groups)+ })+}++func TestParseMountpoints(t *testing.T) {+ data := `36 25 0:32 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw+97 92 0:44 / /app/data rw,relatime - ext4 /dev/sda1 rw+98 92 0:45 / /app/data/projects rw,relatime - ext4 /dev/sdb1 rw+99 92 0:46 / /builds rw,relatime - ext4 /dev/sdc1 rw+`++ parsed := parseMountpointsInternal(data)+ require.Contains(t, parsed, "/app/data")+ require.Contains(t, parsed, "/app/data/projects")+ require.Contains(t, parsed, "/builds")+}++func TestSQLiteDatabasePath(t *testing.T) {+ t.Run("uses default sqlite path when unset", func(t *testing.T) {+ path, ok, err := sqliteDatabasePathInternal("")+ require.NoError(t, err)+ require.True(t, ok)+ require.Equal(t, "data/arcane.db", path)+ })++ t.Run("preserves absolute sqlite path", func(t *testing.T) {+ path, ok, err := sqliteDatabasePathInternal("file:/app/custom/arcane.db?_pragma=journal_mode(WAL)")+ require.NoError(t, err)+ require.True(t, ok)+ require.Equal(t, "/app/custom/arcane.db", path)+ })++ t.Run("returns relative sqlite path", func(t *testing.T) {+ path, ok, err := sqliteDatabasePathInternal("file:data/arcane.db?_pragma=journal_mode(WAL)")+ require.NoError(t, err)+ require.True(t, ok)+ require.Equal(t, "data/arcane.db", path)+ })++ t.Run("skips non sqlite database urls", func(t *testing.T) {+ path, ok, err := sqliteDatabasePathInternal("postgres://arcane:secret@db/arcane")+ require.NoError(t, err)+ require.False(t, ok)+ require.Empty(t, path)+ })+}++func TestEnsureSQLiteFilesExistInternal(t *testing.T) {+ tempDir := t.TempDir()+ dbPath := filepath.Join(tempDir, "arcane.db")++ require.NoError(t, ensureSQLiteFilesExistInternal("file:"+dbPath))++ require.FileExists(t, dbPath)+ require.NoFileExists(t, dbPath+"-wal")+ require.NoFileExists(t, dbPath+"-shm")+}++func TestEnsureSQLiteFilesExistInternalCreatesParentDir(t *testing.T) {+ tempDir := t.TempDir()+ dbPath := filepath.Join(tempDir, "subdir", "arcane.db")++ require.NoError(t, ensureSQLiteFilesExistInternal("file:"+dbPath))++ require.FileExists(t, dbPath)+}++func TestUnescapeMountInfoPath(t *testing.T) {+ tests := []struct {+ name string+ input string+ expect string+ }{+ {"space", `/mnt/my\040dir`, "/mnt/my dir"},+ {"tab", `/mnt/my\011dir`, "/mnt/my\tdir"},+ {"newline", `/mnt/my\012dir`, "/mnt/my\ndir"},+ {"backslash", `/mnt/my\134dir`, `/mnt/my\dir`},+ {"no escapes", `/mnt/simple`, "/mnt/simple"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.expect, unescapeMountInfoPathInternal(tt.input))+ })+ }+}diff --git a/docker/examples/compose.agent-edge.yaml b/docker/examples/compose.agent-edge.yamlindex cc5962809..6988442b2 100644--- a/docker/examples/compose.agent-edge.yaml+++ b/docker/examples/compose.agent-edge.yaml@@ -7,6 +7,10 @@ services:- EDGE_AGENT=true- AGENT_TOKEN=arc_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX- MANAGER_API_URL=https://your-manager.example.com+ # Optional: run the agent 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+ # - PGID=1000# Set to grpc to enable protobuf transport over the manager API port.- EDGE_TRANSPORT=websocketvolumes:diff --git a/docker/examples/compose.agent.yaml b/docker/examples/compose.agent.yamlindex 01ea6f1e0..8fed2829f 100644--- a/docker/examples/compose.agent.yaml+++ b/docker/examples/compose.agent.yaml@@ -8,6 +8,10 @@ services:- AGENT_MODE=true- AGENT_TOKEN=arc_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX- MANAGER_API_URL=http://10.1.1.4:3552+ # Optional: run the agent 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+ # - PGID=1000# Optional gRPC tunnel setting:- EDGE_TRANSPORT=websocketvolumes:diff --git a/docker/examples/compose.basic.yaml b/docker/examples/compose.basic.yamlindex b944c79d9..0ec392ca8 100644--- a/docker/examples/compose.basic.yaml+++ b/docker/examples/compose.basic.yaml@@ -12,6 +12,10 @@ services:environment:- ENCRYPTION_KEY=xxxxxxxxxxxxxxxxxxxxxx- JWT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxx+ # 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+ # - PGID=1000# Timezone for cron job scheduling (e.g., America/New_York, Europe/London, UTC)# See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones- TZ=UTCdiff --git a/docker/examples/compose.proxy.yaml b/docker/examples/compose.proxy.yamlindex edc160db1..8c5793c11 100644--- a/docker/examples/compose.proxy.yaml+++ b/docker/examples/compose.proxy.yaml@@ -47,6 +47,10 @@ services:environment:- ENCRYPTION_KEY=xxxxxxxxxxxxxxxxxxxxxx- JWT_SECRET=xxxxxxxxxxxxxxxxxxxxxx+ # Optional: run Arcane as a specific host UID/GID instead of the default runtime user.+ # With DOCKER_HOST over TCP, no Unix socket group mapping is needed.+ # - PUID=1000+ # - PGID=1000- DOCKER_HOST=tcp://docker-socket-proxy:2375 # Use the proxy instead of direct socketnetworks:- arcane-internaldiff --git a/tests/spec/docker-runtime-identity.spec.ts b/tests/spec/docker-runtime-identity.spec.tsnew file mode 100644index 000000000..a70632ca2--- /dev/null+++ b/tests/spec/docker-runtime-identity.spec.ts@@ -0,0 +1,323 @@+import { test, expect } from '@playwright/test';+import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++const IMAGE = process.env.ARCANE_RUNTIME_TEST_IMAGE || 'arcane:playwright-tests';+const HEALTH_PATH = '/api/health';++function docker(args: string[], options?: { stdio?: 'pipe' | 'inherit' }) {+ const output = execFileSync('docker', args, {+ encoding: 'utf8',+ stdio: options?.stdio ?? 'pipe'+ });+ return typeof output === 'string' ? output.trim() : '';+}++function uniqueName(prefix: string) {+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+}++function dockerRunContainer(args: string[]) {+ return docker(['run', '-d', ...args]);+}++function dockerExec(container: string, command: string) {+ return docker(['exec', container, 'sh', '-lc', command]);+}++function dockerExecAsUser(container: string, user: string, command: string) {+ return docker(['exec', '-u', user, container, 'sh', '-lc', command]);+}++function dockerStatus(container: string) {+ return docker(['inspect', '-f', '{{.State.Status}}', container]);+}++function dockerPort(container: string) {+ const mapping = docker(['port', container, '3552/tcp']);+ return mapping.split(':').at(-1)?.trim() || '';+}++function dockerFileStat(volumePath: string, filePath: string) {+ return docker([+ 'run',+ '--rm',+ '-v',+ `${volumePath}:/mnt`,+ '--entrypoint',+ 'sh',+ IMAGE,+ '-lc',+ `stat -c '%u:%g' '${filePath}'`+ ]);+}++function cleanupContainer(name: string) {+ try {+ docker(['rm', '-f', name], { stdio: 'inherit' });+ } catch {+ // ignore cleanup failures+ }+}++function cleanupDir(dir: string) {+ try {+ // Files may be owned by root inside the container, so use Docker to remove them.+ docker(['run', '--rm', '-v', `${dir}:/mnt`, 'alpine:latest', 'rm', '-rf', '/mnt']);+ } catch {+ // ignore+ }+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {+ // ignore cleanup failures+ }+}++function cleanupNetwork(name: string) {+ try {+ docker(['network', 'rm', name], { stdio: 'inherit' });+ } catch {+ // ignore cleanup failures+ }+}++async function waitForHealth(container: string) {+ const port = dockerPort(container);+ expect(port).not.toBe('');++ await expect+ .poll(+ async () => {+ if (dockerStatus(container) !== 'running') {+ return `container:${dockerStatus(container)}`;+ }++ try {+ const response = await fetch(`http://127.0.0.1:${port}${HEALTH_PATH}`);+ return response.ok ? 'UP' : `http:${response.status}`;+ } catch {+ return 'pending';+ }+ },+ {+ timeout: 120_000,+ interval: 2_000+ }+ )+ .toBe('UP');+}++async function waitForFile(container: string, filePath: string) {+ await expect+ .poll(+ () => {+ try {+ return dockerExec(container, `test -f '${filePath}' && echo present`);+ } catch {+ return 'missing';+ }+ },+ {+ timeout: 60_000,+ interval: 1_000+ }+ )+ .toBe('present');+}++function pidOneStatus(container: string) {+ return dockerExec(container, "grep -E '^(Uid|Gid|Groups):' /proc/1/status");+}++function arcaneProcessStatuses(container: string) {+ return 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";',+ 'done'+ ].join(' ')+ )+ .split('\n')+ .filter(Boolean);+}++function defaultRunArgs(name: string, dataDir: string) {+ return [+ '--name',+ name,+ '-p',+ '0:3552',+ '-e',+ 'ENVIRONMENT=testing',+ '-e',+ 'APP_URL=http://localhost:3552',+ '-e',+ 'ENCRYPTION_KEY=3JDIgolks2tJ9ymm1AdqzlYMWu0DUWyt',+ '-e',+ 'JWT_SECRET=your-super-secret-jwt-key-change-this-in-production',+ '-v',+ `${dataDir}:/app/data`+ ];+}++test.describe.serial('Docker runtime identity', () => {+ test.setTimeout(240_000);++ test('keeps default root runtime behavior when PUID and PGID are unset', async () => {+ const containerName = uniqueName('arcane-default');+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-'));++ try {+ dockerRunContainer([+ ...defaultRunArgs(containerName, dataDir),+ '-v',+ '/var/run/docker.sock:/var/run/docker.sock',+ IMAGE+ ]);++ await waitForHealth(containerName);+ 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');+ } finally {+ cleanupContainer(containerName);+ cleanupDir(dataDir);+ }+ });++ test('runs as the requested UID and GID without chowning a mounted projects directory', async () => {+ const containerName = uniqueName('arcane-puid');+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-puid-data-'));+ const projectsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-puid-projects-'));+ const sentinelPath = path.join(projectsDir, 'sentinel.txt');+ fs.writeFileSync(sentinelPath, 'sentinel\n');++ const baselineProjectsStat = dockerFileStat(projectsDir, '/mnt/sentinel.txt');++ try {+ dockerRunContainer([+ ...defaultRunArgs(containerName, dataDir),+ '-e',+ 'PUID=1001',+ '-e',+ 'PGID=1001',+ '-v',+ '/var/run/docker.sock:/var/run/docker.sock',+ '-v',+ `${projectsDir}:/app/data/projects`,+ IMAGE+ ]);++ await waitForHealth(containerName);+ await waitForFile(containerName, '/app/data/arcane.db');++ const dbStat = dockerExecAsUser(+ containerName,+ '1001:1001',+ "stat -c '%u:%g' /app/data/arcane.db"+ );+ expect(dbStat).toBe('1001:1001');++ const projectsStat = dockerExec(+ containerName,+ "stat -c '%u:%g' /app/data/projects/sentinel.txt"+ );+ 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);+ } finally {+ cleanupContainer(containerName);+ cleanupDir(dataDir);+ cleanupDir(projectsDir);+ }+ });++ test('supports tcp docker host mode without a mounted Unix socket', async () => {+ const networkName = uniqueName('arcane-proxy-net');+ const proxyName = uniqueName('arcane-proxy');+ const containerName = uniqueName('arcane-proxy-app');+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-proxy-data-'));++ try {+ docker(['network', 'create', networkName], { stdio: 'inherit' });++ dockerRunContainer([+ '--name',+ proxyName,+ '--network',+ networkName,+ '-e',+ 'EVENTS=1',+ '-e',+ 'PING=1',+ '-e',+ 'VERSION=1',+ '-e',+ 'AUTH=0',+ '-e',+ 'POST=1',+ '-e',+ 'CONTAINERS=1',+ '-e',+ 'IMAGES=1',+ '-e',+ 'INFO=1',+ '-e',+ 'NETWORKS=1',+ '-e',+ 'VOLUMES=1',+ '-v',+ '/var/run/docker.sock:/var/run/docker.sock:ro',+ 'tecnativa/docker-socket-proxy:latest'+ ]);+ await new Promise((resolve) => setTimeout(resolve, 2_000));++ dockerRunContainer([+ ...defaultRunArgs(containerName, dataDir),+ '--network',+ networkName,+ '-e',+ 'PUID=1001',+ '-e',+ 'PGID=1001',+ '-e',+ `DOCKER_HOST=tcp://${proxyName}:2375`,+ IMAGE+ ]);++ await waitForHealth(containerName);+ await waitForFile(containerName, '/app/data/arcane.db');++ const dbStat = dockerExecAsUser(+ containerName,+ '1001:1001',+ "stat -c '%u:%g' /app/data/arcane.db"+ );+ 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);+ } finally {+ cleanupContainer(containerName);+ cleanupContainer(proxyName);+ cleanupNetwork(networkName);+ cleanupDir(dataDir);+ }+ });+});