ldp.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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.RdfParsingError as e:
  223. return str(e), 400
  224. except exc.IndigestibleError:
  225. return (
  226. f'Unable to parse digest header: {request.headers["digest"]}'
  227. ), 400
  228. except exc.ResourceNotExistsError as e:
  229. return str(e), 404
  230. except (exc.InvalidResourceError, exc.ChecksumValidationError) as e:
  231. return str(e), 409
  232. except exc.TombstoneError as e:
  233. return _tombstone_response(e, uid)
  234. except exc.ServerManagedTermError as e:
  235. rsp_headers['Link'] = (
  236. f'<{uri}>; rel="{nsc["ldp"].constrainedBy}"; '
  237. f'{g.webroot}/info/ldp_constraints"'
  238. )
  239. return str(e), 412
  240. uri = g.tbox.uid_to_uri(rsrc.uid)
  241. with store.txn_ctx():
  242. rsp_headers.update(_headers_from_metadata(rsrc))
  243. rsp_headers['Location'] = uri
  244. if kwargs.get('mimetype') and kwargs.get('rdf_fmt') is None:
  245. rsp_headers['Link'] = (
  246. f'<{uri}/fcr:metadata>; rel="describedby"; anchor="{uri}"'
  247. )
  248. return uri, 201, rsp_headers
  249. @ldp.route('/<path:uid>', methods=['PUT'], strict_slashes=False)
  250. @ldp.route('/<path:uid>/fcr:metadata', defaults={'force_rdf' : True},
  251. methods=['PUT'])
  252. def put_resource(uid):
  253. """
  254. https://www.w3.org/TR/ldp/#ldpr-HTTP_PUT
  255. Add or replace a new resource at a specified URI.
  256. """
  257. # Parse headers.
  258. logger.debug('Request headers: {}'.format(request.headers))
  259. cond_ret = _process_cond_headers(uid, request.headers, False)
  260. if cond_ret:
  261. return cond_ret
  262. try:
  263. kwargs = _create_args_from_req(uid)
  264. evt, rsrc = rsrc_api.create_or_replace(uid, **kwargs)
  265. except exc.RdfParsingError as e:
  266. return str(e), 400
  267. except exc.IndigestibleError:
  268. return (
  269. f'Unable to parse digest header: {request.headers["digest"]}',
  270. 400)
  271. except (
  272. exc.InvalidResourceError, exc.ChecksumValidationError,
  273. exc.ResourceExistsError) as e:
  274. return str(e), 409
  275. except (exc.ServerManagedTermError, exc.SingleSubjectError) as e:
  276. return str(e), 412
  277. except exc.IncompatibleLdpTypeError as e:
  278. return str(e), 415
  279. except exc.TombstoneError as e:
  280. return _tombstone_response(e, uid)
  281. with store.txn_ctx():
  282. rsp_headers = _headers_from_metadata(rsrc)
  283. rsp_headers['Content-Type'] = 'text/plain; charset=utf-8'
  284. uri = g.tbox.uid_to_uri(uid)
  285. if evt == RES_CREATED:
  286. rsp_code = 201
  287. rsp_headers['Location'] = rsp_body = uri
  288. if kwargs.get('mimetype') and not kwargs.get('rdf_data'):
  289. rsp_headers['Link'] = f'<{uri}/fcr:metadata>; rel="describedby"'
  290. else:
  291. rsp_code = 204
  292. rsp_body = ''
  293. return rsp_body, rsp_code, rsp_headers
  294. @ldp.route('/<path:uid>', methods=['PATCH'], strict_slashes=False)
  295. @ldp.route('/', defaults={'uid': '/'}, methods=['PATCH'],
  296. strict_slashes=False)
  297. def patch_resource(uid, is_metadata=False):
  298. """
  299. https://www.w3.org/TR/ldp/#ldpr-HTTP_PATCH
  300. Update an existing resource with a SPARQL-UPDATE payload.
  301. """
  302. # Fist check if it's not a 404 or a 410.
  303. try:
  304. if not rsrc_api.exists(uid):
  305. return '', 404
  306. except exc.TombstoneError as e:
  307. return _tombstone_response(e, uid)
  308. # Then process the condition headers.
  309. cond_ret = _process_cond_headers(uid, request.headers, False)
  310. if cond_ret:
  311. return cond_ret
  312. handling, _ = _set_post_put_params()
  313. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  314. if request.mimetype != 'application/sparql-update':
  315. return 'Provided content type is not a valid parsable format: {}'\
  316. .format(request.mimetype), 415
  317. update_str = request.get_data().decode('utf-8')
  318. local_update_str = g.tbox.localize_ext_str(update_str, nsc['fcres'][uid])
  319. try:
  320. rsrc = rsrc_api.update(uid, local_update_str, is_metadata, handling)
  321. except (exc.ServerManagedTermError, exc.SingleSubjectError) as e:
  322. return str(e), 412
  323. except exc.InvalidResourceError as e:
  324. return str(e), 415
  325. else:
  326. with store.txn_ctx():
  327. rsp_headers.update(_headers_from_metadata(rsrc))
  328. return '', 204, rsp_headers
  329. @ldp.route('/<path:uid>/fcr:metadata', methods=['PATCH'])
  330. def patch_resource_metadata(uid):
  331. return patch_resource(uid, True)
  332. @ldp.route('/<path:uid>', methods=['DELETE'])
  333. def delete_resource(uid):
  334. """
  335. Delete a resource and optionally leave a tombstone.
  336. This behaves differently from FCREPO. A tombstone indicated that the
  337. resource is no longer available at its current location, but its historic
  338. snapshots still are. Also, deleting a resource with a tombstone creates
  339. one more version snapshot of the resource prior to being deleted.
  340. In order to completely wipe out all traces of a resource, the tombstone
  341. must be deleted as well, or the ``Prefer:no-tombstone`` header can be used.
  342. The latter will forget (completely delete) the resource immediately.
  343. """
  344. # Fist check if it's not a 404 or a 410.
  345. try:
  346. if not rsrc_api.exists(uid):
  347. return '', 404
  348. except exc.TombstoneError as e:
  349. return _tombstone_response(e, uid)
  350. # Then process the condition headers.
  351. cond_ret = _process_cond_headers(uid, request.headers, False)
  352. if cond_ret:
  353. return cond_ret
  354. headers = std_headers.copy()
  355. if 'prefer' in request.headers:
  356. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  357. leave_tstone = 'no-tombstone' not in prefer
  358. else:
  359. leave_tstone = True
  360. rsrc_api.delete(uid, leave_tstone)
  361. return '', 204, headers
  362. @ldp.route('/<path:uid>/fcr:tombstone', methods=['GET', 'POST', 'PUT',
  363. 'PATCH', 'DELETE'])
  364. def tombstone(uid):
  365. """
  366. Handle all tombstone operations.
  367. The only allowed methods are POST and DELETE; any other verb will return a
  368. 405.
  369. """
  370. try:
  371. rsrc_api.get(uid)
  372. except exc.TombstoneError as e:
  373. if request.method == 'DELETE':
  374. if e.uid == uid:
  375. rsrc_api.delete(uid, False)
  376. return '', 204
  377. else:
  378. return _tombstone_response(e, uid)
  379. elif request.method == 'POST':
  380. if e.uid == uid:
  381. rsrc_uri = rsrc_api.resurrect(uid)
  382. headers = {'Location' : rsrc_uri}
  383. return rsrc_uri, 201, headers
  384. else:
  385. return _tombstone_response(e, uid)
  386. else:
  387. return 'Method Not Allowed.', 405
  388. except exc.ResourceNotExistsError as e:
  389. return str(e), 404
  390. else:
  391. return '', 404
  392. @ldp.route('/<path:uid>/fcr:versions', methods=['POST', 'PUT'])
  393. def post_version(uid):
  394. """
  395. Create a new resource version.
  396. """
  397. if request.method == 'PUT':
  398. return 'Method not allowed.', 405
  399. ver_uid = request.headers.get('slug', None)
  400. try:
  401. ver_uid = rsrc_api.create_version(uid, ver_uid)
  402. except exc.ResourceNotExistsError as e:
  403. return str(e), 404
  404. except exc.InvalidResourceError as e:
  405. return str(e), 409
  406. except exc.TombstoneError as e:
  407. return _tombstone_response(e, uid)
  408. else:
  409. return '', 201, {'Location': g.tbox.uid_to_uri(ver_uid)}
  410. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['PATCH'])
  411. def patch_version(uid, ver_uid):
  412. """
  413. Revert to a previous version.
  414. NOTE: This creates a new version snapshot.
  415. :param str uid: Resource UID.
  416. :param str ver_uid: Version UID.
  417. """
  418. try:
  419. rsrc_api.revert_to_version(uid, ver_uid)
  420. except exc.ResourceNotExistsError as e:
  421. return str(e), 404
  422. except exc.InvalidResourceError as e:
  423. return str(e), 409
  424. except exc.TombstoneError as e:
  425. return _tombstone_response(e, uid)
  426. else:
  427. return '', 204
  428. ## PRIVATE METHODS ##
  429. def _best_rdf_mimetype():
  430. """
  431. Check if any of the 'Accept' header values provided is a RDF parsable
  432. format.
  433. """
  434. for accept in request.accept_mimetypes:
  435. mimetype = accept[0]
  436. if mimetype in rdf_parsable_mimetypes:
  437. return mimetype
  438. return None
  439. def _negotiate_content(gr, rdf_mimetype, headers=None, **vw_kwargs):
  440. """
  441. Return HTML or serialized RDF depending on accept headers.
  442. """
  443. if request.accept_mimetypes.best == 'text/html':
  444. return render_template(
  445. 'resource.html', gr=gr, nsc=nsc, nsm=nsm,
  446. blacklist=vw_blacklist, arrow=arrow, **vw_kwargs)
  447. else:
  448. for p in vw_blacklist:
  449. gr.remove((None, p, None))
  450. return Response(
  451. gr.serialize(format=rdf_mimetype), 200, headers,
  452. mimetype=rdf_mimetype)
  453. def _create_args_from_req(uid):
  454. """
  455. Set API creation method arguments from request parameters.
  456. The ``kwargs`` variable returned has two keys: either ``rdf_data`` and
  457. ``rdf_fmt`` for LDP-RS or ``stream`` and ``mimetype`` for LDP-NR.
  458. :rtype: dict
  459. """
  460. #logger.debug('Content type: {}'.format(request.mimetype))
  461. #logger.debug('files: {}'.format(request.files))
  462. #logger.debug('stream: {}'.format(request.stream))
  463. #pdb.set_trace()
  464. kwargs = {}
  465. kwargs['handling'], kwargs['disposition'] = _set_post_put_params()
  466. link_hdr = request.headers.get('Link')
  467. if link_hdr:
  468. force_ldpnr = (
  469. nsc['ldp']['NonRDFSource'] in link_hdr
  470. and 'rel="type"' in link_hdr)
  471. else:
  472. force_ldpnr = False
  473. if request.mimetype == 'multipart/form-data':
  474. # This seems the "right" way to upload a binary file, with a
  475. # multipart/form-data MIME type and the file in the `file`
  476. # field. This however is not supported by FCREPO4.
  477. stream = request.files.get('file').stream
  478. mimetype = request.files.get('file').content_type
  479. # @TODO This will turn out useful to provide metadata
  480. # with the binary.
  481. #metadata = request.files.get('metadata').stream
  482. else:
  483. # This is a less clean way, with the file in the form body and
  484. # the request as application/x-www-form-urlencoded.
  485. # This is how FCREPO4 accepts binary uploads.
  486. stream = request.stream
  487. # @FIXME Must decide what to do with this.
  488. mimetype = request.mimetype
  489. if mimetype == 'application/x-www-form-urlencoded':
  490. mimetype = None
  491. if mimetype in rdf_parsable_mimetypes and not force_ldpnr:
  492. # If the content is RDF, localize in-repo URIs.
  493. global_rdf = stream.read()
  494. kwargs['rdf_data'] = g.tbox.localize_payload(global_rdf)
  495. kwargs['rdf_fmt'] = mimetype
  496. else:
  497. # Unspecified mimetype or force_ldpnr creates a LDP-NR.
  498. kwargs['stream'] = stream or BytesIO(b'')
  499. kwargs['mimetype'] = mimetype or 'application/octet-stream'
  500. # Check digest if requested.
  501. if 'digest' in request.headers:
  502. try:
  503. kwargs['prov_cksum_algo'], kwargs['prov_cksum'] = (
  504. request.headers['digest'].split('=')
  505. )
  506. except ValueError:
  507. raise exc.IndigestibleError(uid)
  508. return kwargs
  509. def _tombstone_response(e, uid):
  510. headers = {
  511. 'Link': '<{}/fcr:tombstone>; rel="hasTombstone"'.format(request.url),
  512. } if e.uid == uid else {}
  513. return str(e), 410, headers
  514. def _set_post_put_params():
  515. """
  516. Sets handling and content disposition for POST and PUT by parsing headers.
  517. """
  518. handling = 'strict'
  519. if 'prefer' in request.headers:
  520. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  521. logger.debug('Parsed Prefer header: {}'.format(prefer))
  522. if 'handling' in prefer:
  523. handling = prefer['handling']['value']
  524. try:
  525. disposition = toolbox.parse_rfc7240(
  526. request.headers['content-disposition'])
  527. except KeyError:
  528. disposition = None
  529. return handling, disposition
  530. def parse_repr_options(retr_opts):
  531. """
  532. Set options to retrieve IMR.
  533. Ideally, IMR retrieval is done once per request, so all the options
  534. are set once in the `imr()` property.
  535. :param dict retr_opts:: Options parsed from `Prefer` header.
  536. """
  537. logger.debug('Parsing retrieval options: {}'.format(retr_opts))
  538. imr_options = {}
  539. if retr_opts.get('value') == 'minimal':
  540. imr_options = {
  541. 'embed_children' : False,
  542. 'incl_children' : False,
  543. 'incl_inbound' : False,
  544. 'incl_srv_mgd' : False,
  545. }
  546. else:
  547. # Default.
  548. imr_options = {
  549. 'embed_children' : False,
  550. 'incl_children' : True,
  551. 'incl_inbound' : False,
  552. 'incl_srv_mgd' : True,
  553. }
  554. # Override defaults.
  555. if 'parameters' in retr_opts:
  556. include = retr_opts['parameters']['include'].split(' ') \
  557. if 'include' in retr_opts['parameters'] else []
  558. omit = retr_opts['parameters']['omit'].split(' ') \
  559. if 'omit' in retr_opts['parameters'] else []
  560. logger.debug('Include: {}'.format(include))
  561. logger.debug('Omit: {}'.format(omit))
  562. if str(Ldpr.EMBED_CHILD_RES_URI) in include:
  563. imr_options['embed_children'] = True
  564. if str(Ldpr.RETURN_CHILD_RES_URI) in omit:
  565. imr_options['incl_children'] = False
  566. if str(Ldpr.RETURN_INBOUND_REF_URI) in include:
  567. imr_options['incl_inbound'] = True
  568. if str(Ldpr.RETURN_SRV_MGD_RES_URI) in omit:
  569. imr_options['incl_srv_mgd'] = False
  570. logger.debug('Retrieval options: {}'.format(pformat(imr_options)))
  571. return imr_options
  572. def _headers_from_metadata(rsrc, out_fmt='text/turtle'):
  573. """
  574. Create a dict of headers from a metadata graph.
  575. :param lakesuperior.model.ldp.ldpr.Ldpr rsrc: Resource to extract metadata
  576. from.
  577. """
  578. rsp_headers = defaultdict(list)
  579. digest_p = rsrc.metadata.value(nsc['premis'].hasMessageDigest)
  580. # Only add ETag and digest if output is not RDF.
  581. if digest_p:
  582. rsp_headers['ETag'], rsp_headers['Digest'] = (
  583. _digest_headers(digest_p))
  584. last_updated_term = rsrc.metadata.value(nsc['fcrepo'].lastModified)
  585. if last_updated_term:
  586. rsp_headers['Last-Modified'] = arrow.get(last_updated_term)\
  587. .format('ddd, D MMM YYYY HH:mm:ss Z')
  588. for t in rsrc.ldp_types:
  589. rsp_headers['Link'].append('{};rel="type"'.format(t.n3()))
  590. if rsrc.mimetype:
  591. rsp_headers['Content-Type'] = rsrc.mimetype
  592. return rsp_headers
  593. def _digest_headers(digest):
  594. """
  595. Format ETag and Digest headers from resource checksum.
  596. :param str digest: Resource digest. For an extracted IMR, this is the
  597. value of the ``premis:hasMessageDigest`` property.
  598. """
  599. digest_components = digest.split(':')
  600. cksum_hex = digest_components[-1]
  601. cksum = bytearray.fromhex(cksum_hex)
  602. digest_algo = digest_components[-2]
  603. etag_str = cksum_hex
  604. digest_str = '{}={}'.format(
  605. digest_algo.upper(), b64encode(cksum).decode('ascii'))
  606. return etag_str, digest_str
  607. def _condition_hdr_match(uid, headers, safe=True):
  608. """
  609. Conditional header evaluation for HEAD, GET, PUT and DELETE requests.
  610. Determine whether any conditional headers, and which, is/are imposed in the
  611. request (``If-Match``, ``If-None-Match``, ``If-Modified-Since``,
  612. ``If-Unmodified-Since``, or none) and what the most relevant condition
  613. evaluates to (``True`` or ``False``).
  614. `RFC 7232 <https://tools.ietf.org/html/rfc7232#section-3.1>`__ does not
  615. indicate an exact condition precedence, except that the ETag
  616. matching conditions void the timestamp-based ones. This function
  617. adopts the following precedence:
  618. - ``If-Match`` is evaluated first if present;
  619. - Else, ``If-None-Match`` is evaluated if present;
  620. - Else, ``If-Modified-Since`` and ``If-Unmodified-Since``
  621. are evaluated if present. If both conditions are present they are
  622. both returned so they can be furher evaluated, e.g. using a logical AND
  623. to allow time-range conditions, where the two terms indicate the early
  624. and late boundary, respectively.
  625. Note that the above mentioned RFC mentions several cases in which these
  626. conditions are ignored, e.g. for a 404 in some cases, or for certain
  627. HTTP methods for ``If-Modified-Since``. This must be implemented by the
  628. calling function.
  629. :param str uid: UID of the resource requested.
  630. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  631. headers.
  632. :param bool safe: Whether a "safe" method is being processed. Defaults to
  633. True.
  634. :rtype: dict (str, bool)
  635. :return: Dictionary whose keys are the conditional header names that
  636. have been evaluated, and whose boolean values indicate whether each
  637. condition is met. If no valid conditional header is found, an empty
  638. dict is returned.
  639. """
  640. # ETag-based conditions.
  641. # This ignores headers with empty values.
  642. if headers.get('if-match') or headers.get('if-none-match'):
  643. cond_hdr = 'if-match' if headers.get('if-match') else 'if-none-match'
  644. # Wildcard matching for unsafe methods. Cannot be part of a list of
  645. # ETags nor be enclosed in quotes.
  646. if not safe and headers.get(cond_hdr) == '*':
  647. return {cond_hdr: (cond_hdr == 'if-match') == rsrc_api.exists(uid)}
  648. req_etags = [
  649. et.strip('\'" ') for et in headers.get(cond_hdr).split(',')]
  650. with store.txn_ctx():
  651. try:
  652. rsrc_meta = rsrc_api.get_metadata(uid)
  653. except exc.ResourceNotExistsError:
  654. rsrc_meta = Graph(uri=nsc['fcres'][uid])
  655. digest_prop = rsrc_meta.value(nsc['premis'].hasMessageDigest)
  656. if digest_prop:
  657. etag, _ = _digest_headers(digest_prop)
  658. if cond_hdr == 'if-match':
  659. is_match = etag in req_etags
  660. else:
  661. is_match = etag not in req_etags
  662. else:
  663. is_match = cond_hdr == 'if-none-match'
  664. return {cond_hdr: is_match}
  665. # Timestmp-based conditions.
  666. ret = {}
  667. if headers.get('if-modified-since') or headers.get('if-unmodified-since'):
  668. try:
  669. rsrc_meta = rsrc_api.get_metadata(uid)
  670. except exc.ResourceNotExistsError:
  671. return {
  672. 'if-modified-since': False,
  673. 'if-unmodified-since': False
  674. }
  675. with store.txn_ctx():
  676. lastmod_str = rsrc_meta.value(nsc['fcrepo'].lastModified)
  677. lastmod_ts = arrow.get(lastmod_str)
  678. # If date is not in a RFC 5322 format
  679. # (https://tools.ietf.org/html/rfc5322#section-3.3) parse_date
  680. # evaluates to None.
  681. mod_since_date = parse_date(headers.get('if-modified-since'))
  682. if mod_since_date:
  683. cond_hdr = 'if-modified-since'
  684. ret[cond_hdr] = lastmod_ts > arrow.get(mod_since_date)
  685. unmod_since_date = parse_date(headers.get('if-unmodified-since'))
  686. if unmod_since_date:
  687. cond_hdr = 'if-unmodified-since'
  688. ret[cond_hdr] = lastmod_ts < arrow.get(unmod_since_date)
  689. return ret
  690. def _process_cond_headers(uid, headers, safe=True):
  691. """
  692. Process the outcome of the evaluation of conditional headers.
  693. This yields different response between safe methods (``HEAD``, ``GET``,
  694. etc.) and unsafe ones (``PUT``, ``DELETE``, etc.
  695. :param str uid: Resource UID.
  696. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  697. headers.
  698. :param bool safe: Whether a "safe" method is being processed. Defaults to
  699. True.
  700. """
  701. try:
  702. cond_match = _condition_hdr_match(uid, headers, safe)
  703. except exc.TombstoneError as e:
  704. return _tombstone_response(e, uid)
  705. if cond_match:
  706. if safe:
  707. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  708. # If an expected list of tags is not matched, the response is
  709. # "Precondition Failed". For all other cases, it's "Not Modified".
  710. if not cond_match.get('if-match', True):
  711. return '', 412
  712. if not cond_match.get('if-none-match', True):
  713. return '', 304
  714. # The presence of an Etag-based condition, whether satisfied or not,
  715. # voids the timestamp-based conditions.
  716. elif (
  717. not cond_match.get('if-modified-since', True) or
  718. not cond_match.get('if-unmodified-since', True)):
  719. return '', 304
  720. else:
  721. # Note that If-Modified-Since is only evaluated for safe methods.
  722. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  723. if (
  724. not cond_match.get('if-match', True) or
  725. not cond_match.get('if-none-match', True)):
  726. return '', 412
  727. # The presence of an Etag-based condition, whether satisfied or not,
  728. # voids the timestamp-based conditions.
  729. elif not cond_match.get('if-unmodified-since', True):
  730. return '', 412
  731. def _parse_range_header(ranges, rsrc, headers):
  732. """
  733. Parse a ``Range`` header and return the appropriate response.
  734. """
  735. if len(ranges) == 1:
  736. # Single range.
  737. rng = ranges[0]
  738. logger.debug('Streaming contiguous partial content.')
  739. with open(rsrc.local_path, 'rb') as fh:
  740. size = None if rng[1] is None else rng[1] - rng[0]
  741. hdr_endbyte = (
  742. rsrc.content_size - 1 if rng[1] is None else rng[1] - 1)
  743. fh.seek(rng[0])
  744. out = fh.read(size)
  745. headers['Content-Range'] = \
  746. f'bytes {rng[0]}-{hdr_endbyte} / {rsrc.content_size}'
  747. else:
  748. return make_response('Multiple ranges are not yet supported.', 501)
  749. # TODO Format the response as multipart/byteranges:
  750. # https://tools.ietf.org/html/rfc7233#section-4.1
  751. #out = []
  752. #with open(rsrc.local_path, 'rb') as fh:
  753. # for rng in rng_header.ranges:
  754. # fh.seek(rng[0])
  755. # size = None if rng[1] is None else rng[1] - rng[0]
  756. # out.extend(fh.read(size))
  757. return make_response(out, 206, headers)