2 * Copyright 2018 Intel Corporation, Inc
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 uuid "github.com/hashicorp/go-uuid"
21 vaultapi "github.com/hashicorp/vault/api"
30 // Vault is the main Struct used in Backend to initialize the struct
39 vaultClient *vaultapi.Client
41 vaultTempTokenTTL time.Time
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)
57 v.initRoleDone = false
58 v.policyName = "smsvaultpolicy"
59 v.vaultClient = client
64 //print error message and try to initrole later
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()
78 return sealStatus.Sealed, nil
81 // Unseal is a passthrough API that allows any
82 // unseal or initialization processes for the backend
83 func (v *Vault) Unseal(shard string) error {
84 sys := v.vaultClient.Sys()
85 _, err := sys.Unseal(shard)
93 // GetSecret returns a secret mounted on a particular domain name
94 // The secret itself is referenced via its name which translates to
95 // a mount path in vault
96 func (v *Vault) GetSecret(dom string, name string) (Secret, error) {
99 return Secret{}, errors.New("Token check returned error: " + err.Error())
102 dom = v.vaultMount + "/" + dom
104 sec, err := v.vaultClient.Logical().Read(dom + "/" + name)
106 return Secret{}, errors.New("Unable to read Secret at provided path")
109 // sec and err are nil in the case where a path does not exist
111 return Secret{}, errors.New("Secret not found at the provided path")
114 return Secret{Name: name, Values: sec.Data}, nil
117 // ListSecret returns a list of secret names on a particular domain
118 // The values of the secret are not returned
119 func (v *Vault) ListSecret(dom string) ([]string, error) {
120 err := v.checkToken()
122 return nil, errors.New("Token check returned error: " + err.Error())
125 dom = v.vaultMount + "/" + dom
127 sec, err := v.vaultClient.Logical().List(dom)
129 return nil, errors.New("Unable to read Secret at provided path")
132 // sec and err are nil in the case where a path does not exist
134 return nil, errors.New("Secret not found at the provided path")
137 val, ok := sec.Data["keys"].([]interface{})
139 return nil, errors.New("Secret not found at the provided path")
142 retval := make([]string, len(val))
143 for i, v := range val {
144 retval[i] = fmt.Sprint(v)
150 // CreateSecretDomain mounts the kv backend on a path with the given name
151 func (v *Vault) CreateSecretDomain(name string) (SecretDomain, error) {
152 // Check if token is still valid
153 err := v.checkToken()
155 return SecretDomain{}, err
158 name = strings.TrimSpace(name)
159 mountPath := v.vaultMount + "/" + name
160 mountInput := &vaultapi.MountInput{
162 Description: "Mount point for domain: " + name,
165 Config: vaultapi.MountConfigInput{},
168 err = v.vaultClient.Sys().Mount(mountPath, mountInput)
170 return SecretDomain{}, err
173 uuid, _ := uuid.GenerateUUID()
174 return SecretDomain{uuid, name}, nil
177 // CreateSecret creates a secret mounted on a particular domain name
178 // The secret itself is mounted on a path specified by name
179 func (v *Vault) CreateSecret(dom string, sec Secret) error {
180 err := v.checkToken()
182 return errors.New("Token checking returned an error" + err.Error())
185 dom = v.vaultMount + "/" + dom
187 // Vault return is empty on successful write
188 // TODO: Check if values is not empty
189 _, err = v.vaultClient.Logical().Write(dom+"/"+sec.Name, sec.Values)
191 return errors.New("Unable to create Secret at provided path")
197 // DeleteSecretDomain deletes a secret domain which translates to
198 // an unmount operation on the given path in Vault
199 func (v *Vault) DeleteSecretDomain(name string) error {
200 err := v.checkToken()
205 name = strings.TrimSpace(name)
206 mountPath := v.vaultMount + "/" + name
208 err = v.vaultClient.Sys().Unmount(mountPath)
210 return errors.New("Unable to delete domain specified")
216 // DeleteSecret deletes a secret mounted on the path provided
217 func (v *Vault) DeleteSecret(dom string, name string) error {
218 err := v.checkToken()
220 return errors.New("Token checking returned an error" + err.Error())
223 dom = v.vaultMount + "/" + dom
225 // Vault return is empty on successful delete
226 _, err = v.vaultClient.Logical().Delete(dom + "/" + name)
228 return errors.New("Unable to delete Secret at provided path")
234 // initRole is called only once during the service bring up
235 func (v *Vault) initRole() error {
236 // Use the root token once here
237 v.vaultClient.SetToken(v.vaultToken)
238 defer v.vaultClient.ClearToken()
240 rules := `path "sms/*" { capabilities = ["create", "read", "update", "delete", "list"] }
241 path "sys/mounts/sms*" { capabilities = ["update","delete","create"] }`
242 err := v.vaultClient.Sys().PutPolicy(v.policyName, rules)
244 return errors.New("Unable to create policy for approle creation")
247 rName := v.vaultMount + "-role"
248 data := map[string]interface{}{
250 "policies": [2]string{"default", v.policyName},
253 //Check if applrole is mounted
254 authMounts, err := v.vaultClient.Sys().ListAuth()
256 return errors.New("Unable to get mounted auth backends")
259 approleMounted := false
260 for k, v := range authMounts {
261 if v.Type == "approle" && k == "approle/" {
262 approleMounted = true
267 // Mount approle in case its not already mounted
269 v.vaultClient.Sys().EnableAuth("approle", "approle", "")
273 v.vaultClient.Logical().Write("auth/approle/role/"+rName, data)
274 sec, err := v.vaultClient.Logical().Read("auth/approle/role/" + rName + "/role-id")
276 return errors.New("Unable to create role ID for approle")
278 v.roleID = sec.Data["role_id"].(string)
280 // Create a secret-id to go with it
281 sec, err = v.vaultClient.Logical().Write("auth/approle/role/"+rName+"/secret-id",
282 map[string]interface{}{})
284 return errors.New("Unable to create secret ID for role")
287 v.secretID = sec.Data["secret_id"].(string)
288 v.initRoleDone = true
292 // Function checkToken() gets called multiple times to create
294 func (v *Vault) checkToken() error {
296 defer v.tokenLock.Unlock()
298 // Init Role if it is not yet done
299 // Role needs to be created before token can be created
300 if v.initRoleDone == false {
307 // Return immediately if token still has life
308 if v.vaultClient.Token() != "" &&
309 time.Since(v.vaultTempTokenTTL) < time.Minute*50 {
313 // Create a temporary token using our roleID and secretID
314 out, err := v.vaultClient.Logical().Write("auth/approle/login",
315 map[string]interface{}{"role_id": v.roleID, "secret_id": v.secretID})
320 tok, err := out.TokenID()
322 v.vaultTempTokenTTL = time.Now()
323 v.vaultClient.SetToken(tok)