-
Notifications
You must be signed in to change notification settings - Fork 4
/
trust.go
129 lines (107 loc) · 2.57 KB
/
trust.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
package trust
import (
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"github.com/muesli/termenv"
"github.com/anchordotdev/cli"
"github.com/anchordotdev/cli/api"
"github.com/anchordotdev/cli/truststore"
)
type Command struct {
Config *cli.Config
}
func (c Command) TUI() cli.TUI {
return cli.TUI{
Run: c.run,
}
}
func (c *Command) run(ctx context.Context, tty termenv.File) error {
anc, err := api.Client(c.Config)
if err == api.ErrSignedOut {
fmt.Fprintf(tty, "Authentication required!\n")
return nil
}
if err != nil {
return err
}
res, err := anc.Get("/username/localhost/certs")
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return errors.New("unexpected response")
}
var certs struct {
Items *[]api.Cert `json:"items,omitempty"`
}
if err := json.NewDecoder(res.Body).Decode(&certs); err != nil {
return err
}
rootDir, err := os.MkdirTemp("", "add-cert")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(rootDir)
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
rootFS := truststore.RootFS()
systemStore := &truststore.Platform{
HomeDir: homeDir,
DataFS: rootFS,
SysFS: rootFS,
}
nssStore := &truststore.NSS{
HomeDir: homeDir,
DataFS: rootFS,
SysFS: rootFS,
}
for _, cert := range *certs.Items {
blk, _ := pem.Decode([]byte(*cert.TextualEncoding))
cert, err := x509.ParseCertificate(blk.Bytes)
if err != nil {
log.Fatal(err)
}
uniqueName := cert.SerialNumber.Text(16)
fileName := filepath.Join(uniqueName + ".pem")
file, err := os.Create(filepath.Join(rootDir, fileName))
if err != nil {
log.Fatal(err)
}
if err := pem.Encode(file, blk); err != nil {
log.Fatal(err)
}
if err := file.Close(); err != nil {
log.Fatal(err)
}
ca := &truststore.CA{
Certificate: cert,
FilePath: file.Name(),
UniqueName: uniqueName,
}
if c.Config.Trust.NoSudo {
fmt.Fprintf(tty, "\"%s\" %s cert (%s) installed in the mock store\n", ca.Subject.CommonName, ca.PublicKeyAlgorithm, uniqueName)
continue
}
if installed, err := systemStore.InstallCA(ca); installed {
fmt.Fprintf(tty, "\"%s\" %s cert (%s) installed in the system store\n", ca.Subject.CommonName, ca.PublicKeyAlgorithm, uniqueName)
} else if err != nil {
return err
}
if installed, err := nssStore.InstallCA(ca); installed {
fmt.Fprintf(tty, "\"%s\" %s cert (%s) installed in the NSS store\n", ca.Subject.CommonName, ca.PublicKeyAlgorithm, uniqueName)
} else if err != nil {
return err
}
}
return nil
}