selectSSHKeys evaluates available key pairs and select which should be used to connect to the codespace using the precedence rules below. If there is no error, a keypair is always returned and additionally a bool flag is returned to specify if the private key need be appended to the ssh arguments (i
( ctx context.Context, sshContext ssh.Context, args []string, opts sshOptions, )
| 321 | // 3. First valid keypair in ssh config (according to ssh -G) |
| 322 | // 4. Automatic key, newly created |
| 323 | func selectSSHKeys( |
| 324 | ctx context.Context, |
| 325 | sshContext ssh.Context, |
| 326 | args []string, |
| 327 | opts sshOptions, |
| 328 | ) (*ssh.KeyPair, bool, error) { |
| 329 | customConfigPath := "" |
| 330 | for i := 0; i < len(args); i += 1 { |
| 331 | arg := args[i] |
| 332 | |
| 333 | if arg == "-i" { |
| 334 | if i+1 >= len(args) { |
| 335 | return nil, false, errors.New("missing value to -i argument") |
| 336 | } |
| 337 | |
| 338 | privateKeyPath := args[i+1] |
| 339 | |
| 340 | // The --config setup will set the automatic key with -i, but it might not actually be created, so we need to ensure that here |
| 341 | if automaticPrivateKeyPath, _ := automaticPrivateKeyPath(sshContext); automaticPrivateKeyPath == privateKeyPath { |
| 342 | _, err := generateAutomaticSSHKeys(sshContext) |
| 343 | if err != nil { |
| 344 | return nil, false, fmt.Errorf("generating automatic keypair: %w", err) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // User manually specified an identity file so just trust it is correct |
| 349 | return &ssh.KeyPair{ |
| 350 | PrivateKeyPath: privateKeyPath, |
| 351 | PublicKeyPath: privateKeyPath + ".pub", |
| 352 | }, false, nil |
| 353 | } |
| 354 | |
| 355 | if arg == "-F" && i+1 < len(args) { |
| 356 | // ssh only pays attention to that last specified -F value, so it's correct to overwrite here |
| 357 | customConfigPath = args[i+1] |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | if autoKeyPair := automaticSSHKeyPair(sshContext); autoKeyPair != nil { |
| 362 | // If the automatic keys already exist, just use them |
| 363 | return autoKeyPair, true, nil |
| 364 | } |
| 365 | |
| 366 | keyPair, err := firstConfiguredKeyPair(ctx, customConfigPath, opts.profile) |
| 367 | if err != nil { |
| 368 | if !errors.Is(err, errKeyFileNotFound) { |
| 369 | return nil, false, fmt.Errorf("checking configured keys: %w", err) |
| 370 | } |
| 371 | |
| 372 | // no valid key in ssh config, generate one |
| 373 | keyPair, err = generateAutomaticSSHKeys(sshContext) |
| 374 | if err != nil { |
| 375 | return nil, false, fmt.Errorf("generating automatic keypair: %w", err) |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | return keyPair, true, nil |
| 380 | } |