-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAzureStorageBlobAdapter.php
More file actions
354 lines (314 loc) · 12.9 KB
/
AzureStorageBlobAdapter.php
File metadata and controls
354 lines (314 loc) · 12.9 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
declare(strict_types=1);
namespace AzureOss\Storage\BlobLaravel;
use AzureOss\Identity\AzureAuthorityHosts;
use AzureOss\Identity\ClientCertificateCredential;
use AzureOss\Identity\ClientCertificateCredentialOptions;
use AzureOss\Identity\ClientSecretCredential;
use AzureOss\Identity\ClientSecretCredentialOptions;
use AzureOss\Identity\ManagedIdentityCredential;
use AzureOss\Identity\ManagedIdentityCredentialOptions;
use AzureOss\Identity\TokenCredential;
use AzureOss\Identity\WorkloadIdentityCredential;
use AzureOss\Identity\WorkloadIdentityCredentialOptions;
use AzureOss\Storage\Blob\BlobServiceClient;
use AzureOss\Storage\BlobFlysystem\AzureBlobStorageAdapter;
use AzureOss\Storage\Common\Auth\StorageSharedKeyCredential;
use GuzzleHttp\Psr7\Uri;
use Illuminate\Filesystem\FilesystemAdapter;
use League\Flysystem\Config;
use League\Flysystem\Filesystem;
use Psr\Http\Message\UriInterface;
/**
* @internal
*
* @property AzureBlobStorageAdapter $adapter
*/
final class AzureStorageBlobAdapter extends FilesystemAdapter
{
/**
* Whether the configuration of this adapter allows temporary URLs.
*/
public bool $canProvideTemporaryUrls;
/**
* @param array{
* connection_string?: string,
* endpoint?: string,
* account_name?: string,
* endpoint_suffix?: string,
* credential?: string,
* account_key?: string,
* authority_host?: string,
* tenant_id?: string,
* client_id?: string,
* client_secret?: string,
* client_certificate_path?: string,
* client_certificate_password?: string,
* federated_token_file?: string,
* container: string,
* prefix?: string,
* root?: string,
* is_public_container?: bool
* } $config
*/
public function __construct(array $config)
{
$container = $config['container'];
$prefix = $config['prefix'] ?? null;
$root = $config['root'] ?? null;
$isPublicContainer = $config['is_public_container'] ?? false;
$serviceClient = self::createBlobServiceClient($config);
$containerClient = $serviceClient->getContainerClient($container);
$this->canProvideTemporaryUrls = $containerClient->canGenerateSasUri();
$adapter = new AzureBlobStorageAdapter(
$containerClient,
$prefix ?? $root ?? '',
isPublicContainer: $isPublicContainer,
);
parent::__construct(
new Filesystem($adapter, $config),
$adapter,
$config,
);
}
/**
* @param array{
* connection_string?: string,
* endpoint?: string,
* account_name?: string,
* endpoint_suffix?: string,
* credential?: string,
* account_key?: string,
* authority_host?: string,
* tenant_id?: string,
* client_id?: string,
* client_secret?: string,
* client_certificate_path?: string,
* client_certificate_password?: string,
* federated_token_file?: string,
* container: string,
* prefix?: string,
* root?: string,
* is_public_container?: bool
* } $config
*/
private static function createBlobServiceClient(array $config): BlobServiceClient
{
$connectionString = $config['connection_string'] ?? null;
if ($connectionString !== null && $connectionString !== '') {
$hasEndpointOrAccountName = isset($config['endpoint']) || isset($config['account_name']);
$hasAnyCredentialConfig =
isset($config['credential'])
|| isset($config['account_key'])
|| isset($config['authority_host'])
|| isset($config['tenant_id'])
|| isset($config['client_id'])
|| isset($config['client_secret'])
|| isset($config['client_certificate_path'])
|| isset($config['client_certificate_password'])
|| isset($config['federated_token_file']);
if ($hasEndpointOrAccountName || $hasAnyCredentialConfig) {
throw new \InvalidArgumentException('Cannot use both [connection_string] and token-based credentials in the disk configuration.');
}
return BlobServiceClient::fromConnectionString($connectionString);
}
if (! isset($config['endpoint']) && ! isset($config['account_name'])) {
throw new \InvalidArgumentException(
'Either [connection_string] or [endpoint/account_name] must be provided in the disk configuration.'
);
}
$uri = self::buildBlobEndpointUri($config);
$credential = self::createCredential($config);
return new BlobServiceClient($uri, $credential);
}
/**
* @param array{
* credential?: string,
* account_name?: string,
* account_key?: string,
* authority_host?: string,
* tenant_id?: string,
* client_id?: string,
* client_secret?: string,
* client_certificate_path?: string,
* client_certificate_password?: string,
* federated_token_file?: string
* } $config
*/
private static function createCredential(array $config): StorageSharedKeyCredential|TokenCredential
{
$authorityHost = $config['authority_host'] ?? null;
$credentialType = $config['credential'] ?? null;
$tenantId = $config['tenant_id'] ?? null;
$clientId = $config['client_id'] ?? null;
$clientSecret = $config['client_secret'] ?? null;
if ($credentialType === null) {
if ($tenantId !== null && $clientId !== null && $clientSecret !== null) {
return self::createClientSecretCredential($config, $authorityHost);
}
throw new \InvalidArgumentException('The [credential] must be provided in the disk configuration when not using [connection_string].');
}
return match (strtolower($credentialType)) {
'shared_key' => self::createSharedKeyCredential($config),
'client_secret' => self::createClientSecretCredential($config, $authorityHost),
'client_certificate' => self::createClientCertificateCredential($config, $authorityHost),
'workload_identity' => self::createWorkloadIdentityCredential($config, $authorityHost),
'managed_identity' => self::createManagedIdentityCredential($config, $authorityHost),
default => throw new \InvalidArgumentException(
'Unsupported [credential]. Supported values: [shared_key, client_secret, client_certificate, workload_identity, managed_identity].',
),
};
}
/**
* @param array{account_name?: string, account_key?: string} $config
*/
private static function createSharedKeyCredential(array $config): StorageSharedKeyCredential
{
$accountName = $config['account_name'] ?? null;
$accountKey = $config['account_key'] ?? null;
if ($accountName === null || $accountKey === null) {
throw new \InvalidArgumentException('The [shared_key] credential requires [account_name] and [account_key].');
}
return new StorageSharedKeyCredential($accountName, $accountKey);
}
/**
* @param array{tenant_id?: string, client_id?: string, client_secret?: string} $config
*/
private static function createClientSecretCredential(array $config, ?string $authorityHost): ClientSecretCredential
{
$tenantId = $config['tenant_id'] ?? null;
$clientId = $config['client_id'] ?? null;
$clientSecret = $config['client_secret'] ?? null;
if ($tenantId === null || $clientId === null || $clientSecret === null) {
throw new \InvalidArgumentException('The [client_secret] credential requires [tenant_id], [client_id], and [client_secret].');
}
return new ClientSecretCredential(
$tenantId,
$clientId,
$clientSecret,
new ClientSecretCredentialOptions(authorityHost: $authorityHost ?? AzureAuthorityHosts::AZURE_PUBLIC_CLOUD),
);
}
/**
* @param array{tenant_id?: string, client_id?: string, client_certificate_path?: string, client_certificate_password?: string} $config
*/
private static function createClientCertificateCredential(array $config, ?string $authorityHost): ClientCertificateCredential
{
$tenantId = $config['tenant_id'] ?? null;
$clientId = $config['client_id'] ?? null;
$certificatePath = $config['client_certificate_path'] ?? null;
$certificatePassword = $config['client_certificate_password'] ?? null;
if ($tenantId === null || $clientId === null || $certificatePath === null) {
throw new \InvalidArgumentException('The [client_certificate] credential requires [tenant_id], [client_id], and [client_certificate_path].');
}
return new ClientCertificateCredential(
$tenantId,
$clientId,
$certificatePath,
$certificatePassword,
new ClientCertificateCredentialOptions(authorityHost: $authorityHost ?? AzureAuthorityHosts::AZURE_PUBLIC_CLOUD),
);
}
/**
* @param array{tenant_id?: string, client_id?: string, federated_token_file?: string} $config
*/
private static function createWorkloadIdentityCredential(array $config, ?string $authorityHost): WorkloadIdentityCredential
{
$tenantId = $config['tenant_id'] ?? null;
$clientId = $config['client_id'] ?? null;
$tokenFilePath = $config['federated_token_file'] ?? null;
return new WorkloadIdentityCredential(
new WorkloadIdentityCredentialOptions(
authorityHost: $authorityHost ?? AzureAuthorityHosts::AZURE_PUBLIC_CLOUD,
clientId: $clientId,
tenantId: $tenantId,
tokenFilePath: $tokenFilePath,
)
);
}
/**
* @param array{client_id?: string} $config
*/
private static function createManagedIdentityCredential(array $config, ?string $authorityHost): ManagedIdentityCredential
{
$clientId = $config['client_id'] ?? null;
return new ManagedIdentityCredential(
new ManagedIdentityCredentialOptions(
authorityHost: $authorityHost ?? AzureAuthorityHosts::AZURE_PUBLIC_CLOUD,
clientId: $clientId,
)
);
}
/**
* @param array{endpoint?: string, account_name?: string, endpoint_suffix?: string} $config
*/
private static function buildBlobEndpointUri(array $config): UriInterface
{
$endpoint = $config['endpoint'] ?? null;
if ($endpoint !== null && $endpoint !== '') {
return new Uri(rtrim($endpoint, '/').'/');
}
$accountName = $config['account_name'] ?? null;
if ($accountName === null || $accountName === '') {
throw new \InvalidArgumentException('Either [endpoint] or [account_name] must be provided for token-based credentials.');
}
$endpointSuffix = $config['endpoint_suffix'] ?? 'core.windows.net';
$endpoint = sprintf('https://%s.blob.%s', $accountName, $endpointSuffix);
return new Uri($endpoint.'/');
}
public function url($path)
{
return $this->adapter->publicUrl($path, new Config);
}
/**
* Determine if temporary URLs can be generated.
*
* @return bool
*/
public function providesTemporaryUrls()
{
return $this->canProvideTemporaryUrls;
}
/**
* Get a temporary URL for the file at the given path.
*
* @param string $path
* @param \DateTimeInterface $expiration
* @return string
*/
/** @phpstan-ignore-next-line */
public function temporaryUrl($path, $expiration, array $options = [])
{
return $this->adapter->temporaryUrl(
$path,
$expiration,
new Config(array_merge(['permissions' => 'r'], $options)),
);
}
/**
* Get a temporary upload URL for the file at the given path.
*
* @param string $path
* @param \DateTimeInterface $expiration
* @return array{url: string, headers: array<string, string>}
*/
/** @phpstan-ignore-next-line */
public function temporaryUploadUrl($path, $expiration, array $options = [])
{
$url = $this->adapter->temporaryUrl(
$path,
$expiration,
new Config(array_merge(['permissions' => 'cw'], $options)),
);
$contentType = isset($options['content-type']) && is_string($options['content-type'])
? $options['content-type']
: 'application/octet-stream';
return [
'url' => $url,
'headers' => [
'x-ms-blob-type' => 'BlockBlob',
'Content-Type' => $contentType,
],
];
}
}