Init role does not depend on vault state
[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         "strings"
26         "sync"
27         "time"
28 )
29
30 // Vault is the main Struct used in Backend to initialize the struct
31 type Vault struct {
32         engineType        string
33         initRoleDone      bool
34         policyName        string
35         roleID            string
36         secretID          string
37         tokenLock         sync.Mutex
38         vaultAddress      string
39         vaultClient       *vaultapi.Client
40         vaultMount        string
41         vaultTempTokenTTL time.Time
42         vaultToken        string
43 }
44
45 // Init will initialize the vault connection
46 // It will also create the initial policy if it does not exist
47 // TODO: Check to see if we need to wait for vault to be running
48 func (v *Vault) Init() error {
49         vaultCFG := vaultapi.DefaultConfig()
50         vaultCFG.Address = v.vaultAddress
51         client, err := vaultapi.NewClient(vaultCFG)
52         if err != nil {
53                 return err
54         }
55
56         v.engineType = "kv"
57         v.initRoleDone = false
58         v.policyName = "smsvaultpolicy"
59         v.vaultClient = client
60         v.vaultMount = "sms"
61
62         err = v.initRole()
63         if err != nil {
64                 //print error message and try to initrole later
65         }
66
67         return nil
68 }
69
70 // GetStatus returns the current seal status of vault
71 func (v *Vault) GetStatus() (bool, error) {
72         sys := v.vaultClient.Sys()
73         sealStatus, err := sys.SealStatus()
74         if err != nil {
75                 return false, err
76         }
77
78         return sealStatus.Sealed, nil
79 }
80
81 // GetSecret returns a secret mounted on a particular domain name
82 // The secret itself is referenced via its name which translates to
83 // a mount path in vault
84 func (v *Vault) GetSecret(dom string, name string) (Secret, error) {
85         err := v.checkToken()
86         if err != nil {
87                 return Secret{}, errors.New("Token check returned error: " + err.Error())
88         }
89
90         dom = v.vaultMount + "/" + dom
91
92         sec, err := v.vaultClient.Logical().Read(dom + "/" + name)
93         if err != nil {
94                 return Secret{}, errors.New("Unable to read Secret at provided path")
95         }
96
97         // sec and err are nil in the case where a path does not exist
98         if sec == nil {
99                 return Secret{}, errors.New("Secret not found at the provided path")
100         }
101
102         return Secret{Name: name, Values: sec.Data}, nil
103 }
104
105 // ListSecret returns a list of secret names on a particular domain
106 // The values of the secret are not returned
107 func (v *Vault) ListSecret(dom string) ([]string, error) {
108         err := v.checkToken()
109         if err != nil {
110                 return nil, errors.New("Token check returned error: " + err.Error())
111         }
112
113         dom = v.vaultMount + "/" + dom
114
115         sec, err := v.vaultClient.Logical().List(dom)
116         if err != nil {
117                 return nil, errors.New("Unable to read Secret at provided path")
118         }
119
120         // sec and err are nil in the case where a path does not exist
121         if sec == nil {
122                 return nil, errors.New("Secret not found at the provided path")
123         }
124
125         val, ok := sec.Data["keys"].([]interface{})
126         if !ok {
127                 return nil, errors.New("Secret not found at the provided path")
128         }
129
130         retval := make([]string, len(val))
131         for i, v := range val {
132                 retval[i] = fmt.Sprint(v)
133         }
134
135         return retval, nil
136 }
137
138 // CreateSecretDomain mounts the kv backend on a path with the given name
139 func (v *Vault) CreateSecretDomain(name string) (SecretDomain, error) {
140         // Check if token is still valid
141         err := v.checkToken()
142         if err != nil {
143                 return SecretDomain{}, err
144         }
145
146         name = strings.TrimSpace(name)
147         mountPath := v.vaultMount + "/" + name
148         mountInput := &vaultapi.MountInput{
149                 Type:        v.engineType,
150                 Description: "Mount point for domain: " + name,
151                 Local:       false,
152                 SealWrap:    false,
153                 Config:      vaultapi.MountConfigInput{},
154         }
155
156         err = v.vaultClient.Sys().Mount(mountPath, mountInput)
157         if err != nil {
158                 return SecretDomain{}, err
159         }
160
161         uuid, _ := uuid.GenerateUUID()
162         return SecretDomain{uuid, name}, nil
163 }
164
165 // CreateSecret creates a secret mounted on a particular domain name
166 // The secret itself is mounted on a path specified by name
167 func (v *Vault) CreateSecret(dom string, sec Secret) error {
168         err := v.checkToken()
169         if err != nil {
170                 return errors.New("Token checking returned an error" + err.Error())
171         }
172
173         dom = v.vaultMount + "/" + dom
174
175         // Vault return is empty on successful write
176         // TODO: Check if values is not empty
177         _, err = v.vaultClient.Logical().Write(dom+"/"+sec.Name, sec.Values)
178         if err != nil {
179                 return errors.New("Unable to create Secret at provided path")
180         }
181
182         return nil
183 }
184
185 // DeleteSecretDomain deletes a secret domain which translates to
186 // an unmount operation on the given path in Vault
187 func (v *Vault) DeleteSecretDomain(name string) error {
188         err := v.checkToken()
189         if err != nil {
190                 return err
191         }
192
193         name = strings.TrimSpace(name)
194         mountPath := v.vaultMount + "/" + name
195
196         err = v.vaultClient.Sys().Unmount(mountPath)
197         if err != nil {
198                 return errors.New("Unable to delete domain specified")
199         }
200
201         return nil
202 }
203
204 // DeleteSecret deletes a secret mounted on the path provided
205 func (v *Vault) DeleteSecret(dom string, name string) error {
206         err := v.checkToken()
207         if err != nil {
208                 return errors.New("Token checking returned an error" + err.Error())
209         }
210
211         dom = v.vaultMount + "/" + dom
212
213         // Vault return is empty on successful delete
214         _, err = v.vaultClient.Logical().Delete(dom + "/" + name)
215         if err != nil {
216                 return errors.New("Unable to delete Secret at provided path")
217         }
218
219         return nil
220 }
221
222 // initRole is called only once during the service bring up
223 func (v *Vault) initRole() error {
224         // Use the root token once here
225         v.vaultClient.SetToken(v.vaultToken)
226         defer v.vaultClient.ClearToken()
227
228         rules := `path "sms/*" { capabilities = ["create", "read", "update", "delete", "list"] }
229                         path "sys/mounts/sms*" { capabilities = ["update","delete","create"] }`
230         err := v.vaultClient.Sys().PutPolicy(v.policyName, rules)
231         if err != nil {
232                 return errors.New("Unable to create policy for approle creation")
233         }
234
235         rName := v.vaultMount + "-role"
236         data := map[string]interface{}{
237                 "token_ttl": "60m",
238                 "policies":  [2]string{"default", v.policyName},
239         }
240
241         //Check if applrole is mounted
242         authMounts, err := v.vaultClient.Sys().ListAuth()
243         if err != nil {
244                 return errors.New("Unable to get mounted auth backends")
245         }
246
247         approleMounted := false
248         for k, v := range authMounts {
249                 if v.Type == "approle" && k == "approle/" {
250                         approleMounted = true
251                         break
252                 }
253         }
254
255         // Mount approle in case its not already mounted
256         if !approleMounted {
257                 v.vaultClient.Sys().EnableAuth("approle", "approle", "")
258         }
259
260         // Create a role-id
261         v.vaultClient.Logical().Write("auth/approle/role/"+rName, data)
262         sec, err := v.vaultClient.Logical().Read("auth/approle/role/" + rName + "/role-id")
263         if err != nil {
264                 return errors.New("Unable to create role ID for approle")
265         }
266         v.roleID = sec.Data["role_id"].(string)
267
268         // Create a secret-id to go with it
269         sec, err = v.vaultClient.Logical().Write("auth/approle/role/"+rName+"/secret-id",
270                 map[string]interface{}{})
271         if err != nil {
272                 return errors.New("Unable to create secret ID for role")
273         }
274
275         v.secretID = sec.Data["secret_id"].(string)
276         v.initRoleDone = true
277         return nil
278 }
279
280 // Function checkToken() gets called multiple times to create
281 // temporary tokens
282 func (v *Vault) checkToken() error {
283         v.tokenLock.Lock()
284         defer v.tokenLock.Unlock()
285
286         // Init Role if it is not yet done
287         if v.initRoleDone == false {
288                 err := v.initRole()
289                 if err != nil {
290                         return err
291                 }
292         }
293
294         // Return immediately if token still has life
295         if v.vaultClient.Token() != "" &&
296                 time.Since(v.vaultTempTokenTTL) < time.Minute*50 {
297                 return nil
298         }
299
300         // Create a temporary token using our roleID and secretID
301         out, err := v.vaultClient.Logical().Write("auth/approle/login",
302                 map[string]interface{}{"role_id": v.roleID, "secret_id": v.secretID})
303         if err != nil {
304                 return err
305         }
306
307         tok, err := out.TokenID()
308
309         v.vaultTempTokenTTL = time.Now()
310         v.vaultClient.SetToken(tok)
311         return nil
312 }