Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ type azureBLOBStorage struct {
}

// NewAzure signs requests with the account key, or with TokenCredential
// where no key is set, as with a managed or workload identity.
// where no key is set, as with a managed or workload identity, or else
// appends the SAS token to every request.
func NewAzure(conf *AzureConfig) (Storage, error) {
serviceURL := azureServiceURL(conf)
if _, err := url.Parse(serviceURL); err != nil {
Expand All @@ -86,6 +87,10 @@ func NewAzure(conf *AzureConfig) (Storage, error) {
s.client, err = azblob.NewClient(serviceURL, conf.TokenCredential, &azblob.ClientOptions{ClientOptions: s.options})
return s, err
}
if conf.AccountKey == "" && conf.SASToken != "" {
s.client, err = azblob.NewClientWithNoCredential(azureSASURL(serviceURL, conf.SASToken), &azblob.ClientOptions{ClientOptions: s.options})
return s, err
}
if s.cred, err = azblob.NewSharedKeyCredential(conf.AccountName, conf.AccountKey); err != nil {
return nil, err
}
Expand Down Expand Up @@ -119,6 +124,15 @@ func azureServiceURL(conf *AzureConfig) string {
return fmt.Sprintf("https://%s.blob.core.windows.net/", conf.AccountName)
}

// azureSASURL is the service URL carrying the SAS token as its query, which
// the client copies onto every request. Locations are built from the service
// URL alone, so the token never appears in one.
func azureSASURL(serviceURL, sasToken string) string {
u, _ := url.Parse(serviceURL)
u.RawQuery = strings.TrimPrefix(sasToken, "?")
return u.String()
}

// blobURL is storagePath under the service URL, path-style below an
// emulator's account segment. NewAzure has checked the URL parses.
func (s *azureBLOBStorage) blobURL(storagePath string) *url.URL {
Expand Down Expand Up @@ -339,10 +353,15 @@ func (s *azureBLOBStorage) DeleteObjects(ctx context.Context, storagePaths []str

// PresignedURL signs with the account key unless a token credential is
// set, in which case it signs with a user delegation key as Storage does.
// With only a SAS token it fails: a SAS cannot sign another, and handing out
// the configured one would grant its write access, for its whole lifetime.
func (s *azureBLOBStorage) PresignedURL(ctx context.Context, storagePath string, expiration time.Duration) (string, error) {
if s.conf.TokenCredential != nil {
return s.presignWithUserDelegation(ctx, storagePath, expiration)
}
if s.cred == nil {
return "", errors.New("azure: presigned URLs need an account key or a token credential, not a SAS token")
}
// HTTPS only, as the user delegation SAS, unless the endpoint itself is
// plain HTTP, as an emulator's.
protocol := sas.ProtocolHTTPS
Expand Down
3 changes: 3 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ type AzureConfig struct {
AccountKey string `yaml:"account_key,omitempty"` // (env AZURE_STORAGE_KEY)
ContainerName string `yaml:"container_name,omitempty"`
TokenCredential azcore.TokenCredential `yaml:"-"` // required for presigned url generation
// SASToken is a shared access signature (SAS), used when AccountKey is
// empty and TokenCredential is not set. It cannot sign presigned URLs.
SASToken string `yaml:"sas_token,omitempty"`
// Endpoint replaces the service URL https://<account>.blob.core.windows.net/,
// e.g. an emulator's http://localhost:4577/<account>/.
Endpoint string `yaml:"endpoint,omitempty"`
Expand Down
42 changes: 42 additions & 0 deletions contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,48 @@ func TestProxyCarriesRequests(t *testing.T) {
}
}

// A SAS token goes on every request as its query, with no Authorization
// header, and stays out of the locations returned, which are handed on.
func TestAzureSASToken(t *testing.T) {
requests := make(chan *http.Request, 16)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests <- r
w.WriteHeader(http.StatusCreated)
}))
t.Cleanup(srv.Close)

for name, token := range map[string]string{
"bare": "sv=2024-11-04&sp=cw&sig=c2ln",
"leading question": "?sv=2024-11-04&sp=cw&sig=c2ln",
} {
t.Run(name, func(t *testing.T) {
s, err := storage.New(&storage.AzureConfig{
AccountName: "account",
ContainerName: "container",
SASToken: token,
Endpoint: srv.URL + "/account/",
})
require.NoError(t, err)

file := filepath.Join(t.TempDir(), "f")
require.NoError(t, os.WriteFile(file, []byte("data"), 0o600))
location, _, err := s.UploadFile(context.Background(), "a/b.mp4", file, storage.PutOptions{})
require.NoError(t, err)
require.Equal(t, srv.URL+"/account/container/a/b.mp4", location)

r := <-requests
require.Equal(t, "/account/container/a/b.mp4", r.URL.Path)
require.Equal(t, "2024-11-04", r.URL.Query().Get("sv"))
require.Equal(t, "cw", r.URL.Query().Get("sp"))
require.Equal(t, "c2ln", r.URL.Query().Get("sig"))
require.Empty(t, r.Header.Get("Authorization"))

_, err = s.PresignedURL(context.Background(), "a/b.mp4", time.Hour)
require.Error(t, err)
})
}
}

// Only an http:// endpoint, an emulator's, drops credentials: a private one,
// such as Private Service Connect, is still sent a token.
func TestGCPEndpointKeepsCredentials(t *testing.T) {
Expand Down