Skip to content
178 changes: 170 additions & 8 deletions e2e/tests/ssh/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ssh

import (
"context"
"encoding/base64"
"math/rand"
"net"
"os"
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
}, " && ")

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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()),
Expand Down Expand Up @@ -502,3 +569,98 @@ 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("GIT_CONFIG_GLOBAL", filepath.Join(hostHome, ".gitconfig"))
t.Setenv(envSSHAuthSock, "")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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,
"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",
}, " && ")
}
8 changes: 8 additions & 0 deletions pkg/agent/tunnelserver/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 5 additions & 4 deletions pkg/agent/tunnelserver/tunnelserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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(ctx, t.gitSSHSigningKey)
if err != nil {
return nil, fmt.Errorf("get git ssh signature: %w", err)
}
Expand Down
52 changes: 52 additions & 0 deletions pkg/agent/tunnelserver/tunnelserver_gitssh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -30,3 +34,51 @@ 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("USERPROFILE", 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 <test@example.com> 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-----")
}
Loading
Loading