1
0

S3Storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <?php
  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. if (is_array($options)) {
  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. }
  104. $this->_client = new S3Client($this->_options);
  105. }
  106. /**
  107. * returns all objects in the given prefix.
  108. *
  109. * @access private
  110. * @param $prefix string with prefix
  111. * @return array all objects in the given prefix
  112. */
  113. private function _listAllObjects($prefix)
  114. {
  115. $allObjects = array();
  116. $options = array(
  117. 'Bucket' => $this->_bucket,
  118. 'Prefix' => $prefix,
  119. );
  120. do {
  121. $objectsListResponse = $this->_client->listObjects($options);
  122. $objects = $objectsListResponse['Contents'] ?? array();
  123. foreach ($objects as $object) {
  124. $allObjects[] = $object;
  125. $options['Marker'] = $object['Key'];
  126. }
  127. } while ($objectsListResponse['IsTruncated']);
  128. return $allObjects;
  129. }
  130. /**
  131. * returns the S3 storage object key for $pasteid in $this->_bucket.
  132. *
  133. * @access private
  134. * @param $pasteid string to get the key for
  135. * @return string
  136. */
  137. private function _getKey($pasteid)
  138. {
  139. if ($this->_prefix != '') {
  140. return $this->_prefix . '/' . $pasteid;
  141. }
  142. return $pasteid;
  143. }
  144. /**
  145. * Uploads the payload in the $this->_bucket under the specified key.
  146. * The entire payload is stored as a JSON document. The metadata is replicated
  147. * as the S3 object's metadata except for the fields attachment, attachmentname
  148. * and salt.
  149. *
  150. * @param $key string to store the payload under
  151. * @param $payload array to store
  152. * @return bool true if successful, otherwise false.
  153. */
  154. private function _upload($key, $payload)
  155. {
  156. $metadata = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  157. unset($metadata['attachment'], $metadata['attachmentname'], $metadata['salt']);
  158. foreach ($metadata as $k => $v) {
  159. $metadata[$k] = strval($v);
  160. }
  161. try {
  162. $this->_client->putObject(array(
  163. 'Bucket' => $this->_bucket,
  164. 'Key' => $key,
  165. 'Body' => Json::encode($payload),
  166. 'ContentType' => 'application/json',
  167. 'Metadata' => $metadata,
  168. ));
  169. } catch (S3Exception $e) {
  170. error_log('failed to upload ' . $key . ' to ' . $this->_bucket . ', ' .
  171. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  172. return false;
  173. }
  174. return true;
  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. return false;
  202. }
  203. }
  204. /**
  205. * @inheritDoc
  206. */
  207. public function delete($pasteid)
  208. {
  209. $name = $this->_getKey($pasteid);
  210. try {
  211. $comments = $this->_listAllObjects($name . '/discussion/');
  212. foreach ($comments as $comment) {
  213. try {
  214. $this->_client->deleteObject(array(
  215. 'Bucket' => $this->_bucket,
  216. 'Key' => $comment['Key'],
  217. ));
  218. } catch (S3Exception $e) {
  219. // ignore if already deleted.
  220. }
  221. }
  222. } catch (S3Exception $e) {
  223. // there are no discussions associated with the paste
  224. }
  225. try {
  226. $this->_client->deleteObject(array(
  227. 'Bucket' => $this->_bucket,
  228. 'Key' => $name,
  229. ));
  230. } catch (S3Exception $e) {
  231. // ignore if already deleted
  232. }
  233. }
  234. /**
  235. * @inheritDoc
  236. */
  237. public function exists($pasteid)
  238. {
  239. return $this->_client->doesObjectExistV2($this->_bucket, $this->_getKey($pasteid));
  240. }
  241. /**
  242. * @inheritDoc
  243. */
  244. public function createComment($pasteid, $parentid, $commentid, array $comment)
  245. {
  246. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  247. return false;
  248. }
  249. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  250. return $this->_upload($key, $comment);
  251. }
  252. /**
  253. * @inheritDoc
  254. */
  255. public function readComments($pasteid)
  256. {
  257. $comments = array();
  258. $prefix = $this->_getKey($pasteid) . '/discussion/';
  259. try {
  260. $entries = $this->_listAllObjects($prefix);
  261. foreach ($entries as $entry) {
  262. $object = $this->_client->getObject(array(
  263. 'Bucket' => $this->_bucket,
  264. 'Key' => $entry['Key'],
  265. ));
  266. $body = JSON::decode($object['Body']->getContents());
  267. $items = explode('/', $entry['Key']);
  268. $body['id'] = $items[3];
  269. $body['parentid'] = $items[2];
  270. $slot = $this->getOpenSlot($comments, (int) $object['Metadata']['created']);
  271. $comments[$slot] = $body;
  272. }
  273. } catch (S3Exception $e) {
  274. // no comments found
  275. }
  276. return $comments;
  277. }
  278. /**
  279. * @inheritDoc
  280. */
  281. public function existsComment($pasteid, $parentid, $commentid)
  282. {
  283. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  284. return $this->_client->doesObjectExistV2($this->_bucket, $name);
  285. }
  286. /**
  287. * @inheritDoc
  288. */
  289. public function purgeValues($namespace, $time)
  290. {
  291. $path = $this->_prefix;
  292. if ($path != '') {
  293. $path .= '/';
  294. }
  295. $path .= 'config/' . $namespace;
  296. try {
  297. foreach ($this->_listAllObjects($path) as $object) {
  298. $name = $object['Key'];
  299. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  300. continue;
  301. }
  302. $head = $this->_client->headObject(array(
  303. 'Bucket' => $this->_bucket,
  304. 'Key' => $name,
  305. ));
  306. if ($head->get('Metadata') != null && array_key_exists('value', $head->get('Metadata'))) {
  307. $value = $head->get('Metadata')['value'];
  308. if (is_numeric($value) && intval($value) < $time) {
  309. try {
  310. $this->_client->deleteObject(array(
  311. 'Bucket' => $this->_bucket,
  312. 'Key' => $name,
  313. ));
  314. } catch (S3Exception $e) {
  315. // deleted by another instance.
  316. }
  317. }
  318. }
  319. }
  320. } catch (S3Exception $e) {
  321. // no objects in the bucket yet
  322. }
  323. }
  324. /**
  325. * For S3, the value will also be stored in the metadata for the
  326. * namespaces traffic_limiter and purge_limiter.
  327. * @inheritDoc
  328. */
  329. public function setValue($value, $namespace, $key = '')
  330. {
  331. $prefix = $this->_prefix;
  332. if ($prefix != '') {
  333. $prefix .= '/';
  334. }
  335. if ($key === '') {
  336. $key = $prefix . 'config/' . $namespace;
  337. } else {
  338. $key = $prefix . 'config/' . $namespace . '/' . $key;
  339. }
  340. $metadata = array('namespace' => $namespace);
  341. if ($namespace != 'salt') {
  342. $metadata['value'] = strval($value);
  343. }
  344. try {
  345. $this->_client->putObject(array(
  346. 'Bucket' => $this->_bucket,
  347. 'Key' => $key,
  348. 'Body' => $value,
  349. 'ContentType' => 'application/json',
  350. 'Metadata' => $metadata,
  351. ));
  352. } catch (S3Exception $e) {
  353. error_log('failed to set key ' . $key . ' to ' . $this->_bucket . ', ' .
  354. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  355. return false;
  356. }
  357. return true;
  358. }
  359. /**
  360. * @inheritDoc
  361. */
  362. public function getValue($namespace, $key = '')
  363. {
  364. $prefix = $this->_prefix;
  365. if ($prefix != '') {
  366. $prefix .= '/';
  367. }
  368. if ($key === '') {
  369. $key = $prefix . 'config/' . $namespace;
  370. } else {
  371. $key = $prefix . 'config/' . $namespace . '/' . $key;
  372. }
  373. try {
  374. $object = $this->_client->getObject(array(
  375. 'Bucket' => $this->_bucket,
  376. 'Key' => $key,
  377. ));
  378. return $object['Body']->getContents();
  379. } catch (S3Exception $e) {
  380. return '';
  381. }
  382. }
  383. /**
  384. * @inheritDoc
  385. */
  386. protected function _getExpiredPastes($batchsize)
  387. {
  388. $expired = array();
  389. $now = time();
  390. $prefix = $this->_prefix;
  391. if ($prefix != '') {
  392. $prefix .= '/';
  393. }
  394. try {
  395. foreach ($this->_listAllObjects($prefix) as $object) {
  396. $head = $this->_client->headObject(array(
  397. 'Bucket' => $this->_bucket,
  398. 'Key' => $object['Key'],
  399. ));
  400. if ($head->get('Metadata') != null && array_key_exists('expire_date', $head->get('Metadata'))) {
  401. $expire_at = intval($head->get('Metadata')['expire_date']);
  402. if ($expire_at != 0 && $expire_at < $now) {
  403. array_push($expired, $object['Key']);
  404. }
  405. }
  406. if (count($expired) > $batchsize) {
  407. break;
  408. }
  409. }
  410. } catch (S3Exception $e) {
  411. // no objects in the bucket yet
  412. }
  413. return $expired;
  414. }
  415. /**
  416. * @inheritDoc
  417. */
  418. public function getAllPastes()
  419. {
  420. $pastes = array();
  421. $prefix = $this->_prefix;
  422. if ($prefix != '') {
  423. $prefix .= '/';
  424. }
  425. try {
  426. foreach ($this->_listAllObjects($prefix) as $object) {
  427. $candidate = substr($object['Key'], strlen($prefix));
  428. if (strpos($candidate, '/') === false) {
  429. $pastes[] = $candidate;
  430. }
  431. }
  432. } catch (S3Exception $e) {
  433. // no objects in the bucket yet
  434. }
  435. return $pastes;
  436. }
  437. }