ldp.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. import hashlib
  2. import logging
  3. import pdb
  4. from base64 import b64encode
  5. from collections import defaultdict
  6. from io import BytesIO
  7. from pprint import pformat
  8. from uuid import uuid4
  9. import arrow
  10. from flask import (
  11. Blueprint, Response, g, make_response, render_template,
  12. request, send_file)
  13. from rdflib import Graph, plugin, parser#, serializer
  14. from werkzeug.http import parse_date
  15. from lakesuperior import env
  16. from lakesuperior.api import resource as rsrc_api
  17. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  18. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  19. from lakesuperior.exceptions import (
  20. ChecksumValidationError, ResourceNotExistsError, TombstoneError,
  21. ServerManagedTermError, InvalidResourceError, SingleSubjectError,
  22. ResourceExistsError, IncompatibleLdpTypeError,
  23. IndigestibleError)
  24. from lakesuperior.globals import RES_CREATED
  25. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  26. from lakesuperior.model.ldp.ldp_nr import LdpNr
  27. from lakesuperior.model.ldp.ldp_rs import LdpRs
  28. from lakesuperior.model.ldp.ldpr import Ldpr
  29. from lakesuperior.util import toolbox
  30. from lakesuperior.util.toolbox import RequestUtils
  31. DEFAULT_RDF_MIMETYPE = 'text/turtle'
  32. """
  33. Fallback serialization format used when no acceptable formats are specified.
  34. """
  35. logger = logging.getLogger(__name__)
  36. rdf_parsable_mimetypes = {
  37. mt.name for mt in plugin.plugins()
  38. if mt.kind is parser.Parser and '/' in mt.name
  39. }
  40. """MIMEtypes that can be parsed into RDF."""
  41. store = env.app_globals.rdf_store
  42. rdf_serializable_mimetypes = {
  43. #mt.name for mt in plugin.plugins()
  44. #if mt.kind is serializer.Serializer and '/' in mt.name
  45. 'application/ld+json',
  46. 'application/n-triples',
  47. 'application/rdf+xml',
  48. 'text/turtle',
  49. 'text/n3',
  50. }
  51. """
  52. MIMEtypes that RDF can be serialized into.
  53. These are not automatically derived from RDFLib because only triple
  54. (not quad) serializations are applicable.
  55. """
  56. accept_patch = (
  57. 'application/sparql-update',
  58. )
  59. std_headers = {
  60. 'Accept-Patch' : ','.join(accept_patch),
  61. 'Accept-Post' : ','.join(rdf_parsable_mimetypes),
  62. }
  63. """Predicates excluded by view."""
  64. vw_blacklist = {
  65. }
  66. ldp = Blueprint(
  67. 'ldp', __name__, template_folder='templates',
  68. static_url_path='/static', static_folder='templates/static')
  69. """
  70. Blueprint for LDP REST API. This is what is usually found under ``/rest/`` in
  71. standard fcrepo4. Here, it is under ``/ldp`` but initially ``/rest`` will be
  72. kept for backward compatibility.
  73. """
  74. ## ROUTE PRE- & POST-PROCESSING ##
  75. @ldp.url_defaults
  76. def bp_url_defaults(endpoint, values):
  77. url_prefix = getattr(g, 'url_prefix', None)
  78. if url_prefix is not None:
  79. values.setdefault('url_prefix', url_prefix)
  80. @ldp.url_value_preprocessor
  81. def bp_url_value_preprocessor(endpoint, values):
  82. g.url_prefix = values.pop('url_prefix')
  83. g.webroot = request.host_url + g.url_prefix
  84. # Normalize leading slashes for UID.
  85. if 'uid' in values:
  86. values['uid'] = '/' + values['uid'].lstrip('/')
  87. if 'parent_uid' in values:
  88. values['parent_uid'] = '/' + values['parent_uid'].lstrip('/')
  89. @ldp.before_request
  90. def log_request_start():
  91. logger.info('** Start {} {} **'.format(request.method, request.url))
  92. @ldp.before_request
  93. def instantiate_req_vars():
  94. g.tbox = RequestUtils()
  95. @ldp.after_request
  96. def log_request_end(rsp):
  97. logger.info('** End {} {} **'.format(request.method, request.url))
  98. return rsp
  99. ## REST SERVICES ##
  100. @ldp.route('/<path:uid>', methods=['GET'], strict_slashes=False)
  101. @ldp.route('/', defaults={'uid': '/'}, methods=['GET'], strict_slashes=False)
  102. @ldp.route('/<path:uid>/fcr:metadata', defaults={'out_fmt' : 'rdf'},
  103. methods=['GET'])
  104. @ldp.route('/<path:uid>/fcr:content', defaults={'out_fmt' : 'non_rdf'},
  105. methods=['GET'])
  106. def get_resource(uid, out_fmt=None):
  107. r"""
  108. https://www.w3.org/TR/ldp/#ldpr-HTTP_GET
  109. Retrieve RDF or binary content.
  110. :param str uid: UID of resource to retrieve. The repository root has
  111. an empty string for UID.
  112. :param str out_fmt: Force output to RDF or non-RDF if the resource is
  113. a LDP-NR. This is not available in the API but is used e.g. by the
  114. ``\*/fcr:metadata`` and ``\*/fcr:content`` endpoints. The default is
  115. False.
  116. """
  117. out_headers = std_headers.copy()
  118. repr_options = defaultdict(dict)
  119. # Fist check if it's not a 404 or a 410.
  120. try:
  121. if not rsrc_api.exists(uid):
  122. return '', 404
  123. except TombstoneError as e:
  124. return _tombstone_response(e, uid)
  125. # Then process the condition headers.
  126. cond_ret = _process_cond_headers(uid, request.headers)
  127. if cond_ret:
  128. return cond_ret
  129. # Then, business as usual.
  130. # Evaluate which representation is requested.
  131. if 'prefer' in request.headers:
  132. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  133. logger.debug('Parsed Prefer header: {}'.format(pformat(prefer)))
  134. if 'return' in prefer:
  135. repr_options = parse_repr_options(prefer['return'])
  136. rsrc = rsrc_api.get(uid, repr_options)
  137. with store.txn_ctx():
  138. if out_fmt is None:
  139. rdf_mimetype = _best_rdf_mimetype()
  140. out_fmt = (
  141. 'rdf'
  142. if isinstance(rsrc, LdpRs) or rdf_mimetype is not None
  143. else 'non_rdf')
  144. out_headers.update(_headers_from_metadata(rsrc, out_fmt))
  145. uri = g.tbox.uid_to_uri(uid)
  146. # RDF output.
  147. if out_fmt == 'rdf':
  148. if locals().get('rdf_mimetype', None) is None:
  149. rdf_mimetype = DEFAULT_RDF_MIMETYPE
  150. ggr = g.tbox.globalize_imr(rsrc.out_graph)
  151. ggr.namespace_manager = nsm
  152. return _negotiate_content(
  153. ggr, rdf_mimetype, out_headers, uid=uid, uri=uri)
  154. # Datastream.
  155. else:
  156. if not getattr(rsrc, 'local_path', False):
  157. return ('{} has no binary content.'.format(rsrc.uid), 404)
  158. logger.debug('Streaming out binary content.')
  159. if request.range and request.range.units == 'bytes':
  160. # Stream partial response.
  161. # This is only true if the header is well-formed. Thanks, Werkzeug.
  162. rsp = _parse_range_header(
  163. request.range.ranges, rsrc, out_headers
  164. )
  165. else:
  166. rsp = make_response(send_file(
  167. rsrc.local_path, as_attachment=True,
  168. attachment_filename=rsrc.filename,
  169. mimetype=rsrc.mimetype), 200, out_headers)
  170. # This seems necessary to prevent Flask from setting an
  171. # additional ETag.
  172. if 'ETag' in out_headers:
  173. rsp.set_etag(out_headers['ETag'])
  174. rsp.headers.add('Link', f'<{uri}/fcr:metadata>; rel="describedby"')
  175. return rsp
  176. @ldp.route('/<path:uid>/fcr:versions', methods=['GET'])
  177. def get_version_info(uid):
  178. """
  179. Get version info (`fcr:versions`).
  180. :param str uid: UID of resource to retrieve versions for.
  181. """
  182. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  183. try:
  184. imr = rsrc_api.get_version_info(uid)
  185. except ResourceNotExistsError as e:
  186. return str(e), 404
  187. except InvalidResourceError as e:
  188. return str(e), 409
  189. except TombstoneError as e:
  190. return _tombstone_response(e, uid)
  191. else:
  192. with store.txn_ctx():
  193. return _negotiate_content(g.tbox.globalize_imr(imr), rdf_mimetype)
  194. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['GET'])
  195. def get_version(uid, ver_uid):
  196. """
  197. Get an individual resource version.
  198. :param str uid: Resource UID.
  199. :param str ver_uid: Version UID.
  200. """
  201. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  202. try:
  203. imr = rsrc_api.get_version(uid, ver_uid)
  204. except ResourceNotExistsError as e:
  205. return str(e), 404
  206. except InvalidResourceError as e:
  207. return str(e), 409
  208. except TombstoneError as e:
  209. return _tombstone_response(e, uid)
  210. else:
  211. with store.txn_ctx():
  212. return _negotiate_content(g.tbox.globalize_imr(imr), rdf_mimetype)
  213. @ldp.route('/<path:parent_uid>', methods=['POST'], strict_slashes=False)
  214. @ldp.route('/', defaults={'parent_uid': '/'}, methods=['POST'],
  215. strict_slashes=False)
  216. def post_resource(parent_uid):
  217. """
  218. https://www.w3.org/TR/ldp/#ldpr-HTTP_POST
  219. Add a new resource in a new URI.
  220. """
  221. rsp_headers = std_headers.copy()
  222. slug = request.headers.get('Slug')
  223. kwargs = {}
  224. kwargs['handling'], kwargs['disposition'] = set_post_put_params()
  225. stream, mimetype = _bistream_from_req()
  226. if mimetype in rdf_parsable_mimetypes:
  227. # If the content is RDF, localize in-repo URIs.
  228. global_rdf = stream.read()
  229. kwargs['rdf_data'] = g.tbox.localize_payload(global_rdf)
  230. kwargs['rdf_fmt'] = mimetype
  231. else:
  232. kwargs['stream'] = stream
  233. kwargs['mimetype'] = mimetype
  234. # Check digest if requested.
  235. if 'digest' in request.headers:
  236. try:
  237. kwargs['prov_cksum_algo'], kwargs['prov_cksum'] = (
  238. request.headers['digest'].split('=')
  239. )
  240. except ValueError:
  241. return (
  242. f'Cannot parse digest value: {request.headers["digest"]}',
  243. 400
  244. )
  245. try:
  246. rsrc = rsrc_api.create(parent_uid, slug, **kwargs)
  247. except IndigestibleError:
  248. return (
  249. f'Unable to parse digest header: {request.headers["digest"]}'
  250. ), 400
  251. except ResourceNotExistsError as e:
  252. return str(e), 404
  253. except (InvalidResourceError, ChecksumValidationError) as e:
  254. return str(e), 409
  255. except TombstoneError as e:
  256. return _tombstone_response(e, uid)
  257. except ServerManagedTermError as e:
  258. rsp_headers['Link'] = (
  259. f'<{uri}>; rel="{nsc["ldp"].constrainedBy}"; '
  260. f'{g.webroot}/info/ldp_constraints"'
  261. )
  262. return str(e), 412
  263. uri = g.tbox.uid_to_uri(rsrc.uid)
  264. with store.txn_ctx():
  265. rsp_headers.update(_headers_from_metadata(rsrc))
  266. rsp_headers['Location'] = uri
  267. if mimetype and kwargs.get('rdf_fmt') is None:
  268. rsp_headers['Link'] = (
  269. f'<{uri}/fcr:metadata>; rel="describedby"; anchor="{uri}"'
  270. )
  271. return uri, 201, rsp_headers
  272. @ldp.route('/<path:uid>', methods=['PUT'], strict_slashes=False)
  273. @ldp.route('/<path:uid>/fcr:metadata', defaults={'force_rdf' : True},
  274. methods=['PUT'])
  275. def put_resource(uid):
  276. """
  277. https://www.w3.org/TR/ldp/#ldpr-HTTP_PUT
  278. Add or replace a new resource at a specified URI.
  279. """
  280. # Parse headers.
  281. logger.debug('Request headers: {}'.format(request.headers))
  282. cond_ret = _process_cond_headers(uid, request.headers, False)
  283. if cond_ret:
  284. return cond_ret
  285. kwargs = {}
  286. kwargs['handling'], kwargs['disposition'] = set_post_put_params()
  287. stream, mimetype = _bistream_from_req()
  288. if mimetype in rdf_parsable_mimetypes:
  289. # If the content is RDF, localize in-repo URIs.
  290. global_rdf = stream.read()
  291. kwargs['rdf_data'] = g.tbox.localize_payload(global_rdf)
  292. kwargs['rdf_fmt'] = mimetype
  293. else:
  294. kwargs['stream'] = stream
  295. kwargs['mimetype'] = mimetype
  296. # Check digest if requested.
  297. if 'digest' in request.headers:
  298. kwargs['prov_cksum_algo'], kwargs['prov_cksum'] = \
  299. request.headers['digest'].split('=')
  300. try:
  301. evt, rsrc = rsrc_api.create_or_replace(uid, **kwargs)
  302. except (
  303. InvalidResourceError, ChecksumValidationError,
  304. ResourceExistsError) as e:
  305. return str(e), 409
  306. except (ServerManagedTermError, SingleSubjectError) as e:
  307. return str(e), 412
  308. except IncompatibleLdpTypeError as e:
  309. return str(e), 415
  310. except TombstoneError as e:
  311. return _tombstone_response(e, uid)
  312. with store.txn_ctx():
  313. rsp_headers = _headers_from_metadata(rsrc)
  314. rsp_headers['Content-Type'] = 'text/plain; charset=utf-8'
  315. uri = g.tbox.uid_to_uri(uid)
  316. if evt == RES_CREATED:
  317. rsp_code = 201
  318. rsp_headers['Location'] = rsp_body = uri
  319. if mimetype and not kwargs.get('rdf_data'):
  320. rsp_headers['Link'] = f'<{uri}/fcr:metadata>; rel="describedby"'
  321. else:
  322. rsp_code = 204
  323. rsp_body = ''
  324. return rsp_body, rsp_code, rsp_headers
  325. @ldp.route('/<path:uid>', methods=['PATCH'], strict_slashes=False)
  326. @ldp.route('/', defaults={'uid': '/'}, methods=['PATCH'],
  327. strict_slashes=False)
  328. def patch_resource(uid, is_metadata=False):
  329. """
  330. https://www.w3.org/TR/ldp/#ldpr-HTTP_PATCH
  331. Update an existing resource with a SPARQL-UPDATE payload.
  332. """
  333. # Fist check if it's not a 404 or a 410.
  334. try:
  335. if not rsrc_api.exists(uid):
  336. return '', 404
  337. except TombstoneError as e:
  338. return _tombstone_response(e, uid)
  339. # Then process the condition headers.
  340. cond_ret = _process_cond_headers(uid, request.headers, False)
  341. if cond_ret:
  342. return cond_ret
  343. handling, _ = set_post_put_params()
  344. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  345. if request.mimetype != 'application/sparql-update':
  346. return 'Provided content type is not a valid parsable format: {}'\
  347. .format(request.mimetype), 415
  348. update_str = request.get_data().decode('utf-8')
  349. local_update_str = g.tbox.localize_ext_str(update_str, nsc['fcres'][uid])
  350. try:
  351. rsrc = rsrc_api.update(uid, local_update_str, is_metadata, handling)
  352. except (ServerManagedTermError, SingleSubjectError) as e:
  353. return str(e), 412
  354. except InvalidResourceError as e:
  355. return str(e), 415
  356. else:
  357. with store.txn_ctx():
  358. rsp_headers.update(_headers_from_metadata(rsrc))
  359. return '', 204, rsp_headers
  360. @ldp.route('/<path:uid>/fcr:metadata', methods=['PATCH'])
  361. def patch_resource_metadata(uid):
  362. return patch_resource(uid, True)
  363. @ldp.route('/<path:uid>', methods=['DELETE'])
  364. def delete_resource(uid):
  365. """
  366. Delete a resource and optionally leave a tombstone.
  367. This behaves differently from FCREPO. A tombstone indicated that the
  368. resource is no longer available at its current location, but its historic
  369. snapshots still are. Also, deleting a resource with a tombstone creates
  370. one more version snapshot of the resource prior to being deleted.
  371. In order to completely wipe out all traces of a resource, the tombstone
  372. must be deleted as well, or the ``Prefer:no-tombstone`` header can be used.
  373. The latter will forget (completely delete) the resource immediately.
  374. """
  375. # Fist check if it's not a 404 or a 410.
  376. try:
  377. if not rsrc_api.exists(uid):
  378. return '', 404
  379. except TombstoneError as e:
  380. return _tombstone_response(e, uid)
  381. # Then process the condition headers.
  382. cond_ret = _process_cond_headers(uid, request.headers, False)
  383. if cond_ret:
  384. return cond_ret
  385. headers = std_headers.copy()
  386. if 'prefer' in request.headers:
  387. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  388. leave_tstone = 'no-tombstone' not in prefer
  389. else:
  390. leave_tstone = True
  391. rsrc_api.delete(uid, leave_tstone)
  392. return '', 204, headers
  393. @ldp.route('/<path:uid>/fcr:tombstone', methods=['GET', 'POST', 'PUT',
  394. 'PATCH', 'DELETE'])
  395. def tombstone(uid):
  396. """
  397. Handle all tombstone operations.
  398. The only allowed methods are POST and DELETE; any other verb will return a
  399. 405.
  400. """
  401. try:
  402. rsrc_api.get(uid)
  403. except TombstoneError as e:
  404. if request.method == 'DELETE':
  405. if e.uid == uid:
  406. rsrc_api.delete(uid, False)
  407. return '', 204
  408. else:
  409. return _tombstone_response(e, uid)
  410. elif request.method == 'POST':
  411. if e.uid == uid:
  412. rsrc_uri = rsrc_api.resurrect(uid)
  413. headers = {'Location' : rsrc_uri}
  414. return rsrc_uri, 201, headers
  415. else:
  416. return _tombstone_response(e, uid)
  417. else:
  418. return 'Method Not Allowed.', 405
  419. except ResourceNotExistsError as e:
  420. return str(e), 404
  421. else:
  422. return '', 404
  423. @ldp.route('/<path:uid>/fcr:versions', methods=['POST', 'PUT'])
  424. def post_version(uid):
  425. """
  426. Create a new resource version.
  427. """
  428. if request.method == 'PUT':
  429. return 'Method not allowed.', 405
  430. ver_uid = request.headers.get('slug', None)
  431. try:
  432. ver_uid = rsrc_api.create_version(uid, ver_uid)
  433. except ResourceNotExistsError as e:
  434. return str(e), 404
  435. except InvalidResourceError as e:
  436. return str(e), 409
  437. except TombstoneError as e:
  438. return _tombstone_response(e, uid)
  439. else:
  440. return '', 201, {'Location': g.tbox.uid_to_uri(ver_uid)}
  441. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['PATCH'])
  442. def patch_version(uid, ver_uid):
  443. """
  444. Revert to a previous version.
  445. NOTE: This creates a new version snapshot.
  446. :param str uid: Resource UID.
  447. :param str ver_uid: Version UID.
  448. """
  449. try:
  450. rsrc_api.revert_to_version(uid, ver_uid)
  451. except ResourceNotExistsError as e:
  452. return str(e), 404
  453. except InvalidResourceError as e:
  454. return str(e), 409
  455. except TombstoneError as e:
  456. return _tombstone_response(e, uid)
  457. else:
  458. return '', 204
  459. ## PRIVATE METHODS ##
  460. def _best_rdf_mimetype():
  461. """
  462. Check if any of the 'Accept' header values provided is a RDF parsable
  463. format.
  464. """
  465. for accept in request.accept_mimetypes:
  466. mimetype = accept[0]
  467. if mimetype in rdf_parsable_mimetypes:
  468. return mimetype
  469. return None
  470. def _negotiate_content(gr, rdf_mimetype, headers=None, **vw_kwargs):
  471. """
  472. Return HTML or serialized RDF depending on accept headers.
  473. """
  474. if request.accept_mimetypes.best == 'text/html':
  475. return render_template(
  476. 'resource.html', gr=gr, nsc=nsc, nsm=nsm,
  477. blacklist=vw_blacklist, arrow=arrow, **vw_kwargs)
  478. else:
  479. for p in vw_blacklist:
  480. gr.remove((None, p, None))
  481. return Response(
  482. gr.serialize(format=rdf_mimetype), 200, headers,
  483. mimetype=rdf_mimetype)
  484. def _bistream_from_req():
  485. """
  486. Find how a binary file and its MIMEtype were uploaded in the request.
  487. """
  488. #logger.debug('Content type: {}'.format(request.mimetype))
  489. #logger.debug('files: {}'.format(request.files))
  490. #logger.debug('stream: {}'.format(request.stream))
  491. if request.mimetype == 'multipart/form-data':
  492. # This seems the "right" way to upload a binary file, with a
  493. # multipart/form-data MIME type and the file in the `file`
  494. # field. This however is not supported by FCREPO4.
  495. stream = request.files.get('file').stream
  496. mimetype = request.files.get('file').content_type
  497. # @TODO This will turn out useful to provide metadata
  498. # with the binary.
  499. #metadata = request.files.get('metadata').stream
  500. else:
  501. # This is a less clean way, with the file in the form body and
  502. # the request as application/x-www-form-urlencoded.
  503. # This is how FCREPO4 accepts binary uploads.
  504. stream = request.stream
  505. # @FIXME Must decide what to do with this.
  506. mimetype = request.mimetype
  507. if mimetype == '' or mimetype == 'application/x-www-form-urlencoded':
  508. if getattr(stream, 'limit', 0) == 0:
  509. stream = mimetype = None
  510. else:
  511. mimetype = 'application/octet-stream'
  512. return stream, mimetype
  513. def _tombstone_response(e, uid):
  514. headers = {
  515. 'Link': '<{}/fcr:tombstone>; rel="hasTombstone"'.format(request.url),
  516. } if e.uid == uid else {}
  517. return str(e), 410, headers
  518. def set_post_put_params():
  519. """
  520. Sets handling and content disposition for POST and PUT by parsing headers.
  521. """
  522. handling = 'strict'
  523. if 'prefer' in request.headers:
  524. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  525. logger.debug('Parsed Prefer header: {}'.format(prefer))
  526. if 'handling' in prefer:
  527. handling = prefer['handling']['value']
  528. try:
  529. disposition = toolbox.parse_rfc7240(
  530. request.headers['content-disposition'])
  531. except KeyError:
  532. disposition = None
  533. return handling, disposition
  534. def parse_repr_options(retr_opts):
  535. """
  536. Set options to retrieve IMR.
  537. Ideally, IMR retrieval is done once per request, so all the options
  538. are set once in the `imr()` property.
  539. :param dict retr_opts:: Options parsed from `Prefer` header.
  540. """
  541. logger.debug('Parsing retrieval options: {}'.format(retr_opts))
  542. imr_options = {}
  543. if retr_opts.get('value') == 'minimal':
  544. imr_options = {
  545. 'embed_children' : False,
  546. 'incl_children' : False,
  547. 'incl_inbound' : False,
  548. 'incl_srv_mgd' : False,
  549. }
  550. else:
  551. # Default.
  552. imr_options = {
  553. 'embed_children' : False,
  554. 'incl_children' : True,
  555. 'incl_inbound' : False,
  556. 'incl_srv_mgd' : True,
  557. }
  558. # Override defaults.
  559. if 'parameters' in retr_opts:
  560. include = retr_opts['parameters']['include'].split(' ') \
  561. if 'include' in retr_opts['parameters'] else []
  562. omit = retr_opts['parameters']['omit'].split(' ') \
  563. if 'omit' in retr_opts['parameters'] else []
  564. logger.debug('Include: {}'.format(include))
  565. logger.debug('Omit: {}'.format(omit))
  566. if str(Ldpr.EMBED_CHILD_RES_URI) in include:
  567. imr_options['embed_children'] = True
  568. if str(Ldpr.RETURN_CHILD_RES_URI) in omit:
  569. imr_options['incl_children'] = False
  570. if str(Ldpr.RETURN_INBOUND_REF_URI) in include:
  571. imr_options['incl_inbound'] = True
  572. if str(Ldpr.RETURN_SRV_MGD_RES_URI) in omit:
  573. imr_options['incl_srv_mgd'] = False
  574. logger.debug('Retrieval options: {}'.format(pformat(imr_options)))
  575. return imr_options
  576. def _headers_from_metadata(rsrc, out_fmt='text/turtle'):
  577. """
  578. Create a dict of headers from a metadata graph.
  579. :param lakesuperior.model.ldp.ldpr.Ldpr rsrc: Resource to extract metadata
  580. from.
  581. """
  582. rsp_headers = defaultdict(list)
  583. digest_p = rsrc.metadata.value(nsc['premis'].hasMessageDigest)
  584. # Only add ETag and digest if output is not RDF.
  585. if digest_p:
  586. rsp_headers['ETag'], rsp_headers['Digest'] = (
  587. _digest_headers(digest_p))
  588. last_updated_term = rsrc.metadata.value(nsc['fcrepo'].lastModified)
  589. if last_updated_term:
  590. rsp_headers['Last-Modified'] = arrow.get(last_updated_term)\
  591. .format('ddd, D MMM YYYY HH:mm:ss Z')
  592. for t in rsrc.ldp_types:
  593. rsp_headers['Link'].append('{};rel="type"'.format(t.n3()))
  594. if rsrc.mimetype:
  595. rsp_headers['Content-Type'] = rsrc.mimetype
  596. return rsp_headers
  597. def _digest_headers(digest):
  598. """
  599. Format ETag and Digest headers from resource checksum.
  600. :param str digest: Resource digest. For an extracted IMR, this is the
  601. value of the ``premis:hasMessageDigest`` property.
  602. """
  603. digest_components = digest.split(':')
  604. cksum_hex = digest_components[-1]
  605. cksum = bytearray.fromhex(cksum_hex)
  606. digest_algo = digest_components[-2]
  607. etag_str = cksum_hex
  608. digest_str = '{}={}'.format(
  609. digest_algo.upper(), b64encode(cksum).decode('ascii'))
  610. return etag_str, digest_str
  611. def _condition_hdr_match(uid, headers, safe=True):
  612. """
  613. Conditional header evaluation for HEAD, GET, PUT and DELETE requests.
  614. Determine whether any conditional headers, and which, is/are imposed in the
  615. request (``If-Match``, ``If-None-Match``, ``If-Modified-Since``,
  616. ``If-Unmodified-Since``, or none) and what the most relevant condition
  617. evaluates to (``True`` or ``False``).
  618. `RFC 7232 <https://tools.ietf.org/html/rfc7232#section-3.1>`__ does not
  619. indicate an exact condition precedence, except that the ETag
  620. matching conditions void the timestamp-based ones. This function
  621. adopts the following precedence:
  622. - ``If-Match`` is evaluated first if present;
  623. - Else, ``If-None-Match`` is evaluated if present;
  624. - Else, ``If-Modified-Since`` and ``If-Unmodified-Since``
  625. are evaluated if present. If both conditions are present they are
  626. both returned so they can be furher evaluated, e.g. using a logical AND
  627. to allow time-range conditions, where the two terms indicate the early
  628. and late boundary, respectively.
  629. Note that the above mentioned RFC mentions several cases in which these
  630. conditions are ignored, e.g. for a 404 in some cases, or for certain
  631. HTTP methods for ``If-Modified-Since``. This must be implemented by the
  632. calling function.
  633. :param str uid: UID of the resource requested.
  634. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  635. headers.
  636. :param bool safe: Whether a "safe" method is being processed. Defaults to
  637. True.
  638. :rtype: dict (str, bool)
  639. :return: Dictionary whose keys are the conditional header names that
  640. have been evaluated, and whose boolean values indicate whether each
  641. condition is met. If no valid conditional header is found, an empty
  642. dict is returned.
  643. """
  644. # ETag-based conditions.
  645. # This ignores headers with empty values.
  646. if headers.get('if-match') or headers.get('if-none-match'):
  647. cond_hdr = 'if-match' if headers.get('if-match') else 'if-none-match'
  648. # Wildcard matching for unsafe methods. Cannot be part of a list of
  649. # ETags nor be enclosed in quotes.
  650. if not safe and headers.get(cond_hdr) == '*':
  651. return {cond_hdr: (cond_hdr == 'if-match') == rsrc_api.exists(uid)}
  652. req_etags = [
  653. et.strip('\'" ') for et in headers.get(cond_hdr).split(',')]
  654. with store.txn_ctx():
  655. try:
  656. rsrc_meta = rsrc_api.get_metadata(uid)
  657. except ResourceNotExistsError:
  658. rsrc_meta = Graph(uri=nsc['fcres'][uid])
  659. digest_prop = rsrc_meta.value(nsc['premis'].hasMessageDigest)
  660. if digest_prop:
  661. etag, _ = _digest_headers(digest_prop)
  662. if cond_hdr == 'if-match':
  663. is_match = etag in req_etags
  664. else:
  665. is_match = etag not in req_etags
  666. else:
  667. is_match = cond_hdr == 'if-none-match'
  668. return {cond_hdr: is_match}
  669. # Timestmp-based conditions.
  670. ret = {}
  671. if headers.get('if-modified-since') or headers.get('if-unmodified-since'):
  672. try:
  673. rsrc_meta = rsrc_api.get_metadata(uid)
  674. except ResourceNotExistsError:
  675. return {
  676. 'if-modified-since': False,
  677. 'if-unmodified-since': False
  678. }
  679. with store.txn_ctx():
  680. lastmod_str = rsrc_meta.value(nsc['fcrepo'].lastModified)
  681. lastmod_ts = arrow.get(lastmod_str)
  682. # If date is not in a RFC 5322 format
  683. # (https://tools.ietf.org/html/rfc5322#section-3.3) parse_date
  684. # evaluates to None.
  685. mod_since_date = parse_date(headers.get('if-modified-since'))
  686. if mod_since_date:
  687. cond_hdr = 'if-modified-since'
  688. ret[cond_hdr] = lastmod_ts > arrow.get(mod_since_date)
  689. unmod_since_date = parse_date(headers.get('if-unmodified-since'))
  690. if unmod_since_date:
  691. cond_hdr = 'if-unmodified-since'
  692. ret[cond_hdr] = lastmod_ts < arrow.get(unmod_since_date)
  693. return ret
  694. def _process_cond_headers(uid, headers, safe=True):
  695. """
  696. Process the outcome of the evaluation of conditional headers.
  697. This yields different response between safe methods (``HEAD``, ``GET``,
  698. etc.) and unsafe ones (``PUT``, ``DELETE``, etc.
  699. :param str uid: Resource UID.
  700. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  701. headers.
  702. :param bool safe: Whether a "safe" method is being processed. Defaults to
  703. True.
  704. """
  705. try:
  706. cond_match = _condition_hdr_match(uid, headers, safe)
  707. except TombstoneError as e:
  708. return _tombstone_response(e, uid)
  709. if cond_match:
  710. if safe:
  711. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  712. # If an expected list of tags is not matched, the response is
  713. # "Precondition Failed". For all other cases, it's "Not Modified".
  714. if not cond_match.get('if-match', True):
  715. return '', 412
  716. if not cond_match.get('if-none-match', True):
  717. return '', 304
  718. # The presence of an Etag-based condition, whether satisfied or not,
  719. # voids the timestamp-based conditions.
  720. elif (
  721. not cond_match.get('if-modified-since', True) or
  722. not cond_match.get('if-unmodified-since', True)):
  723. return '', 304
  724. else:
  725. # Note that If-Modified-Since is only evaluated for safe methods.
  726. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  727. if (
  728. not cond_match.get('if-match', True) or
  729. not cond_match.get('if-none-match', True)):
  730. return '', 412
  731. # The presence of an Etag-based condition, whether satisfied or not,
  732. # voids the timestamp-based conditions.
  733. elif not cond_match.get('if-unmodified-since', True):
  734. return '', 412
  735. def _parse_range_header(ranges, rsrc, headers):
  736. """
  737. Parse a ``Range`` header and return the appropriate response.
  738. """
  739. if len(ranges) == 1:
  740. # Single range.
  741. rng = ranges[0]
  742. logger.debug('Streaming contiguous partial content.')
  743. with open(rsrc.local_path, 'rb') as fh:
  744. size = None if rng[1] is None else rng[1] - rng[0]
  745. hdr_endbyte = (
  746. rsrc.content_size - 1 if rng[1] is None else rng[1] - 1)
  747. fh.seek(rng[0])
  748. out = fh.read(size)
  749. headers['Content-Range'] = \
  750. f'bytes {rng[0]}-{hdr_endbyte} / {rsrc.content_size}'
  751. else:
  752. return make_response('Multiple ranges are not yet supported.', 501)
  753. # TODO Format the response as multipart/byteranges:
  754. # https://tools.ietf.org/html/rfc7233#section-4.1
  755. #out = []
  756. #with open(rsrc.local_path, 'rb') as fh:
  757. # for rng in rng_header.ranges:
  758. # fh.seek(rng[0])
  759. # size = None if rng[1] is None else rng[1] - rng[0]
  760. # out.extend(fh.read(size))
  761. return make_response(out, 206, headers)