1
0

S3ConnectionTrait.php 7.6 KB

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