S3ConnectionTrait.php 7.5 KB

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