ldp.py 30 KB

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