-
Notifications
You must be signed in to change notification settings - Fork 152
SSH: fix Include directive escaping and refactor backup logic #4861
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package fileutil | ||
|
|
||
| import ( | ||
| "context" | ||
| "os" | ||
| "path/filepath" | ||
|
|
||
| "github.com/databricks/cli/libs/log" | ||
| ) | ||
|
|
||
| const ( | ||
| SuffixOriginalBak = ".original.bak" | ||
| SuffixLatestBak = ".latest.bak" | ||
| ) | ||
|
|
||
| // BackupFile saves data to path+".original.bak" on the first call, and | ||
| // path+".latest.bak" on subsequent calls. Skips if data is empty. | ||
| func BackupFile(ctx context.Context, path string, data []byte) error { | ||
| if len(data) == 0 { | ||
| return nil | ||
| } | ||
| originalBak := path + SuffixOriginalBak | ||
| latestBak := path + SuffixLatestBak | ||
| var bakPath string | ||
| if _, err := os.Stat(originalBak); os.IsNotExist(err) { | ||
| bakPath = originalBak | ||
| } else { | ||
| bakPath = latestBak | ||
| } | ||
| if err := os.WriteFile(bakPath, data, 0o600); err != nil { | ||
| return err | ||
| } | ||
| log.Infof(ctx, "Backed up %s to %s", filepath.ToSlash(path), filepath.ToSlash(bakPath)) | ||
| return nil | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package fileutil_test | ||
|
|
||
| import ( | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/databricks/cli/experimental/ssh/internal/fileutil" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestBackupFile_EmptyData(t *testing.T) { | ||
| tmpDir := t.TempDir() | ||
| path := filepath.Join(tmpDir, "file.json") | ||
|
|
||
| err := fileutil.BackupFile(t.Context(), path, []byte{}) | ||
| require.NoError(t, err) | ||
|
|
||
| _, err = os.Stat(path + fileutil.SuffixOriginalBak) | ||
| assert.True(t, os.IsNotExist(err)) | ||
| } | ||
|
|
||
| func TestBackupFile_FirstBackup(t *testing.T) { | ||
| tmpDir := t.TempDir() | ||
| path := filepath.Join(tmpDir, "file.json") | ||
| data := []byte(`{"key": "value"}`) | ||
|
|
||
| err := fileutil.BackupFile(t.Context(), path, data) | ||
| require.NoError(t, err) | ||
|
|
||
| content, err := os.ReadFile(path + fileutil.SuffixOriginalBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, data, content) | ||
|
|
||
| _, err = os.Stat(path + fileutil.SuffixLatestBak) | ||
| assert.True(t, os.IsNotExist(err)) | ||
| } | ||
|
|
||
| func TestBackupFile_SubsequentBackup(t *testing.T) { | ||
| tmpDir := t.TempDir() | ||
| path := filepath.Join(tmpDir, "file.json") | ||
| original := []byte(`{"key": "value"}`) | ||
| updated := []byte(`{"key": "updated"}`) | ||
|
|
||
| err := fileutil.BackupFile(t.Context(), path, original) | ||
| require.NoError(t, err) | ||
|
|
||
| err = fileutil.BackupFile(t.Context(), path, updated) | ||
| require.NoError(t, err) | ||
|
|
||
| // .original.bak must remain unchanged | ||
| content, err := os.ReadFile(path + fileutil.SuffixOriginalBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, original, content) | ||
|
|
||
| // .latest.bak should have the updated content | ||
| content, err = os.ReadFile(path + fileutil.SuffixLatestBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, updated, content) | ||
| } | ||
|
|
||
| func TestBackupFile_WriteError(t *testing.T) { | ||
| err := fileutil.BackupFile(t.Context(), "/nonexistent/dir/file.json", []byte("data")) | ||
| assert.Error(t, err) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ import ( | |
| "path/filepath" | ||
| "strings" | ||
|
|
||
| "github.com/databricks/cli/experimental/ssh/internal/fileutil" | ||
| "github.com/databricks/cli/libs/cmdio" | ||
| "github.com/databricks/cli/libs/env" | ||
| ) | ||
|
|
@@ -80,11 +81,25 @@ func EnsureIncludeDirective(ctx context.Context, configPath string) error { | |
| // Convert path to forward slashes for SSH config compatibility across platforms | ||
| configDirUnix := filepath.ToSlash(configDir) | ||
|
|
||
| includeLine := fmt.Sprintf("Include %s/*", configDirUnix) | ||
| if strings.Contains(string(content), includeLine) { | ||
| // Quoted to handle paths with spaces; OpenSSH still expands globs inside quotes. | ||
| includeLine := fmt.Sprintf(`Include "%s/*"`, configDirUnix) | ||
| if containsLine(content, includeLine) { | ||
| return nil | ||
| } | ||
|
|
||
| // Migrate unquoted Include written by older versions of the CLI. | ||
| oldIncludeLine := fmt.Sprintf("Include %s/*", configDirUnix) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a subtle mismatch: |
||
| if containsLine(content, oldIncludeLine) { | ||
| if err := fileutil.BackupFile(ctx, configPath, content); err != nil { | ||
| return fmt.Errorf("failed to backup SSH config before migration: %w", err) | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| migrated := strings.Replace(string(content), oldIncludeLine, includeLine, 1) | ||
| return os.WriteFile(configPath, []byte(migrated), 0o600) | ||
| } | ||
|
|
||
| if err := fileutil.BackupFile(ctx, configPath, content); err != nil { | ||
| return fmt.Errorf("failed to backup SSH config: %w", err) | ||
| } | ||
| newContent := includeLine + "\n" | ||
| if len(content) > 0 && !strings.HasPrefix(string(content), "\n") { | ||
| newContent += "\n" | ||
|
|
@@ -99,6 +114,17 @@ func EnsureIncludeDirective(ctx context.Context, configPath string) error { | |
| return nil | ||
| } | ||
|
|
||
| // containsLine reports whether data contains line as an exact line match, | ||
| // trimming \r to handle Windows line endings. | ||
| func containsLine(data []byte, line string) bool { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This does an exact match with no left-side whitespace trimming. SSH config commonly has indented directives — an |
||
| for l := range strings.SplitSeq(string(data), "\n") { | ||
| if strings.TrimRight(l, "\r") == line { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func GetHostConfigPath(ctx context.Context, hostName string) (string, error) { | ||
| configDir, err := GetConfigDir(ctx) | ||
| if err != nil { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,11 +2,13 @@ package vscode | |
|
|
||
| import ( | ||
| "encoding/json" | ||
| "io" | ||
| "os" | ||
| "path/filepath" | ||
| "runtime" | ||
| "testing" | ||
|
|
||
| "github.com/databricks/cli/experimental/ssh/internal/fileutil" | ||
| "github.com/databricks/cli/libs/cmdio" | ||
| "github.com/databricks/cli/libs/env" | ||
| "github.com/stretchr/testify/assert" | ||
|
|
@@ -428,45 +430,38 @@ func TestUpdateSettings_PartialUpdate(t *testing.T) { | |
| assert.Len(t, exts, 2) | ||
| } | ||
|
|
||
| func TestBackupSettings(t *testing.T) { | ||
| tmpDir := t.TempDir() | ||
| settingsPath := filepath.Join(tmpDir, "settings.json") | ||
| originalBak := settingsPath + ".original.bak" | ||
| latestBak := settingsPath + ".latest.bak" | ||
| func TestCheckAndUpdateSettings_CreatesBackup(t *testing.T) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test only verifies that |
||
| if runtime.GOOS == "windows" { | ||
| t.Skip("path setup differs on windows") | ||
| } | ||
|
|
||
| originalContent := []byte(`{"key": "value"}`) | ||
| err := os.WriteFile(settingsPath, originalContent, 0o600) | ||
| require.NoError(t, err) | ||
| tmpDir := t.TempDir() | ||
| t.Setenv("HOME", tmpDir) | ||
|
|
||
| ctx, _ := cmdio.NewTestContextWithStderr(t.Context()) | ||
| ctx, tst := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) | ||
| defer tst.Done() | ||
|
|
||
| // First backup: should create .original.bak | ||
| err = backupSettings(ctx, settingsPath) | ||
| settingsPath, err := getDefaultSettingsPath(ctx, "cursor") | ||
| require.NoError(t, err) | ||
| require.NoError(t, os.MkdirAll(filepath.Dir(settingsPath), 0o755)) | ||
|
|
||
| content, err := os.ReadFile(originalBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, originalContent, content) | ||
| _, err = os.Stat(latestBak) | ||
| assert.True(t, os.IsNotExist(err)) | ||
| // Settings file with no Databricks-required keys → triggers an update prompt. | ||
| originalContent := []byte(`{}`) | ||
| require.NoError(t, os.WriteFile(settingsPath, originalContent, 0o600)) | ||
|
|
||
| // Second backup: .original.bak exists, should create .latest.bak | ||
| updatedContent := []byte(`{"key": "updated"}`) | ||
| err = os.WriteFile(settingsPath, updatedContent, 0o600) | ||
| require.NoError(t, err) | ||
| // Drain stderr (where the prompt is written) and feed "y" to stdin. | ||
| go func() { _, _ = io.Copy(io.Discard, tst.Stderr) }() | ||
| go func() { | ||
| _, _ = tst.Stdin.WriteString("y\n") | ||
| _ = tst.Stdin.Flush() | ||
| }() | ||
|
|
||
| err = backupSettings(ctx, settingsPath) | ||
| err = CheckAndUpdateSettings(ctx, "cursor", "my-host") | ||
| require.NoError(t, err) | ||
|
|
||
| // .original.bak must remain unchanged | ||
| content, err = os.ReadFile(originalBak) | ||
| content, err := os.ReadFile(settingsPath + fileutil.SuffixOriginalBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, originalContent, content) | ||
|
|
||
| // .latest.bak should have the updated content | ||
| content, err = os.ReadFile(latestBak) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, updatedContent, content) | ||
| } | ||
|
|
||
| func TestSaveSettings_Formatting(t *testing.T) { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
os.Statreturns an error that is notIsNotExist(e.g. permission denied on the directory), the code silently falls through tolatestBak. This could mask real filesystem errors. Consider checkingerr != nil && !os.IsNotExist(err)and returning the error in that case.