-
Notifications
You must be signed in to change notification settings - Fork 3
/
run.go
245 lines (206 loc) · 6.59 KB
/
run.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
package cmd
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/spf13/cobra"
"github.com/capeprivacy/attest/attest"
"github.com/capeprivacy/cli"
"github.com/capeprivacy/cli/entities"
"github.com/capeprivacy/cli/sdk"
)
// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run { <function_id> | <user_name>/<function_name> } [input data]",
Short: "Run a deployed function with data",
Long: `Run a deployed function with data.
Results are output to stdout so you can easily pipe them elsewhere.`,
Example: `
# Run a function named 'echo' created by user 'capedocs'
$ cape run capedocs/echo 'Hello World'
# Run a function with input data provided on stdin
$ echo '1234' | cape run capedocs/echo -f -
# Filter a function's output through sed
$ cape run capedocs/echo 'Hello World' | sed 's/Hello/Hola/'
# Run while verifying PCRs
# PCRs can be retrieved with: 'cape get-pcrs'
# PCRs are specified through a string array of the form: [<PCR_number>:<PCR_value>], example below
$ cape run capedocs/echo 5 --pcr=0:placeholderPCR0,8:placeholderPCR8
`,
RunE: func(cmd *cobra.Command, args []string) error {
err := run(cmd, args)
if _, ok := err.(UserError); !ok {
cmd.SilenceUsage = true
}
return err
},
}
type RunResponse struct {
Type string `json:"type"`
Message []byte `json:"message"`
}
type AttestationResponse struct {
AttestationDoc string `json:"attestation_doc"`
}
type Message struct {
Type string `json:"type"`
Message []byte `json:"message"`
}
type ErrorRunResponse struct {
Message string `json:"message"`
}
func init() {
rootCmd.AddCommand(runCmd)
runCmd.PersistentFlags().StringP("token", "t", "", "authorization token to use")
runCmd.PersistentFlags().StringP("file", "f", "", "input data file (or '-f -' to accept stdin)")
runCmd.PersistentFlags().StringP("function-checksum", "", "", "function checksum to attest")
runCmd.PersistentFlags().StringP("key-policy-checksum", "", "", "key policy checksum to attest")
runCmd.PersistentFlags().StringSliceP("pcr", "p", []string{""}, "pass multiple PCRs to validate against")
}
func run(cmd *cobra.Command, args []string) error {
u := C.EnclaveHost
insecure := C.Insecure
output, err := cmd.Flags().GetString("output")
if err != nil {
return err
}
formatter, ok := runFormatters[output]
if !ok {
return fmt.Errorf("unknown output option: %s", output)
}
if len(args) < 1 {
return UserError{Msg: "you must pass a function ID or a function name", Err: fmt.Errorf("invalid number of input arguments")}
}
if len(args) > 2 {
return UserError{Msg: "you must pass in only one input data (stdin, string or filename)", Err: fmt.Errorf("invalid number of input arguments")}
}
auth := entities.FunctionAuth{Type: entities.AuthenticationTypeUserToken}
token, _ := cmd.Flags().GetString("token")
if token != "" {
auth.Token = token
} else {
token, err := getAuthToken()
if err != nil {
return err
}
auth.Token = token
}
functionID := args[0]
file, err := cmd.Flags().GetString("file")
if err != nil {
return UserError{Msg: "error retrieving file flag", Err: err}
}
funcChecksumArg, err := cmd.Flags().GetString("function-checksum")
if err != nil {
return UserError{Msg: "error retrieving function-checksum flag", Err: err}
}
var funcChecksum []byte
if funcChecksumArg != "" {
funcChecksum, err = hex.DecodeString(funcChecksumArg)
if err != nil {
return UserError{Msg: "error reading in checksum", Err: err}
}
}
pcrSlice, err := cmd.Flags().GetStringSlice("pcr")
if err != nil {
return UserError{Msg: "error retrieving pcr flags", Err: err}
}
keyChecksumArg, err := cmd.Flags().GetString("key-policy-checksum")
if err != nil {
return UserError{Msg: "error retrieving key_checksum flag", Err: err}
}
var keyChecksum []byte
if keyChecksumArg != "" {
keyChecksum, err = hex.DecodeString(keyChecksumArg)
if err != nil {
return UserError{Msg: "error reading in key policy checksum", Err: err}
}
}
input, err := getInput(cmd, args, file)
if err != nil {
return err
}
results, err := sdk.Run(sdk.RunRequest{
URL: u,
FunctionID: functionID,
Data: input,
Insecure: insecure,
FuncChecksum: funcChecksum,
KeyChecksum: keyChecksum,
PcrSlice: pcrSlice,
FunctionAuth: auth,
})
if err != nil {
return fmt.Errorf("run request failed: %w", err)
}
return formatter(*results)
}
func isValidFunctionID(functionID string) bool {
// an alphanumeric string of length 22 is considered a syntactically correct functionID
return regexp.MustCompile(`^[a-zA-Z0-9]{22}$`).MatchString(functionID)
}
func splitFunctionName(function string) (string, string, error) {
userName, functionName, found := strings.Cut(function, "/")
if !found {
return "", "", errors.New("no '/' in function name")
}
if userName == "" {
return "", functionName, errors.New("empty username")
}
if functionName == "" {
return userName, "", errors.New("empty function name")
}
return userName, functionName, nil
}
func getInput(cmd *cobra.Command, args []string, file string) ([]byte, error) {
switch {
case strings.TrimSpace(file) == "-":
// read input from stdin
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, cmd.InOrStdin()); err != nil {
return nil, UserError{Msg: "unable to read data from stdin", Err: err}
}
return buf.Bytes(), nil
case file != "":
// input file was provided
input, err := os.ReadFile(file)
if err != nil {
return nil, UserError{Msg: "unable to read data file", Err: err}
}
return input, nil
case len(args) == 2:
// read input from command line string
return []byte(args[1]), nil
default:
return nil, UserError{Msg: "invalid input", Err: errors.New("please provide input as a string, input file or stdin")}
}
}
var runFormatters = map[string]func(result cli.RunResult) error{
"plain": runPlain,
"json": runJSON,
}
func runPlain(result cli.RunResult) error {
fmt.Println(string(result.Message))
return nil
}
func runJSON(result cli.RunResult) error {
return json.NewEncoder(os.Stdout).Encode(struct {
Output string `json:"output"`
Checksums cli.Checksums `json:"checksums"`
SignedResults []byte `json:"signed_results"`
AttestationDoc *attest.AttestationDoc `json:"attestation_doc"`
RawAttestationDoc []byte `json:"raw_attestation_doc"`
}{
Output: string(result.Message),
Checksums: result.Checksums,
SignedResults: result.SignedChecksums,
AttestationDoc: result.DecodedAttestationDocument,
RawAttestationDoc: result.RawAttestationDocument,
})
}