2017-08-03 17:24:27 +00:00
|
|
|
package azure
|
2016-02-24 12:14:23 +00:00
|
|
|
|
|
|
|
import (
|
2018-01-19 06:44:44 +00:00
|
|
|
"context"
|
2020-10-05 21:37:13 +00:00
|
|
|
"errors"
|
2016-02-24 12:14:23 +00:00
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2020-10-05 21:37:13 +00:00
|
|
|
"net/url"
|
2016-02-24 12:14:23 +00:00
|
|
|
"os"
|
|
|
|
"sort"
|
2016-06-08 16:01:43 +00:00
|
|
|
"strconv"
|
2016-02-24 12:14:23 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
2016-04-25 19:53:07 +00:00
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
"github.com/Azure/azure-storage-blob-go/azblob"
|
2020-10-28 22:04:26 +00:00
|
|
|
"github.com/Azure/go-autorest/autorest/adal"
|
2018-08-15 23:40:36 +00:00
|
|
|
"github.com/Azure/go-autorest/autorest/azure"
|
2020-10-28 22:04:26 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2016-06-08 16:01:43 +00:00
|
|
|
"github.com/hashicorp/errwrap"
|
2018-07-24 18:24:32 +00:00
|
|
|
log "github.com/hashicorp/go-hclog"
|
2019-04-12 21:54:35 +00:00
|
|
|
"github.com/hashicorp/vault/sdk/helper/strutil"
|
|
|
|
"github.com/hashicorp/vault/sdk/physical"
|
2016-02-24 12:14:23 +00:00
|
|
|
)
|
|
|
|
|
2018-07-24 18:24:32 +00:00
|
|
|
const (
|
|
|
|
// MaxBlobSize at this time
|
|
|
|
MaxBlobSize = 1024 * 1024 * 4
|
|
|
|
// MaxListResults is the current default value, setting explicitly
|
|
|
|
MaxListResults = 5000
|
|
|
|
)
|
2016-02-24 12:14:23 +00:00
|
|
|
|
|
|
|
// AzureBackend is a physical backend that stores data
|
|
|
|
// within an Azure blob container.
|
|
|
|
type AzureBackend struct {
|
2020-10-05 21:37:13 +00:00
|
|
|
container *azblob.ContainerURL
|
2016-08-19 20:45:17 +00:00
|
|
|
logger log.Logger
|
2017-08-03 17:24:27 +00:00
|
|
|
permitPool *physical.PermitPool
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
|
2018-01-20 01:44:24 +00:00
|
|
|
// Verify AzureBackend satisfies the correct interfaces
|
|
|
|
var _ physical.Backend = (*AzureBackend)(nil)
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
// NewAzureBackend constructs an Azure backend using a pre-existing
|
2016-02-24 12:14:23 +00:00
|
|
|
// bucket. Credentials can be provided to the backend, sourced
|
2020-10-28 22:04:26 +00:00
|
|
|
// from the environment, via HCL or by using managed identities.
|
2017-08-03 17:24:27 +00:00
|
|
|
func NewAzureBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
|
2017-06-16 16:06:09 +00:00
|
|
|
name := os.Getenv("AZURE_BLOB_CONTAINER")
|
2020-10-28 22:04:26 +00:00
|
|
|
useMSI := false
|
|
|
|
|
2017-06-16 16:06:09 +00:00
|
|
|
if name == "" {
|
|
|
|
name = conf["container"]
|
|
|
|
if name == "" {
|
2016-02-24 12:14:23 +00:00
|
|
|
return nil, fmt.Errorf("'container' must be set")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
accountName := os.Getenv("AZURE_ACCOUNT_NAME")
|
|
|
|
if accountName == "" {
|
|
|
|
accountName = conf["accountName"]
|
|
|
|
if accountName == "" {
|
|
|
|
return nil, fmt.Errorf("'accountName' must be set")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
accountKey := os.Getenv("AZURE_ACCOUNT_KEY")
|
|
|
|
if accountKey == "" {
|
|
|
|
accountKey = conf["accountKey"]
|
|
|
|
if accountKey == "" {
|
2020-10-28 22:04:26 +00:00
|
|
|
logger.Info("accountKey not set, using managed identity auth")
|
|
|
|
useMSI = true
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-15 23:40:36 +00:00
|
|
|
environmentName := os.Getenv("AZURE_ENVIRONMENT")
|
|
|
|
if environmentName == "" {
|
|
|
|
environmentName = conf["environment"]
|
|
|
|
if environmentName == "" {
|
|
|
|
environmentName = "AzurePublicCloud"
|
|
|
|
}
|
|
|
|
}
|
2019-11-07 16:54:34 +00:00
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
environmentURL := os.Getenv("AZURE_ARM_ENDPOINT")
|
|
|
|
if environmentURL == "" {
|
|
|
|
environmentURL = conf["arm_endpoint"]
|
2019-10-08 15:51:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var environment azure.Environment
|
|
|
|
var err error
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
if environmentURL != "" {
|
|
|
|
environment, err = azure.EnvironmentFromURL(environmentURL)
|
2019-10-08 15:51:36 +00:00
|
|
|
if err != nil {
|
|
|
|
errorMsg := fmt.Sprintf("failed to look up Azure environment descriptor for URL %q: {{err}}",
|
2020-10-05 21:37:13 +00:00
|
|
|
environmentURL)
|
2019-10-08 15:51:36 +00:00
|
|
|
return nil, errwrap.Wrapf(errorMsg, err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
environment, err = azure.EnvironmentFromName(environmentName)
|
|
|
|
if err != nil {
|
|
|
|
errorMsg := fmt.Sprintf("failed to look up Azure environment descriptor for name %q: {{err}}",
|
|
|
|
environmentName)
|
|
|
|
return nil, errwrap.Wrapf(errorMsg, err)
|
|
|
|
}
|
2018-08-15 23:40:36 +00:00
|
|
|
}
|
|
|
|
|
2020-10-28 22:04:26 +00:00
|
|
|
var credential azblob.Credential
|
|
|
|
if useMSI {
|
|
|
|
authToken, err := getAuthTokenFromIMDS(environment.ResourceIdentifiers.Storage)
|
|
|
|
if err != nil {
|
|
|
|
errorMsg := fmt.Sprintf("failed to obtain auth token from IMDS %q: {{err}}",
|
|
|
|
environmentName)
|
|
|
|
return nil, errwrap.Wrapf(errorMsg, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
credential = azblob.NewTokenCredential(authToken.OAuthToken(), func(c azblob.TokenCredential) time.Duration {
|
|
|
|
err = authToken.Refresh()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("couldn't refresh token credential", "error", err)
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
expIn, err := authToken.Token().ExpiresIn.Int64()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("couldn't retrieve jwt claim for 'expiresIn' from refreshed token", "error", err)
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Debug("token refreshed, new token expires in", "access_token_expiry", expIn)
|
|
|
|
c.SetToken(authToken.OAuthToken())
|
|
|
|
|
|
|
|
// tokens are valid for 23h59m (86399s) by default, refresh after ~21h
|
|
|
|
return time.Duration(int(float64(expIn)*0.9)) * time.Second
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
credential, err = azblob.NewSharedKeyCredential(accountName, accountKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf("failed to create Azure client: {{err}}", err)
|
|
|
|
}
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
URL, err := url.Parse(
|
|
|
|
fmt.Sprintf("https://%s.blob.%s/%s", accountName, environment.StorageEndpointSuffix, name))
|
2017-04-17 16:15:12 +00:00
|
|
|
if err != nil {
|
2020-10-05 21:37:13 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to create Azure client: {{err}}", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
containerURL := azblob.NewContainerURL(*URL, p)
|
|
|
|
_, err = containerURL.GetProperties(ctx, azblob.LeaseAccessConditions{})
|
|
|
|
if err != nil {
|
|
|
|
var e azblob.StorageError
|
|
|
|
if errors.As(err, &e) {
|
|
|
|
switch e.ServiceCode() {
|
|
|
|
case azblob.ServiceCodeContainerNotFound:
|
|
|
|
_, err := containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf(fmt.Sprintf("failed to create %q container: {{err}}", name), err)
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return nil, errwrap.Wrapf(fmt.Sprintf("failed to get properties for container %q: {{err}}", name), err)
|
|
|
|
}
|
|
|
|
}
|
2017-04-17 16:15:12 +00:00
|
|
|
}
|
2016-02-24 12:14:23 +00:00
|
|
|
|
2016-06-08 16:01:43 +00:00
|
|
|
maxParStr, ok := conf["max_parallel"]
|
|
|
|
var maxParInt int
|
|
|
|
if ok {
|
|
|
|
maxParInt, err = strconv.Atoi(maxParStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
|
|
|
|
}
|
2016-08-19 20:45:17 +00:00
|
|
|
if logger.IsDebug() {
|
2018-04-03 00:46:59 +00:00
|
|
|
logger.Debug("max_parallel set", "max_parallel", maxParInt)
|
2016-08-19 20:45:17 +00:00
|
|
|
}
|
2016-06-08 16:01:43 +00:00
|
|
|
}
|
|
|
|
|
2016-02-24 12:14:23 +00:00
|
|
|
a := &AzureBackend{
|
2020-10-05 21:37:13 +00:00
|
|
|
container: &containerURL,
|
2016-06-08 16:01:43 +00:00
|
|
|
logger: logger,
|
2017-08-03 17:24:27 +00:00
|
|
|
permitPool: physical.NewPermitPool(maxParInt),
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
return a, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put is used to insert or update an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (a *AzureBackend) Put(ctx context.Context, entry *physical.Entry) error {
|
2016-02-24 12:14:23 +00:00
|
|
|
defer metrics.MeasureSince([]string{"azure", "put"}, time.Now())
|
|
|
|
|
|
|
|
if len(entry.Value) >= MaxBlobSize {
|
2017-06-16 16:06:09 +00:00
|
|
|
return fmt.Errorf("value is bigger than the current supported limit of 4MBytes")
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
|
2016-06-08 16:01:43 +00:00
|
|
|
a.permitPool.Acquire()
|
|
|
|
defer a.permitPool.Release()
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
blobURL := a.container.NewBlockBlobURL(entry.Key)
|
|
|
|
_, err := azblob.UploadBufferToBlockBlob(ctx, entry.Value, blobURL, azblob.UploadToBlockBlobOptions{
|
|
|
|
BlockSize: MaxBlobSize,
|
|
|
|
})
|
2016-02-24 12:14:23 +00:00
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
return err
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get is used to fetch an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (a *AzureBackend) Get(ctx context.Context, key string) (*physical.Entry, error) {
|
2016-02-24 12:14:23 +00:00
|
|
|
defer metrics.MeasureSince([]string{"azure", "get"}, time.Now())
|
|
|
|
|
2016-06-08 16:01:43 +00:00
|
|
|
a.permitPool.Acquire()
|
|
|
|
defer a.permitPool.Release()
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
blobURL := a.container.NewBlockBlobURL(key)
|
2020-10-28 22:04:26 +00:00
|
|
|
res, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false)
|
2017-06-16 16:06:09 +00:00
|
|
|
if err != nil {
|
2020-10-05 21:37:13 +00:00
|
|
|
var e azblob.StorageError
|
|
|
|
if errors.As(err, &e) {
|
|
|
|
switch e.ServiceCode() {
|
|
|
|
case azblob.ServiceCodeBlobNotFound:
|
|
|
|
return nil, nil
|
|
|
|
default:
|
|
|
|
return nil, errwrap.Wrapf(fmt.Sprintf("failed to download blob %q: {{err}}", key), err)
|
|
|
|
}
|
|
|
|
}
|
2017-06-16 16:06:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2016-02-24 12:14:23 +00:00
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
reader := res.Body(azblob.RetryReaderOptions{})
|
2017-06-16 16:06:09 +00:00
|
|
|
defer reader.Close()
|
2020-10-28 22:04:26 +00:00
|
|
|
|
2016-02-24 12:14:23 +00:00
|
|
|
data, err := ioutil.ReadAll(reader)
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
ent := &physical.Entry{
|
2016-02-24 12:14:23 +00:00
|
|
|
Key: key,
|
|
|
|
Value: data,
|
|
|
|
}
|
|
|
|
|
|
|
|
return ent, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete is used to permanently delete an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (a *AzureBackend) Delete(ctx context.Context, key string) error {
|
2016-02-24 12:14:23 +00:00
|
|
|
defer metrics.MeasureSince([]string{"azure", "delete"}, time.Now())
|
2016-06-08 16:01:43 +00:00
|
|
|
|
|
|
|
a.permitPool.Acquire()
|
|
|
|
defer a.permitPool.Release()
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
blobURL := a.container.NewBlockBlobURL(key)
|
|
|
|
_, err := blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionInclude, azblob.BlobAccessConditions{})
|
|
|
|
if err != nil {
|
|
|
|
var e azblob.StorageError
|
|
|
|
if errors.As(err, &e) {
|
|
|
|
switch e.ServiceCode() {
|
|
|
|
case azblob.ServiceCodeBlobNotFound:
|
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
return errwrap.Wrapf(fmt.Sprintf("failed to delete blob %q: {{err}}", key), err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-24 12:14:23 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// List is used to list all the keys under a given
|
|
|
|
// prefix, up to the next prefix.
|
2018-01-19 06:44:44 +00:00
|
|
|
func (a *AzureBackend) List(ctx context.Context, prefix string) ([]string, error) {
|
2016-02-24 12:14:23 +00:00
|
|
|
defer metrics.MeasureSince([]string{"azure", "list"}, time.Now())
|
|
|
|
|
2016-06-08 16:01:43 +00:00
|
|
|
a.permitPool.Acquire()
|
2018-07-24 18:24:32 +00:00
|
|
|
defer a.permitPool.Release()
|
2016-02-24 12:14:23 +00:00
|
|
|
|
2020-10-28 22:04:26 +00:00
|
|
|
var keys []string
|
2020-10-05 21:37:13 +00:00
|
|
|
for marker := (azblob.Marker{}); marker.NotDone(); {
|
|
|
|
listBlob, err := a.container.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{
|
2018-07-24 18:24:32 +00:00
|
|
|
Prefix: prefix,
|
|
|
|
MaxResults: MaxListResults,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
for _, blobInfo := range listBlob.Segment.BlobItems {
|
|
|
|
key := strings.TrimPrefix(blobInfo.Name, prefix)
|
2018-07-24 18:24:32 +00:00
|
|
|
if i := strings.Index(key, "/"); i == -1 {
|
|
|
|
// file
|
|
|
|
keys = append(keys, key)
|
|
|
|
} else {
|
|
|
|
// subdirectory
|
|
|
|
keys = strutil.AppendIfMissing(keys, key[:i+1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-05 21:37:13 +00:00
|
|
|
marker = listBlob.NextMarker
|
2016-02-24 12:14:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(keys)
|
|
|
|
return keys, nil
|
|
|
|
}
|
2020-10-28 22:04:26 +00:00
|
|
|
|
|
|
|
// getAuthTokenFromIMDS uses the Azure Instance Metadata Service to retrieve a short-lived credential using OAuth
|
|
|
|
// more info on this https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview
|
|
|
|
func getAuthTokenFromIMDS(resource string) (*adal.ServicePrincipalToken, error) {
|
|
|
|
msiEndpoint, err := adal.GetMSIVMEndpoint()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
spt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, resource)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := spt.Refresh(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
token := spt.Token()
|
|
|
|
if token.IsZero() {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return spt, nil
|
|
|
|
}
|