CORS
You need CORS when a front end is served from another origin than its
API: for example, an admin interface at https://admin.example that
calls https://api.example. An origin is a scheme, a host and a port.
By default, a browser does not let a page call an API of another origin.
It lets the call through only when the API says, in its answers, that
this origin is allowed. This protocol is called CORS (Cross-Origin
Resource Sharing).
If your front end and your API are served from the same origin, you do not need CORS at all, and rind sends no CORS header unless you ask for it.
Coming from Django: this is what
django-cors-headersdoes, with itsCORS_ALLOWED_ORIGINS,CORS_ALLOW_HEADERS,CORS_EXPOSE_HEADERS,CORS_ALLOW_CREDENTIALSandCORS_PREFLIGHT_MAX_AGEsettings. In rind it is a plugin,rind::api::cors::Cors, set from the environment or in code.
Turning it on
CORS needs no Cargo feature: it is part of the web framework adapters
(the axum and actix features of rind, which a served application
has already). Install the plugin in your app() function:
#![allow(unused)]
fn main() {
use rind::api::cors::Cors;
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
// … models, APIs …
.with(Cors::from_env().expect("RIND_CORS_*"))
}
Then say which origins may call the API, in the environment:
RIND_CORS_ORIGINS=https://admin.railway.example
That is all a typical front end needs. Several origins are separated by
commas, and * allows every origin. Each origin is a scheme and a host,
with an optional port, and no path: https://admin.example, not
https://admin.example/.
When RIND_CORS_ORIGINS is not set, from_env still succeeds, and CORS
stays off. So you can install the plugin in every application, and turn
CORS on only where it is needed.
You can also give the settings in code:
#![allow(unused)]
fn main() {
use rind::api::cors::Cors;
app.with(Cors::origins(["https://admin.railway.example"]).allow_headers(["x-route-url"]))
// or every origin, `*`:
app.with(Cors::any())
}
What the browser asks, and what rind answers
Before a call that is not a simple read, the browser sends a preflight:
an OPTIONS request to the same URL, which says where the page comes
from and what it wants to send.
OPTIONS /stations
Origin: https://admin.railway.example
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization,content-type
rind answers with what is allowed (the exact spelling of the lists depends on the web framework):
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://admin.railway.example
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Allow-Headers: accept,authorization,content-type,user-agent,x-requested-with
Access-Control-Max-Age: 86400
Then the browser sends the real request, with its Origin, and reads
Access-Control-Allow-Origin on the answer. A page from an origin that
is not listed gets no Access-Control-Allow-Origin, and the browser
refuses to give it the answer.
The methods allowed are always those rind serves: GET, POST, PUT,
PATCH, DELETE and OPTIONS.
Headers the browser may send, and headers it may read
By default, a browser lets a page send accept, authorization,
content-type, user-agent and x-requested-with: what a client of a
JSON API with a token sends. If your front end sends a header of its
own, add it with RIND_CORS_ALLOW_HEADERS or .allow_headers([..]).
A browser also hides most answer headers from the page. rind lets the
page read the headers it sets for clients: content-disposition (the
name of a downloaded file), etag and last-modified (see
Cache), x-rind-cache, and x-db-position (see
Databases). Add others with RIND_CORS_EXPOSE_HEADERS or
.expose_headers([..]).
Header names are compared in lower case, and a name given twice is kept once.
Cookies and credentials
By default, the browser is told not to send cookies or HTTP
authentication with a cross-origin call. rind’s tokens travel in the
Authorization header, so they do not need it. If your front end
authenticates with cookies, set RIND_CORS_CREDENTIALS=true, or
.credentials(true).
Credentials cannot go with every origin (*): browsers refuse that
combination. rind refuses it first: Cors::from_env() returns an error,
and .with(..) panics when the application is built. List the origins
instead.
Where it acts
CORS is applied around the whole application, before routing, as
django-cors-headers does. This has two effects:
- A preflight is answered on any path: a resource, an action, a plugin’s
route (
/status), even a path the application does not serve. - Every answer carries the headers, errors included: a
401, a404, an adapter’s own404or405. Without this, a browser would hide the error from the page, and the front end could not show it.
The cache needs nothing special: the CORS headers are added
after it, and Origin is added to the answer’s Vary.
How it is applied depends on the web framework:
-
axum:
Application::routerwraps every route in tower-http’sCorsLayer. If you useApplication::routesinstead, to merge rind’s routes into a router of your own, the layer covers rind’s routes only: the paths it does not serve belong to your router. -
actix-web: a middleware belongs to the
App, not to a route, so you wrap theAppwithapp.actix_cors():#![allow(unused)] fn main() { App::new() .wrap(app.actix_cors()) .app_data(web::Data::new(app.state(db.clone()))) .configure(|cfg| app.configure(cfg)) }Without CORS settings,
actix_cors()does nothing.
rind’s own serve command does this for you, with both frameworks.
Reference
| Variable | Meaning | Default |
|---|---|---|
RIND_CORS_ORIGINS | the origins, comma-separated (https://admin.example, no path), or * | none: CORS is off |
RIND_CORS_ALLOW_HEADERS | request headers allowed besides the defaults | accept, authorization, content-type, user-agent, x-requested-with |
RIND_CORS_EXPOSE_HEADERS | answer headers a client may read besides the defaults | content-disposition, etag, last-modified, x-rind-cache, x-db-position |
RIND_CORS_CREDENTIALS | true (or 1, yes, on): cookies and HTTP authentication are sent along | off: rind’s tokens are a header |
RIND_CORS_MAX_AGE | seconds a browser keeps a preflight’s answer | 86400 |
Cors::from_env() returns an error for credentials with *, for an
origin that is not http://… or https://… or that ends with /, and
for a RIND_CORS_MAX_AGE that is not a number.
| In code | Meaning |
|---|---|
Cors::origins([..]) | these origins, exactly |
Cors::any() | every origin (*) |
Cors::default() | off |
.allow_headers([..]) | request headers allowed besides the defaults |
.expose_headers([..]) | answer headers exposed besides the defaults |
.credentials(bool) | credentials sent along; only with listed origins |
.max_age(seconds) | how long a preflight is kept |
.check() | the same checks as from_env, as a Result |
.is_on() | whether any origin is allowed |
.layer() (axum), .actix() (actix-web) | the framework’s own CORS middleware for these settings |
The defaults are the constants ALLOW_HEADERS, EXPOSE_HEADERS and
METHODS of rind::api::cors.