CreateSecret implementaion
[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, sec string) (Secret, error) {
99
100         return Secret{}, nil
101 }
102
103 // CreateSecretDomain mounts the kv backend on a path with the given name
104 func (v *Vault) CreateSecretDomain(name string) (SecretDomain, error) {
105         // Check if token is still valid
106         err := v.checkToken()
107         if err != nil {
108                 return SecretDomain{}, err
109         }
110
111         name = strings.TrimSpace(name)
112         mountPath := v.vaultMount + "/" + name
113         mountInput := &vaultapi.MountInput{
114                 Type:        v.engineType,
115                 Description: "Mount point for domain: " + name,
116                 Local:       false,
117                 SealWrap:    false,
118                 Config:      vaultapi.MountConfigInput{},
119         }
120
121         err = v.vaultClient.Sys().Mount(mountPath, mountInput)
122         if err != nil {
123                 return SecretDomain{}, err
124         }
125
126         uuid, _ := uuid.GenerateUUID()
127         return SecretDomain{uuid, name}, nil
128 }
129
130 // CreateSecret creates a secret mounted on a particular domain name
131 // The secret itself is mounted on a path specified by name
132 func (v *Vault) CreateSecret(dom string, sec Secret) error {
133         err := v.checkToken()
134         if err != nil {
135                 return errors.New("Token checking returned an error" + err.Error())
136         }
137
138         dom = v.vaultMount + "/" + dom
139
140         // Vault write return is empty on successful write
141         _, err = v.vaultClient.Logical().Write(dom+"/"+sec.Name, sec.Values)
142         if err != nil {
143                 return errors.New("Unable to create Secret at provided path")
144         }
145
146         return nil
147 }
148
149 // DeleteSecretDomain deletes a secret domain which translates to
150 // an unmount operation on the given path in Vault
151 func (v *Vault) DeleteSecretDomain(name string) error {
152
153         return nil
154 }
155
156 // DeleteSecret deletes a secret mounted on the path provided
157 func (v *Vault) DeleteSecret(dom string, name string) error {
158
159         return nil
160 }
161
162 // initRole is called only once during the service bring up
163 func (v *Vault) initRole() error {
164         // Use the root token once here
165         v.vaultClient.SetToken(v.vaultToken)
166         defer v.vaultClient.ClearToken()
167
168         rules := `path "sms/*" { capabilities = ["create", "read", "update", "delete", "list"] }
169                         path "sys/mounts/sms*" { capabilities = ["update","delete","create"] }`
170         v.vaultClient.Sys().PutPolicy(v.policyName, rules)
171
172         rName := v.vaultMount + "-role"
173         data := map[string]interface{}{
174                 "token_ttl": "60m",
175                 "policies":  [2]string{"default", v.policyName},
176         }
177
178         // Delete role if it already exists
179         v.vaultClient.Logical().Delete("auth/approle/role/" + rName)
180
181         // Mount approle in case its not already mounted
182         v.vaultClient.Sys().EnableAuth("approle", "approle", "")
183
184         // Create a role-id
185         v.vaultClient.Logical().Write("auth/approle/role/"+rName, data)
186         sec, err := v.vaultClient.Logical().Read("auth/approle/role/" + rName + "/role-id")
187         if err != nil {
188                 log.Fatal(err)
189         }
190         v.roleID = sec.Data["role_id"].(string)
191
192         // Create a secret-id to go with it
193         sec, _ = v.vaultClient.Logical().Write("auth/approle/role/"+rName+"/secret-id",
194                 map[string]interface{}{})
195         v.secretID = sec.Data["secret_id"].(string)
196
197         return nil
198 }
199
200 // Function checkToken() gets called multiple times to create
201 // temporary tokens
202 func (v *Vault) checkToken() error {
203         v.tokenLock.Lock()
204         defer v.tokenLock.Unlock()
205
206         // Return immediately if token still has life
207         if v.vaultClient.Token() != "" &&
208                 time.Since(v.vaultTempTokenTTL) < time.Minute*50 {
209                 return nil
210         }
211
212         // Create a temporary token using our roleID and secretID
213         out, err := v.vaultClient.Logical().Write("auth/approle/login",
214                 map[string]interface{}{"role_id": v.roleID, "secret_id": v.secretID})
215         if err != nil {
216                 return err
217         }
218
219         tok, err := out.TokenID()
220
221         v.vaultTempToken = tok
222         v.vaultTempTokenTTL = time.Now()
223         v.vaultClient.SetToken(v.vaultTempToken)
224         return nil
225 }