-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbufisk.go
322 lines (301 loc) · 9.18 KB
/
bufisk.go
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Copyright 2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"aead.dev/minisign"
)
const (
// If not set, falls back to $XDG_CACHE_HOME and then $HOME/.cache
// on unix, or %LocalAppData% for windows.
cacheDirPathEnvKey = "BUFISK_CACHE_DIR"
useBufVersionEnvKey = "BUF_VERSION"
bufVersionFileName = ".bufversion"
minisignPublicKey = "RWQ/i9xseZwBVE7pEniCNjlNOeeyp4BQgdZDLQcAohxEAH5Uj5DEKjv6"
)
var (
interruptSignals = append(
[]os.Signal{
os.Interrupt,
},
extraInterruptSignals...,
)
)
func main() {
if err := run(); err != nil {
exitError := &exec.ExitError{
ProcessState: nil,
Stderr: nil,
}
if errors.As(err, &exitError) {
// Swallow error message - it was printed via os.Stderr redirection.
os.Exit(exitError.ExitCode())
}
if errString := err.Error(); errString != "" {
_, _ = fmt.Fprintf(os.Stderr, "bufisk: %s\n", errString)
}
os.Exit(1)
}
}
func run() error {
ctx, cancel := withCancelInterruptSignal(context.Background())
defer cancel()
bufVersion, err := getBufVersion()
if err != nil {
return err
}
cacheDirPath := os.Getenv(cacheDirPathEnvKey)
if cacheDirPath == "" {
cacheDirPath, err = getDefaultCacheDirPath()
if err != nil {
return err
}
cacheDirPath = filepath.Join(cacheDirPath, "bufisk")
}
bufFilePath := filepath.Join(cacheDirPath, unameS, unameM, "releases", "buf", bufVersion, "bin", "buf")
if _, err := os.Stat(bufFilePath); err != nil {
if err := downloadBufToFilePath(ctx, bufVersion, bufFilePath); err != nil {
return err
}
if _, err := fmt.Fprintf(os.Stderr, "bufisk: downloaded buf to %s\n\n", bufFilePath); err != nil {
return err
}
}
cmd := exec.CommandContext(ctx, bufFilePath, os.Args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// Should do some check on the returned version format.
func getBufVersion() (string, error) {
if useBufVersionEnvValue := os.Getenv(useBufVersionEnvKey); useBufVersionEnvValue != "" {
return validateBufVersion(useBufVersionEnvValue, useBufVersionEnvKey)
}
pwd, err := os.Getwd()
if err != nil {
return "", err
}
curDirPath := pwd
for {
filePath := filepath.Join(curDirPath, bufVersionFileName)
data, err := os.ReadFile(filePath)
// Ignore all errors, not just fs.ErrNotExist - we don't want this program to fail
// on bad permissions. We could choose to stop on the first bad permissions error.
if err == nil {
return validateBufVersion(strings.TrimSpace(string(data)), filePath)
}
// TODO: Not sure if works for Windows.
if curDirPath == string(os.PathSeparator) {
break
}
curDirPath = filepath.Dir(curDirPath)
}
return "", fmt.Errorf("%s not set and no %s file found", useBufVersionEnvKey, bufVersionFileName)
}
// We could import a SemVer library but this should be enough for now.
func validateBufVersion(bufVersion string, source string) (string, error) {
split := strings.Split(bufVersion, ".")
if len(split) != 3 {
return "", newInvalidBufVersionError(bufVersion, source)
}
for _, s := range split {
if _, err := strconv.Atoi(s); err != nil {
return "", newInvalidBufVersionError(bufVersion, source)
}
}
return bufVersion, nil
}
func downloadBufToFilePath(ctx context.Context, bufVersion string, bufFilePath string) (retErr error) {
fileName := fmt.Sprintf("buf-%s-%s%s", unameS, unameM, executableSuffix)
tempFilePath, err := downloadTempFile(ctx, getFileURL(bufVersion, fileName))
if err != nil {
return fmt.Errorf("could not download buf (are you sure %q is a valid release version?): %w", bufVersion, err)
}
// We could return the temporary *os.File from downloadTemp but oh well.
bufFileData, err := os.ReadFile(tempFilePath)
if err != nil {
return err
}
sha256TxtData, err := downloadData(ctx, getFileURL(bufVersion, "sha256.txt"))
if err != nil {
return err
}
sha256TxtMinisigData, err := downloadData(ctx, getFileURL(bufVersion, "sha256.txt.minisig"))
if err != nil {
return err
}
if err := verifySha256TxtData(sha256TxtData, sha256TxtMinisigData); err != nil {
return err
}
sha256ExpectedHex, err := getSha256HexForTxtData(sha256TxtData, fileName)
if err != nil {
return err
}
hash := sha256.New()
if _, err := hash.Write(bufFileData); err != nil {
return err
}
sha256Hex := hex.EncodeToString(hash.Sum(nil))
if sha256Hex != sha256ExpectedHex {
return fmt.Errorf("sha256 mismatch for %s: expected %q got %q", fileName, sha256Hex, sha256ExpectedHex)
}
if err := os.Chmod(tempFilePath, 0700); err != nil {
return err
}
return moveFileToPath(tempFilePath, bufFilePath)
}
func verifySha256TxtData(sha256TxtData []byte, sha256TxtMinisigData []byte) error {
var publicKey minisign.PublicKey
if err := publicKey.UnmarshalText([]byte(minisignPublicKey)); err != nil {
return err
}
var signature minisign.Signature
if err := signature.UnmarshalText(sha256TxtMinisigData); err != nil {
return err
}
if signature.KeyID != publicKey.ID() {
return fmt.Errorf("minisign key IDs for sha256.txt do not match: ID (public key): %X ID (signature): %X", publicKey.ID(), signature.KeyID)
}
rawSignature, err := signature.MarshalText()
if err != nil {
return err
}
if !minisign.Verify(publicKey, sha256TxtData, rawSignature) {
return errors.New("minisign signature verification of sha256.txt failed")
}
return nil
}
// Downloads to a temp file and returns the file path.
func downloadTempFile(ctx context.Context, url string) (string, error) {
var tempFilePath string
if err := download(
ctx,
url,
func(reader io.Reader) (retErr error) {
file, err := os.CreateTemp("", "bufisk*")
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil && retErr == nil {
retErr = err
}
}()
if _, err := io.Copy(file, reader); err != nil {
return err
}
tempFilePath = file.Name()
return nil
},
); err != nil {
return "", err
}
return tempFilePath, nil
}
func downloadData(ctx context.Context, url string) ([]byte, error) {
var data []byte
if err := download(
ctx,
url,
func(reader io.Reader) error {
var err error
data, err = io.ReadAll(reader)
return err
},
); err != nil {
return nil, err
}
return data, nil
}
func download(ctx context.Context, url string, processResponseBody func(io.Reader) error) (retErr error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
// Maybe don't use default client.
response, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer func() {
if err := response.Body.Close(); err != nil && retErr == nil {
retErr = err
}
}()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("%s: HTTP Status %d", url, response.StatusCode)
}
return processResponseBody(response.Body)
}
func moveFileToPath(fromFilePath string, toFilePath string) error {
if err := os.MkdirAll(filepath.Dir(toFilePath), 0700); err != nil {
return err
}
// This will replace any other file atomically.
return os.Rename(fromFilePath, toFilePath)
}
func getFileURL(bufVersion string, fileName string) string {
return fmt.Sprintf("https://github.com/bufbuild/buf/releases/download/v%s/%s", bufVersion, fileName)
}
func getSha256HexForTxtData(sha256TxtData []byte, fileName string) (string, error) {
// Just assuming we actually have \n in our uploaded file.
for _, line := range strings.Split(string(sha256TxtData), "\n") {
if strings.HasSuffix(line, fileName) {
split := strings.Split(line, " ")
if len(split) != 2 {
return "", fmt.Errorf("invalid sha256.txt line: %q", line)
}
return split[0], nil
}
}
return "", fmt.Errorf("could not find %q in sha256.txt:\n%s", fileName, string(sha256TxtData))
}
// withCancelInterruptSignal returns a context that is cancelled if interrupt signals are sent.
func withCancelInterruptSignal(ctx context.Context) (context.Context, context.CancelFunc) {
interruptSignalC, closer := newInterruptSignalChannel()
ctx, cancel := context.WithCancel(ctx)
go func() {
<-interruptSignalC
closer()
cancel()
}()
return ctx, cancel
}
// newInterruptSignalChannel returns a new channel for interrupt signals.
//
// Call the returned function to cancel sending to this channel.
func newInterruptSignalChannel() (<-chan os.Signal, func()) {
signalC := make(chan os.Signal, 1)
signal.Notify(signalC, interruptSignals...)
return signalC, func() {
signal.Stop(signalC)
close(signalC)
}
}
func newInvalidBufVersionError(bufVersion string, source string) error {
return fmt.Errorf(`invalid buf version from %s (must be in the form "MAJOR.MINOR.PATCH"): %q`, source, bufVersion)
}