/
cloud.go
executable file
·260 lines (204 loc) · 6.39 KB
/
cloud.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
// Copyright (c) OpenFaaS Author(s). All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package commands
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/openfaas/faas-cli/proxy"
"github.com/openfaas/faas-cli/schema"
"github.com/spf13/cobra"
)
var (
namespace string
name string
literal *[]string
outputFile string
fromFile *[]string
certFile string
download bool
downloadVersion string
downloadTo string
)
func init() {
faasCmd.AddCommand(cloudCmd)
cloudSealCmd.Flags().StringVar(&name, "name", "", "Secret name")
cloudSealCmd.Flags().StringVarP(&namespace, "namespace", "n", "openfaas-fn", "Secret name")
cloudSealCmd.Flags().StringVarP(&certFile, "cert", "c", "pub-cert.pem", "Filename of public certificate")
cloudSealCmd.Flags().StringVarP(&outputFile, "output-file", "o", "secrets.yml", "Output file for secrets")
cloudSealCmd.Flags().BoolVar(&download, "download", false, "Download the kubeseal binary required for this command, see also --download-version")
cloudSealCmd.Flags().StringVar(&downloadVersion, "download-version", "", "Specify a kubeseal version to download")
cloudSealCmd.Flags().StringVar(&downloadTo, "download-to", "", "Specify download path for kubeseal, leave empty for a temp dir")
literal = cloudSealCmd.Flags().StringArrayP("literal", "l", []string{}, "Secret literal key-value data")
fromFile = cloudSealCmd.Flags().StringArrayP("from-file", "i", []string{}, "Read a secret from a from file")
cloudCmd.AddCommand(cloudSealCmd)
}
var cloudCmd = &cobra.Command{
Use: `cloud`,
Short: "OpenFaaS Cloud commands",
Long: "Commands for operating with OpenFaaS Cloud",
}
var cloudSealCmd = &cobra.Command{
Use: `seal [--name secret-name] [--literal k=v] [--from-file] [--namespace openfaas-fn] [--download]`,
Short: "Seal a secret for usage with OpenFaaS Cloud",
Example: ` faas-cli cloud seal --name alexellis-github --literal hmac-secret=c4488af0c158e8c
faas-cli cloud seal --name alexellis-token --from-file api-key.txt
faas-cli cloud seal --name alexellis-token --literal a=b --literal c=d --cert pub-cert.pem
faas-cli cloud seal --download
faas-cli cloud seal --download --download-version v0.9.5`,
RunE: runCloudSeal,
}
func runCloudSeal(cmd *cobra.Command, args []string) error {
if download {
return downloadKubeSeal()
}
if len(name) == 0 {
return fmt.Errorf("--name is required")
}
fmt.Printf("Sealing secret: %s in namespace: %s\n", name, namespace)
fmt.Println("")
enc := base64.StdEncoding
secret := schema.KubernetesSecret{
ApiVersion: "v1",
Kind: "Secret",
Metadata: schema.KubernetesSecretMetadata{
Name: name,
Namespace: namespace,
},
Data: make(map[string]string),
}
if literal != nil {
args, _ := parseBuildArgs(*literal)
for k, v := range args {
secret.Data[k] = enc.EncodeToString([]byte(v))
}
}
if fromFile != nil {
for _, file := range *fromFile {
bytesOut, err := ioutil.ReadFile(file)
if err != nil {
return err
}
key := filepath.Base(file)
secret.Data[key] = enc.EncodeToString(bytesOut)
}
}
sec, err := json.Marshal(secret)
if err != nil {
panic(err)
}
if _, err := os.Stat(certFile); err != nil {
return fmt.Errorf("unable to load public certificate %s", certFile)
}
kubeseal := exec.Command("kubeseal", "--format=yaml", "--cert="+certFile)
stdin, stdinErr := kubeseal.StdinPipe()
if stdinErr != nil {
panic(stdinErr)
}
stdin.Write(sec)
stdin.Close()
out, err := kubeseal.CombinedOutput()
if err != nil {
return fmt.Errorf("unable to start \"kubeseal\", check it is installed, error: %s", err.Error())
}
writeErr := ioutil.WriteFile(outputFile, out, 0755)
if writeErr != nil {
return fmt.Errorf("unable to write secret: %s to %s", name, outputFile)
}
fmt.Printf("%s written.\n", outputFile)
return nil
}
func downloadKubeSeal() error {
releases := "https://github.com/bitnami-labs/sealed-secrets/releases/latest"
releaseVersion := downloadVersion
if len(downloadVersion) == 0 {
version, err := findRelease(releases)
if err != nil {
return err
}
releaseVersion = version
}
osVal := runtime.GOOS
arch := runtime.GOARCH
if arch == "x86_64" {
arch = "amd64"
}
downloadURL := "https://github.com/bitnami/sealed-secrets/releases/download/" + releaseVersion + "/kubeseal-" + osVal + "-" + arch
fmt.Printf("Starting download of kubeseal %s, this could take a few moments.\n", releaseVersion)
output, err := downloadBinary(http.DefaultClient, downloadURL, "kubeseal", downloadTo)
if err != nil {
return err
}
fmt.Printf(`Download completed, please run:
chmod +x %s
%s --version
sudo install %s /usr/local/bin/
`, output, output, output)
return nil
}
func findRelease(url string) (string, error) {
timeout := time.Second * 5
client := proxy.MakeHTTPClient(&timeout, false)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodHead, url, nil)
if err != nil {
return "", err
}
res, err := client.Do(req)
if err != nil {
return "", err
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode != 302 {
return "", fmt.Errorf("incorrect status code: %d", res.StatusCode)
}
loc := res.Header.Get("Location")
if len(loc) == 0 {
return "", fmt.Errorf("unable to determine release of kubeseal")
}
version := loc[strings.LastIndex(loc, "/")+1:]
return version, nil
}
func downloadBinary(client *http.Client, url, name, downloadTo string) (string, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
res, err := client.Do(req)
if err != nil {
return "", err
}
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("could not find release, http status code was %d, release may not exist for this architecture", res.StatusCode)
}
var tempDir string
if len(downloadTo) == 0 {
tempDir = os.TempDir()
} else {
tempDir = downloadTo
}
outputPath := path.Join(tempDir, name)
if res.Body != nil {
defer res.Body.Close()
res, _ := ioutil.ReadAll(res.Body)
err := ioutil.WriteFile(outputPath, res, 0600)
if err != nil {
return "", err
}
return outputPath, nil
}
return "", fmt.Errorf("error downloading %s", url)
}