Skip to content

Commit c5c3a54

Browse files
authored
fix: create ssh directory if it doesn't already exist when running coder config-ssh (coder#17711)
Closes [coder/internal#623](coder/internal#623) > [!WARNING] > PR co-authored by Claude Code
1 parent 1bb96b8 commit c5c3a54

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

cli/configssh.go

+5
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,11 @@ func (r *RootCmd) configSSH() *serpent.Command {
440440
}
441441

442442
if !bytes.Equal(configRaw, configModified) {
443+
sshDir := filepath.Dir(sshConfigFile)
444+
if err := os.MkdirAll(sshDir, 0700); err != nil {
445+
return xerrors.Errorf("failed to create directory %q: %w", sshDir, err)
446+
}
447+
443448
err = atomic.WriteFile(sshConfigFile, bytes.NewReader(configModified))
444449
if err != nil {
445450
return xerrors.Errorf("write ssh config failed: %w", err)

cli/configssh_test.go

+41
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(0700), 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)