S3Storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2022 Felix J. Ogris (https://ogris.de/)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. *
  11. * an S3 compatible data backend for PrivateBin with CEPH/RadosGW in mind
  12. * see https://docs.ceph.com/en/latest/radosgw/s3/php/
  13. *
  14. * Installation:
  15. * 1. Make sure you have composer.lock and composer.json in the document root of your PasteBin
  16. * 2. If not, grab a copy from https://github.com/PrivateBin/PrivateBin
  17. * 3. As non-root user, install the AWS SDK for PHP:
  18. * composer require aws/aws-sdk-php
  19. * (On FreeBSD, install devel/php-composer2 prior, e.g.: make -C /usr/ports/devel/php-composer2 install clean)
  20. * 4. In cfg/conf.php, comment out all [model] and [model_options] settings
  21. * 5. Still in cfg/conf.php, add a new [model] section:
  22. * [model]
  23. * class = S3Storage
  24. * 6. Add a new [model_options] as well, e.g. for a Rados gateway as part of your CEPH cluster:
  25. * [model_options]
  26. * region = ""
  27. * version = "2006-03-01"
  28. * endpoint = "https://s3.my-ceph.invalid"
  29. * use_path_style_endpoint = true
  30. * bucket = "my-bucket"
  31. * prefix = "privatebin" (place all PrivateBin data beneath this prefix)
  32. * accesskey = "my-rados-user"
  33. * secretkey = "my-rados-pass"
  34. */
  35. namespace PrivateBin\Data;
  36. use Aws\S3\Exception\S3Exception;
  37. use Aws\S3\S3Client;
  38. use PrivateBin\Exception\JsonException;
  39. use PrivateBin\Json;
  40. class S3Storage extends AbstractData
  41. {
  42. /**
  43. * S3 client
  44. *
  45. * @access private
  46. * @var S3Client
  47. */
  48. private $_client = null;
  49. /**
  50. * S3 client options
  51. *
  52. * @access private
  53. * @var array
  54. */
  55. private $_options = [];
  56. /**
  57. * S3 bucket
  58. *
  59. * @access private
  60. * @var string
  61. */
  62. private $_bucket = null;
  63. /**
  64. * S3 prefix for all PrivateBin data in this bucket
  65. *
  66. * @access private
  67. * @var string
  68. */
  69. private $_prefix = '';
  70. /**
  71. * instantiates a new S3 data backend.
  72. *
  73. * @access public
  74. * @param array $options
  75. */
  76. public function __construct(array $options)
  77. {
  78. // AWS SDK will try to load credentials from environment if credentials are not passed via configuration
  79. // ref: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html#default-credential-chain
  80. if (isset($options['accesskey']) && isset($options['secretkey'])) {
  81. $this->_options['credentials'] = [];
  82. $this->_options['credentials']['key'] = $options['accesskey'];
  83. $this->_options['credentials']['secret'] = $options['secretkey'];
  84. }
  85. if (array_key_exists('region', $options)) {
  86. $this->_options['region'] = $options['region'];
  87. }
  88. if (array_key_exists('version', $options)) {
  89. $this->_options['version'] = $options['version'];
  90. }
  91. if (array_key_exists('endpoint', $options)) {
  92. $this->_options['endpoint'] = $options['endpoint'];
  93. }
  94. if (array_key_exists('use_path_style_endpoint', $options)) {
  95. $this->_options['use_path_style_endpoint'] = filter_var($options['use_path_style_endpoint'], FILTER_VALIDATE_BOOLEAN);
  96. }
  97. if (array_key_exists('bucket', $options)) {
  98. $this->_bucket = $options['bucket'];
  99. }
  100. if (array_key_exists('prefix', $options)) {
  101. $this->_prefix = $options['prefix'];
  102. }
  103. $this->_client = new S3Client($this->_options);
  104. }
  105. /**
  106. * returns all objects in the given prefix.
  107. *
  108. * @access private
  109. * @param $prefix string with prefix
  110. * @return array all objects in the given prefix
  111. */
  112. private function _listAllObjects($prefix)
  113. {
  114. $allObjects = [];
  115. $options = [
  116. 'Bucket' => $this->_bucket,
  117. 'Prefix' => $prefix,
  118. ];
  119. do {
  120. $objectsListResponse = $this->_client->listObjects($options);
  121. $objects = $objectsListResponse['Contents'] ?? [];
  122. foreach ($objects as $object) {
  123. $allObjects[] = $object;
  124. $options['Marker'] = $object['Key'];
  125. }
  126. } while ($objectsListResponse['IsTruncated']);
  127. return $allObjects;
  128. }
  129. /**
  130. * returns the S3 storage object key for $pasteid in $this->_bucket.
  131. *
  132. * @access private
  133. * @param $pasteid string to get the key for
  134. * @return string
  135. */
  136. private function _getKey($pasteid)
  137. {
  138. if (!empty($this->_prefix)) {
  139. return $this->_prefix . '/' . $pasteid;
  140. }
  141. return $pasteid;
  142. }
  143. /**
  144. * Uploads the payload in the $this->_bucket under the specified key.
  145. * The entire payload is stored as a JSON document. The metadata is replicated
  146. * as the S3 object's metadata except for the field salt.
  147. *
  148. * @param $key string to store the payload under
  149. * @param $payload array to store
  150. * @return bool true if successful, otherwise false.
  151. */
  152. private function _upload($key, &$payload)
  153. {
  154. $metadata = $payload['meta'] ?? [];
  155. unset($metadata['salt']);
  156. foreach ($metadata as $k => $v) {
  157. $metadata[$k] = strval($v);
  158. }
  159. try {
  160. $this->_client->putObject([
  161. 'Bucket' => $this->_bucket,
  162. 'Key' => $key,
  163. 'Body' => Json::encode($payload),
  164. 'ContentType' => 'application/json',
  165. 'Metadata' => $metadata,
  166. ]);
  167. return true;
  168. } catch (S3Exception $e) {
  169. error_log('failed to upload ' . $key . ' to ' . $this->_bucket . ', ' .
  170. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  171. } catch (JsonException $e) {
  172. error_log('failed to JSON encode ' . $key . ', ' . $e->getMessage());
  173. }
  174. return false;
  175. }
  176. /**
  177. * @inheritDoc
  178. */
  179. public function create($pasteid, array &$paste)
  180. {
  181. if ($this->exists($pasteid)) {
  182. return false;
  183. }
  184. return $this->_upload($this->_getKey($pasteid), $paste);
  185. }
  186. /**
  187. * @inheritDoc
  188. */
  189. public function read($pasteid)
  190. {
  191. try {
  192. $object = $this->_client->getObject([
  193. 'Bucket' => $this->_bucket,
  194. 'Key' => $this->_getKey($pasteid),
  195. ]);
  196. $data = $object['Body']->getContents();
  197. return Json::decode($data);
  198. } catch (S3Exception $e) {
  199. error_log('failed to read ' . $pasteid . ' from ' . $this->_bucket . ', ' .
  200. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  201. } catch (JsonException $e) {
  202. error_log('failed to JSON decode ' . $pasteid . ', ' . $e->getMessage());
  203. }
  204. return false;
  205. }
  206. /**
  207. * @inheritDoc
  208. */
  209. public function delete($pasteid)
  210. {
  211. $name = $this->_getKey($pasteid);
  212. try {
  213. $comments = $this->_listAllObjects($name . '/discussion/');
  214. foreach ($comments as $comment) {
  215. try {
  216. $this->_client->deleteObject([
  217. 'Bucket' => $this->_bucket,
  218. 'Key' => $comment['Key'],
  219. ]);
  220. } catch (S3Exception $e) {
  221. // ignore if already deleted.
  222. }
  223. }
  224. } catch (S3Exception $e) {
  225. // there are no discussions associated with the paste
  226. }
  227. try {
  228. $this->_client->deleteObject([
  229. 'Bucket' => $this->_bucket,
  230. 'Key' => $name,
  231. ]);
  232. } catch (S3Exception $e) {
  233. // ignore if already deleted
  234. }
  235. }
  236. /**
  237. * @inheritDoc
  238. */
  239. public function exists($pasteid)
  240. {
  241. return $this->_client->doesObjectExistV2($this->_bucket, $this->_getKey($pasteid));
  242. }
  243. /**
  244. * @inheritDoc
  245. */
  246. public function createComment($pasteid, $parentid, $commentid, array &$comment)
  247. {
  248. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  249. return false;
  250. }
  251. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  252. return $this->_upload($key, $comment);
  253. }
  254. /**
  255. * @inheritDoc
  256. */
  257. public function readComments($pasteid)
  258. {
  259. $comments = [];
  260. $prefix = $this->_getKey($pasteid) . '/discussion/';
  261. try {
  262. $entries = $this->_listAllObjects($prefix);
  263. foreach ($entries as $entry) {
  264. $object = $this->_client->getObject([
  265. 'Bucket' => $this->_bucket,
  266. 'Key' => $entry['Key'],
  267. ]);
  268. $data = $object['Body']->getContents();
  269. $body = JSON::decode($data);
  270. $items = explode('/', $entry['Key']);
  271. $body['id'] = $items[3];
  272. $body['parentid'] = $items[2];
  273. $slot = $this->getOpenSlot($comments, (int) $object['Metadata']['created']);
  274. $comments[$slot] = $body;
  275. }
  276. } catch (S3Exception $e) {
  277. // no comments found
  278. }
  279. return $comments;
  280. }
  281. /**
  282. * @inheritDoc
  283. */
  284. public function existsComment($pasteid, $parentid, $commentid)
  285. {
  286. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  287. return $this->_client->doesObjectExistV2($this->_bucket, $name);
  288. }
  289. /**
  290. * @inheritDoc
  291. */
  292. public function purgeValues($namespace, $time)
  293. {
  294. $path = $this->_prefix;
  295. if (!empty($path)) {
  296. $path .= '/';
  297. }
  298. $path .= 'config/' . $namespace;
  299. try {
  300. foreach ($this->_listAllObjects($path) as $object) {
  301. $name = $object['Key'];
  302. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  303. continue;
  304. }
  305. $head = $this->_client->headObject([
  306. 'Bucket' => $this->_bucket,
  307. 'Key' => $name,
  308. ]);
  309. $value = $head->get('Metadata')['value'] ?? '';
  310. if (is_numeric($value) && intval($value) < $time) {
  311. try {
  312. $this->_client->deleteObject([
  313. 'Bucket' => $this->_bucket,
  314. 'Key' => $name,
  315. ]);
  316. } catch (S3Exception $e) {
  317. // deleted by another instance.
  318. }
  319. }
  320. }
  321. } catch (S3Exception $e) {
  322. // no objects in the bucket yet
  323. }
  324. }
  325. /**
  326. * For S3, the value will also be stored in the metadata for the
  327. * namespaces traffic_limiter and purge_limiter.
  328. * @inheritDoc
  329. */
  330. public function setValue($value, $namespace, $key = '')
  331. {
  332. $prefix = $this->_prefix;
  333. if (!empty($prefix)) {
  334. $prefix .= '/';
  335. }
  336. if ($key === '') {
  337. $key = $prefix . 'config/' . $namespace;
  338. } else {
  339. $key = $prefix . 'config/' . $namespace . '/' . $key;
  340. }
  341. $metadata = ['namespace' => $namespace];
  342. if ($namespace !== 'salt') {
  343. $metadata['value'] = strval($value);
  344. }
  345. try {
  346. $this->_client->putObject([
  347. 'Bucket' => $this->_bucket,
  348. 'Key' => $key,
  349. 'Body' => $value,
  350. 'ContentType' => 'application/json',
  351. 'Metadata' => $metadata,
  352. ]);
  353. } catch (S3Exception $e) {
  354. error_log('failed to set key ' . $key . ' to ' . $this->_bucket . ', ' .
  355. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  356. return false;
  357. }
  358. return true;
  359. }
  360. /**
  361. * @inheritDoc
  362. */
  363. public function getValue($namespace, $key = '')
  364. {
  365. $prefix = $this->_prefix;
  366. if (!empty($prefix)) {
  367. $prefix .= '/';
  368. }
  369. if ($key === '') {
  370. $key = $prefix . 'config/' . $namespace;
  371. } else {
  372. $key = $prefix . 'config/' . $namespace . '/' . $key;
  373. }
  374. try {
  375. $object = $this->_client->getObject([
  376. 'Bucket' => $this->_bucket,
  377. 'Key' => $key,
  378. ]);
  379. return $object['Body']->getContents();
  380. } catch (S3Exception $e) {
  381. return '';
  382. }
  383. }
  384. /**
  385. * @inheritDoc
  386. */
  387. protected function _getExpiredPastes($batchsize)
  388. {
  389. $expired = [];
  390. $now = time();
  391. $prefix = $this->_prefix;
  392. if (!empty($prefix)) {
  393. $prefix .= '/';
  394. }
  395. try {
  396. foreach ($this->_listAllObjects($prefix) as $object) {
  397. $head = $this->_client->headObject([
  398. 'Bucket' => $this->_bucket,
  399. 'Key' => $object['Key'],
  400. ]);
  401. $expire_at = $head->get('Metadata')['expire_date'] ?? '';
  402. if (is_numeric($expire_at) && intval($expire_at) < $now) {
  403. array_push($expired, $object['Key']);
  404. }
  405. if (count($expired) > $batchsize) {
  406. break;
  407. }
  408. }
  409. } catch (S3Exception $e) {
  410. // no objects in the bucket yet
  411. }
  412. return $expired;
  413. }
  414. /**
  415. * @inheritDoc
  416. */
  417. public function getAllPastes()
  418. {
  419. $pastes = [];
  420. $prefix = $this->_prefix;
  421. if (!empty($prefix)) {
  422. $prefix .= '/';
  423. }
  424. try {
  425. foreach ($this->_listAllObjects($prefix) as $object) {
  426. $candidate = substr($object['Key'], strlen($prefix));
  427. if (!str_contains($candidate, '/')) {
  428. $pastes[] = $candidate;
  429. }
  430. }
  431. } catch (S3Exception $e) {
  432. // no objects in the bucket yet
  433. }
  434. return $pastes;
  435. }
  436. }