S3ConnectionTrait.php 7.4 KB

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