S3Storage.php 14 KB

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