From 4027234f60e38e4aea0e0d3bb613079d3ee5847c Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 00:03:24 -0600 Subject: [PATCH 1/9] fix(ssh): support tilde private-key signing --- e2e/tests/ssh/ssh.go | 171 ++++++++++++++- pkg/agent/tunnelserver/options.go | 8 + pkg/agent/tunnelserver/tunnelserver.go | 9 +- .../tunnelserver/tunnelserver_gitssh_test.go | 51 +++++ pkg/credentials/integration_test.go | 126 +++++++++++ pkg/gitsshsigning/client.go | 58 +++-- pkg/gitsshsigning/client_test.go | 200 ++++++++++++++++- pkg/gitsshsigning/helper.go | 20 +- pkg/gitsshsigning/helper_test.go | 72 ++++++ pkg/gitsshsigning/key.go | 200 +++++++++++++++++ pkg/gitsshsigning/server.go | 81 ++++--- pkg/gitsshsigning/server_test.go | 206 ++++++++++++++++-- pkg/gitsshsigning/utils.go | 72 ++++++ pkg/gitsshsigning/utils_test.go | 152 ++++++++++++- pkg/tunnel/services.go | 105 +++++---- pkg/tunnel/services_test.go | 75 ++++++- 16 files changed, 1461 insertions(+), 145 deletions(-) create mode 100644 pkg/gitsshsigning/key.go diff --git a/e2e/tests/ssh/ssh.go b/e2e/tests/ssh/ssh.go index aa6f576eeb..2daf4a65dd 100644 --- a/e2e/tests/ssh/ssh.go +++ b/e2e/tests/ssh/ssh.go @@ -2,6 +2,7 @@ package ssh import ( "context" + "encoding/base64" "math/rand" "net" "os" @@ -29,6 +30,12 @@ const ( sshOptStrictHostKeyCheckingNo = "StrictHostKeyChecking=no" sshOptUserKnownHostsFileNull = "UserKnownHostsFile=/dev/null" sshOptForwardAgentNo = "ForwardAgent=no" + + gitCfgUserNameCmd = "git config user.name 'Test User'" + gitCfgUserEmailCmd = "git config user.email 'test@example.com'" + gitCfgCommitSignCmd = "git config commit.gpgsign true" + gitAddFileCmd = "git add file.txt" + gitVerifyCommitCmd = "git verify-commit HEAD 2>&1" ) var _ = ginkgo.Describe( @@ -206,16 +213,16 @@ var _ = ginkgo.Describe("devsy ssh test suite", ginkgo.Label("ssh"), ginkgo.Orde "cd /tmp", "git init test-sign-repo", "cd test-sign-repo", - "git config user.name 'Test User'", - "git config user.email 'test@example.com'", - "git config commit.gpgsign true", + gitCfgUserNameCmd, + gitCfgUserEmailCmd, + gitCfgCommitSignCmd, "echo test > testfile", "git add testfile", "git commit -m 'signed test commit' 2>&1", "ssh-add -L | head -1 > /tmp/test_signing_key.pub", "git config --global user.signingkey /tmp/test_signing_key.pub", "echo world >> file.txt", - "git add file.txt", + gitAddFileCmd, "git commit -m 'signed commit with file path key' 2>&1", }, " && ") @@ -253,7 +260,7 @@ var _ = ginkgo.Describe("devsy ssh test suite", ginkgo.Label("ssh"), ginkgo.Orde "cd /tmp/test-sign-repo", "echo 'test@example.com " + pubKey + "' > /tmp/allowed_signers", "git config gpg.ssh.allowedSignersFile /tmp/allowed_signers", - "git verify-commit HEAD 2>&1", + gitVerifyCommitCmd, }, " && ") stdout, stderr, err = f.ExecCommandCapture(ctx, @@ -359,9 +366,9 @@ var _ = ginkgo.Describe("devsy ssh test suite", ginkgo.Label("ssh"), ginkgo.Orde "cd /tmp", "git init test-sign-err-repo", "cd test-sign-err-repo", - "git config user.name 'Test User'", - "git config user.email 'test@example.com'", - "git config commit.gpgsign true", + gitCfgUserNameCmd, + gitCfgUserEmailCmd, + gitCfgCommitSignCmd, "echo test > testfile", "git add testfile", "git commit -m 'signed test commit' 2>&1", @@ -392,6 +399,66 @@ var _ = ginkgo.Describe("devsy ssh test suite", ginkgo.Label("ssh"), ginkgo.Orde }, ) + ginkgo.It( + "should sign commits via default relay using a tilde private key without ssh-agent", + ginkgo.SpecTimeout(framework.TimeoutLong()), + func(ctx ginkgo.SpecContext) { + if runtime.GOOS == osWindows { + ginkgo.Skip("skipping on windows") + } + + privKeyBase64, pubKey := setupIsolatedTildeSigningHome() + + tempDir, err := framework.CopyToTempDir("tests/ssh/testdata/ssh-signing") + framework.ExpectNoError(err) + + f := framework.NewDefaultFramework(filepath.Join(initialDir, "bin")) + _ = f.DevsyProviderAdd(ctx, "docker") + err = f.DevsyProviderUse(ctx, "docker") + framework.ExpectNoError(err) + + ginkgo.DeferCleanup(func(cleanupCtx context.Context) { + _ = f.DevsyWorkspaceDelete(cleanupCtx, tempDir) + framework.CleanupTempDir(initialDir, tempDir) + }) + + err = f.DevsyUp(ctx, tempDir) + framework.ExpectNoError(err) + + signCmd := buildTildeSigningScript(privKeyBase64, pubKey) + stdout, stderr, err := f.ExecCommandCapture(ctx, []string{ + cmdWorkspace, + cmdSSH, + names.Flag(names.StartServices), + tempDir, + names.Flag(names.Command), + signCmd, + }) + ginkgo.GinkgoWriter.Printf("tilde signing stdout: %s\n", stdout) + ginkgo.GinkgoWriter.Printf("tilde signing stderr: %s\n", stderr) + framework.ExpectNoError(err) + + const goodSig = `Good "git" signature` + combined := stdout + stderr + gomega.Expect(combined).To( + gomega.ContainSubstring("signed via default tilde relay"), + "commit signed via host-forwarded tilde key should succeed", + ) + gomega.Expect(combined).To( + gomega.ContainSubstring("signed via workspace tilde override"), + "commit signed via workspace repo-local tilde private key should succeed", + ) + gomega.Expect(combined).To( + gomega.ContainSubstring(goodSig), + "git verify-commit should report a valid SSH signature", + ) + gomega.Expect(strings.Count(combined, goodSig)).To( + gomega.Equal(2), + "both signed commits should verify with Good \"git\" signature", + ) + }, + ) + ginkgo.It( "should start a new workspace with a docker provider (default) and forward a port into it", ginkgo.SpecTimeout(framework.TimeoutShort()), @@ -502,3 +569,91 @@ func setupSSHWorkspace( return f, tempDir } + +func setupIsolatedTildeSigningHome() (string, string) { + t := ginkgo.GinkgoT() + origHome, err := os.UserHomeDir() + framework.ExpectNoError(err) + if os.Getenv("DOCKER_CONFIG") == "" && origHome != "" { + t.Setenv("DOCKER_CONFIG", filepath.Join(origHome, ".docker")) + } + + hostHome := t.TempDir() + t.Setenv("HOME", hostHome) + t.Setenv("DEVSY_HOME", filepath.Join(hostHome, ".devsy")) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv(envSSHAuthSock, "") + + return writeTildeSigningKeyAndGitConfig(hostHome) +} + +func writeTildeSigningKeyAndGitConfig(hostHome string) (string, string) { + sshDir := filepath.Join(hostHome, ".ssh") + framework.ExpectNoError(os.MkdirAll(sshDir, 0o700)) + + keyPath := filepath.Join(sshDir, "git_signing_ed25519") + // #nosec G204 -- test command with controlled arguments + err := exec.Command( + "ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-q", + ).Run() + framework.ExpectNoError(err) + + gitConfig := "[user]\n" + + "\tsigningkey = ~/.ssh/git_signing_ed25519\n" + + "[gpg]\n" + + "\tformat = ssh\n" + + "[commit]\n" + + "\tgpgsign = true\n" + err = os.WriteFile(filepath.Join(hostHome, ".gitconfig"), []byte(gitConfig), 0o600) + framework.ExpectNoError(err) + + // #nosec G304 -- test file with controlled path + privKeyBytes, err := os.ReadFile(keyPath) + framework.ExpectNoError(err) + + // #nosec G304 -- test file with controlled path + pubKeyBytes, err := os.ReadFile(keyPath + ".pub") + framework.ExpectNoError(err) + + return base64.StdEncoding.EncodeToString(privKeyBytes), + strings.TrimSpace(string(pubKeyBytes)) +} + +func buildTildeSigningScript(privKeyBase64, pubKey string) string { + allowedSignersBase64 := base64.StdEncoding.EncodeToString( + []byte("test@example.com " + pubKey + "\n"), + ) + waitForHelperCmd := "for i in $(seq 1 30); do " + + "test -x /usr/local/bin/devsy-ssh-signature && " + + "test \"$(git config --global gpg.ssh.program)\" = devsy-ssh-signature && " + + "break; sleep 1; done" + + return strings.Join([]string{ + "mkdir -p ~/.ssh", + "chmod 700 ~/.ssh", + "printf '%s' '" + privKeyBase64 + "' | base64 -d > ~/.ssh/git_signing_ed25519", + "chmod 600 ~/.ssh/git_signing_ed25519", + waitForHelperCmd, + "test -x /usr/local/bin/devsy-ssh-signature", + "test \"$(git config --global gpg.ssh.program)\" = devsy-ssh-signature", + "test \"$(git config --global gpg.format)\" = ssh", + "rm -rf /tmp/test-tilde-sign-repo", + "git init /tmp/test-tilde-sign-repo", + "cd /tmp/test-tilde-sign-repo", + gitCfgUserNameCmd, + gitCfgUserEmailCmd, + gitCfgCommitSignCmd, + "printf '%s' '" + allowedSignersBase64 + "' | base64 -d > /tmp/tilde_allowed_signers", + "git config gpg.ssh.allowedSignersFile /tmp/tilde_allowed_signers", + "echo first > file.txt", + gitAddFileCmd, + "git commit -m 'signed via default tilde relay' 2>&1", + gitVerifyCommitCmd, + "git config user.signingkey '~/.ssh/git_signing_ed25519'", + "echo second >> file.txt", + gitAddFileCmd, + "git commit -m 'signed via workspace tilde override' 2>&1", + gitVerifyCommitCmd, + }, " && ") +} diff --git a/pkg/agent/tunnelserver/options.go b/pkg/agent/tunnelserver/options.go index 07fa6c0b37..a44558680d 100644 --- a/pkg/agent/tunnelserver/options.go +++ b/pkg/agent/tunnelserver/options.go @@ -96,6 +96,14 @@ func WithGitToken(token *provider2.GitToken) Option { } } +// WithGitSSHSigningKey configures the host Git SSH signing key for fallback resolution. +func WithGitSSHSigningKey(signingKey string) Option { + return func(s *tunnelServer) *tunnelServer { + s.gitSSHSigningKey = signingKey + return s + } +} + // WithStatusReporter forwards inbound StatusUpdate RPCs to reporter. A nil // reporter is ignored, since it would replace the Nop default and panic. func WithStatusReporter(reporter status.Reporter) Option { diff --git a/pkg/agent/tunnelserver/tunnelserver.go b/pkg/agent/tunnelserver/tunnelserver.go index 86b6489506..be50b26029 100644 --- a/pkg/agent/tunnelserver/tunnelserver.go +++ b/pkg/agent/tunnelserver/tunnelserver.go @@ -152,9 +152,10 @@ type tunnelServer struct { result *config.Result workspace *provider2.Workspace - platformOptions *devsy.PlatformOptions - secrets []*tunnel.Secret - gitToken *provider2.GitToken + platformOptions *devsy.PlatformOptions + secrets []*tunnel.Secret + gitToken *provider2.GitToken + gitSSHSigningKey string statusReporter status.Reporter } @@ -394,7 +395,7 @@ func (t *tunnelServer) GitSSHSignature( return nil, fmt.Errorf("git ssh sign request: %w", err) } - signatureResponse, err := signatureRequest.Sign() + signatureResponse, err := signatureRequest.SignWithHostKey(t.gitSSHSigningKey) if err != nil { return nil, fmt.Errorf("get git ssh signature: %w", err) } diff --git a/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go b/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go index 3eda1c532b..d55a0932de 100644 --- a/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go +++ b/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go @@ -3,6 +3,10 @@ package tunnelserver import ( "context" "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" "testing" "github.com/devsy-org/devsy/pkg/agent/tunnel" @@ -30,3 +34,50 @@ func TestGitSSHSignature_DeserializesPublicKey(t *testing.T) { assert.NotContains(t, err.Error(), "resolve signing key") assert.Contains(t, err.Error(), "failed to sign commit") } + +func TestGitSSHSignature_SignsWithHostKeyWithoutSSHAgent(t *testing.T) { + hostHome := t.TempDir() + t.Setenv("HOME", hostHome) + t.Setenv("SSH_AUTH_SOCK", "") + + sshDir := filepath.Join(hostHome, ".ssh") + require.NoError(t, os.MkdirAll(sshDir, 0o700)) + + privKeyPath := filepath.Join(sshDir, "git_signing_ed25519") + //nolint:gosec // test-only ssh-keygen invocation under t.TempDir. + genOut, err := exec.Command( + "ssh-keygen", + "-t", + "ed25519", + "-N", + "", + "-f", + privKeyPath, + ).CombinedOutput() + require.NoError(t, err, "ssh-keygen failed: %s", string(genOut)) + + // #nosec G304 -- test file path under t.TempDir. + pubKeyBytes, err := os.ReadFile(privKeyPath + ".pub") + require.NoError(t, err) + + req := gitsshsigning.GitSSHSignatureRequest{ + Content: "tree abc\nauthor Test 1700000000 +0000\n\ncommit\n", + KeyPath: "/home/vscode/.ssh/git_signing_ed25519", + PublicKey: strings.TrimSpace(string(pubKeyBytes)), + Namespace: "git", + } + reqJSON, err := json.Marshal(req) + require.NoError(t, err) + + ts := New(WithGitSSHSigningKey("~/.ssh/git_signing_ed25519")) + + respMsg, err := ts.GitSSHSignature(context.Background(), &tunnel.Message{ + Message: string(reqJSON), + }) + require.NoError(t, err) + + var sigResp gitsshsigning.GitSSHSignatureResponse + require.NoError(t, json.Unmarshal([]byte(respMsg.Message), &sigResp)) + assert.Contains(t, string(sigResp.Signature), "-----BEGIN SSH SIGNATURE-----") + assert.Contains(t, string(sigResp.Signature), "-----END SSH SIGNATURE-----") +} diff --git a/pkg/credentials/integration_test.go b/pkg/credentials/integration_test.go index 8974c425c8..98e8a60f19 100644 --- a/pkg/credentials/integration_test.go +++ b/pkg/credentials/integration_test.go @@ -1,13 +1,16 @@ package credentials import ( + "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" + "os/exec" "path/filepath" + "strings" "testing" "github.com/devsy-org/devsy/pkg/agent/tunnel" @@ -137,3 +140,126 @@ func TestIntegration_SignatureRequest_IncludesPublicKeyContent(t *testing.T) { assert.Equal(t, pubKeyContent, req.PublicKey) assert.Equal(t, "commit content", req.Content) } + +func TestIntegration_EndToEndPrivateKeyRelayWithoutSSHAgent(t *testing.T) { + t.Setenv("SSH_AUTH_SOCK", "") + + hostPrivKey, pubKeyLine := generateDisposableEd25519KeyPair(t, t.TempDir()) + + // Simulate shared dotfiles inside the container where certFile points to an + // OpenSSH private key at a different $HOME path without a sibling .pub file. + containerSSHDir := filepath.Join(t.TempDir(), ".ssh") + require.NoError(t, os.MkdirAll(containerSSHDir, 0o700)) + // #nosec G304 -- test file path under t.TempDir. + privKeyBytes, err := os.ReadFile(hostPrivKey) + require.NoError(t, err) + containerPrivKey := filepath.Join(containerSSHDir, "git_signing_ed25519") + require.NoError( + t, + os.WriteFile(containerPrivKey, privKeyBytes, 0o600), + ) // #nosec G304,G703 -- test file path under t.TempDir. + + var capturedTunnelPayload string + client := &mockCredentialsClient{ + gitSSHSignatureFunc: func( + _ context.Context, + msg *tunnel.Message, + ) (*tunnel.Message, error) { + capturedTunnelPayload = msg.Message + var req gitsshsigning.GitSSHSignatureRequest + if err := json.Unmarshal([]byte(msg.Message), &req); err != nil { + return nil, err + } + resp, err := req.SignWithHostKey(hostPrivKey) + if err != nil { + return nil, err + } + out, err := json.Marshal(resp) + if err != nil { + return nil, err + } + return &tunnel.Message{Message: string(out)}, nil + }, + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := handleGitSSHSignatureRequest(context.Background(), w, r, client); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + })) + defer server.Close() + + gitsshsigning.SetSignatureServerURL(server.URL + "/git-ssh-signature") + t.Cleanup(func() { gitsshsigning.SetSignatureServerURL("") }) + + payload := []byte( + "tree deadbeef\nauthor Dev 1700000000 +0000\n\nsigned commit\n", + ) + bufferFile := filepath.Join(t.TempDir(), "buffer") + require.NoError(t, os.WriteFile(bufferFile, payload, 0o600)) + + require.NoError(t, gitsshsigning.HandleGitSSHProgramCall(containerPrivKey, "git", bufferFile)) + assert.NotContains(t, capturedTunnelPayload, "PRIVATE KEY") + + verifyGitSSHSignature(t, pubKeyLine, bufferFile) +} + +func generateDisposableEd25519KeyPair(t *testing.T, rootDir string) (string, string) { + t.Helper() + + sshDir := filepath.Join(rootDir, ".ssh") + require.NoError(t, os.MkdirAll(sshDir, 0o700)) + + privKeyPath := filepath.Join(sshDir, "git_signing_ed25519") + //nolint:gosec // test-only ssh-keygen invocation under t.TempDir. + out, err := exec.Command( + "ssh-keygen", + "-t", + "ed25519", + "-N", + "", + "-C", + "dev@example.com", + "-f", + privKeyPath, + ).CombinedOutput() + require.NoError(t, err, "ssh-keygen keygen failed: %s", string(out)) + + // #nosec G304 -- test file path under t.TempDir. + pubBytes, err := os.ReadFile(privKeyPath + ".pub") + require.NoError(t, err) + return privKeyPath, strings.TrimSpace(string(pubBytes)) +} + +func verifyGitSSHSignature(t *testing.T, pubKeyLine, bufferFile string) { + t.Helper() + + fields := strings.Fields(pubKeyLine) + require.GreaterOrEqual(t, len(fields), 2) + + allowedSigners := filepath.Join(t.TempDir(), "allowed_signers") + signerEntry := fmt.Sprintf("dev@example.com %s %s\n", fields[0], fields[1]) + require.NoError(t, os.WriteFile(allowedSigners, []byte(signerEntry), 0o600)) + + // #nosec G304 -- test file path under t.TempDir. + payload, err := os.ReadFile(bufferFile) + require.NoError(t, err) + + //nolint:gosec // test-only ssh-keygen verification under t.TempDir. + cmd := exec.Command( + "ssh-keygen", + "-Y", + "verify", + "-f", + allowedSigners, + "-I", + "dev@example.com", + "-n", + "git", + "-s", + bufferFile+".sig", + ) + cmd.Stdin = bytes.NewReader(payload) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "ssh-keygen -Y verify failed: %s", string(out)) +} diff --git a/pkg/gitsshsigning/client.go b/pkg/gitsshsigning/client.go index 6b4c36e493..64e9f305a5 100644 --- a/pkg/gitsshsigning/client.go +++ b/pkg/gitsshsigning/client.go @@ -17,17 +17,7 @@ import ( const defaultCredentialsServerPort = "12049" -func getCredentialsPort() (int, error) { - strPort := os.Getenv(config.EnvCredentialsServerPort) - if strPort == "" { - strPort = defaultCredentialsServerPort - } - port, err := strconv.Atoi(strPort) - if err != nil { - return 0, fmt.Errorf("convert port %s: %w", strPort, err) - } - return port, nil -} +var signatureServerURL string // HandleGitSSHProgramCall implements logic handling call from git when signing a commit. func HandleGitSSHProgramCall(certPath, namespace, bufferFile string) error { @@ -36,7 +26,7 @@ func HandleGitSSHProgramCall(certPath, namespace, bufferFile string) error { return err } - signature, err := requestContentSignature(content, certPath) + signature, err := requestContentSignature(content, certPath, namespace) if err != nil { return err } @@ -48,14 +38,31 @@ func HandleGitSSHProgramCall(certPath, namespace, bufferFile string) error { return nil } +// SetSignatureServerURL sets the server URL override for testing. +func SetSignatureServerURL(url string) { + signatureServerURL = url +} + +func getCredentialsPort() (int, error) { + strPort := os.Getenv(config.EnvCredentialsServerPort) + if strPort == "" { + strPort = defaultCredentialsServerPort + } + port, err := strconv.Atoi(strPort) + if err != nil { + return 0, fmt.Errorf("convert port %s: %w", strPort, err) + } + return port, nil +} + // extractContentFromGitBuffer reads the content from the buffer file created by git. func extractContentFromGitBuffer(bufferFile string) ([]byte, error) { - return os.ReadFile(bufferFile) + return os.ReadFile(bufferFile) // #nosec G304 -- bufferFile is created by git } // requestContentSignature sends an HTTP request to the credentials server to sign the content. -func requestContentSignature(content []byte, certPath string) ([]byte, error) { - requestBody, err := createSignatureRequestBody(content, certPath) +func requestContentSignature(content []byte, certPath, namespace string) ([]byte, error) { + requestBody, err := createSignatureRequestBody(content, certPath, namespace) if err != nil { return nil, err } @@ -79,31 +86,16 @@ func writeSignatureToFile(signature []byte, bufferFile string) error { return nil } -func createSignatureRequestBody(content []byte, certPath string) ([]byte, error) { - var publicKey string - pubKeyData, readErr := os.ReadFile( - certPath, - ) // #nosec G304 -- certPath comes from git config, not user input - if readErr == nil { - publicKey = strings.TrimSpace(string(pubKeyData)) - } - +func createSignatureRequestBody(content []byte, certPath, namespace string) ([]byte, error) { request := &GitSSHSignatureRequest{ Content: string(content), KeyPath: certPath, - PublicKey: publicKey, + PublicKey: extractPublicKeyForRequest(certPath), + Namespace: namespace, } return json.Marshal(request) } -// signatureServerURL overrides the server URL for testing. Empty means use credentials.GetPort(). -var signatureServerURL string - -// SetSignatureServerURL sets the server URL override for testing. -func SetSignatureServerURL(url string) { - signatureServerURL = url -} - func getSignatureURL() (string, error) { if signatureServerURL != "" { return signatureServerURL, nil diff --git a/pkg/gitsshsigning/client_test.go b/pkg/gitsshsigning/client_test.go index fea308a2cc..ce4a61d0e5 100644 --- a/pkg/gitsshsigning/client_test.go +++ b/pkg/gitsshsigning/client_test.go @@ -2,15 +2,18 @@ package gitsshsigning import ( "encoding/json" + "encoding/pem" "net/http" "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/devsy-org/devsy/pkg/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "golang.org/x/crypto/ssh" ) func TestParseSignatureResponse_NonJSONBody(t *testing.T) { @@ -44,7 +47,11 @@ func TestRequestContentSignature_ServerError_PlainText(t *testing.T) { signatureServerURL = server.URL + "/git-ssh-signature" t.Cleanup(func() { signatureServerURL = "" }) - _, err := requestContentSignature([]byte("commit content"), "/tmp/key.pub") + _, err := requestContentSignature( + []byte("commit content"), + "/tmp/key.pub", + defaultSigningNamespace, + ) require.Error(t, err) assert.Contains(t, err.Error(), "failed to sign commit") assert.NotContains(t, err.Error(), "invalid character") @@ -61,7 +68,11 @@ func TestRequestContentSignature_ServerError_JSON(t *testing.T) { signatureServerURL = server.URL + "/git-ssh-signature" t.Cleanup(func() { signatureServerURL = "" }) - _, err := requestContentSignature([]byte("commit content"), "/tmp/key.pub") + _, err := requestContentSignature( + []byte("commit content"), + "/tmp/key.pub", + defaultSigningNamespace, + ) require.Error(t, err) assert.Contains(t, err.Error(), "signing failed") } @@ -78,7 +89,11 @@ func TestRequestContentSignature_Success(t *testing.T) { signatureServerURL = server.URL + "/git-ssh-signature" t.Cleanup(func() { signatureServerURL = "" }) - result, err := requestContentSignature([]byte("commit content"), "/tmp/key.pub") + result, err := requestContentSignature( + []byte("commit content"), + "/tmp/key.pub", + defaultSigningNamespace, + ) require.NoError(t, err) assert.Equal(t, sig, result) assert.Contains(t, string(result), "BEGIN SSH SIGNATURE") @@ -94,7 +109,11 @@ func TestRequestContentSignature_InvalidJSON(t *testing.T) { signatureServerURL = server.URL + "/git-ssh-signature" t.Cleanup(func() { signatureServerURL = "" }) - _, err := requestContentSignature([]byte("commit content"), "/tmp/key.pub") + _, err := requestContentSignature( + []byte("commit content"), + "/tmp/key.pub", + defaultSigningNamespace, + ) require.Error(t, err) assert.Contains(t, err.Error(), "not json at all") } @@ -104,7 +123,11 @@ func TestCreateSignatureRequestBody_IncludesPublicKeyContent(t *testing.T) { pubKeyContent := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest test@example.com" require.NoError(t, os.WriteFile(certPath, []byte(pubKeyContent), 0o600)) - body, err := createSignatureRequestBody([]byte("commit content"), certPath) + body, err := createSignatureRequestBody( + []byte("commit content"), + certPath, + defaultSigningNamespace, + ) require.NoError(t, err) var req GitSSHSignatureRequest @@ -115,7 +138,11 @@ func TestCreateSignatureRequestBody_IncludesPublicKeyContent(t *testing.T) { } func TestCreateSignatureRequestBody_MissingCertFile_OmitsPublicKey(t *testing.T) { - body, err := createSignatureRequestBody([]byte("commit content"), "/nonexistent/key.pub") + body, err := createSignatureRequestBody( + []byte("commit content"), + "/nonexistent/key.pub", + defaultSigningNamespace, + ) require.NoError(t, err) var req GitSSHSignatureRequest @@ -170,3 +197,164 @@ func TestGetSignatureURL_ErrorWhenPortInvalid(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "abc") } + +func TestCreateSignatureRequestBody_OpenSSHPrivateKey_ExtractsPublicKeyOnly(t *testing.T) { + tmpHome := t.TempDir() + setTestHome(t, tmpHome) + + keyPath := filepath.Join(tmpHome, testSSHDirName, testSigningKeyName) + pubLine := generateEd25519TestKey(t, keyPath, "") + + body, err := createSignatureRequestBody([]byte("commit content"), keyPath, testCustomNamespace) + require.NoError(t, err) + assert.NotContains(t, string(body), testPrivateKeyMarker) + + var req GitSSHSignatureRequest + require.NoError(t, json.Unmarshal(body, &req)) + assert.Equal(t, keyPath, req.KeyPath) + assert.Equal(t, testCustomNamespace, req.Namespace) + assert.True(t, strings.HasPrefix(req.PublicKey, testEd25519Prefix)) + assert.NotContains(t, req.PublicKey, testPrivateKeyMarker) + + expectedPub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubLine)) + require.NoError(t, err) + gotPub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(req.PublicKey)) + require.NoError(t, err) + assert.Equal(t, expectedPub.Marshal(), gotPub.Marshal()) +} + +func TestCreateSignatureRequestBody_EncryptedPrivateKey_ExtractsPublicKeyOnly(t *testing.T) { + keyPath := filepath.Join(t.TempDir(), "encrypted_ed25519") + pubLine := generateEd25519TestKey(t, keyPath, "secretpass") + require.NoError(t, os.Remove(keyPath+".pub")) + + body, err := createSignatureRequestBody( + []byte("commit content"), + keyPath, + defaultSigningNamespace, + ) + require.NoError(t, err) + assert.NotContains(t, string(body), testPrivateKeyMarker) + + var req GitSSHSignatureRequest + require.NoError(t, json.Unmarshal(body, &req)) + assert.True(t, strings.HasPrefix(req.PublicKey, testEd25519Prefix)) + assert.NotContains(t, req.PublicKey, testPrivateKeyMarker) + + expectedPub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubLine)) + require.NoError(t, err) + gotPub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(req.PublicKey)) + require.NoError(t, err) + assert.Equal(t, expectedPub.Marshal(), gotPub.Marshal()) +} + +func TestCreateSignatureRequestBody_MalformedPrivateKeyStub_NeverLeaksPrivateKey(t *testing.T) { + keyPath := filepath.Join(t.TempDir(), "malformed_id_ed25519") + stub := "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret-private-material\n-----END OPENSSH PRIVATE KEY-----\n" + require.NoError(t, os.WriteFile(keyPath, []byte(stub), 0o600)) + + body, err := createSignatureRequestBody( + []byte("commit content"), + keyPath, + defaultSigningNamespace, + ) + require.NoError(t, err) + assert.NotContains(t, string(body), testPrivateKeyMarker) + assert.NotContains(t, string(body), "secret-private-material") + + var req GitSSHSignatureRequest + require.NoError(t, json.Unmarshal(body, &req)) + assert.Empty(t, req.PublicKey) + + require.NoError(t, os.WriteFile(keyPath+".pub", []byte(testSyntheticPublicKey+"\n"), 0o600)) + + bodyWithPub, err := createSignatureRequestBody( + []byte("commit content"), + keyPath, + defaultSigningNamespace, + ) + require.NoError(t, err) + assert.NotContains(t, string(bodyWithPub), testPrivateKeyMarker) + require.NoError(t, json.Unmarshal(bodyWithPub, &req)) + assert.Equal(t, testSyntheticPublicKey, req.PublicKey) +} + +func TestHandleGitSSHProgramCall_ForwardsNamespace(t *testing.T) { + var receivedReq GitSSHSignatureRequest + sig := []byte("-----BEGIN SSH SIGNATURE-----\nsig\n-----END SSH SIGNATURE-----\n") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewDecoder(r.Body).Decode(&receivedReq) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(&GitSSHSignatureResponse{Signature: sig}) + })) + defer server.Close() + + SetSignatureServerURL(server.URL + "/git-ssh-signature") + t.Cleanup(func() { SetSignatureServerURL("") }) + + dir := t.TempDir() + certPath := filepath.Join(dir, "key.pub") + require.NoError(t, os.WriteFile(certPath, []byte("ssh-ed25519 AAAAC3 test@example.com"), 0o600)) + bufferFile := filepath.Join(dir, "buffer") + require.NoError(t, os.WriteFile(bufferFile, []byte("payload to sign"), 0o600)) + + require.NoError(t, HandleGitSSHProgramCall(certPath, testCustomNamespace, bufferFile)) + assert.Equal(t, testCustomNamespace, receivedReq.Namespace) + writtenSig, err := os.ReadFile(bufferFile + ".sig") // #nosec G304 -- test path from t.TempDir + require.NoError(t, err) + assert.Equal(t, sig, writtenSig) +} + +func TestCreateSignatureRequestBody_UnencryptedFIDO2SKPrivateKeyWithoutPubFile(t *testing.T) { + rawKeyPath := filepath.Join(t.TempDir(), "seed_ed25519") + _ = generateEd25519TestKey(t, rawKeyPath, "") + seedBytes, err := os.ReadFile(rawKeyPath) // #nosec G304 -- test path from t.TempDir + require.NoError(t, err) + signer, err := ssh.ParsePrivateKey(seedBytes) + require.NoError(t, err) + + // Build an openssh-key-v1 unencrypted sk-ssh-ed25519@openssh.com key stub: + // outer header carries a valid sk-ssh-ed25519@openssh.com public key blob, + // while inner private payload uses sk-ssh-ed25519@openssh.com (unhandled by x/crypto/ssh.ParsePrivateKey). + var edWire struct { + KeyType string + Pub []byte + } + require.NoError(t, ssh.Unmarshal(signer.PublicKey().Marshal(), &edWire)) + skPubWire := ssh.Marshal(struct { + KeyType string + Pub []byte + App string + }{ + KeyType: "sk-ssh-ed25519@openssh.com", + Pub: edWire.Pub, + App: "ssh:", + }) + hdrBytes := ssh.Marshal(openSSHPrivateKeyHeader{ + CipherName: "none", + KdfName: "none", + KdfOpts: "", + NumKeys: 1, + PubKey: skPubWire, + Rest: []byte("unhandled-sk-private-section"), + }) + pemBytes := pem.EncodeToMemory(&pem.Block{ + Type: openSSHPrivateKeyType, + Bytes: append([]byte(openSSHKeyV1Magic), hdrBytes...), + }) + + skKeyPath := filepath.Join(t.TempDir(), "id_ed25519_sk") + require.NoError(t, os.WriteFile(skKeyPath, pemBytes, 0o600)) + + body, err := createSignatureRequestBody( + []byte("commit content"), + skKeyPath, + defaultSigningNamespace, + ) + require.NoError(t, err) + assert.NotContains(t, string(body), testPrivateKeyMarker) + + var req GitSSHSignatureRequest + require.NoError(t, json.Unmarshal(body, &req)) + assert.True(t, strings.HasPrefix(req.PublicKey, "sk-ssh-ed25519@openssh.com ")) +} diff --git a/pkg/gitsshsigning/helper.go b/pkg/gitsshsigning/helper.go index 6e0ef475e3..dc8a84da77 100644 --- a/pkg/gitsshsigning/helper.go +++ b/pkg/gitsshsigning/helper.go @@ -20,7 +20,8 @@ devsy internal agent git-ssh-signature "$@" ` ) -var GitConfigTemplate = ` +var ( + GitConfigTemplate = ` [gpg "ssh"] program = ` + pkgconfig.SSHSignatureHelperName + ` [gpg] @@ -28,6 +29,14 @@ var GitConfigTemplate = ` [user] signingkey = %s ` + gitConfigValueEscaper = strings.NewReplacer( + `\`, `\\`, + `"`, `\"`, + "\n", `\n`, + "\t", `\t`, + "\r", "", + ) +) // ConfigureHelper sets up the Git SSH signing helper script and updates the Git configuration for the specified user. // @@ -114,7 +123,7 @@ func updateGitConfig(gitConfigPath, userName, gitSigningKey string) error { // with the current key. The previous guard (checking whether the program // line already existed) would silently skip key updates after unclean // shutdowns or key rotations. - newConfig := fmt.Sprintf(GitConfigTemplate, gitSigningKey) + newConfig := fmt.Sprintf(GitConfigTemplate, formatGitConfigValue(gitSigningKey)) newContent := removeSignatureHelper(configContent) + newConfig if err := writeGitConfig(gitConfigPath, newContent, userName); err != nil { return err @@ -123,6 +132,13 @@ func updateGitConfig(gitConfigPath, userName, gitSigningKey string) error { return nil } +func formatGitConfigValue(val string) string { + if !strings.ContainsAny(val, "\\\"\n\r\t#;") && strings.TrimSpace(val) == val { + return val + } + return `"` + gitConfigValueEscaper.Replace(val) + `"` +} + func readGitConfig(gitConfigPath string) (string, error) { out, err := os.ReadFile(gitConfigPath) if err != nil && !os.IsNotExist(err) { diff --git a/pkg/gitsshsigning/helper_test.go b/pkg/gitsshsigning/helper_test.go index f668d3a8ce..82b24eda9a 100644 --- a/pkg/gitsshsigning/helper_test.go +++ b/pkg/gitsshsigning/helper_test.go @@ -2,6 +2,7 @@ package gitsshsigning import ( "os" + "os/exec" "path/filepath" "strings" "testing" @@ -154,3 +155,74 @@ func (s *HelperTestSuite) TestRemoveSignatureHelper_DropsEmptyGpgSSHSection() { "empty section should be dropped entirely") assert.Contains(s.T(), result, "[commit]") } + +func TestUpdateGitConfig_WindowsBackslashPathQuotingAndCleanRemoval(t *testing.T) { + dir := t.TempDir() + gitConfigPath := filepath.Join(dir, ".gitconfig") + initial := "[user]\n\tname = Test User\n\temail = test@example.com" + require.NoError(t, os.WriteFile(gitConfigPath, []byte(initial), 0o600)) + + winKeyPath := `C:\Users\alice\.ssh\git_signing_ed25519` + require.NoError(t, updateGitConfig(gitConfigPath, "", winKeyPath)) + + content, err := os.ReadFile(gitConfigPath) // #nosec G304 -- test path from t.TempDir + require.NoError(t, err) + assert.Contains( + t, + string(content), + `signingkey = "C:\\Users\\alice\\.ssh\\git_signing_ed25519"`, + ) + + //nolint:gosec // test-only git config verification + out, err := exec.Command( + "git", + "config", + "--file", + gitConfigPath, + "--get", + "user.signingkey", + ).CombinedOutput() + require.NoError(t, err, "git config failed to parse quoted path: %s", string(out)) + assert.Equal(t, winKeyPath, strings.TrimSpace(string(out))) + + cleaned := removeSignatureHelper(string(content)) + assert.NotContains(t, cleaned, "git_signing_ed25519") + assert.NotContains(t, cleaned, "devsy-ssh-signature") + assert.Equal(t, initial, cleaned) +} + +func TestFormatGitConfigValue_QuotesOnlySpecialCharacters(t *testing.T) { + unixPath := "/Users/alice/.ssh/id_ed25519" + assert.Equal(t, unixPath, formatGitConfigValue(unixPath)) + assert.Equal( + t, + testSyntheticPublicKey, + formatGitConfigValue(testSyntheticPublicKey), + ) + assert.Equal( + t, + `"/path/with \"quotes\"/key"`, + formatGitConfigValue(`/path/with "quotes"/key`), + ) + assert.Equal( + t, + `"/path/with\ninjected"`, + formatGitConfigValue("/path/with\r\ninjected"), + ) + hashAndSemiPath := "/Users/alice/c#-app;v2/.ssh/git_signing_ed25519" + assert.Equal(t, `"`+hashAndSemiPath+`"`, formatGitConfigValue(hashAndSemiPath)) + + gitConfigPath := filepath.Join(t.TempDir(), ".gitconfig") + require.NoError(t, updateGitConfig(gitConfigPath, "", hashAndSemiPath)) + //nolint:gosec // test-only git config verification + out, err := exec.Command( + "git", + "config", + "--file", + gitConfigPath, + "--get", + "user.signingkey", + ).CombinedOutput() + require.NoError(t, err, "git config failed on #/; path: %s", string(out)) + assert.Equal(t, hashAndSemiPath, strings.TrimSpace(string(out))) +} diff --git a/pkg/gitsshsigning/key.go b/pkg/gitsshsigning/key.go new file mode 100644 index 0000000000..9a8c76899b --- /dev/null +++ b/pkg/gitsshsigning/key.go @@ -0,0 +1,200 @@ +package gitsshsigning + +import ( + "bytes" + "encoding/pem" + "errors" + "fmt" + "os" + "strings" + + "golang.org/x/crypto/ssh" +) + +const ( + maxKeyFileSize = 64 * 1024 + base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" + openSSHPrivateKeyType = "OPENSSH PRIVATE KEY" + openSSHKeyV1Magic = "openssh-key-v1\x00" +) + +var sshPublicKeyPrefixes = [...]string{ + "ssh-", + "ecdsa-sha2-", + "sk-ssh-", + "sk-ecdsa-", +} + +type openSSHPrivateKeyHeader struct { + CipherName string + KdfName string + KdfOpts string + NumKeys uint32 + PubKey []byte + Rest []byte `ssh:"rest"` +} + +func readRegularKeyFile(path string) ([]byte, error) { + if path == "" { + return nil, errors.New("empty key path") + } + info, err := os.Stat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("key path %q is not a regular file", path) + } + if info.Size() > maxKeyFileSize { + return nil, fmt.Errorf("key file %q exceeds max size", path) + } + // #nosec G304 -- signing key path comes from git configuration + return os.ReadFile(path) +} + +func regularFileExists(path string) bool { + if path == "" { + return false + } + info, err := os.Stat(path) + return err == nil && info.Mode().IsRegular() +} + +func looksLikePrivateKey(data []byte) bool { + return bytes.Contains(data, []byte("PRIVATE KEY-----")) || + bytes.HasPrefix(bytes.TrimSpace(data), []byte("PuTTY-User-Key-File-")) +} + +func extractPublicKeyForRequest(certPath string) string { + data, err := readRegularKeyFile(certPath) + if err != nil { + return "" + } + if pub, ok := publicKeyFromPrivateKeyBytes(data); ok { + return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pub))) + } + if looksLikePrivateKey(data) { + pubData, pubErr := readRegularKeyFile(certPath + ".pub") + if pubErr != nil { + return "" + } + return parsePublicKeyLine(pubData) + } + return parsePublicKeyLine(data) +} + +func publicKeyFromPrivateKeyBytes(data []byte) (ssh.PublicKey, bool) { + signer, err := ssh.ParsePrivateKey(data) + if err == nil { + return signer.PublicKey(), true + } + var pmErr *ssh.PassphraseMissingError + if errors.As(err, &pmErr) && pmErr.PublicKey != nil { + return pmErr.PublicKey, true + } + return parseOpenSSHV1CleartextPublicKey(data) +} + +func parseOpenSSHV1CleartextPublicKey(data []byte) (ssh.PublicKey, bool) { + block, _ := pem.Decode(data) + if block == nil || block.Type != openSSHPrivateKeyType { + return nil, false + } + body, ok := bytes.CutPrefix(block.Bytes, []byte(openSSHKeyV1Magic)) + if !ok { + return nil, false + } + var hdr openSSHPrivateKeyHeader + if err := ssh.Unmarshal(body, &hdr); err != nil || hdr.NumKeys != 1 { + return nil, false + } + pub, err := ssh.ParsePublicKey(hdr.PubKey) + if err != nil { + return nil, false + } + return pub, true +} + +func parsePublicKeyLine(data []byte) string { + if looksLikePrivateKey(data) { + return "" + } + trimmed := strings.TrimSpace(string(data)) + if trimmed == "" || strings.ContainsAny(trimmed, "\r\n") { + return "" + } + if _, _, _, _, err := ssh.ParseAuthorizedKey(data); err == nil { + return trimmed + } + if hasSSHPublicKeyPrefix(trimmed) { + return trimmed + } + return "" +} + +func hasSSHPublicKeyPrefix(line string) bool { + fields := strings.Fields(line) + if len(fields) < 2 || !isBase64Token(fields[1]) { + return false + } + for _, prefix := range sshPublicKeyPrefixes { + if strings.HasPrefix(fields[0], prefix) && len(fields[0]) > len(prefix) { + return true + } + } + return false +} + +func isBase64Token(s string) bool { + if s == "" { + return false + } + for i := range len(s) { + if strings.IndexByte(base64Alphabet, s[i]) < 0 { + return false + } + } + return true +} + +func hostFileMatchesPublicKey(hostPath, publicKey string) bool { + if hostPath == "" || publicKey == "" { + return false + } + reqPub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKey)) + if err != nil { + return false + } + hostPub, err := extractSSHPublicKeyFromFile(hostPath) + if err != nil { + return false + } + return bytes.Equal(hostPub.Marshal(), reqPub.Marshal()) +} + +func extractSSHPublicKeyFromFile(path string) (ssh.PublicKey, error) { + data, err := readRegularKeyFile(path) + if err != nil { + return nil, err + } + if pub, ok := publicKeyFromPrivateKeyBytes(data); ok { + return pub, nil + } + if looksLikePrivateKey(data) { + return parseAdjacentPublicKeyFile(path + ".pub") + } + pub, _, _, _, err := ssh.ParseAuthorizedKey(data) + return pub, err +} + +func parseAdjacentPublicKeyFile(pubPath string) (ssh.PublicKey, error) { + pubData, err := readRegularKeyFile(pubPath) + if err != nil { + return nil, err + } + if looksLikePrivateKey(pubData) { + return nil, errors.New("adjacent public key file contains private key") + } + pub, _, _, _, err := ssh.ParseAuthorizedKey(pubData) + return pub, err +} diff --git a/pkg/gitsshsigning/server.go b/pkg/gitsshsigning/server.go index 8d2ea01d53..b513122834 100644 --- a/pkg/gitsshsigning/server.go +++ b/pkg/gitsshsigning/server.go @@ -2,39 +2,48 @@ package gitsshsigning import ( "bytes" + "errors" "fmt" "os" "os/exec" + "strings" ) +const defaultSigningNamespace = "git" + +// GitSSHSignatureRequest describes an SSH signature request forwarded from a workspace container. type GitSSHSignatureRequest struct { Content string KeyPath string - PublicKey string // Public key content; when set, written to a temp file for ssh-keygen + PublicKey string // Public key content; when set, written to a temp file for ssh-keygen. + Namespace string `json:",omitempty"` } +// GitSSHSignatureResponse holds the raw SSH signature produced by ssh-keygen. type GitSSHSignatureResponse struct { Signature []byte } -// Sign signs the content using the private key and returns the signature. -// This is intended to be a drop-in replacement for gpg.ssh.program for git, -// so we simply execute ssh-keygen in the same way as git would do locally. -// -// When PublicKey is set, it is written to a temporary file that ssh-keygen -// can read. This is necessary because the original KeyPath comes from -// inside the container and does not exist on the host where Sign() runs. +// Sign signs the content using the requested key and returns the signature. func (req *GitSSHSignatureRequest) Sign() (*GitSSHSignatureResponse, error) { - keyFile, cleanup, err := req.resolveKeyFile() + return req.SignWithHostKey("") +} + +// SignWithHostKey signs the content, preferring a matching host signing key file when available. +func (req *GitSSHSignatureRequest) SignWithHostKey( + hostSigningKey string, +) (*GitSSHSignatureResponse, error) { + namespace, err := resolveSigningNamespace(req.Namespace) + if err != nil { + return nil, err + } + + keyFile, cleanup, err := req.resolveKeyFile(hostSigningKey) if err != nil { return nil, fmt.Errorf("resolve signing key: %w", err) } defer cleanup() - - var commitBuffer bytes.Buffer - commitBuffer.WriteString(req.Content) - - //nolint:gosec // keyFile is a controlled temp path or validated KeyPath + //nolint:gosec // keyFile is a controlled temp path or validated signing key path cmd := exec.Command( "ssh-keygen", "-Y", @@ -42,17 +51,16 @@ func (req *GitSSHSignatureRequest) Sign() (*GitSSHSignatureResponse, error) { "-f", keyFile, "-n", - "git", + namespace, ) - cmd.Stdin = &commitBuffer + cmd.Stdin = strings.NewReader(req.Content) var out bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr - err = cmd.Run() - if err != nil { + if err := cmd.Run(); err != nil { return nil, fmt.Errorf("failed to sign commit: %w, stderr: %s", err, stderr.String()) } @@ -62,33 +70,52 @@ func (req *GitSSHSignatureRequest) Sign() (*GitSSHSignatureResponse, error) { } // resolveKeyFile returns the path to use for ssh-keygen -f and a cleanup function. -// When PublicKey content is available, it writes a temp file. Otherwise falls back to KeyPath. -func (req *GitSSHSignatureRequest) resolveKeyFile() (string, func(), error) { +func (req *GitSSHSignatureRequest) resolveKeyFile(hostSigningKey string) (string, func(), error) { noop := func() {} + hostKeyPath := ExpandSigningKeyPath(hostSigningKey) if req.PublicKey == "" { - return req.KeyPath, noop, nil + if regularFileExists(hostKeyPath) { + return hostKeyPath, noop, nil + } + return "", noop, errors.New("no public key content or host signing key file") + } + + if hostKeyPath != "" && hostFileMatchesPublicKey(hostKeyPath, req.PublicKey) { + return hostKeyPath, noop, nil } - // ssh-keygen -Y sign -f reads the public key directly from - // to identify which SSH agent key to use for signing. We write the public - // key content to a temp file and pass that path to -f. + return writeTempPublicKeyFile(req.PublicKey) +} + +func writeTempPublicKeyFile(publicKey string) (string, func(), error) { + noop := func() {} tmpFile, err := os.CreateTemp("", ".git_signing_key_*") if err != nil { return "", noop, fmt.Errorf("create temp key file: %w", err) } keyPath := tmpFile.Name() - if _, err := tmpFile.WriteString(req.PublicKey); err != nil { + content := strings.TrimRight(publicKey, "\r\n") + "\n" + if _, err := tmpFile.WriteString(content); err != nil { _ = tmpFile.Close() _ = os.Remove(keyPath) return "", noop, fmt.Errorf("write public key: %w", err) } - _ = tmpFile.Close() + if err := tmpFile.Close(); err != nil { + _ = os.Remove(keyPath) + return "", noop, fmt.Errorf("close temp key file: %w", err) + } cleanup := func() { _ = os.Remove(keyPath) } - return keyPath, cleanup, nil } + +func resolveSigningNamespace(raw string) (string, error) { + if raw == "" || raw == defaultSigningNamespace { + return defaultSigningNamespace, nil + } + return "", fmt.Errorf("invalid signing namespace %q", raw) +} diff --git a/pkg/gitsshsigning/server_test.go b/pkg/gitsshsigning/server_test.go index 143e3ab16c..909a106cad 100644 --- a/pkg/gitsshsigning/server_test.go +++ b/pkg/gitsshsigning/server_test.go @@ -3,13 +3,26 @@ package gitsshsigning import ( "io" "os" + "os/exec" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) +const ( + testCommitPayload = "tree abc123\nauthor Test \n\ntest commit" + testTildeKeyPath = "~/.ssh/git_signing_ed25519" + testContainerKeyPath = "/home/vscode/.ssh/git_signing_ed25519" + testCustomNamespace = "file" + testPrivateKeyMarker = "PRIVATE KEY" + testEd25519Prefix = "ssh-ed25519 " + testSignerPrincipal = "test@example.com" + envSSHAuthSock = "SSH_AUTH_SOCK" +) + func TestSign_WithPublicKeyContent_WritesToTempFile(t *testing.T) { req := &GitSSHSignatureRequest{ Content: "tree abc123\nauthor Test \n\ntest commit", @@ -24,13 +37,12 @@ func TestSign_WithPublicKeyContent_WritesToTempFile(t *testing.T) { func TestSign_NonExistentKeyPath_ReturnsError(t *testing.T) { req := &GitSSHSignatureRequest{ - Content: "tree abc123\nauthor Test \n\ntest commit", + Content: testCommitPayload, KeyPath: "/tmp/.git_signing_key_does_not_exist", } _, err := req.Sign() - require.Error(t, err) - assert.Contains(t, err.Error(), "failed to sign commit") + require.ErrorContains(t, err, "no public key content or host signing key file") } func TestResolveKeyFile_PublicKey_CreatesAndCleansTempFile(t *testing.T) { @@ -40,7 +52,7 @@ func TestResolveKeyFile_PublicKey_CreatesAndCleansTempFile(t *testing.T) { KeyPath: "/nonexistent/original/key", } - resolved, cleanup, err := req.resolveKeyFile() + resolved, cleanup, err := req.resolveKeyFile("") require.NoError(t, err) defer cleanup() @@ -52,7 +64,7 @@ func TestResolveKeyFile_PublicKey_CreatesAndCleansTempFile(t *testing.T) { defer func() { _ = f.Close() }() got, err := io.ReadAll(f) require.NoError(t, err) - assert.Equal(t, publicKey, string(got)) + assert.Equal(t, publicKey+"\n", string(got)) } func TestResolveKeyFile_PublicKey_CleanupRemovesTempFile(t *testing.T) { @@ -60,7 +72,7 @@ func TestResolveKeyFile_PublicKey_CleanupRemovesTempFile(t *testing.T) { PublicKey: "ssh-ed25519 AAAAC3 test@example.com", } - resolved, cleanup, err := req.resolveKeyFile() + resolved, cleanup, err := req.resolveKeyFile("") require.NoError(t, err) require.FileExists(t, resolved) @@ -70,15 +82,183 @@ func TestResolveKeyFile_PublicKey_CleanupRemovesTempFile(t *testing.T) { assert.True(t, os.IsNotExist(statErr), "temp file should be removed after cleanup") } -func TestResolveKeyFile_EmptyPublicKey_ReturnsKeyPath(t *testing.T) { - keyPath := filepath.Join(t.TempDir(), "signing-key") - require.NoError(t, os.WriteFile(keyPath, []byte("key"), 0o600)) +func TestResolveKeyFile_EmptyPublicKey_RequiresHostKey(t *testing.T) { + req := &GitSSHSignatureRequest{KeyPath: "/host/untrusted/key"} + _, cleanup, err := req.resolveKeyFile("") + + require.ErrorContains(t, err, "no public key content or host signing key file") + cleanup() +} + +func TestSign_HostTildePrivateKey_WithoutSSHAgent(t *testing.T) { + hostHome := t.TempDir() + setTestHome(t, hostHome) + t.Setenv(envSSHAuthSock, "") + + hostKeyPath := filepath.Join(hostHome, testSSHDirName, testSigningKeyName) + pubLine := generateEd25519TestKey(t, hostKeyPath, "") + + req := &GitSSHSignatureRequest{ + Content: testCommitPayload, + KeyPath: testTildeKeyPath, + } + + resp, err := req.SignWithHostKey(testTildeKeyPath) + require.NoError(t, err) + assertValidSSHSignature(t, pubLine, req, resp.Signature) +} + +func TestSignWithHostKey_ContainerPrivateKeyDifferentHome_WithoutSSHAgent(t *testing.T) { + hostHome := t.TempDir() + setTestHome(t, hostHome) + t.Setenv(envSSHAuthSock, "") - req := &GitSSHSignatureRequest{KeyPath: keyPath} - resolved, cleanup, err := req.resolveKeyFile() + hostKeyPath := filepath.Join(hostHome, testSSHDirName, testSigningKeyName) + pubLine := generateEd25519TestKey(t, hostKeyPath, "") + derivedPub := extractPublicKeyForRequest(hostKeyPath) + require.NotEmpty(t, derivedPub) + + reqWithPub := &GitSSHSignatureRequest{ + Content: testCommitPayload, + KeyPath: testContainerKeyPath, + PublicKey: derivedPub, + } + resp, err := reqWithPub.SignWithHostKey(testTildeKeyPath) + require.NoError(t, err) + assertValidSSHSignature(t, pubLine, reqWithPub, resp.Signature) + + reqWithoutPub := &GitSSHSignatureRequest{ + Content: testCommitPayload, + KeyPath: testContainerKeyPath, + } + respFallback, err := reqWithoutPub.SignWithHostKey(testTildeKeyPath) + require.NoError(t, err) + assertValidSSHSignature(t, pubLine, reqWithoutPub, respFallback.Signature) +} + +func TestSign_SamePathHostAndContainerPrivateKey_WithoutSSHAgent(t *testing.T) { + t.Setenv(envSSHAuthSock, "") + + sharedKeyPath := filepath.Join(t.TempDir(), testSSHDirName, testSigningKeyName) + pubLine := generateEd25519TestKey(t, sharedKeyPath, "") + derivedPub := extractPublicKeyForRequest(sharedKeyPath) + require.NotEmpty(t, derivedPub) + + req := &GitSSHSignatureRequest{ + Content: testCommitPayload, + KeyPath: sharedKeyPath, + PublicKey: derivedPub, + } + resolved, cleanup, err := req.resolveKeyFile(sharedKeyPath) require.NoError(t, err) - assert.Equal(t, keyPath, resolved) + assert.Equal(t, sharedKeyPath, resolved) cleanup() - assert.FileExists(t, keyPath, "original key file must not be removed by cleanup") + assert.FileExists(t, sharedKeyPath) + + resp, err := req.SignWithHostKey(sharedKeyPath) + require.NoError(t, err) + assertValidSSHSignature(t, pubLine, req, resp.Signature) +} + +func TestSign_RejectsInvalidNamespace(t *testing.T) { + for _, badNS := range []string{"file", "git2", "-U", "-f", " ", "git extra", "git\nfoo", "git\x7f"} { + req := &GitSSHSignatureRequest{ + Content: testCommitPayload, + Namespace: badNS, + } + _, err := req.Sign() + require.ErrorContains(t, err, "invalid signing namespace") + } +} + +func TestResolveKeyFile_DoesNotUseRequestKeyPath(t *testing.T) { + hostKeyPath := filepath.Join(t.TempDir(), "host-signing-key") + requestKeyPath := filepath.Join(t.TempDir(), "container-selected-key") + _ = generateEd25519TestKey(t, hostKeyPath, "") + _ = generateEd25519TestKey(t, requestKeyPath, "") + + req := &GitSSHSignatureRequest{ + KeyPath: requestKeyPath, + PublicKey: extractPublicKeyForRequest(requestKeyPath), + } + resolved, cleanup, err := req.resolveKeyFile(hostKeyPath) + require.NoError(t, err) + defer cleanup() + + assert.NotEqual(t, hostKeyPath, resolved) + assert.NotEqual(t, requestKeyPath, resolved) + require.FileExists(t, resolved) +} + +func generateEd25519TestKey(t *testing.T, keyPath, passphrase string) string { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(keyPath), 0o700)) + //nolint:gosec // test helper generating ephemeral ed25519 key + out, err := exec.Command( + "ssh-keygen", + "-q", + "-t", + "ed25519", + "-N", + passphrase, + "-C", + testSignerPrincipal, + "-f", + keyPath, + ).CombinedOutput() + require.NoError(t, err, "ssh-keygen keygen failed: %s", string(out)) + // #nosec G304 -- test path under t.TempDir() + pubBytes, err := os.ReadFile(keyPath + ".pub") + require.NoError(t, err) + return strings.TrimSpace(string(pubBytes)) +} + +func assertValidSSHSignature( + t *testing.T, + pubKeyLine string, + req *GitSSHSignatureRequest, + sig []byte, +) { + t.Helper() + require.NoError(t, verifySSHSignatureRaw(t, pubKeyLine, req, sig)) +} + +func verifySSHSignatureRaw( + t *testing.T, + pubKeyLine string, + req *GitSSHSignatureRequest, + sig []byte, +) error { + t.Helper() + namespace := req.Namespace + if namespace == "" { + namespace = defaultSigningNamespace + } + + verifyDir := t.TempDir() + allowedSigners := filepath.Join(verifyDir, "allowed_signers") + sigPath := filepath.Join(verifyDir, "message.sig") + + entry := testSignerPrincipal + " " + strings.TrimSpace(pubKeyLine) + "\n" + require.NoError(t, os.WriteFile(allowedSigners, []byte(entry), 0o600)) + require.NoError(t, os.WriteFile(sigPath, sig, 0o600)) + + //nolint:gosec // test helper verifying signature with ssh-keygen + cmd := exec.Command( + "ssh-keygen", + "-Y", + "verify", + "-f", + allowedSigners, + "-I", + testSignerPrincipal, + "-n", + namespace, + "-s", + sigPath, + ) + cmd.Stdin = strings.NewReader(req.Content) + _, err := cmd.CombinedOutput() + return err } diff --git a/pkg/gitsshsigning/utils.go b/pkg/gitsshsigning/utils.go index 6670c8803f..ae1ef5d809 100644 --- a/pkg/gitsshsigning/utils.go +++ b/pkg/gitsshsigning/utils.go @@ -2,6 +2,10 @@ package gitsshsigning import ( "context" + "os" + "os/user" + "path/filepath" + "strings" "github.com/devsy-org/devsy/pkg/git" ) @@ -12,6 +16,42 @@ const ( GPGFormatSSH = "ssh" ) +// IsLiteralSSHKey reports whether signingKey is an inline SSH public key rather than a file path. +func IsLiteralSSHKey(signingKey string) bool { + return strings.HasPrefix(signingKey, "key::") || strings.HasPrefix(signingKey, "ssh-") +} + +// ExpandSigningKeyPath expands a leading ~ or ~user prefix in an SSH signing key path. +func ExpandSigningKeyPath(signingKey string) string { + if signingKey == "" || IsLiteralSSHKey(signingKey) { + return signingKey + } + rest, ok := strings.CutPrefix(signingKey, "~") + if !ok { + return signingKey + } + if rest == "" { + return expandCurrentUserHome("", signingKey) + } + if rest[0] == '/' || rest[0] == '\\' { + return expandCurrentUserHome(rest[1:], signingKey) + } + return expandNamedUserHome(rest, signingKey) +} + +// ResolveSigningKey expands ~ prefixes and resolves relative SSH key paths against workingDir. +func ResolveSigningKey(signingKey, workingDir string) string { + if signingKey == "" || IsLiteralSSHKey(signingKey) { + return signingKey + } + expanded := ExpandSigningKeyPath(signingKey) + if !strings.HasPrefix(expanded, "~") && !filepath.IsAbs(expanded) && workingDir != "" { + return filepath.Join(workingDir, expanded) + } + return expanded +} + +// ExtractGitConfiguration reads gpg.format and user.signingkey from git config at workingDir. func ExtractGitConfiguration(ctx context.Context, workingDir string) (string, string, error) { config := git.At(workingDir).Config() @@ -25,5 +65,37 @@ func ExtractGitConfiguration(ctx context.Context, workingDir string) (string, st return "", "", err } + if format == GPGFormatSSH && signingKey != "" { + signingKey = ResolveSigningKey(signingKey, workingDir) + } + return format, signingKey, nil } + +func expandCurrentUserHome(subpath, fallback string) string { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return fallback + } + if subpath == "" { + return home + } + return filepath.Join(home, subpath) +} + +func expandNamedUserHome(rest, fallback string) string { + username := rest + subpath := "" + if idx := strings.IndexAny(rest, `/\`); idx >= 0 { + username = rest[:idx] + subpath = rest[idx+1:] + } + usr, err := user.Lookup(username) + if err != nil || usr.HomeDir == "" { + return fallback + } + if subpath == "" { + return usr.HomeDir + } + return filepath.Join(usr.HomeDir, subpath) +} diff --git a/pkg/gitsshsigning/utils_test.go b/pkg/gitsshsigning/utils_test.go index cfb792ee2a..d7fa68482b 100644 --- a/pkg/gitsshsigning/utils_test.go +++ b/pkg/gitsshsigning/utils_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "os/exec" + "os/user" "path/filepath" "testing" @@ -12,11 +13,17 @@ import ( "github.com/stretchr/testify/require" ) +const ( + testSyntheticPublicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest test@example.com" + testKeyPrefixedPublicKey = "key::ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest" + testSSHDirName = ".ssh" + testSigningKeyName = "git_signing_ed25519" + testGPGKeyID = "ABCDEF1234567890" +) + func TestExtractGitConfiguration_WorkingDirResolvesIncludeIf(t *testing.T) { tmpHome := tempDirResolved(t) - t.Setenv("HOME", tmpHome) - t.Setenv("XDG_CONFIG_HOME", "") - t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + setupIsolatedGitEnv(t, tmpHome) projectDir := tempDirResolved(t) //nolint:gosec // test-only, args are constants @@ -42,9 +49,7 @@ func TestExtractGitConfiguration_WorkingDirResolvesIncludeIf(t *testing.T) { func TestExtractGitConfiguration_WorkingDirWithGlobalSigningConfig(t *testing.T) { tmpHome := t.TempDir() - t.Setenv("HOME", tmpHome) - t.Setenv("XDG_CONFIG_HOME", "") - t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + setupIsolatedGitEnv(t, tmpHome) projectDir := t.TempDir() //nolint:gosec // test-only, args are constants @@ -63,6 +68,141 @@ func TestExtractGitConfiguration_WorkingDirWithGlobalSigningConfig(t *testing.T) assert.Equal(t, "/global/key.pub", signingKey) } +func TestIsLiteralSSHKey(t *testing.T) { + assert.True(t, IsLiteralSSHKey(testSyntheticPublicKey)) + assert.True(t, IsLiteralSSHKey(testKeyPrefixedPublicKey)) + assert.True(t, IsLiteralSSHKey("key::ecdsa-sha2-nistp256 AAAAE2VjZHNh")) + assert.False(t, IsLiteralSSHKey(testTildeKeyPath)) + assert.False(t, IsLiteralSSHKey("/Users/test/.ssh/git_signing_ed25519")) + assert.False(t, IsLiteralSSHKey(testGPGKeyID)) + assert.False(t, IsLiteralSSHKey("")) +} + +func TestExpandSigningKeyPath(t *testing.T) { + tmpHome := t.TempDir() + setTestHome(t, tmpHome) + + assert.Equal(t, "", ExpandSigningKeyPath("")) + assert.Equal(t, tmpHome, ExpandSigningKeyPath("~")) + assert.Equal( + t, + filepath.Join(tmpHome, testSSHDirName, testSigningKeyName), + ExpandSigningKeyPath(testTildeKeyPath), + ) + assert.Equal( + t, + filepath.Join(tmpHome, `.ssh\git_signing_ed25519`), + ExpandSigningKeyPath(`~\.ssh\git_signing_ed25519`), + ) + assert.Equal(t, testSyntheticPublicKey, ExpandSigningKeyPath(testSyntheticPublicKey)) + assert.Equal(t, testKeyPrefixedPublicKey, ExpandSigningKeyPath(testKeyPrefixedPublicKey)) + + unknownUser := "~nonexistent_devsy_user_1723/.ssh/id_ed25519" + assert.Equal(t, unknownUser, ExpandSigningKeyPath(unknownUser)) + + currentUser, err := user.Current() + if err == nil && currentUser.Username != "" && currentUser.HomeDir != "" { + assert.Equal( + t, + currentUser.HomeDir, + ExpandSigningKeyPath("~"+currentUser.Username), + ) + assert.Equal( + t, + filepath.Join(currentUser.HomeDir, testSSHDirName, "id_ed25519"), + ExpandSigningKeyPath("~"+currentUser.Username+"/.ssh/id_ed25519"), + ) + } +} + +func TestExtractGitConfiguration_ResolvesSSHKeyFormats(t *testing.T) { + tmpHome := t.TempDir() + setupIsolatedGitEnv(t, tmpHome) + + projectDir := t.TempDir() + //nolint:gosec // test-only, args are constants + require.NoError(t, exec.Command("git", "init", projectDir).Run()) + + cases := []struct { + name, format, rawKey, expectedKey string + }{ + { + "tilde ssh", + GPGFormatSSH, + testTildeKeyPath, + filepath.Join(tmpHome, testSSHDirName, testSigningKeyName), + }, + {"literal ssh-", GPGFormatSSH, testSyntheticPublicKey, testSyntheticPublicKey}, + {"literal key::", GPGFormatSSH, testKeyPrefixedPublicKey, testKeyPrefixedPublicKey}, + { + "relative ssh", + GPGFormatSSH, + ".ssh/repo_key", + filepath.Join(projectDir, testSSHDirName, "repo_key"), + }, + {"non-ssh gpg id", "openpgp", testGPGKeyID, testGPGKeyID}, + } + globalConfigPath := filepath.Join(tmpHome, ".gitconfig") + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := fmt.Sprintf( + "[gpg]\n\tformat = %s\n[user]\n\tsigningkey = %s\n", + tc.format, + tc.rawKey, + ) + require.NoError(t, os.WriteFile(globalConfigPath, []byte(cfg), 0o600)) + + gotFormat, gotKey, err := ExtractGitConfiguration(context.Background(), projectDir) + require.NoError(t, err) + assert.Equal(t, tc.format, gotFormat) + assert.Equal(t, tc.expectedKey, gotKey) + }) + } +} + +func TestExtractGitConfiguration_ExpandsNamedUserForSSH(t *testing.T) { + currentUser, err := user.Current() + if err != nil || currentUser.Username == "" || currentUser.HomeDir == "" { + t.Skip("current OS user unavailable") + } + + tmpHome := t.TempDir() + setupIsolatedGitEnv(t, tmpHome) + + projectDir := t.TempDir() + //nolint:gosec // test-only, args are constants + require.NoError(t, exec.Command("git", "init", projectDir).Run()) + + globalConfigPath := filepath.Join(tmpHome, ".gitconfig") + cfg := fmt.Sprintf( + "[gpg]\n\tformat = ssh\n[user]\n\tsigningkey = ~%s/.ssh/git_signing_ed25519\n", + currentUser.Username, + ) + require.NoError(t, os.WriteFile(globalConfigPath, []byte(cfg), 0o600)) + + gotFormat, gotKey, err := ExtractGitConfiguration(context.Background(), projectDir) + require.NoError(t, err) + assert.Equal(t, GPGFormatSSH, gotFormat) + assert.Equal( + t, + filepath.Join(currentUser.HomeDir, testSSHDirName, testSigningKeyName), + gotKey, + ) +} + +func setTestHome(t *testing.T, home string) { + t.Helper() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) +} + +func setupIsolatedGitEnv(t *testing.T, home string) { + t.Helper() + setTestHome(t, home) + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") +} + // tempDirResolved returns a t.TempDir() with symlinks resolved. On macOS the // temp dir lives under /var (a symlink to /private/var); git's `includeIf // gitdir:` matches against the resolved path, so tests that build such patterns diff --git a/pkg/tunnel/services.go b/pkg/tunnel/services.go index 5922f0d2bc..498663f973 100644 --- a/pkg/tunnel/services.go +++ b/pkg/tunnel/services.go @@ -65,6 +65,15 @@ type RunServicesOptions struct { DisableIdleTimeout bool } +type tunnelServerParams struct { + opts RunServicesOptions + stdoutReader *os.File + stdinWriter *os.File + forwarder netstat.Forwarder + gitSSHSigningKey string + errChan chan error +} + // getExitAfterTimeout resolves the per-forward idle-shutdown duration. // Returns 0 (no idle shutdown) when disableIdleTimeout is set or when // EXIT_AFTER_TIMEOUT is not true in the active context. @@ -93,15 +102,6 @@ func createForwarder( return newForwarder(opts.ContainerClient, ports, resolver) } -// tunnelServerParams contains parameters for running the tunnel server. -type tunnelServerParams struct { - opts RunServicesOptions - stdoutReader *os.File - stdinWriter *os.File - forwarder netstat.Forwarder - errChan chan error -} - // runTunnelServer runs the tunnel server in a goroutine. func runTunnelServer(ctx context.Context, cancel context.CancelFunc, p tunnelServerParams) { defer cancel() @@ -117,6 +117,7 @@ func runTunnelServer(ctx context.Context, cancel context.CancelFunc, p tunnelSer p.opts.Workspace, tunnelserver.WithPlatformOptions(p.opts.PlatformOptions), tunnelserver.WithAllowGitHubCredentials(p.opts.ConfigureGitHubCredentials), + tunnelserver.WithGitSSHSigningKey(p.gitSSHSigningKey), ) if err != nil { p.errChan <- fmt.Errorf("run tunnel server: %w", err) @@ -124,35 +125,59 @@ func runTunnelServer(ctx context.Context, cancel context.CancelFunc, p tunnelSer close(p.errChan) } -// addGitSSHSigningKey adds SSH signing key to command if configured. -// When explicitKey is set (from --git-ssh-signing-key flag), it takes -// precedence over the host's .gitconfig. This ensures signing works -// even when user.signingkey is not in the host git configuration. +func resolveGitSSHSigningKey(ctx context.Context, opts RunServicesOptions) string { + if !opts.ConfigureGitSSHSignatureHelper { + return "" + } + workingDir := "" + if opts.Workspace != nil { + workingDir = opts.Workspace.Source.LocalFolder + } + return resolveHostGitSSHSigningKey(ctx, opts.GitSSHSigningKey, workingDir) +} + +func resolveHostGitSSHSigningKey( + ctx context.Context, + explicitKey string, + workingDir string, +) string { + if explicitKey != "" { + return gitsshsigning.ExpandSigningKeyPath(explicitKey) + } + format, extracted, err := gitsshsigning.ExtractGitConfiguration(ctx, workingDir) + if err != nil { + log.Debugf("failed to extract git configuration: %v", err) + return "" + } + if format != gitsshsigning.GPGFormatSSH || extracted == "" { + return "" + } + return extracted +} + +func appendGitSSHSigningKey(command, signingKey string) string { + if signingKey == "" { + return command + } + encodedKey := base64.StdEncoding.EncodeToString([]byte(signingKey)) + return command + fmt.Sprintf(" --git-user-signing-key %s", encodedKey) +} + func addGitSSHSigningKey( ctx context.Context, command string, explicitKey string, workingDir string, ) string { - userSigningKey := explicitKey - if userSigningKey == "" { - format, extracted, err := gitsshsigning.ExtractGitConfiguration(ctx, workingDir) - if err != nil { - log.Debugf("failed to extract git configuration: %v", err) - return command - } - if format != gitsshsigning.GPGFormatSSH || extracted == "" { - return command - } - userSigningKey = extracted - } - encodedKey := base64.StdEncoding.EncodeToString([]byte(userSigningKey)) - command += fmt.Sprintf(" --git-user-signing-key %s", encodedKey) - return command + signingKey := resolveHostGitSSHSigningKey(ctx, explicitKey, workingDir) + return appendGitSSHSigningKey(command, signingKey) } -// buildCredentialsCommand builds the credentials server command. func buildCredentialsCommand(ctx context.Context, opts RunServicesOptions) string { + return formatCredentialsCommand(opts, resolveGitSSHSigningKey(ctx, opts)) +} + +func formatCredentialsCommand(opts RunServicesOptions, gitSSHSigningKey string) string { command := fmt.Sprintf( "%s internal agent container credentials-server --user %s", shellescape.Quote(config.ContainerDevsyHelperLocation), @@ -165,13 +190,7 @@ func buildCredentialsCommand(ctx context.Context, opts RunServicesOptions) strin command += " --host-owner " + shellescape.Quote(opts.HostOwner) command += " --configure-github-helper" } - if opts.ConfigureGitSSHSignatureHelper { - workingDir := "" - if opts.Workspace != nil { - workingDir = opts.Workspace.Source.LocalFolder - } - command = addGitSSHSigningKey(ctx, command, opts.GitSSHSigningKey, workingDir) - } + command = appendGitSSHSigningKey(command, gitSSHSigningKey) if opts.ConfigureDockerCredentials { command += " --configure-docker-helper" } @@ -208,14 +227,16 @@ func runServicesIteration( defer cancel() forwarder := createForwarder(opts, forwardedPorts, resolver) + gitSSHSigningKey := resolveGitSSHSigningKey(ctx, opts) errChan := make(chan error, 1) go runTunnelServer(cancelCtx, cancel, tunnelServerParams{ - opts: opts, - stdoutReader: stdoutReader, - stdinWriter: stdinWriter, - forwarder: forwarder, - errChan: errChan, + opts: opts, + stdoutReader: stdoutReader, + stdinWriter: stdinWriter, + forwarder: forwarder, + gitSSHSigningKey: gitSSHSigningKey, + errChan: errChan, }) writer, writerDone := log.PipeJSONStream() @@ -224,7 +245,7 @@ func runServicesIteration( <-writerDone }() - command := buildCredentialsCommand(ctx, opts) + command := formatCredentialsCommand(opts, gitSSHSigningKey) diagnostic := &boundedPreparationOutput{} err = devssh.Run(cancelCtx, devssh.RunOptions{ diff --git a/pkg/tunnel/services_test.go b/pkg/tunnel/services_test.go index 7891a2f19d..a2390c4bbb 100644 --- a/pkg/tunnel/services_test.go +++ b/pkg/tunnel/services_test.go @@ -4,11 +4,14 @@ import ( "context" "encoding/base64" "errors" + "os" + "path/filepath" "testing" "time" "github.com/devsy-org/devsy/pkg/config" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const testCtxName = "default" @@ -58,7 +61,10 @@ func TestGetExitAfterTimeout_DisableIdleTimeoutOverridesDisabled(t *testing.T) { ) } -const testBaseCommand = "devsy internal agent container credentials-server --user root" +const ( + testBaseCommand = "devsy internal agent container credentials-server --user root" + testUser = "testuser" +) func TestAddGitSSHSigningKey_ExplicitKey(t *testing.T) { command := testBaseCommand @@ -71,7 +77,7 @@ func TestAddGitSSHSigningKey_ExplicitKey(t *testing.T) { func TestAddGitSSHSigningKey_ExplicitKeyTakesPrecedence(t *testing.T) { // When an explicit key is provided, it should be used regardless // of what ExtractGitConfiguration might return from host .gitconfig. - command := testBaseCommand + command := "credentials-server --user dev" explicitKey := "/explicit/key.pub" result := addGitSSHSigningKey(context.Background(), command, explicitKey, "") @@ -94,7 +100,7 @@ func TestAddGitSSHSigningKey_EmptyExplicitKey_FallsBackToHostConfig(t *testing.T func TestBuildCredentialsCommand_IncludesSigningKey(t *testing.T) { opts := RunServicesOptions{ - User: "testuser", + User: testUser, ConfigureGitSSHSignatureHelper: true, GitSSHSigningKey: "/my/key.pub", } @@ -107,7 +113,7 @@ func TestBuildCredentialsCommand_IncludesSigningKey(t *testing.T) { func TestBuildCredentialsCommand_NoSigningKey(t *testing.T) { opts := RunServicesOptions{ - User: "testuser", + User: testUser, ConfigureGitSSHSignatureHelper: false, } command := buildCredentialsCommand(context.Background(), opts) @@ -217,3 +223,64 @@ func TestOptionalGitHubServicePreservesPolicyAfterUnrelatedFailure(t *testing.T) }) } } + +func TestAddGitSSHSigningKey_ExpandsTildeExplicitKey(t *testing.T) { + tmpHome := t.TempDir() + t.Setenv("HOME", tmpHome) + + result := addGitSSHSigningKey( + context.Background(), + testBaseCommand, + "~/.ssh/git_signing_ed25519", + "", + ) + + expectedPath := filepath.Join(tmpHome, ".ssh", "git_signing_ed25519") + encoded := base64.StdEncoding.EncodeToString([]byte(expectedPath)) + assert.Equal(t, testBaseCommand+" --git-user-signing-key "+encoded, result) +} + +func TestAddGitSSHSigningKey_ExpandsTildeFromHostGitConfig(t *testing.T) { + tmpHome := t.TempDir() + t.Setenv("HOME", tmpHome) + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + + gitConfig := "[gpg]\n\tformat = ssh\n[user]\n\tsigningkey = ~/.ssh/git_signing_ed25519\n" + require.NoError(t, os.WriteFile(filepath.Join(tmpHome, ".gitconfig"), []byte(gitConfig), 0o600)) + + workingDir := t.TempDir() + result := addGitSSHSigningKey(context.Background(), testBaseCommand, "", workingDir) + + expectedPath := filepath.Join(tmpHome, ".ssh", "git_signing_ed25519") + encoded := base64.StdEncoding.EncodeToString([]byte(expectedPath)) + assert.Equal(t, testBaseCommand+" --git-user-signing-key "+encoded, result) +} + +func TestBuildCredentialsCommand_ExpandsTildeSigningKey(t *testing.T) { + tmpHome := t.TempDir() + t.Setenv("HOME", tmpHome) + + opts := RunServicesOptions{ + User: testUser, + ConfigureGitSSHSignatureHelper: true, + GitSSHSigningKey: "~/.ssh/id_ed25519", + } + command := buildCredentialsCommand(context.Background(), opts) + + expectedPath := filepath.Join(tmpHome, ".ssh", "id_ed25519") + encoded := base64.StdEncoding.EncodeToString([]byte(expectedPath)) + assert.Contains(t, command, "--git-user-signing-key "+encoded) + assert.Contains(t, command, "--user testuser") +} + +func TestResolveGitSSHSigningKey_DisabledHelperReturnsEmpty(t *testing.T) { + tmpHome := t.TempDir() + t.Setenv("HOME", tmpHome) + + opts := RunServicesOptions{ + ConfigureGitSSHSignatureHelper: false, + GitSSHSigningKey: "~/.ssh/id_ed25519", + } + assert.Empty(t, resolveGitSSHSigningKey(context.Background(), opts)) +} From 2d19e40ccbc1eeea83fa152b161eb4f6934089d9 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 00:40:11 -0600 Subject: [PATCH 2/9] test(ssh): set USERPROFILE in signing tests --- pkg/agent/tunnelserver/tunnelserver_gitssh_test.go | 1 + pkg/tunnel/services_test.go | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go b/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go index d55a0932de..6219c4c38c 100644 --- a/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go +++ b/pkg/agent/tunnelserver/tunnelserver_gitssh_test.go @@ -38,6 +38,7 @@ func TestGitSSHSignature_DeserializesPublicKey(t *testing.T) { func TestGitSSHSignature_SignsWithHostKeyWithoutSSHAgent(t *testing.T) { hostHome := t.TempDir() t.Setenv("HOME", hostHome) + t.Setenv("USERPROFILE", hostHome) t.Setenv("SSH_AUTH_SOCK", "") sshDir := filepath.Join(hostHome, ".ssh") diff --git a/pkg/tunnel/services_test.go b/pkg/tunnel/services_test.go index a2390c4bbb..22441cc71f 100644 --- a/pkg/tunnel/services_test.go +++ b/pkg/tunnel/services_test.go @@ -227,6 +227,7 @@ func TestOptionalGitHubServicePreservesPolicyAfterUnrelatedFailure(t *testing.T) func TestAddGitSSHSigningKey_ExpandsTildeExplicitKey(t *testing.T) { tmpHome := t.TempDir() t.Setenv("HOME", tmpHome) + t.Setenv("USERPROFILE", tmpHome) result := addGitSSHSigningKey( context.Background(), @@ -243,6 +244,7 @@ func TestAddGitSSHSigningKey_ExpandsTildeExplicitKey(t *testing.T) { func TestAddGitSSHSigningKey_ExpandsTildeFromHostGitConfig(t *testing.T) { tmpHome := t.TempDir() t.Setenv("HOME", tmpHome) + t.Setenv("USERPROFILE", tmpHome) t.Setenv("XDG_CONFIG_HOME", "") t.Setenv("GIT_CONFIG_NOSYSTEM", "1") @@ -260,6 +262,7 @@ func TestAddGitSSHSigningKey_ExpandsTildeFromHostGitConfig(t *testing.T) { func TestBuildCredentialsCommand_ExpandsTildeSigningKey(t *testing.T) { tmpHome := t.TempDir() t.Setenv("HOME", tmpHome) + t.Setenv("USERPROFILE", tmpHome) opts := RunServicesOptions{ User: testUser, @@ -277,6 +280,7 @@ func TestBuildCredentialsCommand_ExpandsTildeSigningKey(t *testing.T) { func TestResolveGitSSHSigningKey_DisabledHelperReturnsEmpty(t *testing.T) { tmpHome := t.TempDir() t.Setenv("HOME", tmpHome) + t.Setenv("USERPROFILE", tmpHome) opts := RunServicesOptions{ ConfigureGitSSHSignatureHelper: false, From da159753f9369dd5067b2cece5d42cd15ed1e59a Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 01:14:35 -0600 Subject: [PATCH 3/9] fix(ssh): reject mismatched host-key fallback --- pkg/gitsshsigning/server.go | 6 ++++-- pkg/gitsshsigning/server_test.go | 23 ++++++++++++++++++++--- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/pkg/gitsshsigning/server.go b/pkg/gitsshsigning/server.go index b513122834..3dfbb2d858 100644 --- a/pkg/gitsshsigning/server.go +++ b/pkg/gitsshsigning/server.go @@ -75,10 +75,12 @@ func (req *GitSSHSignatureRequest) resolveKeyFile(hostSigningKey string) (string hostKeyPath := ExpandSigningKeyPath(hostSigningKey) if req.PublicKey == "" { - if regularFileExists(hostKeyPath) { + if hostKeyPath != "" && + (req.KeyPath == hostSigningKey || req.KeyPath == hostKeyPath) && + regularFileExists(hostKeyPath) { return hostKeyPath, noop, nil } - return "", noop, errors.New("no public key content or host signing key file") + return "", noop, errors.New("no public key content or matching host signing key file") } if hostKeyPath != "" && hostFileMatchesPublicKey(hostKeyPath, req.PublicKey) { diff --git a/pkg/gitsshsigning/server_test.go b/pkg/gitsshsigning/server_test.go index 909a106cad..dbdcc76abd 100644 --- a/pkg/gitsshsigning/server_test.go +++ b/pkg/gitsshsigning/server_test.go @@ -42,7 +42,7 @@ func TestSign_NonExistentKeyPath_ReturnsError(t *testing.T) { } _, err := req.Sign() - require.ErrorContains(t, err, "no public key content or host signing key file") + require.ErrorContains(t, err, "no public key content or matching host signing key file") } func TestResolveKeyFile_PublicKey_CreatesAndCleansTempFile(t *testing.T) { @@ -86,10 +86,27 @@ func TestResolveKeyFile_EmptyPublicKey_RequiresHostKey(t *testing.T) { req := &GitSSHSignatureRequest{KeyPath: "/host/untrusted/key"} _, cleanup, err := req.resolveKeyFile("") - require.ErrorContains(t, err, "no public key content or host signing key file") + require.ErrorContains(t, err, "no public key content or matching host signing key file") cleanup() } +func TestSign_MissingWorkspaceOverrideDoesNotUseHostKey(t *testing.T) { + hostHome := t.TempDir() + setTestHome(t, hostHome) + t.Setenv(envSSHAuthSock, "") + + hostKeyPath := filepath.Join(hostHome, testSSHDirName, testSigningKeyName) + _ = generateEd25519TestKey(t, hostKeyPath, "") + + req := &GitSSHSignatureRequest{ + Content: testCommitPayload, + KeyPath: "/home/vscode/.ssh/missing", + } + _, err := req.SignWithHostKey(hostKeyPath) + + require.ErrorContains(t, err, "no public key content or matching host signing key file") +} + func TestSign_HostTildePrivateKey_WithoutSSHAgent(t *testing.T) { hostHome := t.TempDir() setTestHome(t, hostHome) @@ -129,7 +146,7 @@ func TestSignWithHostKey_ContainerPrivateKeyDifferentHome_WithoutSSHAgent(t *tes reqWithoutPub := &GitSSHSignatureRequest{ Content: testCommitPayload, - KeyPath: testContainerKeyPath, + KeyPath: testTildeKeyPath, } respFallback, err := reqWithoutPub.SignWithHostKey(testTildeKeyPath) require.NoError(t, err) From 14627f8fcbfc80071f570feafb48ac0fb04ac6df Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:03:14 -0600 Subject: [PATCH 4/9] refactor(ssh): remove unused Sign wrapper --- pkg/gitsshsigning/server.go | 5 ----- pkg/gitsshsigning/server_test.go | 6 +++--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/pkg/gitsshsigning/server.go b/pkg/gitsshsigning/server.go index 3dfbb2d858..f0febf3a26 100644 --- a/pkg/gitsshsigning/server.go +++ b/pkg/gitsshsigning/server.go @@ -24,11 +24,6 @@ type GitSSHSignatureResponse struct { Signature []byte } -// Sign signs the content using the requested key and returns the signature. -func (req *GitSSHSignatureRequest) Sign() (*GitSSHSignatureResponse, error) { - return req.SignWithHostKey("") -} - // SignWithHostKey signs the content, preferring a matching host signing key file when available. func (req *GitSSHSignatureRequest) SignWithHostKey( hostSigningKey string, diff --git a/pkg/gitsshsigning/server_test.go b/pkg/gitsshsigning/server_test.go index dbdcc76abd..2e59bfb7c2 100644 --- a/pkg/gitsshsigning/server_test.go +++ b/pkg/gitsshsigning/server_test.go @@ -30,7 +30,7 @@ func TestSign_WithPublicKeyContent_WritesToTempFile(t *testing.T) { PublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeKeyForTesting test@example.com", } - _, err := req.Sign() + _, err := req.SignWithHostKey("") require.Error(t, err) assert.NotContains(t, err.Error(), "/tmp/.git_signing_key_does_not_exist") } @@ -41,7 +41,7 @@ func TestSign_NonExistentKeyPath_ReturnsError(t *testing.T) { KeyPath: "/tmp/.git_signing_key_does_not_exist", } - _, err := req.Sign() + _, err := req.SignWithHostKey("") require.ErrorContains(t, err, "no public key content or matching host signing key file") } @@ -184,7 +184,7 @@ func TestSign_RejectsInvalidNamespace(t *testing.T) { Content: testCommitPayload, Namespace: badNS, } - _, err := req.Sign() + _, err := req.SignWithHostKey("") require.ErrorContains(t, err, "invalid signing namespace") } } From fd176ba6d2adfa24223297338b353a4a9af6708c Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:04:42 -0600 Subject: [PATCH 5/9] fix(ssh): stop ssh-keygen when the signing request is cancelled --- pkg/agent/tunnelserver/tunnelserver.go | 2 +- pkg/credentials/integration_test.go | 4 ++-- pkg/gitsshsigning/server.go | 5 +++- pkg/gitsshsigning/server_test.go | 33 +++++++++++++++++++------- 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/pkg/agent/tunnelserver/tunnelserver.go b/pkg/agent/tunnelserver/tunnelserver.go index be50b26029..6e09ce970f 100644 --- a/pkg/agent/tunnelserver/tunnelserver.go +++ b/pkg/agent/tunnelserver/tunnelserver.go @@ -395,7 +395,7 @@ func (t *tunnelServer) GitSSHSignature( return nil, fmt.Errorf("git ssh sign request: %w", err) } - signatureResponse, err := signatureRequest.SignWithHostKey(t.gitSSHSigningKey) + signatureResponse, err := signatureRequest.SignWithHostKey(ctx, t.gitSSHSigningKey) if err != nil { return nil, fmt.Errorf("get git ssh signature: %w", err) } diff --git a/pkg/credentials/integration_test.go b/pkg/credentials/integration_test.go index 98e8a60f19..2bd33c9b8e 100644 --- a/pkg/credentials/integration_test.go +++ b/pkg/credentials/integration_test.go @@ -162,7 +162,7 @@ func TestIntegration_EndToEndPrivateKeyRelayWithoutSSHAgent(t *testing.T) { var capturedTunnelPayload string client := &mockCredentialsClient{ gitSSHSignatureFunc: func( - _ context.Context, + ctx context.Context, msg *tunnel.Message, ) (*tunnel.Message, error) { capturedTunnelPayload = msg.Message @@ -170,7 +170,7 @@ func TestIntegration_EndToEndPrivateKeyRelayWithoutSSHAgent(t *testing.T) { if err := json.Unmarshal([]byte(msg.Message), &req); err != nil { return nil, err } - resp, err := req.SignWithHostKey(hostPrivKey) + resp, err := req.SignWithHostKey(ctx, hostPrivKey) if err != nil { return nil, err } diff --git a/pkg/gitsshsigning/server.go b/pkg/gitsshsigning/server.go index f0febf3a26..02bd6f6571 100644 --- a/pkg/gitsshsigning/server.go +++ b/pkg/gitsshsigning/server.go @@ -2,6 +2,7 @@ package gitsshsigning import ( "bytes" + "context" "errors" "fmt" "os" @@ -26,6 +27,7 @@ type GitSSHSignatureResponse struct { // SignWithHostKey signs the content, preferring a matching host signing key file when available. func (req *GitSSHSignatureRequest) SignWithHostKey( + ctx context.Context, hostSigningKey string, ) (*GitSSHSignatureResponse, error) { namespace, err := resolveSigningNamespace(req.Namespace) @@ -39,7 +41,8 @@ func (req *GitSSHSignatureRequest) SignWithHostKey( } defer cleanup() //nolint:gosec // keyFile is a controlled temp path or validated signing key path - cmd := exec.Command( + cmd := exec.CommandContext( + ctx, "ssh-keygen", "-Y", "sign", diff --git a/pkg/gitsshsigning/server_test.go b/pkg/gitsshsigning/server_test.go index 2e59bfb7c2..950a47ddec 100644 --- a/pkg/gitsshsigning/server_test.go +++ b/pkg/gitsshsigning/server_test.go @@ -1,6 +1,7 @@ package gitsshsigning import ( + "context" "io" "os" "os/exec" @@ -30,7 +31,7 @@ func TestSign_WithPublicKeyContent_WritesToTempFile(t *testing.T) { PublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeKeyForTesting test@example.com", } - _, err := req.SignWithHostKey("") + _, err := req.SignWithHostKey(t.Context(), "") require.Error(t, err) assert.NotContains(t, err.Error(), "/tmp/.git_signing_key_does_not_exist") } @@ -41,7 +42,7 @@ func TestSign_NonExistentKeyPath_ReturnsError(t *testing.T) { KeyPath: "/tmp/.git_signing_key_does_not_exist", } - _, err := req.SignWithHostKey("") + _, err := req.SignWithHostKey(t.Context(), "") require.ErrorContains(t, err, "no public key content or matching host signing key file") } @@ -102,7 +103,7 @@ func TestSign_MissingWorkspaceOverrideDoesNotUseHostKey(t *testing.T) { Content: testCommitPayload, KeyPath: "/home/vscode/.ssh/missing", } - _, err := req.SignWithHostKey(hostKeyPath) + _, err := req.SignWithHostKey(t.Context(), hostKeyPath) require.ErrorContains(t, err, "no public key content or matching host signing key file") } @@ -120,7 +121,7 @@ func TestSign_HostTildePrivateKey_WithoutSSHAgent(t *testing.T) { KeyPath: testTildeKeyPath, } - resp, err := req.SignWithHostKey(testTildeKeyPath) + resp, err := req.SignWithHostKey(t.Context(), testTildeKeyPath) require.NoError(t, err) assertValidSSHSignature(t, pubLine, req, resp.Signature) } @@ -140,7 +141,7 @@ func TestSignWithHostKey_ContainerPrivateKeyDifferentHome_WithoutSSHAgent(t *tes KeyPath: testContainerKeyPath, PublicKey: derivedPub, } - resp, err := reqWithPub.SignWithHostKey(testTildeKeyPath) + resp, err := reqWithPub.SignWithHostKey(t.Context(), testTildeKeyPath) require.NoError(t, err) assertValidSSHSignature(t, pubLine, reqWithPub, resp.Signature) @@ -148,7 +149,7 @@ func TestSignWithHostKey_ContainerPrivateKeyDifferentHome_WithoutSSHAgent(t *tes Content: testCommitPayload, KeyPath: testTildeKeyPath, } - respFallback, err := reqWithoutPub.SignWithHostKey(testTildeKeyPath) + respFallback, err := reqWithoutPub.SignWithHostKey(t.Context(), testTildeKeyPath) require.NoError(t, err) assertValidSSHSignature(t, pubLine, reqWithoutPub, respFallback.Signature) } @@ -173,7 +174,7 @@ func TestSign_SamePathHostAndContainerPrivateKey_WithoutSSHAgent(t *testing.T) { cleanup() assert.FileExists(t, sharedKeyPath) - resp, err := req.SignWithHostKey(sharedKeyPath) + resp, err := req.SignWithHostKey(t.Context(), sharedKeyPath) require.NoError(t, err) assertValidSSHSignature(t, pubLine, req, resp.Signature) } @@ -184,11 +185,27 @@ func TestSign_RejectsInvalidNamespace(t *testing.T) { Content: testCommitPayload, Namespace: badNS, } - _, err := req.SignWithHostKey("") + _, err := req.SignWithHostKey(t.Context(), "") require.ErrorContains(t, err, "invalid signing namespace") } } +func TestSignWithHostKey_CancelledContextStopsSigning(t *testing.T) { + t.Setenv(envSSHAuthSock, "") + hostKeyPath := filepath.Join(t.TempDir(), testSSHDirName, testSigningKeyName) + _ = generateEd25519TestKey(t, hostKeyPath, "") + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + req := &GitSSHSignatureRequest{ + Content: testCommitPayload, + PublicKey: extractPublicKeyForRequest(hostKeyPath), + } + _, err := req.SignWithHostKey(ctx, hostKeyPath) + + require.ErrorIs(t, err, context.Canceled) +} + func TestResolveKeyFile_DoesNotUseRequestKeyPath(t *testing.T) { hostKeyPath := filepath.Join(t.TempDir(), "host-signing-key") requestKeyPath := filepath.Join(t.TempDir(), "container-selected-key") From ae4c87d9ab6160199969f9b52b47be4cbc738b0c Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:17:57 -0600 Subject: [PATCH 6/9] refactor(ssh): forward only parseable public keys --- pkg/credentials/integration_test.go | 5 ++-- pkg/gitsshsigning/client_test.go | 33 ++++++++++++++++++++------ pkg/gitsshsigning/key.go | 36 ----------------------------- 3 files changed, 28 insertions(+), 46 deletions(-) diff --git a/pkg/credentials/integration_test.go b/pkg/credentials/integration_test.go index 2bd33c9b8e..cb713890d3 100644 --- a/pkg/credentials/integration_test.go +++ b/pkg/credentials/integration_test.go @@ -125,9 +125,8 @@ func TestIntegration_SignatureRequest_IncludesPublicKeyContent(t *testing.T) { t.Cleanup(func() { gitsshsigning.SetSignatureServerURL("") }) tmpDir := t.TempDir() - certFile := filepath.Join(tmpDir, "test_key.pub") - pubKeyContent := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest test@example.com" - require.NoError(t, os.WriteFile(certFile, []byte(pubKeyContent), 0o600)) + privPath, pubKeyContent := generateDisposableEd25519KeyPair(t, tmpDir) + certFile := privPath + ".pub" bufferFile := filepath.Join(tmpDir, "buffer") require.NoError(t, os.WriteFile(bufferFile, []byte("commit content"), 0o600)) diff --git a/pkg/gitsshsigning/client_test.go b/pkg/gitsshsigning/client_test.go index ce4a61d0e5..9c762334e1 100644 --- a/pkg/gitsshsigning/client_test.go +++ b/pkg/gitsshsigning/client_test.go @@ -119,9 +119,9 @@ func TestRequestContentSignature_InvalidJSON(t *testing.T) { } func TestCreateSignatureRequestBody_IncludesPublicKeyContent(t *testing.T) { - certPath := filepath.Join(t.TempDir(), "test_key.pub") - pubKeyContent := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest test@example.com" - require.NoError(t, os.WriteFile(certPath, []byte(pubKeyContent), 0o600)) + keyPath := filepath.Join(t.TempDir(), "test_key") + pubKeyContent := generateEd25519TestKey(t, keyPath, "") + certPath := keyPath + ".pub" body, err := createSignatureRequestBody( []byte("commit content"), @@ -150,6 +150,23 @@ func TestCreateSignatureRequestBody_MissingCertFile_OmitsPublicKey(t *testing.T) assert.Empty(t, req.PublicKey) } +func TestCreateSignatureRequestBody_UnparseablePublicKey_OmitsPublicKey(t *testing.T) { + certPath := filepath.Join(t.TempDir(), "bogus.pub") + bogus := "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITest test@example.com" + require.NoError(t, os.WriteFile(certPath, []byte(bogus), 0o600)) + + body, err := createSignatureRequestBody( + []byte("commit content"), + certPath, + defaultSigningNamespace, + ) + require.NoError(t, err) + + var req GitSSHSignatureRequest + require.NoError(t, json.Unmarshal(body, &req)) + assert.Empty(t, req.PublicKey) +} + func TestGetCredentialsPort_DefaultWhenEnvUnset(t *testing.T) { t.Setenv(config.EnvCredentialsServerPort, "") port, err := getCredentialsPort() @@ -266,7 +283,8 @@ func TestCreateSignatureRequestBody_MalformedPrivateKeyStub_NeverLeaksPrivateKey require.NoError(t, json.Unmarshal(body, &req)) assert.Empty(t, req.PublicKey) - require.NoError(t, os.WriteFile(keyPath+".pub", []byte(testSyntheticPublicKey+"\n"), 0o600)) + realPub := generateEd25519TestKey(t, filepath.Join(t.TempDir(), "real_ed25519"), "") + require.NoError(t, os.WriteFile(keyPath+".pub", []byte(realPub+"\n"), 0o600)) bodyWithPub, err := createSignatureRequestBody( []byte("commit content"), @@ -276,7 +294,7 @@ func TestCreateSignatureRequestBody_MalformedPrivateKeyStub_NeverLeaksPrivateKey require.NoError(t, err) assert.NotContains(t, string(bodyWithPub), testPrivateKeyMarker) require.NoError(t, json.Unmarshal(bodyWithPub, &req)) - assert.Equal(t, testSyntheticPublicKey, req.PublicKey) + assert.Equal(t, realPub, req.PublicKey) } func TestHandleGitSSHProgramCall_ForwardsNamespace(t *testing.T) { @@ -293,8 +311,9 @@ func TestHandleGitSSHProgramCall_ForwardsNamespace(t *testing.T) { t.Cleanup(func() { SetSignatureServerURL("") }) dir := t.TempDir() - certPath := filepath.Join(dir, "key.pub") - require.NoError(t, os.WriteFile(certPath, []byte("ssh-ed25519 AAAAC3 test@example.com"), 0o600)) + certKeyPath := filepath.Join(dir, "key") + _ = generateEd25519TestKey(t, certKeyPath, "") + certPath := certKeyPath + ".pub" bufferFile := filepath.Join(dir, "buffer") require.NoError(t, os.WriteFile(bufferFile, []byte("payload to sign"), 0o600)) diff --git a/pkg/gitsshsigning/key.go b/pkg/gitsshsigning/key.go index 9a8c76899b..694effee81 100644 --- a/pkg/gitsshsigning/key.go +++ b/pkg/gitsshsigning/key.go @@ -13,18 +13,10 @@ import ( const ( maxKeyFileSize = 64 * 1024 - base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" openSSHPrivateKeyType = "OPENSSH PRIVATE KEY" openSSHKeyV1Magic = "openssh-key-v1\x00" ) -var sshPublicKeyPrefixes = [...]string{ - "ssh-", - "ecdsa-sha2-", - "sk-ssh-", - "sk-ecdsa-", -} - type openSSHPrivateKeyHeader struct { CipherName string KdfName string @@ -126,37 +118,9 @@ func parsePublicKeyLine(data []byte) string { if _, _, _, _, err := ssh.ParseAuthorizedKey(data); err == nil { return trimmed } - if hasSSHPublicKeyPrefix(trimmed) { - return trimmed - } return "" } -func hasSSHPublicKeyPrefix(line string) bool { - fields := strings.Fields(line) - if len(fields) < 2 || !isBase64Token(fields[1]) { - return false - } - for _, prefix := range sshPublicKeyPrefixes { - if strings.HasPrefix(fields[0], prefix) && len(fields[0]) > len(prefix) { - return true - } - } - return false -} - -func isBase64Token(s string) bool { - if s == "" { - return false - } - for i := range len(s) { - if strings.IndexByte(base64Alphabet, s[i]) < 0 { - return false - } - } - return true -} - func hostFileMatchesPublicKey(hostPath, publicKey string) bool { if hostPath == "" || publicKey == "" { return false From c678f9a87ac9764f38e6506bed5955d761808cac Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:18:42 -0600 Subject: [PATCH 7/9] fix(ssh): keep carriage returns in quoted signing key values --- pkg/gitsshsigning/helper.go | 1 - pkg/gitsshsigning/helper_test.go | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/pkg/gitsshsigning/helper.go b/pkg/gitsshsigning/helper.go index dc8a84da77..cbf1c2314e 100644 --- a/pkg/gitsshsigning/helper.go +++ b/pkg/gitsshsigning/helper.go @@ -34,7 +34,6 @@ var ( `"`, `\"`, "\n", `\n`, "\t", `\t`, - "\r", "", ) ) diff --git a/pkg/gitsshsigning/helper_test.go b/pkg/gitsshsigning/helper_test.go index 82b24eda9a..882e3b43f5 100644 --- a/pkg/gitsshsigning/helper_test.go +++ b/pkg/gitsshsigning/helper_test.go @@ -206,7 +206,7 @@ func TestFormatGitConfigValue_QuotesOnlySpecialCharacters(t *testing.T) { ) assert.Equal( t, - `"/path/with\ninjected"`, + "\"/path/with\r\\ninjected\"", formatGitConfigValue("/path/with\r\ninjected"), ) hashAndSemiPath := "/Users/alice/c#-app;v2/.ssh/git_signing_ed25519" @@ -225,4 +225,19 @@ func TestFormatGitConfigValue_QuotesOnlySpecialCharacters(t *testing.T) { ).CombinedOutput() require.NoError(t, err, "git config failed on #/; path: %s", string(out)) assert.Equal(t, hashAndSemiPath, strings.TrimSpace(string(out))) + + crPath := "/tmp/a\r\nb/key" + crConfigPath := filepath.Join(t.TempDir(), ".gitconfig") + require.NoError(t, updateGitConfig(crConfigPath, "", crPath)) + //nolint:gosec // test-only git config verification + crOut, err := exec.Command( + "git", + "config", + "--file", + crConfigPath, + "--get", + "user.signingkey", + ).Output() + require.NoError(t, err) + assert.Equal(t, crPath, strings.TrimSuffix(string(crOut), "\n")) } From 09c5647691d9d1aca179b844c047b450ca94a635 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:20:10 -0600 Subject: [PATCH 8/9] test(ssh): assert a workspace-only signing key cannot sign without an agent --- e2e/tests/ssh/ssh.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/e2e/tests/ssh/ssh.go b/e2e/tests/ssh/ssh.go index 2daf4a65dd..41f19cfee8 100644 --- a/e2e/tests/ssh/ssh.go +++ b/e2e/tests/ssh/ssh.go @@ -583,6 +583,7 @@ func setupIsolatedTildeSigningHome() (string, string) { t.Setenv("DEVSY_HOME", filepath.Join(hostHome, ".devsy")) t.Setenv("GIT_CONFIG_NOSYSTEM", "1") t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(hostHome, ".gitconfig")) t.Setenv(envSSHAuthSock, "") return writeTildeSigningKeyAndGitConfig(hostHome) @@ -655,5 +656,11 @@ func buildTildeSigningScript(privKeyBase64, pubKey string) string { gitAddFileCmd, "git commit -m 'signed via workspace tilde override' 2>&1", gitVerifyCommitCmd, + "ssh-keygen -q -t ed25519 -N '' -f ~/.ssh/workspace_only_ed25519", + "git config user.signingkey '~/.ssh/workspace_only_ed25519'", + "echo third >> file.txt", + gitAddFileCmd, + "! git commit -m 'workspace-only key must not sign' 2>&1", + "test \"$(git rev-list --count HEAD)\" = 2", }, " && ") } From 7bc99780fb6e58c340dcf1d0cea45c551dab4759 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Fri, 30 Oct 2026 10:20:40 -0600 Subject: [PATCH 9/9] docs(credentials): document Git SSH commit signing --- .../docs/developing-in-workspaces/credentials.mdx | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/credentials.mdx b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/credentials.mdx index 70e6ad30cd..f573b43675 100644 --- a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/credentials.mdx +++ b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/credentials.mdx @@ -27,6 +27,18 @@ devsy context set default -o SSH_AGENT_FORWARDING=false Disabling HTTPS credential injection does not disable SSH agent forwarding. +### Commit signing + +When your host Git configuration sets `gpg.format = ssh` and `user.signingkey`, Devsy signs commits made in the workspace with your host key. The workspace never receives the private key. This is controlled by the `GIT_SSH_SIGNATURE_FORWARDING` context option, which is on by default: + +```sh +devsy context set default -o GIT_SSH_SIGNATURE_FORWARDING=false +``` + +`user.signingkey` can be a path to a private or public key file, or a literal public key. Devsy expands `~/` and `~user/` on the host, so a path such as `~/.ssh/git_signing_ed25519` points at your host home directory, not the workspace home directory. A private key file needs no ssh-agent. Pass `--git-ssh-signing-key` to `devsy workspace up` or `devsy workspace ssh` to use a key other than the one in your Git configuration. + +Only the key from your host configuration can be used as a file on the host. A workspace that selects a different key through its own `user.signingkey` can sign only if an ssh-agent holds that key. Otherwise signing fails and no commit is created. Devsy signs with the `git` namespace only. + ## GitHub CLI GitHub CLI credential forwarding is **off by default**. Enable it for a trusted context: