forked from loft-sh/devpod
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathserver.go
More file actions
94 lines (79 loc) · 2.45 KB
/
server.go
File metadata and controls
94 lines (79 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package gitsshsigning
import (
"bytes"
"fmt"
"os"
"os/exec"
)
type GitSSHSignatureRequest struct {
Content string
KeyPath string
PublicKey string // Public key content; when set, written to a temp file for 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.
func (req *GitSSHSignatureRequest) Sign() (*GitSSHSignatureResponse, error) {
keyFile, cleanup, err := req.resolveKeyFile()
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
cmd := exec.Command(
"ssh-keygen",
"-Y",
"sign",
"-f",
keyFile,
"-n",
"git",
)
cmd.Stdin = &commitBuffer
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
return nil, fmt.Errorf("failed to sign commit: %w, stderr: %s", err, stderr.String())
}
return &GitSSHSignatureResponse{
Signature: out.Bytes(),
}, nil
}
// 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) {
noop := func() {}
if req.PublicKey == "" {
return req.KeyPath, noop, nil
}
// ssh-keygen -Y sign -f <path> reads the public key directly from <path>
// 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.
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 {
_ = tmpFile.Close()
_ = os.Remove(keyPath)
return "", noop, fmt.Errorf("write public key: %w", err)
}
_ = tmpFile.Close()
cleanup := func() {
_ = os.Remove(keyPath)
}
return keyPath, cleanup, nil
}