S3ConnectionTrait.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Florent <florent@coppint.com>
  8. * @author James Letendre <James.Letendre@gmail.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author S. Cat <33800996+sparrowjack63@users.noreply.github.com>
  13. * @author Stephen Cuppett <steve@cuppett.com>
  14. * @author Jasper Weyne <jasperweyne@gmail.com>
  15. *
  16. * @license GNU AGPL version 3 or any later version
  17. *
  18. * This program is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License as
  20. * published by the Free Software Foundation, either version 3 of the
  21. * License, or (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. *
  31. */
  32. namespace OC\Files\ObjectStore;
  33. use Aws\ClientResolver;
  34. use Aws\Credentials\CredentialProvider;
  35. use Aws\Credentials\Credentials;
  36. use Aws\Exception\CredentialsException;
  37. use Aws\S3\Exception\S3Exception;
  38. use Aws\S3\S3Client;
  39. use GuzzleHttp\Promise;
  40. use GuzzleHttp\Promise\RejectedPromise;
  41. use OCP\ICertificateManager;
  42. use Psr\Log\LoggerInterface;
  43. trait S3ConnectionTrait {
  44. use S3ConfigTrait;
  45. protected string $id;
  46. protected bool $test;
  47. protected ?S3Client $connection = null;
  48. protected function parseParams($params) {
  49. if (empty($params['bucket'])) {
  50. throw new \Exception("Bucket has to be configured.");
  51. }
  52. $this->id = 'amazon::' . $params['bucket'];
  53. $this->test = isset($params['test']);
  54. $this->bucket = $params['bucket'];
  55. // Default to 5 like the S3 SDK does
  56. $this->concurrency = $params['concurrency'] ?? 5;
  57. $this->proxy = $params['proxy'] ?? false;
  58. $this->timeout = $params['timeout'] ?? 15;
  59. $this->storageClass = !empty($params['storageClass']) ? $params['storageClass'] : 'STANDARD';
  60. $this->uploadPartSize = $params['uploadPartSize'] ?? 524288000;
  61. $this->putSizeLimit = $params['putSizeLimit'] ?? 104857600;
  62. $this->copySizeLimit = $params['copySizeLimit'] ?? 5242880000;
  63. $this->useMultipartCopy = (bool)($params['useMultipartCopy'] ?? true);
  64. $params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
  65. $params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
  66. if (!isset($params['port']) || $params['port'] === '') {
  67. $params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
  68. }
  69. $params['verify_bucket_exists'] = $params['verify_bucket_exists'] ?? true;
  70. $this->params = $params;
  71. }
  72. public function getBucket() {
  73. return $this->bucket;
  74. }
  75. public function getProxy() {
  76. return $this->proxy;
  77. }
  78. /**
  79. * Returns the connection
  80. *
  81. * @return S3Client connected client
  82. * @throws \Exception if connection could not be made
  83. */
  84. public function getConnection() {
  85. if ($this->connection !== null) {
  86. return $this->connection;
  87. }
  88. $scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
  89. $base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
  90. // Adding explicit credential provider to the beginning chain.
  91. // Including default credential provider (skipping AWS shared config files).
  92. $provider = CredentialProvider::memoize(
  93. CredentialProvider::chain(
  94. $this->paramCredentialProvider(),
  95. CredentialProvider::defaultProvider(['use_aws_shared_config_files' => false])
  96. )
  97. );
  98. $options = [
  99. 'version' => $this->params['version'] ?? 'latest',
  100. 'credentials' => $provider,
  101. 'endpoint' => $base_url,
  102. 'region' => $this->params['region'],
  103. 'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
  104. 'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider()),
  105. 'csm' => false,
  106. 'use_arn_region' => false,
  107. 'http' => ['verify' => $this->getCertificateBundlePath()],
  108. 'use_aws_shared_config_files' => false,
  109. ];
  110. if ($this->getProxy()) {
  111. $options['http']['proxy'] = $this->getProxy();
  112. }
  113. if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
  114. $options['signature_version'] = 'v2';
  115. }
  116. $this->connection = new S3Client($options);
  117. if (!$this->connection::isBucketDnsCompatible($this->bucket)) {
  118. $logger = \OC::$server->get(LoggerInterface::class);
  119. $logger->debug('Bucket "' . $this->bucket . '" This bucket name is not dns compatible, it may contain invalid characters.',
  120. ['app' => 'objectstore']);
  121. }
  122. if ($this->params['verify_bucket_exists'] && !$this->connection->doesBucketExist($this->bucket)) {
  123. $logger = \OC::$server->get(LoggerInterface::class);
  124. try {
  125. $logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
  126. if (!$this->connection::isBucketDnsCompatible($this->bucket)) {
  127. throw new \Exception("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket);
  128. }
  129. $this->connection->createBucket(['Bucket' => $this->bucket]);
  130. $this->testTimeout();
  131. } catch (S3Exception $e) {
  132. $logger->debug('Invalid remote storage.', [
  133. 'exception' => $e,
  134. 'app' => 'objectstore',
  135. ]);
  136. throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
  137. }
  138. }
  139. // google cloud's s3 compatibility doesn't like the EncodingType parameter
  140. if (strpos($base_url, 'storage.googleapis.com')) {
  141. $this->connection->getHandlerList()->remove('s3.auto_encode');
  142. }
  143. return $this->connection;
  144. }
  145. /**
  146. * when running the tests wait to let the buckets catch up
  147. */
  148. private function testTimeout() {
  149. if ($this->test) {
  150. sleep($this->timeout);
  151. }
  152. }
  153. public static function legacySignatureProvider($version, $service, $region) {
  154. switch ($version) {
  155. case 'v2':
  156. case 's3':
  157. return new S3Signature();
  158. default:
  159. return null;
  160. }
  161. }
  162. /**
  163. * This function creates a credential provider based on user parameter file
  164. */
  165. protected function paramCredentialProvider(): callable {
  166. return function () {
  167. $key = empty($this->params['key']) ? null : $this->params['key'];
  168. $secret = empty($this->params['secret']) ? null : $this->params['secret'];
  169. if ($key && $secret) {
  170. return Promise\promise_for(
  171. new Credentials($key, $secret)
  172. );
  173. }
  174. $msg = 'Could not find parameters set for credentials in config file.';
  175. return new RejectedPromise(new CredentialsException($msg));
  176. };
  177. }
  178. protected function getCertificateBundlePath(): ?string {
  179. if ((int)($this->params['use_nextcloud_bundle'] ?? "0")) {
  180. // since we store the certificate bundles on the primary storage, we can't get the bundle while setting up the primary storage
  181. if (!isset($this->params['primary_storage'])) {
  182. /** @var ICertificateManager $certManager */
  183. $certManager = \OC::$server->get(ICertificateManager::class);
  184. return $certManager->getAbsoluteBundlePath();
  185. } else {
  186. return \OC::$SERVERROOT . '/resources/config/ca-bundle.crt';
  187. }
  188. } else {
  189. return null;
  190. }
  191. }
  192. protected function getSSECKey(): ?string {
  193. if (isset($this->params['sse_c_key'])) {
  194. return $this->params['sse_c_key'];
  195. }
  196. return null;
  197. }
  198. protected function getSSECParameters(bool $copy = false): array {
  199. $key = $this->getSSECKey();
  200. if ($key === null) {
  201. return [];
  202. }
  203. $rawKey = base64_decode($key);
  204. if ($copy) {
  205. return [
  206. 'CopySourceSSECustomerAlgorithm' => 'AES256',
  207. 'CopySourceSSECustomerKey' => $rawKey,
  208. 'CopySourceSSECustomerKeyMD5' => md5($rawKey, true)
  209. ];
  210. }
  211. return [
  212. 'SSECustomerAlgorithm' => 'AES256',
  213. 'SSECustomerKey' => $rawKey,
  214. 'SSECustomerKeyMD5' => md5($rawKey, true)
  215. ];
  216. }
  217. }