1
0

S3Storage.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 = array();
  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'] = array();
  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 = array();
  115. $options = array(
  116. 'Bucket' => $this->_bucket,
  117. 'Prefix' => $prefix,
  118. );
  119. do {
  120. $objectsListResponse = $this->_client->listObjects($options);
  121. $objects = $objectsListResponse['Contents'] ?? array();
  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 ($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 = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  155. unset($metadata['salt']);
  156. foreach ($metadata as $k => $v) {
  157. $metadata[$k] = strval($v);
  158. }
  159. try {
  160. $this->_client->putObject(array(
  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(array(
  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 ' . $key . ', ' . $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(array(
  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(array(
  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 = array();
  260. $prefix = $this->_getKey($pasteid) . '/discussion/';
  261. try {
  262. $entries = $this->_listAllObjects($prefix);
  263. foreach ($entries as $entry) {
  264. $object = $this->_client->getObject(array(
  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 ($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(array(
  306. 'Bucket' => $this->_bucket,
  307. 'Key' => $name,
  308. ));
  309. if ($head->get('Metadata') != null && array_key_exists('value', $head->get('Metadata'))) {
  310. $value = $head->get('Metadata')['value'];
  311. if (is_numeric($value) && intval($value) < $time) {
  312. try {
  313. $this->_client->deleteObject(array(
  314. 'Bucket' => $this->_bucket,
  315. 'Key' => $name,
  316. ));
  317. } catch (S3Exception $e) {
  318. // deleted by another instance.
  319. }
  320. }
  321. }
  322. }
  323. } catch (S3Exception $e) {
  324. // no objects in the bucket yet
  325. }
  326. }
  327. /**
  328. * For S3, the value will also be stored in the metadata for the
  329. * namespaces traffic_limiter and purge_limiter.
  330. * @inheritDoc
  331. */
  332. public function setValue($value, $namespace, $key = '')
  333. {
  334. $prefix = $this->_prefix;
  335. if ($prefix != '') {
  336. $prefix .= '/';
  337. }
  338. if ($key === '') {
  339. $key = $prefix . 'config/' . $namespace;
  340. } else {
  341. $key = $prefix . 'config/' . $namespace . '/' . $key;
  342. }
  343. $metadata = array('namespace' => $namespace);
  344. if ($namespace != 'salt') {
  345. $metadata['value'] = strval($value);
  346. }
  347. try {
  348. $this->_client->putObject(array(
  349. 'Bucket' => $this->_bucket,
  350. 'Key' => $key,
  351. 'Body' => $value,
  352. 'ContentType' => 'application/json',
  353. 'Metadata' => $metadata,
  354. ));
  355. } catch (S3Exception $e) {
  356. error_log('failed to set key ' . $key . ' to ' . $this->_bucket . ', ' .
  357. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  358. return false;
  359. }
  360. return true;
  361. }
  362. /**
  363. * @inheritDoc
  364. */
  365. public function getValue($namespace, $key = '')
  366. {
  367. $prefix = $this->_prefix;
  368. if ($prefix != '') {
  369. $prefix .= '/';
  370. }
  371. if ($key === '') {
  372. $key = $prefix . 'config/' . $namespace;
  373. } else {
  374. $key = $prefix . 'config/' . $namespace . '/' . $key;
  375. }
  376. try {
  377. $object = $this->_client->getObject(array(
  378. 'Bucket' => $this->_bucket,
  379. 'Key' => $key,
  380. ));
  381. return $object['Body']->getContents();
  382. } catch (S3Exception $e) {
  383. return '';
  384. }
  385. }
  386. /**
  387. * @inheritDoc
  388. */
  389. protected function _getExpiredPastes($batchsize)
  390. {
  391. $expired = array();
  392. $now = time();
  393. $prefix = $this->_prefix;
  394. if ($prefix != '') {
  395. $prefix .= '/';
  396. }
  397. try {
  398. foreach ($this->_listAllObjects($prefix) as $object) {
  399. $head = $this->_client->headObject(array(
  400. 'Bucket' => $this->_bucket,
  401. 'Key' => $object['Key'],
  402. ));
  403. if ($head->get('Metadata') != null && array_key_exists('expire_date', $head->get('Metadata'))) {
  404. $expire_at = intval($head->get('Metadata')['expire_date']);
  405. if ($expire_at != 0 && $expire_at < $now) {
  406. array_push($expired, $object['Key']);
  407. }
  408. }
  409. if (count($expired) > $batchsize) {
  410. break;
  411. }
  412. }
  413. } catch (S3Exception $e) {
  414. // no objects in the bucket yet
  415. }
  416. return $expired;
  417. }
  418. /**
  419. * @inheritDoc
  420. */
  421. public function getAllPastes()
  422. {
  423. $pastes = array();
  424. $prefix = $this->_prefix;
  425. if ($prefix != '') {
  426. $prefix .= '/';
  427. }
  428. try {
  429. foreach ($this->_listAllObjects($prefix) as $object) {
  430. $candidate = substr($object['Key'], strlen($prefix));
  431. if (!str_contains($candidate, '/')) {
  432. $pastes[] = $candidate;
  433. }
  434. }
  435. } catch (S3Exception $e) {
  436. // no objects in the bucket yet
  437. }
  438. return $pastes;
  439. }
  440. }