open-vault/builtin/logical/mongodb/path_creds_create.go

117 lines
2.7 KiB
Go
Raw Normal View History

2016-05-13 20:42:09 +00:00
package mongodb
import (
"fmt"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathCredsCreate(b *backend) *framework.Path {
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role to generate credentials for.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathCredsCreateRead,
},
HelpSynopsis: pathCredsCreateReadHelpSyn,
HelpDescription: pathCredsCreateReadHelpDesc,
}
}
func (b *backend) pathCredsCreateRead(req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
// Get the role
role, err := b.Role(req.Storage, name)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil
}
// Determine if we have a lease configuration
leaseConfig, err := b.LeaseConfig(req.Storage)
if err != nil {
return nil, err
}
if leaseConfig == nil {
leaseConfig = &configLease{}
}
// Generate the username and password
displayName := req.DisplayName
if displayName != "" {
displayName += "-"
}
2016-05-13 20:42:09 +00:00
userUUID, err := uuid.GenerateUUID()
if err != nil {
return nil, err
}
username := fmt.Sprintf("vault-%s%s", displayName, userUUID)
2016-05-13 20:42:09 +00:00
password, err := uuid.GenerateUUID()
if err != nil {
return nil, err
}
// Build the user creation command
createUserCmd := createUserCommand{
Username: username,
Password: password,
Roles: role.MongoDBRoles.toStandardRolesArray(),
2016-05-13 20:42:09 +00:00
}
// Get our connection
session, err := b.Session(req.Storage)
if err != nil {
return nil, err
}
// Create the user
err = session.DB(role.DB).Run(createUserCmd, nil)
if err != nil {
return nil, err
}
// Return the secret
resp := b.Secret(SecretCredsType).Response(map[string]interface{}{
2016-07-08 03:16:11 +00:00
"db": role.DB,
2016-05-13 20:42:09 +00:00
"username": username,
"password": password,
}, map[string]interface{}{
"username": username,
"db": role.DB,
})
resp.Secret.TTL = leaseConfig.TTL
return resp, nil
}
type createUserCommand struct {
Username string `bson:"createUser"`
Password string `bson:"pwd"`
Roles []interface{} `bson:"roles"`
}
const pathCredsCreateReadHelpSyn = `
Request MongoDB database credentials for a particular role.
`
const pathCredsCreateReadHelpDesc = `
This path reads generates MongoDB database credentials for
a particular role. The database credentials will be
generated on demand and will be automatically revoked when
the lease is up.
`