@ -19,6 +19,7 @@ import (
"strings"
"time"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/util"
)
@ -27,14 +28,16 @@ type AzureBlobUploader struct {
account_name string
account_key string
container_name string
sas_token_expiration_days int
log log . Logger
}
func NewAzureBlobUploader ( account_name string , account_key string , container_name string ) * AzureBlobUploader {
func NewAzureBlobUploader ( account_name string , account_key string , container_name string , sas_token_expiration_days int ) * AzureBlobUploader {
return & AzureBlobUploader {
account_name : account_name ,
account_key : account_key ,
container_name : container_name ,
sas_token_expiration_days : sas_token_expiration_days ,
log : log . New ( "azureBlobUploader" ) ,
}
}
@ -91,9 +94,49 @@ func (az *AzureBlobUploader) Upload(ctx context.Context, imageDiskPath string) (
}
url := fmt . Sprintf ( "https://%s.blob.core.windows.net/%s/%s" , az . account_name , az . container_name , randomFileName )
if az . sas_token_expiration_days > 0 {
url , err = blob . GetBlobSasUrl ( ctx , az . container_name , randomFileName , az . sas_token_expiration_days )
if err != nil {
return "" , err
}
}
return url , nil
}
// SignWithSharedKey uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS query parameters.
func ( c * StorageClient ) GetBlobSasUrl ( ctx context . Context , containerName , blobName string , sasTokenExpiration int ) ( string , error ) {
if c . Auth == nil {
return "" , fmt . Errorf ( "cannot sign SAS query without Shared Key Credential" )
}
// create source blob SAS url
credential , err := azblob . NewSharedKeyCredential ( c . Auth . Account , c . Auth . Key )
if err != nil {
return "" , err
}
// Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query parameters.
sasQueryParams , err := azblob . BlobSASSignatureValues {
Protocol : azblob . SASProtocolHTTPS , // Users MUST use HTTPS (not HTTP)
ExpiryTime : time . Now ( ) . UTC ( ) . AddDate ( 0 , 0 , sasTokenExpiration ) , // Expiration time
ContainerName : containerName ,
BlobName : blobName ,
Permissions : azblob . BlobSASPermissions { Add : false , Read : true , Write : false } . String ( ) , // Read only permissions
} . NewSASQueryParameters ( credential )
if err != nil {
return "" , err
}
// Create the URL of the resource you wish to access and append the SAS query parameters.
// Since this is a blob SAS, the URL is to the Azure storage blob.
qp := sasQueryParams . Encode ( )
blobSasUrl := fmt . Sprintf ( "https://%s.blob.core.windows.net/%s/%s?%s" , c . Auth . Account , containerName , blobName , qp )
// Return Blob SAS token URL
return blobSasUrl , nil
}
// --- AZURE LIBRARY
type Error struct {
Code int