Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,15 @@ applies whatever the cookies' `SameSite` setting (a sibling subdomain is same-si

- A `null` `Origin` (in any case) is refused first, whatever `Sec-Fetch-Site` and
`allowed_origins` say.
- `Sec-Fetch-Site: cross-site` is refused, and `same-origin` (or `none`) passes.
- `Sec-Fetch-Site: same-site` also covers a sibling subdomain, so when `allowed_origins` is set
the `Origin` must be on it, and a request with no `Origin` is refused. Without
`allowed_origins` it passes.
- `Sec-Fetch-Site: same-origin` (or `none`) passes. `cross-site`, and any value this check does
not know, is refused.
- `Sec-Fetch-Site: same-site` also covers a sibling subdomain, so the `Origin` must be trusted, and
a request with no `Origin` is refused.
- With no `Sec-Fetch-Site` (an older browser or a server), a request with no `Origin` passes, and
when `allowed_origins` is set the `Origin` must be on it.
one with an `Origin` needs it trusted.
- A trusted `Origin` is one on `allowed_origins` when that is set. Without it, only the request's
own host is trusted: the `Origin`'s `host[:port]` must equal the `Host` header (or the HTTP/2
authority), a default port aside. Behind a proxy that rewrites `Host`, set `allowed_origins`.
- An empty `allowed_origins` is still set: it allows no cross-origin caller.

A bearer token is never attached by a browser, so it is not checked.
Expand Down Expand Up @@ -275,8 +278,8 @@ API cannot be reached.
| `jwks_kid` | `dev-main` | `kid` header on service tokens |
| `cookie_domain` | none | Cookie `Domain` |
| `insecure_cookies` | `false` | Drops `Secure`, for local development over HTTP, and allows example secrets |
| `same_site` | `None`, or `Lax` with `insecure_cookies` | Cookie `SameSite` |
| `allowed_origins` | none | The only cross-origin (including same-site) callers allowed to change state; an empty list allows none |
| `same_site` | `Lax` | Cookie `SameSite`; a frontend on another site needs `None` |
| `allowed_origins` | none (only the request's own `Host`) | The only cross-origin (including same-site) callers allowed to change state; an empty list allows none |
| `session_cookie_names` | `seamless-access`, `seamless-refresh` | Session cookie names |
| `flow_cookie_names` | `seamless-ephemeral` | Sign-in flow cookie names |
| `deliver` | none | Sends OTP codes and magic links through your own transports |
Expand Down
6 changes: 5 additions & 1 deletion conformance/refapp/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ use std::sync::{Arc, Mutex};
use axum::extract::Path;
use axum::routing::get;
use axum::{Json, Router};
use seamless_auth::{Adapter, Delivery, PermissionRule, StepUp, TokenUser, User, Verifier};
use seamless_auth::{
Adapter, Delivery, PermissionRule, SameSite, StepUp, TokenUser, User, Verifier,
};
use serde_json::{Value, json};

type Captured = Arc<Mutex<HashMap<String, Value>>>;
Expand All @@ -25,6 +27,8 @@ async fn main() {
.cookie_secret(env("COOKIE_SIGNING_KEY"))
.service_secret(env("SEAMLESS_SERVICE_TOKEN"))
.jwks_kid(env("JWKS_KID"))
// The conformance contract pins SameSite=None, which is no longer the default.
.same_site(SameSite::None)
.deliver(move |d: Delivery| {
let sink = sink.clone();
async move {
Expand Down
3 changes: 2 additions & 1 deletion src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ impl Inner {
async fn serve(self: Arc<Self>, req: Request) -> Response {
let (parts, body) = req.into_parts();

if let Some(blocked) = check_origin(&self.config, &parts.method, &parts.headers) {
if let Some(blocked) = check_origin(&self.config, &parts.method, &parts.uri, &parts.headers)
{
return self.write(blocked, false);
}

Expand Down
3 changes: 2 additions & 1 deletion src/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,8 @@ where
// A cookie session gets the same cross-site check as the auth
// routes, or a form on another site could act as the user.
Ok((_, true))
if check_origin(&adapter.config, req.method(), req.headers()).is_some() =>
if check_origin(&adapter.config, req.method(), req.uri(), req.headers())
.is_some() =>
{
json_response(
StatusCode::FORBIDDEN,
Expand Down
15 changes: 6 additions & 9 deletions src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,17 +212,18 @@ impl Builder {
self
}

/// The cookie `SameSite` attribute. Defaults to `None`, or `Lax` with
/// [`insecure_cookies`](Self::insecure_cookies).
/// The cookie `SameSite` attribute. Defaults to `Lax`. A frontend on another
/// site that calls the adapter with credentials needs `None`.
pub fn same_site(mut self, same_site: SameSite) -> Self {
self.same_site = Some(same_site);
self
}

/// The only cross-origin callers allowed to change state. With it set, a
/// The only cross-origin callers allowed to change state. A
/// `Sec-Fetch-Site: same-site` request (which includes a sibling subdomain),
/// or a request without fetch metadata that carries an `Origin`, needs that
/// `Origin` on the list. An empty list allows no cross-origin caller.
/// `Origin` on the list. Without the list that `Origin` must name the request's
/// own `Host`. An empty list allows no cross-origin caller.
pub fn allowed_origins<I, S>(mut self, origins: I) -> Self
where
I: IntoIterator<Item = S>,
Expand Down Expand Up @@ -385,11 +386,7 @@ impl Builder {
);
"dev-main".to_string()
});
let same_site = self.same_site.unwrap_or(if self.insecure_cookies {
SameSite::Lax
} else {
SameSite::None
});
let same_site = self.same_site.unwrap_or(SameSite::Lax);

let http_client = match self.http_client {
Some(client) => client,
Expand Down
67 changes: 53 additions & 14 deletions src/origin.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use axum::http::{HeaderMap, Method, StatusCode};
use axum::http::{HeaderMap, Method, StatusCode, Uri};

use crate::adapter::Reply;
use crate::options::Config;

/// Blocks cross-site state changes whatever the cookies' `SameSite` setting: a
/// sibling subdomain is same-site, so `Lax` and `Strict` cookies still reach it.
pub(crate) fn check_origin(config: &Config, method: &Method, headers: &HeaderMap) -> Option<Reply> {
pub(crate) fn check_origin(
config: &Config,
method: &Method,
uri: &Uri,
headers: &HeaderMap,
) -> Option<Reply> {
if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
return None;
}
Expand All @@ -26,32 +31,33 @@ pub(crate) fn check_origin(config: &Config, method: &Method, headers: &HeaderMap
return blocked();
}

let trusted = |origin: &[u8]| match &config.allowed_origins {
Some(allowed) => is_allowed(allowed, origin),
None => is_own_host(origin, uri, headers),
};

if let Some(site) = headers.get("sec-fetch-site") {
let site = site.as_bytes();
if site.eq_ignore_ascii_case(b"cross-site") {
return blocked();
if site.eq_ignore_ascii_case(b"same-origin") || site.eq_ignore_ascii_case(b"none") {
return None;
}
// Anything else, a value this check does not know included, is treated
// as cross-site unless it is same-site from a trusted Origin.
if !site.eq_ignore_ascii_case(b"same-site") {
return None;
return blocked();
}
let Some(allowed) = &config.allowed_origins else {
return None;
};
return match headers.get("origin") {
Some(origin) if is_allowed(allowed, origin.as_bytes()) => None,
Some(origin) if trusted(origin.as_bytes()) => None,
_ => blocked(),
};
}

let origin = headers.get("origin")?;
// An Origin a browser would never send is not one to trust.
if origin.to_str().is_err() {
if origin.to_str().is_err() || !trusted(origin.as_bytes()) {
return blocked();
}
match &config.allowed_origins {
Some(allowed) if !is_allowed(allowed, origin.as_bytes()) => blocked(),
_ => None,
}
None
}

/// Whether an Origin is on the allowlist. An Origin, or an allowlist entry, that
Expand All @@ -67,6 +73,39 @@ fn is_allowed(allowed: &[String], origin: &[u8]) -> bool {
.any(|allowed| allowed == origin)
}

/// Whether the Origin names the host this request was sent to: the `Host`
/// header, or the URI authority an HTTP/2 request carries instead. A default
/// port written on either side does not count against a match.
fn is_own_host(origin: &[u8], uri: &Uri, headers: &HeaderMap) -> bool {
let Some(origin) = std::str::from_utf8(origin).ok().and_then(normalize_origin) else {
return false;
};
let Some(host) = headers
.get("host")
.and_then(|host| host.to_str().ok())
.or_else(|| uri.authority().map(|authority| authority.as_str()))
else {
return false;
};
let host = host.trim().to_ascii_lowercase();
if host.is_empty() || host.contains(['@', '/', '?', '#']) {
return false;
}
let (scheme, authority) = origin.split_once("://").unwrap_or_default();
let default_port = match scheme {
"https" => ":443",
"http" => ":80",
_ => "",
};
let strip = |authority: &str| {
authority
.strip_suffix(default_port)
.unwrap_or(authority)
.to_string()
};
strip(authority) == strip(&host)
}

/// `scheme://host[:port]`, lowercased, or `None` for anything that is not one.
fn normalize_origin(origin: &str) -> Option<String> {
let origin = origin.trim();
Expand Down
106 changes: 103 additions & 3 deletions src/tests/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ async fn login_stores_the_pre_auth_token_and_picks_the_body() {
let cookie = &r.cookies["seamless-ephemeral"];
assert_eq!(attribute(cookie, "Max-Age"), Some("300"));
assert_eq!(attribute(cookie, "Path"), Some("/"));
assert_eq!(attribute(cookie, "SameSite"), Some("None"));
assert_eq!(attribute(cookie, "SameSite"), Some("Lax"));
assert!(
flag(cookie, "HttpOnly") && flag(cookie, "Secure"),
"{cookie}"
Expand Down Expand Up @@ -685,7 +685,7 @@ async fn the_origin_guard_follows_sec_fetch_site() {
&'a [(&'a str, &'a str)],
bool,
);
let cases: [Case; 17] = [
let cases: [Case; 27] = [
(
"cross-site",
&open,
Expand All @@ -708,12 +708,112 @@ async fn the_origin_guard_follows_sec_fetch_site() {
false,
),
(
"same-site without an allowlist",
"same-site without an allowlist or Origin",
&open,
"POST",
&[("sec-fetch-site", "same-site")],
true,
),
(
"same-site without an allowlist, from a sibling",
&open,
"POST",
&[
("sec-fetch-site", "same-site"),
("host", "auth.example.com"),
("origin", "https://app.example.com"),
],
true,
),
(
"same-site without an allowlist, from the Host",
&open,
"POST",
&[
("sec-fetch-site", "same-site"),
("host", "auth.example.com"),
("origin", "https://AUTH.example.com"),
],
false,
),
(
"an unknown Sec-Fetch-Site",
&open,
"POST",
&[
("sec-fetch-site", "same-planet"),
("host", "auth.example.com"),
("origin", "https://auth.example.com"),
],
true,
),
(
"no Sec-Fetch-Site, an Origin and no allowlist",
&open,
"POST",
&[
("host", "auth.example.com"),
("origin", "https://evil.example"),
],
true,
),
(
"no Sec-Fetch-Site, an Origin and no Host",
&open,
"POST",
&[("origin", "https://auth.example.com")],
true,
),
(
"no Sec-Fetch-Site, the Host's Origin",
&open,
"POST",
&[
("host", "auth.example.com"),
("origin", "https://auth.example.com"),
],
false,
),
(
"no Sec-Fetch-Site, the Host's Origin with the default port",
&open,
"POST",
&[
("host", "auth.example.com:443"),
("origin", "https://auth.example.com"),
],
false,
),
(
"no Sec-Fetch-Site, the Host on another port",
&open,
"POST",
&[
("host", "auth.example.com:8443"),
("origin", "https://auth.example.com"),
],
true,
),
(
"no Sec-Fetch-Site, a scheme's default port on another scheme",
&open,
"POST",
&[
("host", "auth.example.com:80"),
("origin", "https://auth.example.com"),
],
true,
),
(
"no Sec-Fetch-Site, a Host with userinfo",
&open,
"POST",
&[
("host", "evil@auth.example.com"),
("origin", "https://auth.example.com"),
],
true,
),
("none", &open, "POST", &[("sec-fetch-site", "none")], false),
("server to server", &open, "POST", &[], false),
("null Origin", &open, "POST", &[("origin", "null")], true),
Expand Down
4 changes: 3 additions & 1 deletion src/tests/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,13 +497,15 @@ async fn a_cookie_session_from_a_sibling_subdomain_needs_an_allowlisted_origin()
);
assert_eq!(post(&listed, None).await.status, 403);

// Without an allowlist only the request's own Host counts as a trusted Origin.
let unlisted = api.adapter(|b| b);
assert_eq!(
post(&unlisted, Some("https://evil.example.com"))
.await
.status,
200
403
);
assert_eq!(post(&unlisted, None).await.status, 403);
}

fn bearer(token: &str) -> String {
Expand Down
Loading
Loading