forked from delta-io/delta-sharing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudFileSigner.scala
220 lines (194 loc) · 8.23 KB
/
CloudFileSigner.scala
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
/*
* Copyright (2021) The Delta Lake Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.delta.sharing.server
import java.net.URI
import java.util.Date
import java.util.concurrent.TimeUnit.SECONDS
import com.amazonaws.HttpMethod
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest
import com.google.cloud.hadoop.gcsio.StorageResourceId
import com.google.cloud.storage.BlobId
import com.google.cloud.storage.BlobInfo
import com.google.cloud.storage.Storage
import com.google.cloud.storage.StorageOptions
import com.microsoft.azure.storage.{CloudStorageAccount, SharedAccessProtocols, StorageCredentialsSharedAccessSignature}
import com.microsoft.azure.storage.blob.{SharedAccessBlobPermissions, SharedAccessBlobPolicy}
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.hadoop.fs.azure.{AzureNativeFileSystemStore, NativeAzureFileSystem}
import org.apache.hadoop.fs.azurebfs.{AzureBlobFileSystem, AzureBlobFileSystemStore}
import org.apache.hadoop.fs.azurebfs.services.AuthType
import org.apache.hadoop.fs.s3a.DefaultS3ClientFactory
import org.apache.hadoop.util.ReflectionUtils
trait CloudFileSigner {
def sign(path: Path): String
}
class S3FileSigner(
name: URI,
conf: Configuration,
preSignedUrlTimeoutSeconds: Long) extends CloudFileSigner {
private val s3Client = ReflectionUtils.newInstance(classOf[DefaultS3ClientFactory], conf)
.createS3Client(name)
override def sign(path: Path): String = {
val absPath = path.toUri
val bucketName = absPath.getHost
val objectKey = absPath.getPath.stripPrefix("/")
val expiration =
new Date(System.currentTimeMillis() + SECONDS.toMillis(preSignedUrlTimeoutSeconds))
assert(objectKey.nonEmpty, s"cannot get object key from $path")
val request = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration)
s3Client.generatePresignedUrl(request).toString
}
}
class AzureFileSigner(
accountName: String,
storageKey: String,
container: String,
preSignedUrlTimeoutSeconds: Long,
objectKeyExtractor: Path => String) extends CloudFileSigner {
private val (rawAccountName, endpointSuffix) = {
val splits = accountName.split("\\.", 3)
if (splits.length != 3) {
throw new IllegalArgumentException(s"Incorrect account name: $accountName")
}
(splits(0), splits(2))
}
private def getCloudStorageAccount: CloudStorageAccount = {
val connectionString = Seq(
"DefaultEndpointsProtocol=https",
s"AccountName=$rawAccountName",
s"AccountKey=$storageKey",
s"EndpointSuffix=$endpointSuffix"
).mkString(";")
CloudStorageAccount.parse(connectionString)
}
private val cloudStorageAccount = getCloudStorageAccount
private val blobClient = cloudStorageAccount.createCloudBlobClient()
private def getAccessPolicy: SharedAccessBlobPolicy = {
val expiration =
new Date(System.currentTimeMillis() + SECONDS.toMillis(preSignedUrlTimeoutSeconds))
val sharedAccessPolicy = new SharedAccessBlobPolicy()
sharedAccessPolicy.setPermissions(java.util.EnumSet.of(SharedAccessBlobPermissions.READ))
sharedAccessPolicy.setSharedAccessExpiryTime(expiration)
sharedAccessPolicy
}
override def sign(path: Path): String = {
val containerRef = blobClient.getContainerReference(container)
val objectKey = objectKeyExtractor(path)
assert(objectKey.nonEmpty, s"cannot get object key from $path")
val blobRef = containerRef.getBlockBlobReference(objectKey)
val accessPolicy = getAccessPolicy
val sasToken = blobRef.generateSharedAccessSignature(
accessPolicy,
/* headers */ null,
/* groupPolicyIdentifier */ null,
/* ipRange */ null,
SharedAccessProtocols.HTTPS_ONLY
)
val sasTokenCredentials = new StorageCredentialsSharedAccessSignature(sasToken)
sasTokenCredentials.transformUri(blobRef.getUri).toString
}
}
object WasbFileSigner {
private def getAccountFromAuthority(store: AzureNativeFileSystemStore, uri: URI): String = {
val getAccountFromAuthorityMethod = classOf[AzureNativeFileSystemStore]
.getDeclaredMethod("getAccountFromAuthority", classOf[URI])
getAccountFromAuthorityMethod.setAccessible(true)
getAccountFromAuthorityMethod.invoke(store, uri).asInstanceOf[String]
}
private def getContainerFromAuthority(store: AzureNativeFileSystemStore, uri: URI): String = {
val getContainerFromAuthorityMethod = classOf[AzureNativeFileSystemStore]
.getDeclaredMethod("getContainerFromAuthority", classOf[URI])
getContainerFromAuthorityMethod.setAccessible(true)
getContainerFromAuthorityMethod.invoke(store, uri).asInstanceOf[String]
}
def apply(
fs: NativeAzureFileSystem,
uri: URI,
conf: Configuration,
preSignedUrlTimeoutSeconds: Long): CloudFileSigner = {
val accountName = getAccountFromAuthority(fs.getStore, uri)
val accountKey = AzureNativeFileSystemStore.getAccountKeyFromConfiguration(accountName, conf)
val container = getContainerFromAuthority(fs.getStore, uri)
new AzureFileSigner(
accountName,
accountKey,
container,
preSignedUrlTimeoutSeconds,
fs.pathToKey)
}
}
object AbfsFileSigner {
private def getAbfsStore(fs: AzureBlobFileSystem): AzureBlobFileSystemStore = {
val getAbfsStoreMethod = classOf[AzureBlobFileSystem].getDeclaredMethod("getAbfsStore")
getAbfsStoreMethod.setAccessible(true)
getAbfsStoreMethod.invoke(fs).asInstanceOf[AzureBlobFileSystemStore]
}
private def getRelativePath(abfsStore: AzureBlobFileSystemStore, path: Path): String = {
val getRelativePathMethod = classOf[AzureBlobFileSystemStore]
.getDeclaredMethod("getRelativePath", classOf[Path])
getRelativePathMethod.setAccessible(true)
getRelativePathMethod.invoke(abfsStore, path).asInstanceOf[String]
}
private def authorityParts(abfsStore: AzureBlobFileSystemStore, uri: URI): Array[String] = {
val authorityPartsMethod = classOf[AzureBlobFileSystemStore]
.getDeclaredMethod("authorityParts", classOf[URI])
authorityPartsMethod.setAccessible(true)
authorityPartsMethod.invoke(abfsStore, uri).asInstanceOf[Array[String]]
}
def apply(
fs: AzureBlobFileSystem,
uri: URI,
preSignedUrlTimeoutSeconds: Long): CloudFileSigner = {
val abfsStore = getAbfsStore(fs)
val abfsConfiguration = abfsStore.getAbfsConfiguration
val accountName = abfsConfiguration.accountConf("dummy").stripPrefix("dummy.")
val authType = abfsConfiguration.getAuthType(accountName)
if (authType != AuthType.SharedKey) {
throw new UnsupportedOperationException(s"unsupported auth type: $authType")
}
val accountKey = abfsConfiguration.getStorageAccountKey
val container = authorityParts(abfsStore, uri)(0)
new AzureFileSigner(
accountName,
accountKey,
container,
preSignedUrlTimeoutSeconds,
getRelativePath(abfsStore, _))
}
}
class GCSFileSigner(
name: URI,
conf: Configuration,
preSignedUrlTimeoutSeconds: Long) extends CloudFileSigner {
private val storage = StorageOptions.newBuilder.build.getService
override def sign(path: Path): String = {
val (bucketName, objectName) = GCSFileSigner.getBucketAndObjectNames(path)
assert(objectName.nonEmpty, s"cannot get object key from $path")
val blobInfo = BlobInfo.newBuilder(BlobId.of(bucketName, objectName)).build
storage.signUrl(
blobInfo, preSignedUrlTimeoutSeconds, SECONDS, Storage.SignUrlOption.withV4Signature())
.toString
}
}
object GCSFileSigner {
def getBucketAndObjectNames(path: Path): (String, String) = {
val resourceId = StorageResourceId.fromUriPath(path.toUri, false /* = allowEmptyObjectName */)
(resourceId.getBucketName, resourceId.getObjectName)
}
}