-
Notifications
You must be signed in to change notification settings - Fork 0
/
azblob.go
224 lines (186 loc) · 5.75 KB
/
azblob.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright © 2021 Luther Systems, Ltd. All right reserved.
package azblob
import (
"bytes"
"context"
"crypto/rsa"
"crypto/x509"
"fmt"
"net/url"
"os"
"path/filepath"
"time"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/luthersystems/svc/docstore"
"golang.org/x/crypto/pkcs12"
)
const (
azureStorageResourceName = "https://storage.azure.com/"
)
var _ docstore.DocStore = &Store{}
func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {
privateKey, certificate, err := pkcs12.Decode(pkcs, password)
if err != nil {
return nil, nil, err
}
rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey)
if !isRsaKey {
return nil, nil, fmt.Errorf("PKCS#12 certificate must contain an RSA private key")
}
return certificate, rsaPrivateKey, nil
}
// NewFromCertificate generates a Store using an Azure certificate.
func NewFromCertificate(prefix, accountName, containerName, path, password, clientID, tenantID string) (*Store, error) {
oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, tenantID)
if err != nil {
return nil, fmt.Errorf("oauth config: %w", err)
}
path = filepath.Clean(path)
certData, err := os.ReadFile(path) // #nosec G304
if err != nil {
return nil, fmt.Errorf("failed to read the certificate file (%s): %w", path, err)
}
certificate, rsaPrivateKey, err := decodePkcs12(certData, password)
if err != nil {
return nil, fmt.Errorf("failed to decode pkcs12 certificate: %w", err)
}
spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, clientID, certificate, rsaPrivateKey, azureStorageResourceName)
if err != nil {
return nil, fmt.Errorf("new token: %w", err)
}
// obtain a fresh token
err = spt.Refresh()
if err != nil {
return nil, fmt.Errorf("refresh: %w", err)
}
credential := azblob.NewTokenCredential(spt.Token().AccessToken, func(tc azblob.TokenCredential) time.Duration {
err := spt.Refresh()
if err != nil {
// something went wrong, prevent the refresher from being triggered again
return 0
}
tc.SetToken(spt.Token().AccessToken)
// get the next token slightly before the current one expires
return time.Until(spt.Token().Expires()) - 10*time.Second
})
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
URL, err := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName))
if err != nil {
return nil, err
}
containerURL := azblob.NewContainerURL(*URL, p)
return &Store{
prefix: prefix,
containerURL: containerURL,
}, nil
}
// New constructs a storage blob from an access key.
func New(prefix, accountName, containerName, accountKey string) (*Store, error) {
if len(prefix) == 0 {
return nil, fmt.Errorf("missing prefix")
}
if len(accountName) == 0 {
return nil, fmt.Errorf("missing account name")
}
if len(containerName) == 0 {
return nil, fmt.Errorf("missing container name")
}
// accountkey?
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
return nil, err
}
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
URL, err := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, containerName))
if err != nil {
return nil, err
}
// pipeline to make requests.
containerURL := azblob.NewContainerURL(*URL, p)
return &Store{
prefix: prefix,
containerURL: containerURL,
}, nil
}
// Store objects to azure.
type Store struct {
prefix string
containerURL azblob.ContainerURL
}
func getBufFromBlob(ctx context.Context, blobURL azblob.BlockBlobURL) ([]byte, error) {
_, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
if err != nil {
serr, ok := err.(azblob.StorageError)
if ok && serr.Response().StatusCode == 404 {
return nil, docstore.ErrRequestNotFound
}
return nil, err
}
downloadResponse, err := blobURL.Download(ctx,
0,
azblob.CountToEnd,
azblob.BlobAccessConditions{},
false,
azblob.ClientProvidedKeyOptions{})
if err != nil {
return nil, err
}
bodyStream := downloadResponse.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3})
downloadedData := bytes.Buffer{}
_, err = downloadedData.ReadFrom(bodyStream)
if err != nil {
return nil, err
}
return downloadedData.Bytes(), nil
}
// Get reads bytes from azure blob.
func (s *Store) Get(ctx context.Context, key string) ([]byte, error) {
err := docstore.ValidKey(key)
if err != nil {
return nil, err
}
blobURL := s.containerURL.NewBlockBlobURL(fmt.Sprintf("%s/%s", s.prefix, key))
b, err := getBufFromBlob(ctx, blobURL)
if err != nil {
return nil, fmt.Errorf("az get: %w", err)
}
return b, nil
}
func putBufToBlob(ctx context.Context, blobURL azblob.BlockBlobURL, blob []byte) error {
_, err := azblob.UploadStreamToBlockBlob(ctx,
bytes.NewReader(blob),
blobURL,
azblob.UploadStreamToBlockBlobOptions{})
if err != nil {
return err
}
return nil
}
// Put writes bytes to azure blob.
func (s *Store) Put(ctx context.Context, key string, body []byte) error {
err := docstore.ValidKey(key)
if err != nil {
return err
}
blobURL := s.containerURL.NewBlockBlobURL(fmt.Sprintf("%s/%s", s.prefix, key))
err = putBufToBlob(ctx, blobURL, body)
if err != nil {
return fmt.Errorf("az put: %w", err)
}
return nil
}
// Delete deletes bytes from azure blob.
func (s *Store) Delete(ctx context.Context, key string) error {
err := docstore.ValidKey(key)
if err != nil {
return err
}
blobURL := s.containerURL.NewBlockBlobURL(fmt.Sprintf("%s/%s", s.prefix, key))
_, err = blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionInclude, azblob.BlobAccessConditions{})
if err != nil {
return fmt.Errorf("az delete: %w", err)
}
return nil
}