1
0

S3ConnectionTrait.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Files\ObjectStore;
  7. use Aws\ClientResolver;
  8. use Aws\Credentials\CredentialProvider;
  9. use Aws\Credentials\Credentials;
  10. use Aws\Exception\CredentialsException;
  11. use Aws\S3\Exception\S3Exception;
  12. use Aws\S3\S3Client;
  13. use GuzzleHttp\Promise\Create;
  14. use GuzzleHttp\Promise\RejectedPromise;
  15. use OCP\Files\StorageNotAvailableException;
  16. use OCP\ICertificateManager;
  17. use OCP\Server;
  18. use Psr\Log\LoggerInterface;
  19. trait S3ConnectionTrait {
  20. use S3ConfigTrait;
  21. protected string $id;
  22. protected bool $test;
  23. protected ?S3Client $connection = null;
  24. protected function parseParams($params) {
  25. if (empty($params['bucket'])) {
  26. throw new \Exception("Bucket has to be configured.");
  27. }
  28. $this->id = 'amazon::' . $params['bucket'];
  29. $this->test = isset($params['test']);
  30. $this->bucket = $params['bucket'];
  31. // Default to 5 like the S3 SDK does
  32. $this->concurrency = $params['concurrency'] ?? 5;
  33. $this->proxy = $params['proxy'] ?? false;
  34. $this->timeout = $params['timeout'] ?? 15;
  35. $this->storageClass = !empty($params['storageClass']) ? $params['storageClass'] : 'STANDARD';
  36. $this->uploadPartSize = $params['uploadPartSize'] ?? 524288000;
  37. $this->putSizeLimit = $params['putSizeLimit'] ?? 104857600;
  38. $this->copySizeLimit = $params['copySizeLimit'] ?? 5242880000;
  39. $this->useMultipartCopy = (bool)($params['useMultipartCopy'] ?? true);
  40. $params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
  41. $params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
  42. $params['s3-accelerate'] = $params['hostname'] === 's3-accelerate.amazonaws.com' || $params['hostname'] === 's3-accelerate.dualstack.amazonaws.com';
  43. if (!isset($params['port']) || $params['port'] === '') {
  44. $params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
  45. }
  46. $params['verify_bucket_exists'] = $params['verify_bucket_exists'] ?? true;
  47. if ($params['s3-accelerate']) {
  48. $params['verify_bucket_exists'] = false;
  49. }
  50. $this->params = $params;
  51. }
  52. public function getBucket() {
  53. return $this->bucket;
  54. }
  55. public function getProxy() {
  56. return $this->proxy;
  57. }
  58. /**
  59. * Returns the connection
  60. *
  61. * @return S3Client connected client
  62. * @throws \Exception if connection could not be made
  63. */
  64. public function getConnection() {
  65. if ($this->connection !== null) {
  66. return $this->connection;
  67. }
  68. $scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
  69. $base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
  70. // Adding explicit credential provider to the beginning chain.
  71. // Including default credential provider (skipping AWS shared config files).
  72. $provider = CredentialProvider::memoize(
  73. CredentialProvider::chain(
  74. $this->paramCredentialProvider(),
  75. CredentialProvider::defaultProvider(['use_aws_shared_config_files' => false])
  76. )
  77. );
  78. $options = [
  79. 'version' => $this->params['version'] ?? 'latest',
  80. 'credentials' => $provider,
  81. 'endpoint' => $base_url,
  82. 'region' => $this->params['region'],
  83. 'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
  84. 'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider()),
  85. 'csm' => false,
  86. 'use_arn_region' => false,
  87. 'http' => [
  88. 'verify' => $this->getCertificateBundlePath(),
  89. // Timeout for the connection to S3 server, not for the request.
  90. 'connect_timeout' => 5
  91. ],
  92. 'use_aws_shared_config_files' => false,
  93. ];
  94. if ($this->params['s3-accelerate']) {
  95. $options['use_accelerate_endpoint'] = true;
  96. } else {
  97. $options['endpoint'] = $base_url;
  98. }
  99. if ($this->getProxy()) {
  100. $options['http']['proxy'] = $this->getProxy();
  101. }
  102. if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
  103. $options['signature_version'] = 'v2';
  104. }
  105. $this->connection = new S3Client($options);
  106. try {
  107. $logger = Server::get(LoggerInterface::class);
  108. if (!$this->connection::isBucketDnsCompatible($this->bucket)) {
  109. $logger->debug('Bucket "' . $this->bucket . '" This bucket name is not dns compatible, it may contain invalid characters.',
  110. ['app' => 'objectstore']);
  111. }
  112. if ($this->params['verify_bucket_exists'] && !$this->connection->doesBucketExist($this->bucket)) {
  113. try {
  114. $logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
  115. if (!$this->connection::isBucketDnsCompatible($this->bucket)) {
  116. throw new StorageNotAvailableException("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket);
  117. }
  118. $this->connection->createBucket(['Bucket' => $this->bucket]);
  119. $this->testTimeout();
  120. } catch (S3Exception $e) {
  121. $logger->debug('Invalid remote storage.', [
  122. 'exception' => $e,
  123. 'app' => 'objectstore',
  124. ]);
  125. if ($e->getAwsErrorCode() !== 'BucketAlreadyOwnedByYou') {
  126. throw new StorageNotAvailableException('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
  127. }
  128. }
  129. }
  130. // google cloud's s3 compatibility doesn't like the EncodingType parameter
  131. if (strpos($base_url, 'storage.googleapis.com')) {
  132. $this->connection->getHandlerList()->remove('s3.auto_encode');
  133. }
  134. } catch (S3Exception $e) {
  135. throw new StorageNotAvailableException('S3 service is unable to handle request: ' . $e->getMessage());
  136. }
  137. return $this->connection;
  138. }
  139. /**
  140. * when running the tests wait to let the buckets catch up
  141. */
  142. private function testTimeout() {
  143. if ($this->test) {
  144. sleep($this->timeout);
  145. }
  146. }
  147. public static function legacySignatureProvider($version, $service, $region) {
  148. switch ($version) {
  149. case 'v2':
  150. case 's3':
  151. return new S3Signature();
  152. default:
  153. return null;
  154. }
  155. }
  156. /**
  157. * This function creates a credential provider based on user parameter file
  158. */
  159. protected function paramCredentialProvider(): callable {
  160. return function () {
  161. $key = empty($this->params['key']) ? null : $this->params['key'];
  162. $secret = empty($this->params['secret']) ? null : $this->params['secret'];
  163. if ($key && $secret) {
  164. return Create::promiseFor(
  165. new Credentials($key, $secret)
  166. );
  167. }
  168. $msg = 'Could not find parameters set for credentials in config file.';
  169. return new RejectedPromise(new CredentialsException($msg));
  170. };
  171. }
  172. protected function getCertificateBundlePath(): ?string {
  173. if ((int)($this->params['use_nextcloud_bundle'] ?? "0")) {
  174. // since we store the certificate bundles on the primary storage, we can't get the bundle while setting up the primary storage
  175. if (!isset($this->params['primary_storage'])) {
  176. /** @var ICertificateManager $certManager */
  177. $certManager = Server::get(ICertificateManager::class);
  178. return $certManager->getAbsoluteBundlePath();
  179. } else {
  180. return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  181. }
  182. } else {
  183. return null;
  184. }
  185. }
  186. protected function getSSECKey(): ?string {
  187. if (isset($this->params['sse_c_key'])) {
  188. return $this->params['sse_c_key'];
  189. }
  190. return null;
  191. }
  192. protected function getSSECParameters(bool $copy = false): array {
  193. $key = $this->getSSECKey();
  194. if ($key === null) {
  195. return [];
  196. }
  197. $rawKey = base64_decode($key);
  198. if ($copy) {
  199. return [
  200. 'CopySourceSSECustomerAlgorithm' => 'AES256',
  201. 'CopySourceSSECustomerKey' => $rawKey,
  202. 'CopySourceSSECustomerKeyMD5' => md5($rawKey, true)
  203. ];
  204. }
  205. return [
  206. 'SSECustomerAlgorithm' => 'AES256',
  207. 'SSECustomerKey' => $rawKey,
  208. 'SSECustomerKeyMD5' => md5($rawKey, true)
  209. ];
  210. }
  211. }