Merge "Adding Listsecret capability"
[aaf/sms.git] / sms-service / src / sms / backend / vault.go
1 /*
2  * Copyright 2018 Intel Corporation, Inc
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package backend
18
19 import (
20         uuid "github.com/hashicorp/go-uuid"
21         vaultapi "github.com/hashicorp/vault/api"
22
23         "errors"
24         "fmt"
25         "log"
26         "strings"
27         "sync"
28         "time"
29 )
30
31 // Vault is the main Struct used in Backend to initialize the struct
32 type Vault struct {
33         vaultAddress   string
34         vaultToken     string
35         vaultMount     string
36         vaultTempToken string
37
38         vaultClient       *vaultapi.Client
39         engineType        string
40         policyName        string
41         roleID            string
42         secretID          string
43         vaultTempTokenTTL time.Time
44
45         tokenLock sync.Mutex
46 }
47
48 // Init will initialize the vault connection
49 // It will also create the initial policy if it does not exist
50 // TODO: Check to see if we need to wait for vault to be running
51 func (v *Vault) Init() error {
52         vaultCFG := vaultapi.DefaultConfig()
53         vaultCFG.Address = v.vaultAddress
54         client, err := vaultapi.NewClient(vaultCFG)
55         if err != nil {
56                 return err
57         }
58
59         v.engineType = "kv"
60         v.policyName = "smsvaultpolicy"
61         v.vaultMount = "sms"
62         v.vaultClient = client
63
64         // Check if vault is ready and unsealed
65         seal, err := v.GetStatus()
66         if err != nil {
67                 return err
68         }
69         if seal == true {
70                 return fmt.Errorf("Vault is still sealed. Unseal before use")
71         }
72
73         v.initRole()
74         v.checkToken()
75         return nil
76 }
77
78 // GetStatus returns the current seal status of vault
79 func (v *Vault) GetStatus() (bool, error) {
80         sys := v.vaultClient.Sys()
81         sealStatus, err := sys.SealStatus()
82         if err != nil {
83                 return false, err
84         }
85
86         return sealStatus.Sealed, nil
87 }
88
89 // GetSecretDomain returns any information related to the secretDomain
90 // More information can be added in the future with updates to the struct
91 func (v *Vault) GetSecretDomain(name string) (SecretDomain, error) {
92         return SecretDomain{}, nil
93 }
94
95 // GetSecret returns a secret mounted on a particular domain name
96 // The secret itself is referenced via its name which translates to
97 // a mount path in vault
98 func (v *Vault) GetSecret(dom string, name string) (Secret, error) {
99         err := v.checkToken()
100         if err != nil {
101                 return Secret{}, errors.New("Token check returned error: " + err.Error())
102         }
103
104         dom = v.vaultMount + "/" + dom
105
106         sec, err := v.vaultClient.Logical().Read(dom + "/" + name)
107         if err != nil {
108                 return Secret{}, errors.New("Unable to read Secret at provided path")
109         }
110
111         // sec and err are nil in the case where a path does not exist
112         if sec == nil {
113                 return Secret{}, errors.New("Secret not found at the provided path")
114         }
115
116         return Secret{Name: name, Values: sec.Data}, nil
117 }
118
119 // ListSecret returns a list of secret names on a particular domain
120 // The values of the secret are not returned
121 func (v *Vault) ListSecret(dom string) ([]string, error) {
122         err := v.checkToken()
123         if err != nil {
124                 return nil, errors.New("Token check returned error: " + err.Error())
125         }
126
127         dom = v.vaultMount + "/" + dom
128
129         sec, err := v.vaultClient.Logical().List(dom)
130         if err != nil {
131                 return nil, errors.New("Unable to read Secret at provided path")
132         }
133
134         // sec and err are nil in the case where a path does not exist
135         if sec == nil {
136                 return nil, errors.New("Secret not found at the provided path")
137         }
138
139         val, ok := sec.Data["keys"].([]interface{})
140         if !ok {
141                 return nil, errors.New("Secret not found at the provided path")
142         }
143
144         retval := make([]string, len(val))
145         for i, v := range val {
146                 retval[i] = fmt.Sprint(v)
147         }
148
149         return retval, nil
150 }
151
152 // CreateSecretDomain mounts the kv backend on a path with the given name
153 func (v *Vault) CreateSecretDomain(name string) (SecretDomain, error) {
154         // Check if token is still valid
155         err := v.checkToken()
156         if err != nil {
157                 return SecretDomain{}, err
158         }
159
160         name = strings.TrimSpace(name)
161         mountPath := v.vaultMount + "/" + name
162         mountInput := &vaultapi.MountInput{
163                 Type:        v.engineType,
164                 Description: "Mount point for domain: " + name,
165                 Local:       false,
166                 SealWrap:    false,
167                 Config:      vaultapi.MountConfigInput{},
168         }
169
170         err = v.vaultClient.Sys().Mount(mountPath, mountInput)
171         if err != nil {
172                 return SecretDomain{}, err
173         }
174
175         uuid, _ := uuid.GenerateUUID()
176         return SecretDomain{uuid, name}, nil
177 }
178
179 // CreateSecret creates a secret mounted on a particular domain name
180 // The secret itself is mounted on a path specified by name
181 func (v *Vault) CreateSecret(dom string, sec Secret) error {
182         err := v.checkToken()
183         if err != nil {
184                 return errors.New("Token checking returned an error" + err.Error())
185         }
186
187         dom = v.vaultMount + "/" + dom
188
189         // Vault return is empty on successful write
190         _, err = v.vaultClient.Logical().Write(dom+"/"+sec.Name, sec.Values)
191         if err != nil {
192                 return errors.New("Unable to create Secret at provided path")
193         }
194
195         return nil
196 }
197
198 // DeleteSecretDomain deletes a secret domain which translates to
199 // an unmount operation on the given path in Vault
200 func (v *Vault) DeleteSecretDomain(name string) error {
201
202         return nil
203 }
204
205 // DeleteSecret deletes a secret mounted on the path provided
206 func (v *Vault) DeleteSecret(dom string, name string) error {
207         err := v.checkToken()
208         if err != nil {
209                 return errors.New("Token checking returned an error" + err.Error())
210         }
211
212         dom = v.vaultMount + "/" + dom
213
214         // Vault return is empty on successful delete
215         _, err = v.vaultClient.Logical().Delete(dom + "/" + name)
216         if err != nil {
217                 return errors.New("Unable to delete Secret at provided path")
218         }
219
220         return nil
221 }
222
223 // initRole is called only once during the service bring up
224 func (v *Vault) initRole() error {
225         // Use the root token once here
226         v.vaultClient.SetToken(v.vaultToken)
227         defer v.vaultClient.ClearToken()
228
229         rules := `path "sms/*" { capabilities = ["create", "read", "update", "delete", "list"] }
230                         path "sys/mounts/sms*" { capabilities = ["update","delete","create"] }`
231         v.vaultClient.Sys().PutPolicy(v.policyName, rules)
232
233         rName := v.vaultMount + "-role"
234         data := map[string]interface{}{
235                 "token_ttl": "60m",
236                 "policies":  [2]string{"default", v.policyName},
237         }
238
239         // Delete role if it already exists
240         v.vaultClient.Logical().Delete("auth/approle/role/" + rName)
241
242         //Check if approle is mounted
243         authMounts, err := v.vaultClient.Sys().ListAuth()
244         if err != nil {
245                 return err
246         }
247
248         approleMounted := false
249         for k, v := range authMounts {
250                 if v.Type == "approle" && k == "approle/" {
251                         approleMounted = true
252                         break
253                 }
254         }
255
256         // Mount approle in case its not already mounted
257         if !approleMounted {
258                 v.vaultClient.Sys().EnableAuth("approle", "approle", "")
259         }
260
261         // Create a role-id
262         v.vaultClient.Logical().Write("auth/approle/role/"+rName, data)
263         sec, err := v.vaultClient.Logical().Read("auth/approle/role/" + rName + "/role-id")
264         if err != nil {
265                 log.Fatal(err)
266         }
267         v.roleID = sec.Data["role_id"].(string)
268
269         // Create a secret-id to go with it
270         sec, _ = v.vaultClient.Logical().Write("auth/approle/role/"+rName+"/secret-id",
271                 map[string]interface{}{})
272         v.secretID = sec.Data["secret_id"].(string)
273
274         return nil
275 }
276
277 // Function checkToken() gets called multiple times to create
278 // temporary tokens
279 func (v *Vault) checkToken() error {
280         v.tokenLock.Lock()
281         defer v.tokenLock.Unlock()
282
283         // Return immediately if token still has life
284         if v.vaultClient.Token() != "" &&
285                 time.Since(v.vaultTempTokenTTL) < time.Minute*50 {
286                 return nil
287         }
288
289         // Create a temporary token using our roleID and secretID
290         out, err := v.vaultClient.Logical().Write("auth/approle/login",
291                 map[string]interface{}{"role_id": v.roleID, "secret_id": v.secretID})
292         if err != nil {
293                 return err
294         }
295
296         tok, err := out.TokenID()
297
298         v.vaultTempToken = tok
299         v.vaultTempTokenTTL = time.Now()
300         v.vaultClient.SetToken(v.vaultTempToken)
301         return nil
302 }