S3ConnectionTrait.php 8.4 KB

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