S3Storage.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. <?php
  2. /**
  3. * S3.php
  4. *
  5. * an S3 compatible data backend for PrivateBin with CEPH/RadosGW in mind
  6. * see https://docs.ceph.com/en/latest/radosgw/s3/php/
  7. * based on lib/Data/GoogleCloudStorage.php from PrivateBin version 1.7.1
  8. *
  9. * @link https://github.com/PrivateBin/PrivateBin
  10. * @copyright 2022 Felix J. Ogris (https://ogris.de/)
  11. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  12. * @version 1.4.1
  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. * @return
  75. */
  76. public function __construct(array $options)
  77. {
  78. if (is_array($options)) {
  79. // AWS SDK will try to load credentials from environment if credentials are not passed via configuration
  80. // ref: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html#default-credential-chain
  81. if (isset($options['accesskey']) && isset($options['secretkey'])) {
  82. $this->_options['credentials'] = array();
  83. $this->_options['credentials']['key'] = $options['accesskey'];
  84. $this->_options['credentials']['secret'] = $options['secretkey'];
  85. }
  86. if (array_key_exists('region', $options)) {
  87. $this->_options['region'] = $options['region'];
  88. }
  89. if (array_key_exists('version', $options)) {
  90. $this->_options['version'] = $options['version'];
  91. }
  92. if (array_key_exists('endpoint', $options)) {
  93. $this->_options['endpoint'] = $options['endpoint'];
  94. }
  95. if (array_key_exists('use_path_style_endpoint', $options)) {
  96. $this->_options['use_path_style_endpoint'] = filter_var($options['use_path_style_endpoint'], FILTER_VALIDATE_BOOLEAN);
  97. }
  98. if (array_key_exists('bucket', $options)) {
  99. $this->_bucket = $options['bucket'];
  100. }
  101. if (array_key_exists('prefix', $options)) {
  102. $this->_prefix = $options['prefix'];
  103. }
  104. }
  105. $this->_client = new S3Client($this->_options);
  106. }
  107. /**
  108. * returns all objects in the given prefix.
  109. *
  110. * @access private
  111. * @param $prefix string with prefix
  112. * @return array all objects in the given prefix
  113. */
  114. private function _listAllObjects($prefix)
  115. {
  116. $allObjects = array();
  117. $options = array(
  118. 'Bucket' => $this->_bucket,
  119. 'Prefix' => $prefix,
  120. );
  121. do {
  122. $objectsListResponse = $this->_client->listObjects($options);
  123. $objects = $objectsListResponse['Contents'] ?? array();
  124. foreach ($objects as $object) {
  125. $allObjects[] = $object;
  126. $options['Marker'] = $object['Key'];
  127. }
  128. } while ($objectsListResponse['IsTruncated']);
  129. return $allObjects;
  130. }
  131. /**
  132. * returns the S3 storage object key for $pasteid in $this->_bucket.
  133. *
  134. * @access private
  135. * @param $pasteid string to get the key for
  136. * @return string
  137. */
  138. private function _getKey($pasteid)
  139. {
  140. if ($this->_prefix != '') {
  141. return $this->_prefix . '/' . $pasteid;
  142. }
  143. return $pasteid;
  144. }
  145. /**
  146. * Uploads the payload in the $this->_bucket under the specified key.
  147. * The entire payload is stored as a JSON document. The metadata is replicated
  148. * as the S3 object's metadata except for the fields attachment, attachmentname
  149. * and salt.
  150. *
  151. * @param $key string to store the payload under
  152. * @param $payload array to store
  153. * @return bool true if successful, otherwise false.
  154. */
  155. private function _upload($key, $payload)
  156. {
  157. $metadata = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  158. unset($metadata['attachment'], $metadata['attachmentname'], $metadata['salt']);
  159. foreach ($metadata as $k => $v) {
  160. $metadata[$k] = strval($v);
  161. }
  162. try {
  163. $this->_client->putObject(array(
  164. 'Bucket' => $this->_bucket,
  165. 'Key' => $key,
  166. 'Body' => Json::encode($payload),
  167. 'ContentType' => 'application/json',
  168. 'Metadata' => $metadata,
  169. ));
  170. } catch (S3Exception $e) {
  171. error_log('failed to upload ' . $key . ' to ' . $this->_bucket . ', ' .
  172. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  173. return false;
  174. }
  175. return true;
  176. }
  177. /**
  178. * @inheritDoc
  179. */
  180. public function create($pasteid, array $paste)
  181. {
  182. if ($this->exists($pasteid)) {
  183. return false;
  184. }
  185. return $this->_upload($this->_getKey($pasteid), $paste);
  186. }
  187. /**
  188. * @inheritDoc
  189. */
  190. public function read($pasteid)
  191. {
  192. try {
  193. $object = $this->_client->getObject(array(
  194. 'Bucket' => $this->_bucket,
  195. 'Key' => $this->_getKey($pasteid),
  196. ));
  197. $data = $object['Body']->getContents();
  198. return Json::decode($data);
  199. } catch (S3Exception $e) {
  200. error_log('failed to read ' . $pasteid . ' from ' . $this->_bucket . ', ' .
  201. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  202. return false;
  203. }
  204. }
  205. /**
  206. * @inheritDoc
  207. */
  208. public function delete($pasteid)
  209. {
  210. $name = $this->_getKey($pasteid);
  211. try {
  212. $comments = $this->_listAllObjects($name . '/discussion/');
  213. foreach ($comments as $comment) {
  214. try {
  215. $this->_client->deleteObject(array(
  216. 'Bucket' => $this->_bucket,
  217. 'Key' => $comment['Key'],
  218. ));
  219. } catch (S3Exception $e) {
  220. // ignore if already deleted.
  221. }
  222. }
  223. } catch (S3Exception $e) {
  224. // there are no discussions associated with the paste
  225. }
  226. try {
  227. $this->_client->deleteObject(array(
  228. 'Bucket' => $this->_bucket,
  229. 'Key' => $name,
  230. ));
  231. } catch (S3Exception $e) {
  232. // ignore if already deleted
  233. }
  234. }
  235. /**
  236. * @inheritDoc
  237. */
  238. public function exists($pasteid)
  239. {
  240. return $this->_client->doesObjectExistV2($this->_bucket, $this->_getKey($pasteid));
  241. }
  242. /**
  243. * @inheritDoc
  244. */
  245. public function createComment($pasteid, $parentid, $commentid, array $comment)
  246. {
  247. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  248. return false;
  249. }
  250. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  251. return $this->_upload($key, $comment);
  252. }
  253. /**
  254. * @inheritDoc
  255. */
  256. public function readComments($pasteid)
  257. {
  258. $comments = array();
  259. $prefix = $this->_getKey($pasteid) . '/discussion/';
  260. try {
  261. $entries = $this->_listAllObjects($prefix);
  262. foreach ($entries as $entry) {
  263. $object = $this->_client->getObject(array(
  264. 'Bucket' => $this->_bucket,
  265. 'Key' => $entry['Key'],
  266. ));
  267. $body = JSON::decode($object['Body']->getContents());
  268. $items = explode('/', $entry['Key']);
  269. $body['id'] = $items[3];
  270. $body['parentid'] = $items[2];
  271. $slot = $this->getOpenSlot($comments, (int) $object['Metadata']['created']);
  272. $comments[$slot] = $body;
  273. }
  274. } catch (S3Exception $e) {
  275. // no comments found
  276. }
  277. return $comments;
  278. }
  279. /**
  280. * @inheritDoc
  281. */
  282. public function existsComment($pasteid, $parentid, $commentid)
  283. {
  284. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  285. return $this->_client->doesObjectExistV2($this->_bucket, $name);
  286. }
  287. /**
  288. * @inheritDoc
  289. */
  290. public function purgeValues($namespace, $time)
  291. {
  292. $path = $this->_prefix;
  293. if ($path != '') {
  294. $path .= '/';
  295. }
  296. $path .= 'config/' . $namespace;
  297. try {
  298. foreach ($this->_listAllObjects($path) as $object) {
  299. $name = $object['Key'];
  300. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  301. continue;
  302. }
  303. $head = $this->_client->headObject(array(
  304. 'Bucket' => $this->_bucket,
  305. 'Key' => $name,
  306. ));
  307. if ($head->get('Metadata') != null && array_key_exists('value', $head->get('Metadata'))) {
  308. $value = $head->get('Metadata')['value'];
  309. if (is_numeric($value) && intval($value) < $time) {
  310. try {
  311. $this->_client->deleteObject(array(
  312. 'Bucket' => $this->_bucket,
  313. 'Key' => $name,
  314. ));
  315. } catch (S3Exception $e) {
  316. // deleted by another instance.
  317. }
  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 ($prefix != '') {
  334. $prefix .= '/';
  335. }
  336. if ($key === '') {
  337. $key = $prefix . 'config/' . $namespace;
  338. } else {
  339. $key = $prefix . 'config/' . $namespace . '/' . $key;
  340. }
  341. $metadata = array('namespace' => $namespace);
  342. if ($namespace != 'salt') {
  343. $metadata['value'] = strval($value);
  344. }
  345. try {
  346. $this->_client->putObject(array(
  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 ($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(array(
  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 = array();
  390. $now = time();
  391. $prefix = $this->_prefix;
  392. if ($prefix != '') {
  393. $prefix .= '/';
  394. }
  395. try {
  396. foreach ($this->_listAllObjects($prefix) as $object) {
  397. $head = $this->_client->headObject(array(
  398. 'Bucket' => $this->_bucket,
  399. 'Key' => $object['Key'],
  400. ));
  401. if ($head->get('Metadata') != null && array_key_exists('expire_date', $head->get('Metadata'))) {
  402. $expire_at = intval($head->get('Metadata')['expire_date']);
  403. if ($expire_at != 0 && $expire_at < $now) {
  404. array_push($expired, $object['Key']);
  405. }
  406. }
  407. if (count($expired) > $batchsize) {
  408. break;
  409. }
  410. }
  411. } catch (S3Exception $e) {
  412. // no objects in the bucket yet
  413. }
  414. return $expired;
  415. }
  416. /**
  417. * @inheritDoc
  418. */
  419. public function getAllPastes()
  420. {
  421. $pastes = array();
  422. $prefix = $this->_prefix;
  423. if ($prefix != '') {
  424. $prefix .= '/';
  425. }
  426. try {
  427. foreach ($this->_listAllObjects($prefix) as $object) {
  428. $candidate = substr($object['Key'], strlen($prefix));
  429. if (strpos($candidate, '/') === false) {
  430. $pastes[] = $candidate;
  431. }
  432. }
  433. } catch (S3Exception $e) {
  434. // no objects in the bucket yet
  435. }
  436. return $pastes;
  437. }
  438. }