better-argo-tunnels/internal/server/keyutil.go

45 lines
1.0 KiB
Go

package server
import (
"fmt"
"os"
"strings"
"golang.org/x/crypto/ssh"
)
// LoadSigner loads an SSH private key from either a file path or raw PEM content.
// If the value starts with "/" or "./" or "~", it's treated as a file path.
// If it contains "-----BEGIN", it's treated as raw PEM content.
func LoadSigner(keyOrPath string) (ssh.Signer, error) {
var keyBytes []byte
if isFilePath(keyOrPath) {
data, err := os.ReadFile(keyOrPath)
if err != nil {
return nil, fmt.Errorf("read key file %s: %w", keyOrPath, err)
}
keyBytes = data
} else {
keyBytes = []byte(keyOrPath)
}
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return nil, fmt.Errorf("parse private key: %w", err)
}
return signer, nil
}
// isFilePath heuristic: paths start with / ./ ~ or don't contain PEM markers.
func isFilePath(v string) bool {
if strings.HasPrefix(v, "/") || strings.HasPrefix(v, "./") || strings.HasPrefix(v, "~") {
return true
}
if !strings.Contains(v, "-----BEGIN") {
return true
}
return false
}