Skip to content

Modern Docker Management, Designed for Everyone

fix: add option for ssh host key verification and known hosts (#1443)

Kyle Mendellf7997a4618f1
diff --git a/backend/go.mod b/backend/go.mod
index 5b6ad9a3a..1c196d43f 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -22,6 +22,7 @@ require (
github.com/go-co-op/gocron/v2 v2.19.0
github.com/go-git/go-git/v5 v5.16.4
github.com/goccy/go-yaml v1.19.2
+ github.com/gofrs/flock v0.13.0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/golang-migrate/migrate/v4 v4.19.1
github.com/google/uuid v1.6.0
@@ -103,7 +104,6 @@ require (
github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
- github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/protobuf v1.5.4 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 63cb1ce15..4b5601c13 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -668,10 +668,12 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
+golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
+golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
-golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY=
+golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
+golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
diff --git a/backend/internal/models/git_repository.go b/backend/internal/models/git_repository.go
index 87b744b79..13fbc28aa 100644
--- a/backend/internal/models/git_repository.go
+++ b/backend/internal/models/git_repository.go
@@ -1,14 +1,15 @@
package models
type GitRepository struct {
- Name string `json:"name" sortable:"true" search:"git,repository,repo,source,version,control,github,gitlab,bitbucket"`
- URL string `json:"url" sortable:"true" search:"url,git,clone,remote,https,ssh"`
- AuthType string `json:"authType" sortable:"true" search:"auth,authentication,credentials,token,ssh,http"` // none, http, ssh
- Username string `json:"username" sortable:"true" search:"username,user,login,account"`
- Token string `json:"token" search:"token,password,credentials,secret,auth"` // encrypted
- SSHKey string `json:"sshKey" search:"ssh,key,private,public,certificate"` // encrypted
- Description *string `json:"description,omitempty" sortable:"true"`
- Enabled bool `json:"enabled" sortable:"true" search:"enabled,active,disabled"`
+ Name string `json:"name" sortable:"true" search:"git,repository,repo,source,version,control,github,gitlab,bitbucket"`
+ URL string `json:"url" sortable:"true" search:"url,git,clone,remote,https,ssh"`
+ AuthType string `json:"authType" sortable:"true" search:"auth,authentication,credentials,token,ssh,http"` // none, http, ssh
+ Username string `json:"username" sortable:"true" search:"username,user,login,account"`
+ Token string `json:"token" search:"token,password,credentials,secret,auth"` // encrypted
+ SSHKey string `json:"sshKey" search:"ssh,key,private,public,certificate"` // encrypted
+ SSHHostKeyVerification string `json:"sshHostKeyVerification" gorm:"default:accept_new"` // strict, accept_new, skip
+ Description *string `json:"description,omitempty" sortable:"true"`
+ Enabled bool `json:"enabled" sortable:"true" search:"enabled,active,disabled"`
BaseModel
}
@@ -17,23 +18,25 @@ func (GitRepository) TableName() string {
}
type CreateGitRepositoryRequest struct {
- Name string `json:"name" binding:"required"`
- URL string `json:"url" binding:"required"`
- AuthType string `json:"authType" binding:"required,oneof=none http ssh"`
- Username string `json:"username,omitempty"`
- Token string `json:"token,omitempty"`
- SSHKey string `json:"sshKey,omitempty"`
- Description *string `json:"description,omitempty"`
- Enabled *bool `json:"enabled,omitempty"`
+ Name string `json:"name" binding:"required"`
+ URL string `json:"url" binding:"required"`
+ AuthType string `json:"authType" binding:"required,oneof=none http ssh"`
+ Username string `json:"username,omitempty"`
+ Token string `json:"token,omitempty"`
+ SSHKey string `json:"sshKey,omitempty"`
+ SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty" binding:"omitempty,oneof=strict accept_new skip"`
+ Description *string `json:"description,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
}
type UpdateGitRepositoryRequest struct {
- Name *string `json:"name,omitempty"`
- URL *string `json:"url,omitempty"`
- AuthType *string `json:"authType,omitempty" binding:"omitempty,oneof=none http ssh"`
- Username *string `json:"username,omitempty"`
- Token *string `json:"token,omitempty"`
- SSHKey *string `json:"sshKey,omitempty"`
- Description *string `json:"description,omitempty"`
- Enabled *bool `json:"enabled,omitempty"`
+ Name *string `json:"name,omitempty"`
+ URL *string `json:"url,omitempty"`
+ AuthType *string `json:"authType,omitempty" binding:"omitempty,oneof=none http ssh"`
+ Username *string `json:"username,omitempty"`
+ Token *string `json:"token,omitempty"`
+ SSHKey *string `json:"sshKey,omitempty"`
+ SSHHostKeyVerification *string `json:"sshHostKeyVerification,omitempty" binding:"omitempty,oneof=strict accept_new skip"`
+ Description *string `json:"description,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
}
diff --git a/backend/internal/services/git_repository_service.go b/backend/internal/services/git_repository_service.go
index 2e5d7a59f..a2091f577 100644
--- a/backend/internal/services/git_repository_service.go
+++ b/backend/internal/services/git_repository_service.go
@@ -83,12 +83,18 @@ func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name str
func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.CreateGitRepositoryRequest) (*models.GitRepository, error) {
repository := models.GitRepository{
- Name: req.Name,
- URL: req.URL,
- AuthType: req.AuthType,
- Username: req.Username,
- Description: req.Description,
- Enabled: true,
+ Name: req.Name,
+ URL: req.URL,
+ AuthType: req.AuthType,
+ Username: req.Username,
+ SSHHostKeyVerification: req.SSHHostKeyVerification,
+ Description: req.Description,
+ Enabled: true,
+ }
+
+ // Default to accept_new if not specified
+ if repository.SSHHostKeyVerification == "" {
+ repository.SSHHostKeyVerification = "accept_new"
}
if req.Enabled != nil {
@@ -157,6 +163,9 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
if req.Enabled != nil {
updates["enabled"] = *req.Enabled
}
+ if req.SSHHostKeyVerification != nil {
+ updates["ssh_host_key_verification"] = *req.SSHHostKeyVerification
+ }
if req.Token != nil {
if *req.Token == "" {
@@ -245,25 +254,9 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, br
return err
}
- authConfig := git.AuthConfig{
- AuthType: repository.AuthType,
- Username: repository.Username,
- }
-
- if repository.Token != "" {
- token, err := crypto.Decrypt(repository.Token)
- if err != nil {
- return fmt.Errorf("failed to decrypt token: %w", err)
- }
- authConfig.Token = token
- }
-
- if repository.SSHKey != "" {
- sshKey, err := crypto.Decrypt(repository.SSHKey)
- if err != nil {
- return fmt.Errorf("failed to decrypt SSH key: %w", err)
- }
- authConfig.SSHKey = sshKey
+ authConfig, err := s.GetAuthConfig(ctx, repository)
+ if err != nil {
+ return err
}
if branch == "" {
@@ -303,8 +296,9 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, br
func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *models.GitRepository) (git.AuthConfig, error) {
authConfig := git.AuthConfig{
- AuthType: repository.AuthType,
- Username: repository.Username,
+ AuthType: repository.AuthType,
+ Username: repository.Username,
+ SSHHostKeyVerification: repository.SSHHostKeyVerification,
}
if repository.Token != "" {
@@ -450,6 +444,7 @@ func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.Repository
needsUpdate = utils.UpdateIfChanged(&existing.URL, item.URL) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.AuthType, item.AuthType) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.Username, item.Username) || needsUpdate
+ needsUpdate = utils.UpdateIfChanged(&existing.SSHHostKeyVerification, item.SSHHostKeyVerification) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.Description, item.Description) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.Enabled, item.Enabled) || needsUpdate
@@ -496,15 +491,21 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item git
}
}
+ sshHostKeyVerification := item.SSHHostKeyVerification
+ if sshHostKeyVerification == "" {
+ sshHostKeyVerification = "accept_new"
+ }
+
repo := models.GitRepository{
- Name: item.Name,
- URL: item.URL,
- AuthType: item.AuthType,
- Username: item.Username,
- Token: encryptedToken,
- SSHKey: encryptedSSHKey,
- Description: item.Description,
- Enabled: item.Enabled,
+ Name: item.Name,
+ URL: item.URL,
+ AuthType: item.AuthType,
+ Username: item.Username,
+ Token: encryptedToken,
+ SSHKey: encryptedSSHKey,
+ SSHHostKeyVerification: sshHostKeyVerification,
+ Description: item.Description,
+ Enabled: item.Enabled,
}
repo.ID = item.ID
diff --git a/backend/internal/utils/git/git.go b/backend/internal/utils/git/git.go
index 4963161e2..90c7b672a 100644
--- a/backend/internal/utils/git/git.go
+++ b/backend/internal/utils/git/git.go
@@ -1,7 +1,9 @@
package git
import (
+ "errors"
"fmt"
+ "net"
"os"
"path/filepath"
"sort"
@@ -15,6 +17,9 @@ import (
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
+ "github.com/gofrs/flock"
+ gossh "golang.org/x/crypto/ssh"
+ "golang.org/x/crypto/ssh/knownhosts"
)
// Client handles git operations
@@ -29,12 +34,20 @@ func NewClient(workDir string) *Client {
}
}
+// SSH host key verification modes
+const (
+ SSHHostKeyVerificationStrict = "strict" // Require host key in known_hosts
+ SSHHostKeyVerificationAcceptNew = "accept_new" // Auto-add unknown host keys
+ SSHHostKeyVerificationSkip = "skip" // Skip host key verification (insecure)
+)
+
// AuthConfig holds authentication configuration
type AuthConfig struct {
- AuthType string
- Username string
- Token string
- SSHKey string
+ AuthType string
+ Username string
+ Token string
+ SSHKey string
+ SSHHostKeyVerification string // strict, accept_new, skip
}
// getAuth returns the appropriate transport.AuthMethod
@@ -54,6 +67,16 @@ func (c *Client) getAuth(config AuthConfig) (transport.AuthMethod, error) {
if err != nil {
return nil, fmt.Errorf("failed to create ssh auth: %w", err)
}
+
+ // Configure host key verification based on mode
+ hostKeyCallback, err := c.getSSHHostKeyCallback(config.SSHHostKeyVerification)
+ if err != nil {
+ return nil, fmt.Errorf("failed to configure SSH host key verification: %w", err)
+ }
+ publicKeys.HostKeyCallbackHelper = ssh.HostKeyCallbackHelper{
+ HostKeyCallback: hostKeyCallback,
+ }
+
return publicKeys, nil
}
return nil, fmt.Errorf("ssh key required for ssh authentication")
@@ -64,6 +87,124 @@ func (c *Client) getAuth(config AuthConfig) (transport.AuthMethod, error) {
}
}
+// getSSHHostKeyCallback returns the appropriate SSH host key callback based on verification mode
+func (c *Client) getSSHHostKeyCallback(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:
+ // 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()
+ default:
+ // Fall back to accept_new for unknown modes
+ return c.createAcceptNewHostKeyCallback()
+ }
+}
+
+// createAcceptNewHostKeyCallback creates a callback that accepts new host keys and saves them
+func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error) {
+ knownHostsPath := getKnownHostsPath()
+
+ // Ensure the directory exists
+ dir := filepath.Dir(knownHostsPath)
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return nil, fmt.Errorf("failed to create known_hosts directory: %w", err)
+ }
+
+ // Create the file if it doesn't exist
+ if _, err := os.Stat(knownHostsPath); os.IsNotExist(err) {
+ file, err := os.OpenFile(knownHostsPath, os.O_CREATE|os.O_WRONLY, 0600)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create known_hosts file: %w", err)
+ }
+ if err := file.Close(); err != nil {
+ fmt.Fprintf(os.Stderr, "Warning: failed to close known_hosts file %s: %v\n", knownHostsPath, err)
+ }
+ }
+
+ 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)
+ if err != nil {
+ existingCallback = nil
+ }
+
+ // Check if the host is already known
+ if existingCallback != nil {
+ err := existingCallback(hostname, remote, key)
+ if err == nil {
+ return nil // Host key matches
+ }
+ // Check if it's a "key mismatch" error vs "unknown host"
+ var keyErr *knownhosts.KeyError
+ if errors.As(err, &keyErr) && 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, err)
+ }
+ // Otherwise, host is unknown - we'll add it
+ }
+
+ // Add the new host key to known_hosts
+ if err := addHostKey(knownHostsPath, hostname, key); err != nil {
+ // Log the error but don't fail - still allow the connection
+ // The host key just won't be remembered for next time
+ fmt.Fprintf(os.Stderr, "Warning: failed to save host key for %s: %v\n", hostname, err)
+ }
+
+ return nil
+ }, nil
+}
+
+// getKnownHostsPath returns the path to the known_hosts file
+func getKnownHostsPath() string {
+ // Check environment variable first
+ if path := os.Getenv("SSH_KNOWN_HOSTS"); path != "" {
+ return path
+ }
+
+ // Fall back to default location
+ homeDir, err := os.UserHomeDir()
+ if err != nil {
+ // Use a fallback in the working directory
+ return filepath.Join(os.TempDir(), ".ssh", "known_hosts")
+ }
+ return filepath.Join(homeDir, ".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 err := fileLock.Lock(); err != nil {
+ return fmt.Errorf("failed to acquire lock on known_hosts file: %w", err)
+ }
+ defer fileLock.Unlock() //nolint:errcheck
+
+ // Append to the file
+ file, err := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
+ if err != nil {
+ return fmt.Errorf("failed to open known_hosts file: %w", err)
+ }
+ defer func() {
+ if cerr := file.Close(); cerr != nil && err == nil {
+ err = fmt.Errorf("failed to close known_hosts file: %w", cerr)
+ }
+ }()
+
+ if _, err := file.WriteString(line + "\n"); err != nil {
+ return fmt.Errorf("failed to write to known_hosts file: %w", err)
+ }
+
+ return nil
+}
+
// Clone clones a repository to a temporary directory
func (c *Client) Clone(url, branch string, auth AuthConfig) (string, error) {
// Create a temporary directory
diff --git a/backend/internal/utils/git/git_test.go b/backend/internal/utils/git/git_test.go
new file mode 100644
index 000000000..cad662b0f
--- /dev/null
+++ b/backend/internal/utils/git/git_test.go
@@ -0,0 +1,341 @@
+package git
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ gossh "golang.org/x/crypto/ssh"
+)
+
+func TestGetKnownHostsPath(t *testing.T) {
+ t.Run("returns SSH_KNOWN_HOSTS env var when set", func(t *testing.T) {
+ customPath := "/custom/path/known_hosts"
+ t.Setenv("SSH_KNOWN_HOSTS", customPath)
+
+ result := getKnownHostsPath()
+ if result != customPath {
+ t.Errorf("expected %s, got %s", customPath, result)
+ }
+ })
+
+ t.Run("returns default path when env var not set", func(t *testing.T) {
+ t.Setenv("SSH_KNOWN_HOSTS", "")
+
+ result := getKnownHostsPath()
+ homeDir, _ := os.UserHomeDir()
+ expected := filepath.Join(homeDir, ".ssh", "known_hosts")
+
+ if result != expected {
+ t.Errorf("expected %s, got %s", expected, result)
+ }
+ })
+}
+
+func TestGetSSHHostKeyCallback(t *testing.T) {
+ client := NewClient("")
+
+ t.Run("skip mode returns InsecureIgnoreHostKey", func(t *testing.T) {
+ callback, err := client.getSSHHostKeyCallback(SSHHostKeyVerificationSkip)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if callback == nil {
+ t.Fatal("expected non-nil callback")
+ }
+ // InsecureIgnoreHostKey always returns nil
+ err = callback("example.com:22", &net.TCPAddr{}, nil)
+ if err != nil {
+ t.Errorf("skip mode should not return error, got: %v", err)
+ }
+ })
+
+ t.Run("empty mode defaults to accept_new", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ callback, err := client.getSSHHostKeyCallback("")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if callback == nil {
+ t.Fatal("expected non-nil callback")
+ }
+ })
+
+ t.Run("accept_new mode creates callback", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ callback, err := client.getSSHHostKeyCallback(SSHHostKeyVerificationAcceptNew)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if callback == nil {
+ t.Fatal("expected non-nil callback")
+ }
+ })
+}
+
+func TestAddHostKey(t *testing.T) {
+ t.Run("adds host key to file", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+
+ // Generate a test key
+ key := generateTestPublicKey(t)
+
+ err := addHostKey(knownHostsPath, "example.com:22", key)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ // Verify file was created and contains content
+ content, err := os.ReadFile(knownHostsPath)
+ if err != nil {
+ t.Fatalf("failed to read known_hosts: %v", err)
+ }
+ if len(content) == 0 {
+ t.Error("expected non-empty known_hosts file")
+ }
+ })
+
+ t.Run("concurrent writes don't corrupt file", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ key := generateTestPublicKey(t)
+ var wg sync.WaitGroup
+ errChan := make(chan error, 10)
+
+ // Simulate concurrent writes
+ for i := range 10 {
+ wg.Add(1)
+ go func(idx int) {
+ defer wg.Done()
+ hostname := "host" + string(rune('0'+idx)) + ".example.com:22"
+ if err := addHostKey(knownHostsPath, hostname, key); err != nil {
+ errChan <- err
+ }
+ }(i)
+ }
+
+ wg.Wait()
+ close(errChan)
+
+ for err := range errChan {
+ t.Errorf("concurrent write error: %v", err)
+ }
+
+ // Verify file exists and has content
+ content, err := os.ReadFile(knownHostsPath)
+ if err != nil {
+ t.Fatalf("failed to read known_hosts: %v", err)
+ }
+ if len(content) == 0 {
+ t.Error("expected non-empty known_hosts file after concurrent writes")
+ }
+ })
+}
+
+func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
+ t.Run("creates known_hosts directory and file", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "subdir", "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ client := NewClient("")
+ callback, err := client.createAcceptNewHostKeyCallback()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if callback == nil {
+ t.Fatal("expected non-nil callback")
+ }
+
+ // Verify directory was created
+ if _, err := os.Stat(filepath.Dir(knownHostsPath)); os.IsNotExist(err) {
+ t.Error("expected known_hosts directory to be created")
+ }
+ })
+
+ t.Run("callback adds new host keys", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ client := NewClient("")
+ callback, err := client.createAcceptNewHostKeyCallback()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ key := generateTestPublicKey(t)
+ addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 22}
+
+ err = callback("192.168.1.1:22", addr, key)
+ if err != nil {
+ t.Errorf("callback returned error: %v", err)
+ }
+
+ // Verify host was added to file
+ content, err := os.ReadFile(knownHostsPath)
+ if err != nil {
+ t.Fatalf("failed to read known_hosts: %v", err)
+ }
+ if len(content) == 0 {
+ t.Error("expected host key to be added to known_hosts")
+ }
+ })
+
+ t.Run("callback accepts known host", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ client := NewClient("")
+ callback, err := client.createAcceptNewHostKeyCallback()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ key := generateTestPublicKey(t)
+ addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 22}
+
+ // First call adds the key
+ err = callback("192.168.1.1:22", addr, key)
+ if err != nil {
+ t.Fatalf("first callback returned error: %v", err)
+ }
+
+ // Second call should recognize the known host
+ err = callback("192.168.1.1:22", addr, key)
+ if err != nil {
+ t.Errorf("second callback returned error for known host: %v", err)
+ }
+ })
+
+ t.Run("callback detects host key mismatch", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ knownHostsPath := filepath.Join(tmpDir, "known_hosts")
+ t.Setenv("SSH_KNOWN_HOSTS", knownHostsPath)
+
+ client := NewClient("")
+ callback, err := client.createAcceptNewHostKeyCallback()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ key1 := generateTestPublicKey(t)
+ key2 := generateTestPublicKeyVariant(t)
+ addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 22}
+
+ // First call adds key1
+ err = callback("192.168.1.1:22", addr, key1)
+ if err != nil {
+ t.Fatalf("first callback returned error: %v", err)
+ }
+
+ // Second call with different key for same host should fail
+ err = callback("192.168.1.1:22", addr, key2)
+ if err == nil {
+ t.Error("expected error for host key mismatch, got nil")
+ } else if !strings.Contains(err.Error(), "host key mismatch") {
+ t.Errorf("expected host key mismatch error, got: %v", err)
+ }
+ })
+}
+
+func TestValidatePath(t *testing.T) {
+ t.Run("allows valid paths", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ err := ValidatePath(tmpDir, "subdir/file.txt")
+ if err != nil {
+ t.Errorf("expected valid path to be allowed: %v", err)
+ }
+ })
+
+ t.Run("rejects path traversal", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ err := ValidatePath(tmpDir, "../../../etc/passwd")
+ if err == nil {
+ t.Error("expected path traversal to be rejected")
+ }
+ })
+
+ t.Run("rejects absolute path escape", func(t *testing.T) {
+ tmpDir := t.TempDir()
+ err := ValidatePath(tmpDir, "foo/../../..")
+ if err == nil {
+ t.Error("expected path escape to be rejected")
+ }
+ })
+}
+
+func TestNewClient(t *testing.T) {
+ t.Run("creates client with work dir", func(t *testing.T) {
+ client := NewClient("/tmp/test")
+ if client.workDir != "/tmp/test" {
+ t.Errorf("expected workDir /tmp/test, got %s", client.workDir)
+ }
+ })
+
+ t.Run("creates client with empty work dir", func(t *testing.T) {
+ client := NewClient("")
+ if client.workDir != "" {
+ t.Errorf("expected empty workDir, got %s", client.workDir)
+ }
+ })
+}
+
+// generateTestPublicKey creates a test ED25519 public key for testing
+func generateTestPublicKey(t *testing.T) gossh.PublicKey {
+ t.Helper()
+
+ // Use a fixed ED25519 public key for deterministic tests
+ // This is a valid ED25519 public key format
+ pubKeyBytes := []byte{
+ 0x00, 0x00, 0x00, 0x0b, // key type length (11)
+ 's', 's', 'h', '-', 'e', 'd', '2', '5', '5', '1', '9', // "ssh-ed25519"
+ 0x00, 0x00, 0x00, 0x20, // key length (32)
+ // 32 bytes of key data
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+ 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
+ }
+
+ key, err := gossh.ParsePublicKey(pubKeyBytes)
+ if err != nil {
+ t.Fatalf("failed to parse test public key: %v", err)
+ }
+ return key
+}
+
+// generateTestPublicKeyVariant creates a different test ED25519 public key
+func generateTestPublicKeyVariant(t *testing.T) gossh.PublicKey {
+ t.Helper()
+
+ pubKeyBytes := []byte{
+ 0x00, 0x00, 0x00, 0x0b, // key type length (11)
+ 's', 's', 'h', '-', 'e', 'd', '2', '5', '5', '1', '9', // "ssh-ed25519"
+ 0x00, 0x00, 0x00, 0x20, // key length (32)
+ // 32 bytes of different key data
+ 0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8,
+ 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0,
+ 0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8,
+ 0xE7, 0xE6, 0xE5, 0xE4, 0xE3, 0xE2, 0xE1, 0xE0,
+ }
+
+ key, err := gossh.ParsePublicKey(pubKeyBytes)
+ if err != nil {
+ t.Fatalf("failed to parse test public key variant: %v", err)
+ }
+ return key
+}
diff --git a/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.down.sql b/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.down.sql
new file mode 100644
index 000000000..f476480b3
--- /dev/null
+++ b/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.down.sql
@@ -0,0 +1 @@
+ALTER TABLE git_repositories DROP COLUMN IF EXISTS ssh_host_key_verification;
diff --git a/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.up.sql b/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.up.sql
new file mode 100644
index 000000000..23c4c7178
--- /dev/null
+++ b/backend/resources/migrations/postgres/029_add_ssh_host_key_verification.up.sql
@@ -0,0 +1,3 @@
+-- Add ssh_host_key_verification column to git_repositories table
+-- Values: 'strict' (use known_hosts), 'accept_new' (default - auto-add unknown hosts), 'skip' (disable verification)
+ALTER TABLE git_repositories ADD COLUMN IF NOT EXISTS ssh_host_key_verification TEXT NOT NULL DEFAULT 'accept_new';
diff --git a/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.down.sql b/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.down.sql
new file mode 100644
index 000000000..7ae4b4a5c
--- /dev/null
+++ b/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.down.sql
@@ -0,0 +1,3 @@
+-- SQLite doesn't support DROP COLUMN directly, but we can recreate the table
+-- For simplicity, we'll just leave the column in place (it's harmless)
+-- In production, you'd want to recreate the table without this column
diff --git a/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.up.sql b/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.up.sql
new file mode 100644
index 000000000..b6b8597cc
--- /dev/null
+++ b/backend/resources/migrations/sqlite/029_add_ssh_host_key_verification.up.sql
@@ -0,0 +1,3 @@
+-- Add ssh_host_key_verification column to git_repositories table
+-- Values: 'strict' (use known_hosts), 'accept_new' (default - auto-add unknown hosts), 'skip' (disable verification)
+ALTER TABLE git_repositories ADD COLUMN ssh_host_key_verification TEXT NOT NULL DEFAULT 'accept_new';
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index d12b7131b..07eb90753 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1118,6 +1118,14 @@
"git_repository_remove_message": "Are you sure you want to remove this repository? This will also remove all associated sync configurations.",
"git_repository_ssh_key_label": "SSH Private Key",
"git_repository_ssh_key_placeholder": "Paste your SSH private key here",
+ "git_repository_ssh_host_key_verification": "Host Key Verification",
+ "git_repository_ssh_host_key_verification_description": "How to verify the SSH server's host key. Set SSH_KNOWN_HOSTS env to customize the known_hosts file path.",
+ "git_repository_ssh_host_key_strict": "Strict",
+ "git_repository_ssh_host_key_strict_description": "Require host key in known_hosts file",
+ "git_repository_ssh_host_key_accept_new": "Accept New (Recommended)",
+ "git_repository_ssh_host_key_accept_new_description": "Auto-accept and save new host keys to known_hosts",
+ "git_repository_ssh_host_key_skip": "Skip Verification",
+ "git_repository_ssh_host_key_skip_description": "Disable host key verification (insecure)",
"_comment_customize_Git_syncs": "=== CUSTOMIZATION - GIT SYNCS ===",
"git_syncs_title": "Git Syncs",
"git_syncs_subtitle": "Manage automated synchronization from Git repositories to projects",
diff --git a/frontend/src/lib/components/sheets/git-repository-sheet.svelte b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
index a394cf54a..0eb5d39e9 100644
--- a/frontend/src/lib/components/sheets/git-repository-sheet.svelte
+++ b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
@@ -3,7 +3,6 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import FormInput from '$lib/components/form/form-input.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
- import { Spinner } from '$lib/components/ui/spinner/index.js';
import * as Select from '$lib/components/ui/select/index.js';
import { Textarea } from '$lib/components/ui/textarea/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -11,7 +10,6 @@
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import { m } from '$lib/paraglide/messages';
- import { GitBranchIcon } from '$lib/icons';
type GitRepositoryFormProps = {
open: boolean;
@@ -31,6 +29,7 @@
username: z.string().optional(),
token: z.string().optional(),
sshKey: z.string().optional(),
+ sshHostKeyVerification: z.enum(['strict', 'accept_new', 'skip']).default('accept_new'),
description: z.string().optional(),
enabled: z.boolean().default(true)
});
@@ -42,6 +41,9 @@
username: open && repositoryToEdit ? repositoryToEdit.username || '' : '',
token: '',
sshKey: '',
+ sshHostKeyVerification: (open && repositoryToEdit
+ ? repositoryToEdit.sshHostKeyVerification || 'accept_new'
+ : 'accept_new') as 'strict' | 'accept_new' | 'skip',
description: open && repositoryToEdit ? repositoryToEdit.description || '' : '',
enabled: open && repositoryToEdit ? (repositoryToEdit.enabled ?? true) : true
});
@@ -53,6 +55,11 @@
label: m.git_repository_auth_http()
});
+ let selectedSshHostKeyVerification = $state<{ value: string; label: string }>({
+ value: 'accept_new',
+ label: m.git_repository_ssh_host_key_accept_new()
+ });
+
function getAuthTypeLabel(type: string): string {
switch (type) {
case 'http':
@@ -64,14 +71,30 @@
}
}
+ function getSshHostKeyVerificationLabel(mode: string): string {
+ switch (mode) {
+ case 'strict':
+ return m.git_repository_ssh_host_key_strict();
+ case 'skip':
+ return m.git_repository_ssh_host_key_skip();
+ default:
+ return m.git_repository_ssh_host_key_accept_new();
+ }
+ }
+
$effect(() => {
if (open && repositoryToEdit) {
selectedAuthType = {
value: repositoryToEdit.authType,
label: getAuthTypeLabel(repositoryToEdit.authType)
};
+ selectedSshHostKeyVerification = {
+ value: repositoryToEdit.sshHostKeyVerification || 'accept_new',
+ label: getSshHostKeyVerificationLabel(repositoryToEdit.sshHostKeyVerification || 'accept_new')
+ };
} else if (open && !repositoryToEdit) {
selectedAuthType = { value: 'http', label: m.git_repository_auth_http() };
+ selectedSshHostKeyVerification = { value: 'accept_new', label: m.git_repository_ssh_host_key_accept_new() };
}
});
@@ -92,6 +115,7 @@
if (data.token) payload.token = data.token;
} else if (selectedAuthType.value === 'ssh') {
if (data.sshKey) payload.sshKey = data.sshKey;
+ payload.sshHostKeyVerification = selectedSshHostKeyVerification.value;
}
onSubmit({ repository: payload, isEditMode });
@@ -138,7 +162,7 @@
}
}}
>
- <Select.Trigger id="authType">
+ <Select.Trigger id="authType" class="w-full">
<span>{selectedAuthType.label}</span>
</Select.Trigger>
<Select.Content>
@@ -170,6 +194,45 @@
/>
</div>
{/if}
+
+ <div class="space-y-2">
+ <Label for="sshHostKeyVerification">{m.git_repository_ssh_host_key_verification()}</Label>
+ <Select.Root
+ type="single"
+ bind:value={selectedSshHostKeyVerification.value}
+ onValueChange={(v) => {
+ if (v) {
+ selectedSshHostKeyVerification = { value: v, label: getSshHostKeyVerificationLabel(v) };
+ $inputs.sshHostKeyVerification.value = v as any;
+ }
+ }}
+ >
+ <Select.Trigger id="sshHostKeyVerification" class="w-full">
+ <span>{selectedSshHostKeyVerification.label}</span>
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="accept_new">
+ <div class="flex flex-col">
+ <span>{m.git_repository_ssh_host_key_accept_new()}</span>
+ <span class="text-muted-foreground text-xs">{m.git_repository_ssh_host_key_accept_new_description()}</span>
+ </div>
+ </Select.Item>
+ <Select.Item value="strict">
+ <div class="flex flex-col">
+ <span>{m.git_repository_ssh_host_key_strict()}</span>
+ <span class="text-muted-foreground text-xs">{m.git_repository_ssh_host_key_strict_description()}</span>
+ </div>
+ </Select.Item>
+ <Select.Item value="skip">
+ <div class="flex flex-col">
+ <span>{m.git_repository_ssh_host_key_skip()}</span>
+ <span class="text-muted-foreground text-xs">{m.git_repository_ssh_host_key_skip_description()}</span>
+ </div>
+ </Select.Item>
+ </Select.Content>
+ </Select.Root>
+ <p class="text-muted-foreground text-xs">{m.git_repository_ssh_host_key_verification_description()}</p>
+ </div>
{/if}
<FormInput
diff --git a/frontend/src/lib/types/gitops.type.ts b/frontend/src/lib/types/gitops.type.ts
index 527d75212..cd6f6bab1 100644
--- a/frontend/src/lib/types/gitops.type.ts
+++ b/frontend/src/lib/types/gitops.type.ts
@@ -5,6 +5,7 @@ export interface GitRepositoryCreateDto {
username?: string;
token?: string;
sshKey?: string;
+ sshHostKeyVerification?: string;
description?: string;
enabled?: boolean;
}
@@ -16,6 +17,7 @@ export interface GitRepositoryUpdateDto {
username?: string;
token?: string;
sshKey?: string;
+ sshHostKeyVerification?: string;
description?: string;
enabled?: boolean;
}
@@ -26,6 +28,7 @@ export interface GitRepository {
url: string;
authType: string;
username?: string;
+ sshHostKeyVerification?: string;
description?: string;
enabled: boolean;
createdAt: string;
diff --git a/types/gitops/gitops.go b/types/gitops/gitops.go
index 3fe278a9c..222dba416 100644
--- a/types/gitops/gitops.go
+++ b/types/gitops/gitops.go
@@ -29,6 +29,11 @@ type GitRepository struct {
// Required: false
Username string `json:"username,omitempty"`
+ // SSHHostKeyVerification specifies how SSH host keys are verified (strict, accept_new, skip).
+ //
+ // Required: false
+ SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty"`
+
// Description of the git repository.
//
// Required: false
@@ -175,6 +180,13 @@ type CreateRepositoryRequest struct {
// Required: false
SSHKey string `json:"sshKey,omitempty"`
+ // SSHHostKeyVerification specifies how SSH host keys are verified.
+ // Options: strict (require known_hosts), accept_new (auto-add new hosts), skip (disable verification).
+ // Default: accept_new
+ //
+ // Required: false
+ SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty"`
+
// Description of the git repository.
//
// Required: false
@@ -218,6 +230,12 @@ type UpdateRepositoryRequest struct {
// Required: false
SSHKey *string `json:"sshKey,omitempty"`
+ // SSHHostKeyVerification specifies how SSH host keys are verified.
+ // Options: strict (require known_hosts), accept_new (auto-add new hosts), skip (disable verification).
+ //
+ // Required: false
+ SSHHostKeyVerification *string `json:"sshHostKeyVerification,omitempty"`
+
// Description of the git repository.
//
// Required: false
@@ -457,6 +475,11 @@ type RepositorySync struct {
// Required: false
SSHKey string `json:"sshKey,omitempty"`
+ // SSHHostKeyVerification specifies how SSH host keys are verified.
+ //
+ // Required: false
+ SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty"`
+
// Description of the git repository.
//
// Required: false