ldp.py 33 KB

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