Skip to content

Modern Docker Management, Designed for Everyone

fix: use persistent Git storage for SSH host keys on native installs (#4300)

Kyle Mendella2c740ae162b
diff --git a/.env.example b/.env.example
index 7ca340e7a..37c103e34 100644
--- a/.env.example
+++ b/.env.example
@@ -51,6 +51,13 @@ ALLOW_DOWNGRADE=false
# Docker Configuration
# DOCKER_HOST=unix:///var/run/docker.sock # Default: direct socket access
# DOCKER_HOST=tcp://docker-socket-proxy:2375 # Example: via socket proxy for enhanced security
+# Git storage (default: data/git, relative to Arcane's working directory).
+# Native installs keep saved host keys here; an existing home trust file is used
+# only before this trust file exists. Home path permission errors use Git storage.
+# GIT_WORK_DIR=/opt/arcane/data/git
+# Override the SSH trust file for Strict and Accept New verification.
+# Its parent must be writable in Accept New mode, including under hardened systemd units.
+# SSH_KNOWN_HOSTS=/opt/arcane/data/.ssh/known_hosts
# Trivy scan container security options (optional, useful on SELinux hosts)
# Separate multiple entries with commas or new lines, for example: label=disable,label=type:container_runtime_t
# TRIVY_SECURITY_OPTS=label=disable
diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.go
index 0aa345205..19a60f338 100644
--- a/backend/pkg/gitutil/git.go
+++ b/backend/pkg/gitutil/git.go
@@ -76,10 +76,10 @@ type Client struct {
var scpLikeURLPattern = regexp.MustCompile(`^[^@/]+@[^:/]+:`)
-// normalizeURL coerces a repository URL into a form go-git resolves to a
+// normalizeURLInternal coerces a repository URL into a form go-git resolves to a
// network transport, never the file transport (which execs the git binary).
// Schemeless host-style URLs (e.g. github.com/org/repo.git) get https://.
-func normalizeURL(raw string) (string, error) {
+func normalizeURLInternal(raw string) (string, error) {
url := strings.TrimSpace(raw)
if url == "" {
return "", errors.New("repository URL is empty")
@@ -145,7 +145,7 @@ func (c *Client) getAuthInternal(ctx context.Context, url string, localConfig Au
}
// Configure host key verification based on mode
- hostKeyCallback, err := c.getSSHHostKeyCallback(ctx, localConfig.SSHHostKeyVerification)
+ hostKeyCallback, err := c.getSSHHostKeyCallbackInternal(ctx, localConfig.SSHHostKeyVerification)
if err != nil {
return nil, fmt.Errorf("failed to configure SSH host key verification: %w", err)
}
@@ -163,31 +163,30 @@ func (c *Client) getAuthInternal(ctx context.Context, url string, localConfig Au
}
}
-// getSSHHostKeyCallback returns the appropriate SSH host key callback based on verification mode
-func (c *Client) getSSHHostKeyCallback(ctx context.Context, mode string) (gossh.HostKeyCallback, error) {
- switch mode {
- case SSHHostKeyVerificationStrict:
- // Use known_hosts verification respecting SSH_KNOWN_HOSTS env var
- return knownhosts.New(getKnownHostsPath())
- case SSHHostKeyVerificationSkip:
+// getSSHHostKeyCallbackInternal returns the SSH host key callback for the verification mode.
+func (c *Client) getSSHHostKeyCallbackInternal(ctx context.Context, mode string) (gossh.HostKeyCallback, error) {
+ if mode == SSHHostKeyVerificationSkip {
// Skip host key verification - intentionally insecure, user explicitly opted in via UI
return gossh.InsecureIgnoreHostKey(), nil //nolint:gosec // User explicitly chose to skip verification
- case SSHHostKeyVerificationAcceptNew, "":
- // Default: accept and remember new host keys
- return c.createAcceptNewHostKeyCallback(ctx)
- default:
- // Fall back to accept_new for unknown modes
- return c.createAcceptNewHostKeyCallback(ctx)
}
-}
-// createAcceptNewHostKeyCallback creates a callback that accepts new host keys and saves them
-func (c *Client) createAcceptNewHostKeyCallback(ctx context.Context) (gossh.HostKeyCallback, error) {
- knownHostsPath := getKnownHostsPath()
+ knownHostsPaths, pathErr := getKnownHostsPathsInternal(
+ c.workDir,
+ os.Getenv,
+ os.Stat,
+ os.UserHomeDir,
+ )
+ if pathErr != nil {
+ return nil, pathErr
+ }
+ if mode == SSHHostKeyVerificationStrict {
+ return knownhosts.New(knownHostsPaths...)
+ }
+ // Other modes default to accepting and remembering new host keys.
// Ensure the directory exists
- // os.* rather than acfs: known_hosts lives under the user home (not an arcane
- // confinement root), and acfs has no append/flock API for the writes below.
+ // os.* supports home and override paths outside acfs roots, plus append/flock.
+ knownHostsPath := knownHostsPaths[0]
dir := filepath.Dir(knownHostsPath)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, fmt.Errorf("failed to create known_hosts directory: %w", err)
@@ -205,98 +204,119 @@ func (c *Client) createAcceptNewHostKeyCallback(ctx context.Context) (gossh.Host
}
return func(hostname string, remote net.Addr, key gossh.PublicKey) error {
- // Re-read known_hosts on each call to handle concurrent modifications
- existingCallback, err := knownhosts.New(knownHostsPath)
+ // Re-read known_hosts on each call to handle concurrent modifications.
+ // Unreadable trust must fail closed so changed keys are never accepted.
+ existingCallback, err := knownhosts.New(knownHostsPaths...)
if err != nil {
- existingCallback = nil
+ return fmt.Errorf("failed to read known_hosts: %w", err)
}
- // Check if the host is already known
- if existingCallback != nil {
- existingCallbackErr := existingCallback(hostname, remote, key)
- if existingCallbackErr == nil {
- return nil // Host key matches
- }
- // Check if it's a "key mismatch" error vs "unknown host"
- if keyErr, ok := errors.AsType[*knownhosts.KeyError](existingCallbackErr); ok && len(keyErr.Want) > 0 {
- // Host is known but key doesn't match - this is a security concern
- return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, existingCallbackErr)
- }
- // Otherwise, host is unknown - we'll add it
+ existingCallbackErr := existingCallback(hostname, remote, key)
+ if existingCallbackErr == nil {
+ return nil // Host key matches
}
+ // Check if it's a "key mismatch" error vs "unknown host"
+ if keyErr, ok := errors.AsType[*knownhosts.KeyError](existingCallbackErr); ok && len(keyErr.Want) > 0 {
+ // Host is known but key doesn't match - this is a security concern
+ return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, existingCallbackErr)
+ }
+ // Otherwise, host is unknown - we'll add it
+
+ // Log persistence failures after closing the file and releasing its lock.
+ var saveErr error
+ defer func() {
+ if saveErr != nil {
+ slog.WarnContext(ctx, "Failed to save host key", "hostname", hostname, "error", saveErr)
+ }
+ }()
- // Add the new host key to known_hosts
- if addHostKeyErr := addHostKey(knownHostsPath, hostname, key); addHostKeyErr != nil {
- // Log the error but don't fail - still allow the connection
- // The host key just won't be remembered for next time
- slog.WarnContext(ctx, "Failed to save host key", "hostname", hostname, "error", addHostKeyErr)
+ fileLock := flock.New(knownHostsPath)
+ if lockErr := fileLock.Lock(); lockErr != nil {
+ saveErr = fmt.Errorf("failed to acquire lock on known_hosts file: %w", lockErr)
+ return nil
}
+ defer func() {
+ if unlockErr := fileLock.Unlock(); unlockErr != nil && saveErr == nil {
+ saveErr = fmt.Errorf("failed to release lock on known_hosts file: %w", unlockErr)
+ }
+ }()
+ // acfs has no append API, and override paths can be outside its roots.
+ file, openErr := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
+ if openErr != nil {
+ saveErr = fmt.Errorf("failed to open known_hosts file: %w", openErr)
+ return nil
+ }
+ defer func() {
+ if closeErr := file.Close(); closeErr != nil && saveErr == nil {
+ saveErr = fmt.Errorf("failed to close known_hosts file: %w", closeErr)
+ }
+ }()
+ line := knownhosts.Line([]string{hostname}, key)
+ if _, writeErr := file.WriteString(line + "\n"); writeErr != nil {
+ saveErr = fmt.Errorf("failed to write to known_hosts file: %w", writeErr)
+ }
return nil
}, nil
}
-// getKnownHostsPath returns the path to the known_hosts file
-func getKnownHostsPath() string {
- return getKnownHostsPathInternal(os.Getenv, os.Stat, os.UserHomeDir)
-}
-
-func getKnownHostsPathInternal(getenv func(string) string, stat func(string) (os.FileInfo, error), userHomeDir func() (string, error)) string {
+// getKnownHostsPathsInternal returns trusted known_hosts files; new keys are saved to the first.
+func getKnownHostsPathsInternal(
+ workDir string,
+ getenv func(string) string,
+ stat func(string) (os.FileInfo, error),
+ userHomeDir func() (string, error),
+) ([]string, error) {
// Check environment variable first
if localPath := getenv("SSH_KNOWN_HOSTS"); localPath != "" {
- return localPath
+ return []string{localPath}, nil
}
// Prefer Arcane's writable persistent data directory when it is available,
// which is the case for published container images and PUID/PGID setups.
if info, err := stat(defaultKnownHostsDataDir); err == nil && info.IsDir() {
- return defaultKnownHostsPath
+ return []string{defaultKnownHostsPath}, nil
}
- // Fall back to the user's home directory for local development and CI.
+ var homePath string
+ homeExists := false
homeDir, err := userHomeDir()
if err == nil && homeDir != "" {
- return filepath.Join(homeDir, ".ssh", "known_hosts")
+ homePath = filepath.Join(homeDir, ".ssh", "known_hosts")
+ _, statErr := stat(homePath)
+ switch {
+ case statErr == nil:
+ homeExists = true
+ case errors.Is(statErr, fs.ErrNotExist):
+ case workDir != "" && errors.Is(statErr, fs.ErrPermission):
+ // Inaccessible home trust falls back to native storage.
+ default:
+ return nil, fmt.Errorf("failed to check existing known_hosts file %s: %w", homePath, statErr)
+ }
}
- // Last resort for environments without a resolvable home directory.
- return filepath.Join(os.TempDir(), ".ssh", "known_hosts")
-}
-
-// addHostKey adds a host key to the known_hosts file
-func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error) {
- // Format the known_hosts line
- line := knownhosts.Line([]string{hostname}, key)
-
- // Acquire exclusive lock to prevent concurrent writes
- fileLock := flock.New(knownHostsPath)
- if lockErr := fileLock.Lock(); lockErr != nil {
- return fmt.Errorf("failed to acquire lock on known_hosts file: %w", lockErr)
- }
- defer func() {
- if unlockErr := fileLock.Unlock(); unlockErr != nil && err == nil {
- err = fmt.Errorf("failed to release lock on known_hosts file: %w", unlockErr)
+ if workDir == "" {
+ if homePath != "" {
+ return []string{homePath}, nil
}
- }()
-
- // Append to the file
- // os.* rather than acfs: acfs has no append API, and known_hosts lives under
- // the user home rather than an arcane confinement root.
- file, err := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
- if err != nil {
- return fmt.Errorf("failed to open known_hosts file: %w", err)
+ // Last resort for environments without a resolvable home directory.
+ return []string{filepath.Join(os.TempDir(), ".ssh", "known_hosts")}, nil
}
- defer func() {
- if cerr := file.Close(); cerr != nil && err == nil {
- err = fmt.Errorf("failed to close known_hosts file: %w", cerr)
- }
- }()
- if _, writeStringErr := file.WriteString(line + "\n"); writeStringErr != nil {
- return fmt.Errorf("failed to write to known_hosts file: %w", writeStringErr)
+ // Native storage keeps saved keys while honoring every readable trust file.
+ workPath := filepath.Join(workDir, ".ssh", "known_hosts")
+ _, workErr := stat(workPath)
+ if workErr != nil && !errors.Is(workErr, fs.ErrNotExist) {
+ return nil, fmt.Errorf("failed to check git known_hosts file %s: %w", workPath, workErr)
+ }
+ switch {
+ case workErr == nil && homeExists:
+ return []string{workPath, homePath}, nil
+ case homeExists:
+ return []string{homePath}, nil
+ default:
+ return []string{workPath}, nil
}
-
- return nil
}
// Clone clones a repository to a temporary directory
@@ -327,7 +347,7 @@ func (c *Client) Clone(ctx context.Context, url, branch string, auth AuthConfig)
return "", fmt.Errorf("failed to create temp dir: %w", err)
}
- url, err = normalizeURL(url)
+ url, err = normalizeURLInternal(url)
if err != nil {
_ = os.RemoveAll(tmpDir)
return "", err
@@ -391,7 +411,7 @@ func (c *Client) ListBranches(ctx context.Context, url string, auth AuthConfig)
if err := ctx.Err(); err != nil {
return nil, err
}
- refs, err := c.listRemoteReferences(ctx, url, auth)
+ refs, err := c.listRemoteReferencesInternal(ctx, url, auth)
if err != nil {
return nil, err
}
@@ -447,12 +467,12 @@ func (c *Client) ProbeRemote(ctx context.Context, url string, auth AuthConfig) e
return err
}
- _, err := c.listRemoteReferences(ctx, url, auth)
+ _, err := c.listRemoteReferencesInternal(ctx, url, auth)
return err
}
-func (c *Client) listRemoteReferences(ctx context.Context, url string, auth AuthConfig) ([]*plumbing.Reference, error) {
- url, err := normalizeURL(url)
+func (c *Client) listRemoteReferencesInternal(ctx context.Context, url string, auth AuthConfig) ([]*plumbing.Reference, error) {
+ url, err := normalizeURLInternal(url)
if err != nil {
return nil, err
}
@@ -671,12 +691,6 @@ type DirectoryWalkResult struct {
SkippedBinaries int
}
-type syncWalkLimits struct {
- maxFiles int
- maxTotalSize int64
- maxBinarySize int64
-}
-
// WalkDirectory walks the directory containing the compose file and returns all files.
// It enforces limits on file count, total size, and skips large binary files.
// The composePath is the path to the compose file within the repo - the directory
@@ -699,103 +713,79 @@ func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath string
result := &DirectoryWalkResult{
Files: make([]SyncFileInfo, 0),
}
- limits := syncWalkLimits{
- maxFiles: maxFiles,
- maxTotalSize: maxTotalSize,
- maxBinarySize: maxBinarySize,
- }
-
err := acfs.Walk(ctx, syncDir, "/", func(entry acfstypes.Entry) error {
- return c.walkSyncEntry(ctx, syncDir, entry, result, limits)
- })
- if err != nil {
- return nil, err
- }
-
- // Validate we found at least one file
- if len(result.Files) == 0 {
- return nil, errors.New("no files found in sync directory (directory may be empty or all files were skipped)")
- }
-
- return result, nil
-}
-
-func (c *Client) walkSyncEntry(ctx context.Context, syncDir string, entry acfstypes.Entry, result *DirectoryWalkResult, limits syncWalkLimits) error {
- if err := ctx.Err(); err != nil {
- return err
- }
- if entry.IsSymlink {
- return nil
- }
- if entry.IsDirectory {
- return kit.Ternary(entry.Name == ".git", fs.SkipDir, nil)
- }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if entry.IsSymlink {
+ return nil
+ }
+ if entry.IsDirectory {
+ if entry.Name == ".git" {
+ return fs.SkipDir
+ }
+ return nil
+ }
- return c.appendSyncFile(ctx, syncDir, entry, result, limits)
-}
+ relativePath := strings.TrimPrefix(entry.Path, "/")
+ if maxFiles > 0 && result.TotalFiles >= maxFiles {
+ return fmt.Errorf("file count limit exceeded (max %d files)", maxFiles)
+ }
-func (c *Client) appendSyncFile(ctx context.Context, syncDir string, entry acfstypes.Entry, result *DirectoryWalkResult, limits syncWalkLimits) error {
- relativePath := strings.TrimPrefix(entry.Path, "/")
- if limits.maxFiles > 0 && result.TotalFiles >= limits.maxFiles {
- return fmt.Errorf("file count limit exceeded (max %d files)", limits.maxFiles)
- }
+ if maxBinarySize > 0 && entry.Size > maxBinarySize {
+ reader, _, openErr := acfs.OpenRead(ctx, syncDir, entry.Path, binarySniffBytes)
+ if openErr != nil {
+ return fmt.Errorf("failed to inspect file %s: %w", relativePath, openErr)
+ }
+ buf := make([]byte, binarySniffBytes)
+ n, readErr := reader.Read(buf)
+ closeErr := reader.Close()
+ if readErr != nil && !errors.Is(readErr, io.EOF) {
+ return fmt.Errorf("failed to inspect file %s: %w", relativePath, errors.Join(readErr, closeErr))
+ }
+ if closeErr != nil {
+ return fmt.Errorf("failed to close file %s after inspection: %w", relativePath, closeErr)
+ }
+ if IsBinaryContent(buf[:n]) {
+ result.SkippedBinaries++
+ return nil
+ }
+ }
- if limits.maxBinarySize > 0 && entry.Size > limits.maxBinarySize {
- isBinary, err := c.isBinarySyncFile(ctx, syncDir, entry.Path)
- if err != nil {
- return fmt.Errorf("failed to inspect file %s: %w", relativePath, err)
+ content, readErr := acfs.ReadFile(ctx, syncDir, entry.Path)
+ if readErr != nil {
+ return fmt.Errorf("failed to read file %s: %w", relativePath, readErr)
}
- if isBinary {
+
+ fileSize := int64(len(content))
+ isBinary := IsBinaryContent(content)
+ if isBinary && maxBinarySize > 0 && fileSize > maxBinarySize {
result.SkippedBinaries++
return nil
}
- }
-
- content, err := acfs.ReadFile(ctx, syncDir, entry.Path)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", relativePath, err)
- }
-
- fileSize := int64(len(content))
- isBinary := IsBinaryContent(content)
+ if maxTotalSize > 0 && result.TotalSize+fileSize > maxTotalSize {
+ return fmt.Errorf("total size limit exceeded (max %d bytes)", maxTotalSize)
+ }
- if isBinary && limits.maxBinarySize > 0 && fileSize > limits.maxBinarySize {
- result.SkippedBinaries++
+ result.Files = append(result.Files, SyncFileInfo{
+ RelativePath: relativePath,
+ Content: content,
+ Size: fileSize,
+ IsBinary: isBinary,
+ Executable: os.FileMode(entry.UnixMode)&0o111 != 0,
+ })
+ result.TotalFiles++
+ result.TotalSize += fileSize
return nil
- }
-
- if limits.maxTotalSize > 0 && result.TotalSize+fileSize > limits.maxTotalSize {
- return fmt.Errorf("total size limit exceeded (max %d bytes)", limits.maxTotalSize)
- }
-
- executable := os.FileMode(entry.UnixMode)&0o111 != 0
- result.Files = append(result.Files, SyncFileInfo{
- RelativePath: relativePath,
- Content: content,
- Size: fileSize,
- IsBinary: isBinary,
- Executable: executable,
})
- result.TotalFiles++
- result.TotalSize += fileSize
-
- return nil
-}
-
-func (c *Client) isBinarySyncFile(ctx context.Context, syncDir, logicalPath string) (bool, error) {
- reader, _, err := acfs.OpenRead(ctx, syncDir, logicalPath, binarySniffBytes)
- if err != nil {
- return false, err
- }
- defer func() { _ = reader.Close() }()
-
- buf := make([]byte, binarySniffBytes)
- n, err := reader.Read(buf)
- if err != nil && !errors.Is(err, io.EOF) {
- return false, err
+ switch {
+ case err != nil:
+ return nil, err
+ case len(result.Files) == 0:
+ return nil, errors.New("no files found in sync directory (directory may be empty or all files were skipped)")
}
- return IsBinaryContent(buf[:n]), nil
+ return result, nil
}
// IsBinaryContent reports whether content looks binary rather than text.
diff --git a/backend/pkg/gitutil/git_test.go b/backend/pkg/gitutil/git_test.go
index 0ba74546c..cb95984e7 100644
--- a/backend/pkg/gitutil/git_test.go
+++ b/backend/pkg/gitutil/git_test.go
@@ -28,63 +28,125 @@ func TestInitAllowsMultiAckCapabilities(t *testing.T) {
}
func TestGetKnownHostsPath(t *testing.T) {
- t.Run("returns SSH_KNOWN_HOSTS env var when set", func(t *testing.T) {
- customPath := "/custom/path/known_hosts"
-
- result := getKnownHostsPathInternal(
- func(string) string { return customPath },
- os.Stat,
- os.UserHomeDir,
- )
-
- assert.Equal(t, customPath, result,
- "expected %s, got %s", customPath, result)
- })
-
- t.Run("returns Arcane data path when data directory exists", func(t *testing.T) {
- result := getKnownHostsPathInternal(
- func(string) string { return "" },
- func(path string) (os.FileInfo, error) {
- if path == defaultKnownHostsDataDir {
- return stubFileInfo{dir: true}, nil
- }
- return nil, os.ErrNotExist
- },
- func() (string, error) { return "/home/tester", nil },
- )
-
- expected := defaultKnownHostsPath
-
- assert.Equal(t, expected, result,
- "expected %s, got %s", expected, result)
- })
-
- t.Run("falls back to home directory when Arcane data directory is unavailable", func(t *testing.T) {
- homeDir := "/home/tester"
- result := getKnownHostsPathInternal(
- func(string) string { return "" },
- func(string) (os.FileInfo, error) { return nil, os.ErrNotExist },
- func() (string, error) { return homeDir, nil },
- )
-
- expected := filepath.Join(homeDir, ".ssh", "known_hosts")
-
- assert.Equal(t, expected, result,
- "expected %s, got %s", expected, result)
- })
-
- t.Run("falls back to temp dir when data directory and home are unavailable", func(t *testing.T) {
- result := getKnownHostsPathInternal(
- func(string) string { return "" },
- func(string) (os.FileInfo, error) { return nil, os.ErrNotExist },
- func() (string, error) { return "", errors.New("no home directory") },
- )
-
- expected := filepath.Join(os.TempDir(), ".ssh", "known_hosts")
-
- assert.Equal(t, expected, result,
- "expected %s, got %s", expected, result)
- })
+ homePath := "/home/tester/.ssh/known_hosts"
+ tests := []struct {
+ name string
+ workDir string
+ override string
+ dataDir bool
+ homeDir string
+ homeExists bool
+ workExists bool
+ homeErr error
+ statErr error
+ workErr error
+ want []string
+ wantErr error
+ }{
+ {
+ name: "returns SSH_KNOWN_HOSTS env var when set",
+ workDir: "/opt/arcane/data/git", override: "/custom/path/known_hosts",
+ dataDir: true, homeDir: "/home/tester", homeExists: true,
+ want: []string{"/custom/path/known_hosts"},
+ },
+ {
+ name: "returns Arcane data path when data directory exists",
+ workDir: "/opt/arcane/data/git", dataDir: true,
+ homeDir: "/home/tester", homeExists: true,
+ want: []string{defaultKnownHostsPath},
+ },
+ {
+ name: "preserves existing home trust file before native storage",
+ workDir: "/opt/arcane/data/git", homeDir: "/home/tester", homeExists: true,
+ want: []string{homePath},
+ },
+ {
+ name: "trusts both native and home files when both exist",
+ workDir: "/opt/arcane/data/git",
+ homeDir: "/home/tester",
+ homeExists: true,
+ workExists: true,
+ want: []string{"/opt/arcane/data/git/.ssh/known_hosts", homePath},
+ },
+ {
+ name: "uses native storage when the home trust file is absent",
+ workDir: "/opt/arcane/data/git", homeDir: "/var/lib/arcane",
+ want: []string{"/opt/arcane/data/git/.ssh/known_hosts"},
+ },
+ {
+ name: "keeps relative native storage relative to the working directory",
+ workDir: "data/git", homeDir: "/var/lib/arcane",
+ want: []string{filepath.Join("data", "git", ".ssh", "known_hosts")},
+ },
+ {
+ name: "uses native storage without a resolvable home",
+ workDir: "/opt/arcane/data/git", homeErr: errors.New("no home directory"),
+ want: []string{"/opt/arcane/data/git/.ssh/known_hosts"},
+ },
+ {
+ name: "falls back to home directory without a work directory",
+ homeDir: "/home/tester", want: []string{homePath},
+ },
+ {
+ name: "falls back to temp dir when data directory and home are unavailable",
+ homeErr: errors.New("no home directory"),
+ want: []string{filepath.Join(os.TempDir(), ".ssh", "known_hosts")},
+ },
+ {
+ name: "uses native storage when the home trust file is inaccessible",
+ workDir: "/opt/arcane/data/git", homeDir: "/home/tester",
+ statErr: os.ErrPermission, want: []string{"/opt/arcane/data/git/.ssh/known_hosts"},
+ },
+ {
+ name: "surfaces home trust file access errors without native storage",
+ homeDir: "/home/tester", statErr: os.ErrPermission, wantErr: os.ErrPermission,
+ },
+ {
+ name: "does not replace inaccessible native trust with a home trust file",
+ workDir: "/opt/arcane/data/git", homeDir: "/home/tester", homeExists: true,
+ workErr: os.ErrPermission, wantErr: os.ErrPermission,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result, err := getKnownHostsPathsInternal(
+ tt.workDir,
+ func(key string) string {
+ require.Equal(t, "SSH_KNOWN_HOSTS", key)
+ return tt.override
+ },
+ func(path string) (os.FileInfo, error) {
+ if path == defaultKnownHostsDataDir && tt.dataDir {
+ return stubFileInfo{dir: true}, nil
+ }
+ if path == filepath.Join(tt.workDir, ".ssh", "known_hosts") {
+ if tt.workErr != nil {
+ return nil, tt.workErr
+ }
+ if tt.workExists {
+ return stubFileInfo{}, nil
+ }
+ }
+ if path == homePath {
+ if tt.statErr != nil {
+ return nil, tt.statErr
+ }
+ if tt.homeExists {
+ return stubFileInfo{}, nil
+ }
+ }
+ return nil, os.ErrNotExist
+ },
+ func() (string, error) { return tt.homeDir, tt.homeErr },
+ )
+ if tt.wantErr != nil {
+ require.ErrorIs(t, err, tt.wantErr)
+ } else {
+ require.NoError(t, err)
+ }
+ assert.Equal(t, tt.want, result)
+ })
+ }
}
type stubFileInfo struct {
@@ -102,7 +164,8 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
client := NewClient("")
t.Run("skip mode returns InsecureIgnoreHostKey", func(t *testing.T) {
- callback, err := client.getSSHHostKeyCallback(t.Context(), SSHHostKeyVerificationSkip)
+ t.Setenv("SSH_KNOWN_HOSTS", filepath.Join(t.TempDir(), "missing", "known_hosts"))
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationSkip)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -122,7 +185,7 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
knownHostsPath := filepath.Join(tmpDir, "known_hosts")
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
- callback, err := client.getSSHHostKeyCallback(t.Context(), "")
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), "")
require.NoError(t, err,
"unexpected error: %v", err)
@@ -136,7 +199,7 @@ func TestGetSSHHostKeyCallback(t *testing.T) {
knownHostsPath := filepath.Join(tmpDir, "known_hosts")
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
- callback, err := client.getSSHHostKeyCallback(t.Context(), SSHHostKeyVerificationAcceptNew)
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -154,7 +217,10 @@ func TestAddHostKey(t *testing.T) {
// Generate a test key
key := generateTestPublicKey(t)
- err := addHostKey(knownHostsPath, "example.com:22", key)
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+ callback, err := NewClient("").getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
+ require.NoError(t, err)
+ err = callback("example.com:22", &net.TCPAddr{}, key)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -175,6 +241,8 @@ func TestAddHostKey(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
key := generateTestPublicKey(t)
+ callback, callbackErr := NewClient("").getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
+ require.NoError(t, callbackErr)
var wg sync.WaitGroup
errChan := make(chan error, 10)
@@ -184,7 +252,7 @@ func TestAddHostKey(t *testing.T) {
go func(idx int) {
defer wg.Done()
hostname := "host" + string(rune('0'+idx)) + ".example.com:22"
- if err := addHostKey(knownHostsPath, hostname, key); err != nil {
+ if err := callback(hostname, &net.TCPAddr{}, key); err != nil {
errChan <- err
}
}(i)
@@ -203,8 +271,8 @@ func TestAddHostKey(t *testing.T) {
require.NoError(t, err,
"failed to read known_hosts: %v", err)
- assert.NotEmpty(t, content,
- "expected non-empty known_hosts file after concurrent writes")
+ assert.Len(t, strings.Split(strings.TrimSpace(string(content)), "\n"), 10,
+ "every concurrent callback must persist its host key")
})
}
@@ -215,7 +283,7 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
client := NewClient("")
- callback, err := client.createAcceptNewHostKeyCallback(t.Context())
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -237,7 +305,7 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
client := NewClient("")
- callback, err := client.createAcceptNewHostKeyCallback(t.Context())
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -266,7 +334,7 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
client := NewClient("")
- callback, err := client.createAcceptNewHostKeyCallback(t.Context())
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -280,7 +348,9 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
require.NoError(t, err,
"first callback returned error: %v", err)
- // Second call should recognize the known host
+ // A new client must reuse the persisted trust file.
+ callback, err = NewClient("").getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationStrict)
+ require.NoError(t, err)
err = callback("192.168.1.1:22", addr, key)
assert.NoError(t, err,
@@ -293,7 +363,7 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
client := NewClient("")
- callback, err := client.createAcceptNewHostKeyCallback(t.Context())
+ callback, err := client.getSSHHostKeyCallbackInternal(t.Context(), SSHHostKeyVerificationAcceptNew)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -704,11 +774,13 @@ func TestPurgeScratchDirs(t *testing.T) {
staleDir := filepath.Join(workDir, "gitops-stale")
freshDir := filepath.Join(workDir, "gitops-fresh")
- keepDir := filepath.Join(workDir, "keep-me")
+ keepDir := filepath.Join(workDir, ".ssh")
scratchFile := filepath.Join(workDir, "gitops-file")
require.NoError(t, os.MkdirAll(staleDir, 0o755))
require.NoError(t, os.MkdirAll(freshDir, 0o755))
- require.NoError(t, os.MkdirAll(keepDir, 0o755))
+ require.NoError(t, os.MkdirAll(keepDir, 0o700))
+ knownHostsPath := filepath.Join(keepDir, "known_hosts")
+ require.NoError(t, os.WriteFile(knownHostsPath, []byte("persisted trust"), 0o600))
require.NoError(t, os.WriteFile(scratchFile, []byte("x"), 0o644))
staleTime := time.Now().Add(-3 * time.Hour)
require.NoError(t, os.Chtimes(staleDir, staleTime, staleTime))
@@ -719,7 +791,7 @@ func TestPurgeScratchDirs(t *testing.T) {
_, err = os.Stat(staleDir)
require.ErrorIs(t, err, os.ErrNotExist, "stale clone dir should be removed")
- for _, p := range []string{freshDir, keepDir, scratchFile} {
+ for _, p := range []string{freshDir, keepDir, knownHostsPath, scratchFile} {
_, statErr := os.Stat(p)
require.NoError(t, statErr, "must be kept by the age-cutoff purge: %s", p)
}
@@ -730,7 +802,7 @@ func TestPurgeScratchDirs(t *testing.T) {
_, err = os.Stat(freshDir)
require.ErrorIs(t, err, os.ErrNotExist, "boot sweep should remove fresh clone dirs")
- for _, p := range []string{keepDir, scratchFile} {
+ for _, p := range []string{keepDir, knownHostsPath, scratchFile} {
_, statErr2 := os.Stat(p)
require.NoError(t, statErr2, "boot sweep must keep non-scratch entries: %s", p)
}
@@ -764,7 +836,7 @@ func TestNormalizeURL(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got, err := normalizeURL(tc.in)
+ got, err := normalizeURLInternal(tc.in)
if tc.wantErr {
require.Error(t, err,
diff --git a/backend/pkg/gitutil/git_write.go b/backend/pkg/gitutil/git_write.go
index ebff3939b..caed9309c 100644
--- a/backend/pkg/gitutil/git_write.go
+++ b/backend/pkg/gitutil/git_write.go
@@ -210,7 +210,7 @@ func (c *Client) CheckoutForWrite(ctx context.Context, url, branch string, auth
if strings.TrimSpace(branch) == "" {
return nil, errors.New("branch is required")
}
- normalized, err := normalizeURL(url)
+ normalized, err := normalizeURLInternal(url)
if err != nil {
return nil, err
}
@@ -400,7 +400,7 @@ func isPushRejectedInternal(err error) bool {
// RemoteBranchHead resolves the remote head of branch without cloning.
func (c *Client) RemoteBranchHead(ctx context.Context, url, branch string, auth AuthConfig) (string, bool, error) {
- refs, err := c.listRemoteReferences(ctx, url, auth)
+ refs, err := c.listRemoteReferencesInternal(ctx, url, auth)
if err != nil {
return "", false, kit.Ternary(errors.Is(err, transport.ErrEmptyRemoteRepository), nil, err)
}