-
Notifications
You must be signed in to change notification settings - Fork 3
/
deploy.go
359 lines (296 loc) · 8.17 KB
/
deploy.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package cmd
import (
"archive/zip"
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/lestrrat-go/jwx/v2/jwt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/capeprivacy/cli/render"
"github.com/capeprivacy/cli/sdk"
czip "github.com/capeprivacy/cli/zip"
)
type PublicKeyRequest struct {
FunctionTokenPublicKey string `json:"function_token_pk"`
}
type DeployResponse struct {
ID string `json:"id"`
}
const storedFunctionMaxBytes = 1_000_000_000
type OversizeFunctionError struct {
bytes int64
}
func (e OversizeFunctionError) Error() string {
return fmt.Sprintf("deployment (%d bytes) exceeds size limit of %d bytes", e.bytes, storedFunctionMaxBytes)
}
// deployCmd represents the request command
var deployCmd = &cobra.Command{
Use: "deploy { <directory> | <zip_file> }",
Short: "Deploy a function",
Long: `Deploy a function to Cape.
This will return an ID that can later be used to invoke the deployed function
with cape run (see cape run -h for details).
`,
RunE: func(cmd *cobra.Command, args []string) error {
err := deploy(cmd, args)
if _, ok := err.(UserError); !ok {
cmd.SilenceUsage = true
}
return err
},
}
func init() {
rootCmd.AddCommand(deployCmd)
deployCmd.PersistentFlags().StringP("name", "n", "", "a name to give this function (default is the directory name)")
deployCmd.PersistentFlags().StringSliceP("pcr", "p", []string{""}, "pass multiple PCRs to validate against")
deployCmd.PersistentFlags().BoolP("public", "", false, "make the function public (anyone can run it)")
registerTemplate(deployCmd.Name(), deployTmpl)
}
func deploy(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return UserError{Msg: "you must specify a directory to upload", Err: fmt.Errorf("invalid number of input arguments")}
}
u := C.EnclaveHost
insecure := C.Insecure
n, err := cmd.Flags().GetString("name")
if err != nil {
return UserError{Msg: "name not specified correctly", Err: err}
}
pcrSlice, err := cmd.Flags().GetStringSlice("pcr")
if err != nil {
return UserError{Msg: "error retrieving pcr flags", Err: err}
}
public, err := cmd.Flags().GetBool("public")
if err != nil {
return UserError{Msg: "error retrieving public flag", Err: err}
}
functionInput := args[0]
name := getName(functionInput, n)
dID, checksum, err := doDeploy(u, functionInput, name, insecure, pcrSlice, public)
if err != nil {
return err
}
username, err := getUsername()
if err != nil {
return err
}
// older tokens might not have a username, in that case, we just won't tell them the function alias
functionName := ""
if username != "" {
functionName = fmt.Sprintf("%s/%s", username, name)
}
output := struct {
ID string `json:"function_id"`
Checksum string `json:"function_checksum"`
FunctionName string `json:"function_name,omitempty"`
}{
ID: dID,
Checksum: fmt.Sprintf("%x", checksum),
FunctionName: functionName,
}
return render.Ctx(cmd.Context()).Render(cmd.OutOrStdout(), output)
}
func getName(functionInput string, nameFlag string) string {
if nameFlag != "" {
return nameFlag
}
return strings.Split(filepath.Base(functionInput), ".")[0]
}
func doDeploy(url string, functionInput string, functionName string, insecure bool, pcrSlice []string, public bool) (string, []byte, error) {
file, err := os.Open(functionInput)
if err != nil {
return "", nil, fmt.Errorf("unable to read function directory or file: %w", err)
}
st, err := file.Stat()
if err != nil {
return "", nil, fmt.Errorf("unable to read function file or directory: %w", err)
}
isZip := false
var fileSize int64
if st.IsDir() {
_, err = file.Readdirnames(1)
if err != nil {
return "", nil, fmt.Errorf("please pass in a non-empty directory: %w", err)
}
fileSize, err = dirSize(functionInput)
if err != nil {
return "", nil, fmt.Errorf("error reading file size: %w", err)
}
} else {
// Check if file ends with ".zip" extension.
fileExtension := filepath.Ext(functionInput)
if fileExtension != ".zip" {
return "", nil, fmt.Errorf("expected argument %s to be a zip file or directory", functionInput)
}
isZip = true
zSize, err := zipSize(functionInput)
if err != nil {
return "", nil, err
}
fileSize = int64(zSize)
}
log.Debugf("Deployment size: %d bytes", fileSize)
if fileSize > storedFunctionMaxBytes {
err = OversizeFunctionError{bytes: fileSize}
log.Error(err.Error())
return "", nil, err
}
err = file.Close()
if err != nil {
return "", nil, fmt.Errorf("something went wrong: %w", err)
}
var reader io.Reader
if isZip {
f, err := os.Open(functionInput)
if err != nil {
return "", nil, fmt.Errorf("unable to read function file: %w", err)
}
reader = f
} else {
buf, err := czip.Create(functionInput)
if err != nil {
return "", nil, err
}
reader = bytes.NewBuffer(buf)
}
token, err := getAuthToken()
if err != nil {
return "", nil, err
}
// Public functions do not include a public key.
// Public keys are used for function tokens.
functionTokenPublicKey := ""
if !public {
functionTokenPublicKey, err = getFunctionTokenPublicKey()
if err != nil {
return "", nil, err
}
}
keyReq, err := GetKeyRequest(pcrSlice)
if err != nil {
return "", nil, err
}
id, checksum, err := sdk.Deploy(sdk.DeployRequest{
URL: url,
Name: functionName,
Reader: reader,
Insecure: insecure,
PcrSlice: pcrSlice,
FunctionTokenPublicKey: functionTokenPublicKey,
AuthToken: token,
}, keyReq)
if err != nil {
return "", nil, fmt.Errorf("unable to deploy function: %w", err)
}
return id, checksum, nil
}
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += info.Size()
}
return nil
})
return size, err
}
func zipSize(path string) (uint64, error) {
var size uint64
r, err := zip.OpenReader(path)
if err != nil {
return 0, err
}
for _, f := range r.File {
size += f.UncompressedSize64
}
return size, nil
}
func getUsername() (string, error) {
t, err := getAuthToken()
if err != nil {
return "", err
}
token, err := jwt.Parse([]byte(t), jwt.WithVerify(false))
if err != nil {
return "", err
}
return token.PrivateClaims()["https://capeprivacy.com/username"].(string), nil
}
func getAuthToken() (string, error) {
tokenResponse, err := getTokenResponse()
if err != nil {
return "", fmt.Errorf("failed to get auth token (did you run 'cape login'?): %v", err)
}
if tokenResponse.AccessToken == "" {
return "", fmt.Errorf("empty access token (did you run 'cape login'?)")
}
log.Debug("* Retrieved Auth Token")
return tokenResponse.AccessToken, nil
}
func getOrGeneratePublicKey() (*rsa.PublicKey, error) {
publicKey, err := getPublicKey()
if err != nil {
// Attempt to generate a key pair if reading public key fails.
err = generateKeyPair()
if err != nil {
return nil, nil
}
publicKey, err = getPublicKey()
if err != nil {
return nil, nil
}
}
return publicKey, err
}
func getPublicKey() (*rsa.PublicKey, error) {
keyPEM, err := getPublicKeyPEM()
if err != nil {
return nil, err
}
block, _ := pem.Decode(keyPEM.Bytes())
if block == nil || block.Type != "PUBLIC KEY" {
return nil, errors.New("failed to decode public key")
}
publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
return publicKey.(*rsa.PublicKey), nil
}
func getPublicKeyPEM() (*bytes.Buffer, error) {
publicKeyPEM, err := os.Open(filepath.Join(C.LocalConfigDir, publicKeyFile))
if err != nil {
return nil, err
}
defer publicKeyPEM.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(publicKeyPEM)
if err != nil {
return nil, err
}
return buf, nil
}
func getFunctionTokenPublicKey() (string, error) {
_, err := getOrGeneratePublicKey()
if err != nil {
return "", err
}
// Read the raw PEM.
pem, err := getPublicKeyPEM()
if err != nil {
return "", err
}
return pem.String(), nil
}
var deployTmpl = `Function ID ➜ {{ .ID }}
Function Checksum ➜ {{ .Checksum }}
Function Name ➜ {{ .FunctionName }}
`