Skip to content

Commit 873e320

Browse files
committed
fix: create ssh conf directory if it doesn't exist
1 parent 29bce8d commit 873e320

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

cli/configssh.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,12 @@ func (r *RootCmd) configSSH() *serpent.Command {
440440
}
441441

442442
if !bytes.Equal(configRaw, configModified) {
443+
// Ensure the parent directory exists before writing the file
444+
sshDir := filepath.Dir(sshConfigFile)
445+
if err := os.MkdirAll(sshDir, os.ModePerm); err != nil {
446+
return xerrors.Errorf("failed to create directory %q: %w", sshDir, err)
447+
}
448+
443449
err = atomic.WriteFile(sshConfigFile, bytes.NewReader(configModified))
444450
if err != nil {
445451
return xerrors.Errorf("write ssh config failed: %w", err)

cli/configssh_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,47 @@ func TestConfigSSH(t *testing.T) {
169169
<-copyDone
170170
}
171171

172+
func TestConfigSSH_MissingDirectory(t *testing.T) {
173+
t.Parallel()
174+
175+
if runtime.GOOS == "windows" {
176+
t.Skip("See coder/internal#117")
177+
}
178+
179+
client := coderdtest.New(t, nil)
180+
_ = coderdtest.CreateFirstUser(t, client)
181+
182+
// Create a temporary directory but don't create .ssh subdirectory
183+
tmpdir := t.TempDir()
184+
sshConfigPath := filepath.Join(tmpdir, ".ssh", "config")
185+
186+
// Run config-ssh with a non-existent .ssh directory
187+
args := []string{
188+
"config-ssh",
189+
"--ssh-config-file", sshConfigPath,
190+
"--yes", // Skip confirmation prompts
191+
}
192+
inv, root := clitest.New(t, args...)
193+
clitest.SetupConfig(t, client, root)
194+
195+
err := inv.Run()
196+
require.NoError(t, err, "config-ssh should succeed with non-existent directory")
197+
198+
// Verify that the .ssh directory was created
199+
sshDir := filepath.Dir(sshConfigPath)
200+
_, err = os.Stat(sshDir)
201+
require.NoError(t, err, ".ssh directory should exist")
202+
203+
// Verify that the config file was created
204+
_, err = os.Stat(sshConfigPath)
205+
require.NoError(t, err, "config file should exist")
206+
207+
// Check that the directory has proper permissions (0700)
208+
sshDirInfo, err := os.Stat(sshDir)
209+
require.NoError(t, err)
210+
require.Equal(t, os.FileMode(os.ModePerm), sshDirInfo.Mode().Perm(), "directory should have 0700 permissions")
211+
}
212+
172213
func TestConfigSSH_FileWriteAndOptionsFlow(t *testing.T) {
173214
t.Parallel()
174215

0 commit comments

Comments
 (0)