View source with raw comments or as raw
    1/*  Part of the SWI-Prolog HTTP package
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2012-2014, University of Amsterdam,
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(http_cors,
   37          [ cors_enable/0,
   38            cors_enable/2                       % +Request, +Options
   39          ]).   40:- use_module(library(settings)).   41:- autoload(library(http/http_wrapper), [http_current_request/1]).   42:- autoload(library(lists), [member/2]).   43
   44:- setting(http:cors, list(atom), [],
   45           'Enable CORS for the listed domains.  Use [*] for all domains').

Enable CORS: Cross-Origin Resource Sharing

This small module allows for enabling Cross-Origin Resource Sharing (CORS) for a specific request. Typically, CORS is enabled for API services that you want to have usable from browser client code that is loaded from another domain. An example are the LOD and SPARQL services in ClioPatria.

Because CORS is a security risk (see references), it is disabled by default. It is enabled through the setting http:cors. The value of this setting is a list of origins (e.g., 'https://example.org') that are allowed to access the service. If the Origin header of the request is in this list, it is echoed in the Access-Control-Allow-Origin header. Because * is used as a wildcard match, the value [*] allows access from anywhere.

Services for which CORS is relevant must call cors_enable/0 as part of the HTTP response, as shown below. Note that cors_enable/0 is a no-op if the setting http:cors is set to the empty list ([]).

my_handler(Request) :-
      ....,
      cors_enable,
      reply_json(Response, []).

If a site uses a Preflight OPTIONS request to find the server's capabilities and access politics, cors_enable/2 can be used to formulate an appropriate reply. For example:

my_handler(Request) :-
      option(method(options), Request), !,
      cors_enable(Request,
                  [ methods([get,post,delete])
                  ]),
      format('~n').                           % 200 with empty body
See also
- http://en.wikipedia.org/wiki/Cross-site_scripting for understanding Cross-site scripting.
- http://www.w3.org/TR/cors/ for understanding CORS
 cors_enable is det
Emit the HTTP header Access-Control-Allow-Origin using domains from the setting http:cors. This this setting is [] (default), nothing is written. This predicate is typically used for replying to API HTTP-request (e.g., replies to an AJAX request that typically serve JSON or XML).
  101cors_enable :-
  102    cors_enable_domain,
  103    !.
  104cors_enable.                            % CORS not enabled
  105
  106cors_enable_domain :-
  107    setting(http:cors, List),
  108    List \== [],
  109    allowed_origin(List, Origin),
  110    !,
  111    format('Access-Control-Allow-Origin: ~w~n', [Origin]),
  112    (   Origin == (*)
  113    ->  true
  114    ;   format('Vary: Origin~n')
  115    ).
  116
  117%   allowed_origin(+List, -Origin) is semidet.
  118%
  119%   Origin is the value for the Access-Control-Allow-Origin header.  This
  120%   header only allows for a single origin or `*`.  If the request has
  121%   an Origin header that appears in List, we echo this origin.
  122
  123allowed_origin(List, Origin) :-
  124    catch(http_current_request(Request), _, fail),
  125    memberchk(origin(Origin0), Request),
  126    member(Allowed, List),
  127    Allowed \== (*),
  128    same_origin(Allowed, Origin0),
  129    !,
  130    Origin = Origin0.
  131allowed_origin(List, *) :-
  132    memberchk(*, List),
  133    !.
  134allowed_origin([Origin], Origin) :-
  135    \+ ( catch(http_current_request(Request), _, fail),
  136          memberchk(origin(_), Request)
  137        ).
  138
  139same_origin(Allowed, Origin) :-
  140    downcase_atom(Allowed, L),
  141    downcase_atom(Origin, L).
 cors_enable(+Request, +Options) is det
CORS reply to a Preflight OPTIONS request. Request is the HTTP request. Options provides:
methods(+List)
List of supported HTTP methods. The default is GET, only allowing for read requests.
headers(+List)
List of headers the client asks for and we allow. The default is to simply echo what has been requested for.

Both methods and headers may use Prolog friendly syntax, e.g., get for a method and content_type for a header.

See also
- http://www.html5rocks.com/en/tutorials/cors/
  160cors_enable(Request, Options) :-
  161    cors_enable_domain,
  162    !,
  163    option(methods(Methods), Options, [get]),
  164    cors_methods(Methods),
  165    (   option(headers(ReqHeaders), Options)
  166    ->  cors_request_headers(ReqHeaders)
  167    ;   option(access_control_request_headers(ReqHeader), Request)
  168    ->  format('Access-Control-Allow-Headers: ~w~n', [ReqHeader])
  169    ;   true
  170    ).
  171cors_enable(_, _).
  172
  173cors_methods([]) :- !.
  174cors_methods(Methods) :-
  175    format('Access-Control-Allow-Methods: '),
  176    write_methods(Methods),
  177    nl.
  178
  179write_methods([H|T]) :-
  180    upcase_atom(H, U),
  181    write(U),
  182    (   T == []
  183    ->  true
  184    ;   write(', '),
  185        write_methods(T)
  186    ).
  187
  188cors_request_headers([]) :- !.
  189cors_request_headers(ReqHeaders) :-
  190    phrase(field_names(ReqHeaders), String),
  191    format('Access-Control-Allow-Headers: ~s~n', [String]).
  192
  193
  194field_names([H|T]) -->
  195    http_header:field_name(H),
  196    (   {T==[]}
  197    ->  ""
  198    ;   ", ",
  199        field_names(T)
  200    )