~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

The console's cookie is __Host-, and only its own pages use it

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/cookie
crates/group-host/src/console_login.rs+76−28
@@ -7,10 +7,15 @@
//! says so, it revokes the token it was given, and keeps nothing of theirs.
//!
//! The browser holds only a cookie the host signed, naming the person,
//! HttpOnly and SameSite=Lax. A sign-in is answered only in the browser
//! that started it, by a cookie naming its state, so a link to someone
//! else's approval cannot sign a person in as them. Signing out refuses
//! every cookie signed before.
//! HttpOnly and SameSite=Lax; where the console is on https, named
//! `__Host-` first, so the browser keeps it as the console's alone,
//! Secure and for its whole path, and nothing at a name beside it can set
//! one in its place. A request that says it comes from a page elsewhere
//! (an `Origin` other than the console's) is as nobody's, whatever cookie
//! it carries, and signs nobody in or out. A sign-in is answered only in
//! the browser that started it, by a cookie naming its state, so a link
//! to someone else's approval cannot sign a person in as them. Signing
//! out refuses every cookie signed before.
//!
//! A browser can be signed in to several accounts at once: signing in to
//! another keeps the one before in a second cookie, of such signed
@@ -39,7 +44,8 @@ use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
/// The session cookie, and the cookie naming a sign-in under way.
/// The session cookie, and the cookie naming a sign-in under way, as
/// named before `__Host-` (`Host::cookie_name`).
pub const COOKIE: &str = "group_host_session";
const STARTED: &str = "group_host_login";
/// The cookie holding the other accounts a browser is signed in to: their
@@ -148,26 +154,18 @@ fn failed(status: StatusCode, why: impl Into<String>) -> Response {
}
/// A cookie, as the host sets one: for the whole site, HttpOnly, Lax, and
/// Secure where the console is on https.
/// Secure, named `__Host-`, where the console is on https.
fn cookie(host: &Host, name: &str, value: &str, max_age: i64) -> String {
let secure = if host.config.console_url.starts_with("https://") {
"; Secure"
} else {
""
};
let secure = if host.secure() { "; Secure" } else { "" };
let name = host.cookie_name(name);
format!("{name}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}")
}
/// The value of the cookie `name` a request carries.
pub fn cookie_of<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.filter_map(|kv| kv.trim().split_once('='))
.find(|(k, _)| *k == name)
.map(|(_, v)| v)
/// Refuses what only the console's own pages may ask: signing in to
/// another account, or out.
fn elsewhere() -> Response {
let why = "only the console's own pages sign in and out";
failed(StatusCode::FORBIDDEN, why)
}
/// The `Set-Cookie` keeping `others`, as many as a browser keeps: none
@@ -190,6 +188,43 @@ fn back_to(asked: Option<&String>) -> String {
}
impl Host {
/// Whether the console is on https, where its cookies are Secure.
fn secure(&self) -> bool {
self.config.console_url.starts_with("https://")
}
/// A cookie's name, as the host sets it: `__Host-` first where the
/// console is on https.
pub fn cookie_name(&self, name: &str) -> String {
match self.secure() {
true => format!("__Host-{name}"),
false => name.to_string(),
}
}
/// The value of the cookie `name` a request carries.
fn cookie_of<'a>(&self, headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
let name = self.cookie_name(name);
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.filter_map(|kv| kv.trim().split_once('='))
.find(|(k, _)| *k == name)
.map(|(_, v)| v)
}
/// Whether a request says it comes from a page somewhere other than
/// the console: by an `Origin` other than the console's own.
fn asked_elsewhere(&self, headers: &HeaderMap) -> bool {
let console = reqwest::Url::parse(&self.config.console_url).expect("CONSOLE_URL is a URL");
let ours = console.origin().ascii_serialization();
headers
.get(header::ORIGIN)
.is_some_and(|o| o.as_bytes() != ours.as_bytes())
}
/// The key the host signs its client assertions with, as the console.
fn console_key(&self) -> Keypair {
let secret = hmac(
@@ -226,7 +261,10 @@ impl Host {
/// Who a request's session cookie names, while it lasts and they have
/// not signed out since it was signed.
pub fn console_caller(&self, headers: &HeaderMap) -> anyhow::Result<Option<String>> {
match cookie_of(headers, COOKIE) {
if self.asked_elsewhere(headers) {
return Ok(None);
}
match self.cookie_of(headers, COOKIE) {
Some(value) => self.session_of(value),
None => Ok(None),
}
@@ -241,7 +279,11 @@ impl Host {
but: Option<&str>,
) -> anyhow::Result<Vec<(String, String)>> {
let mut found: Vec<(String, String)> = Vec::new();
for value in cookie_of(headers, OTHERS).unwrap_or_default().split('~') {
for value in self
.cookie_of(headers, OTHERS)
.unwrap_or_default()
.split('~')
{
let Some(did) = self.session_of(value)? else {
continue;
};
@@ -530,7 +572,7 @@ pub async fn callback(
Query(q): Query<HashMap<String, String>>,
) -> Result<Response, XrpcError> {
let state = q.get("state").map(String::as_str).unwrap_or_default();
let ours = cookie_of(&headers, STARTED) == Some(state);
let ours = host.cookie_of(&headers, STARTED) == Some(state);
let since = now_millis() - TAKES;
let pending = host
.store
@@ -619,7 +661,7 @@ pub async fn callback(
let mut others = host
.console_others(&headers, Some(&p.did))
.map_err(XrpcError::internal)?;
if let (Some(did), Some(value)) = (before, cookie_of(&headers, COOKIE))
if let (Some(did), Some(value)) = (before, host.cookie_of(&headers, COOKIE))
&& did != p.did
{
others.retain(|(d, _)| *d != did);
@@ -631,7 +673,7 @@ pub async fn callback(
for c in [session, done] {
set.append(header::SET_COOKIE, c.parse().expect("a cookie is a header"));
}
if !others.is_empty() || cookie_of(&headers, OTHERS).is_some() {
if !others.is_empty() || host.cookie_of(&headers, OTHERS).is_some() {
let kept = others_cookie(&host, &others);
set.append(
header::SET_COOKIE,
@@ -649,6 +691,9 @@ pub async fn switch(
headers: HeaderMap,
Form(form): Form<HashMap<String, String>>,
) -> Result<Response, XrpcError> {
if host.asked_elsewhere(&headers) {
return Ok(elsewhere());
}
let to = form.get("did").map(String::as_str).unwrap_or_default();
let current = host.console_caller(&headers).map_err(XrpcError::internal)?;
let mut others = host
@@ -659,7 +704,7 @@ pub async fn switch(
return Ok(failed(StatusCode::BAD_REQUEST, why));
};
let (_, value) = others.remove(at);
if let (Some(did), Some(was)) = (current, cookie_of(&headers, COOKIE)) {
if let (Some(did), Some(was)) = (current, host.cookie_of(&headers, COOKIE)) {
others.insert(0, (did, was.to_string()));
}
let headers = AppendHeaders([
@@ -678,6 +723,9 @@ pub async fn logout(
State(host): State<Arc<Host>>,
headers: HeaderMap,
) -> Result<Response, XrpcError> {
if host.asked_elsewhere(&headers) {
return Ok(elsewhere());
}
let who = host.console_caller(&headers).map_err(XrpcError::internal)?;
if let Some(did) = &who {
host.store
@@ -698,7 +746,7 @@ pub async fn logout(
header::SET_COOKIE,
next.parse().expect("a cookie is a header"),
);
if cookie_of(&headers, OTHERS).is_some() {
if host.cookie_of(&headers, OTHERS).is_some() {
let kept = others_cookie(&host, &others);
set.append(
header::SET_COOKIE,
crates/group-host/src/mcp.rs+4−1
@@ -880,7 +880,10 @@ impl Host {
input: &Value,
) -> Result<Value, String> {
let cookie = self.session_cookie(&who.member, now_millis());
let cookie = format!("{}={cookie}", crate::console_login::COOKIE);
let cookie = format!(
"{}={cookie}",
self.cookie_name(crate::console_login::COOKIE)
);
let path = format!("/xrpc/{nsid}");
let request = match procedure {
true => Request::post(path)
crates/group-host/tests/console_login.rs+67−0
@@ -764,3 +764,70 @@ async fn switches_between_accounts_signed_in_in_one_browser() {
let none = kept(&last, &res);
assert_eq!(viewer(&h, &none).await.1.get("actor"), None);
}
#[tokio::test]
async fn a_session_is_the_consoles_alone_and_only_its_pages_use_it() {
// The console on https, as deployed: its cookies named `__Host-`.
let console = "https://console.test";
let h = start_reachable(&[("CONSOLE_URL", console)]).await;
let (did, _) = person(&h, true).await;
let value = h.host.session_cookie(&did, group_host::time::now_millis());
let name = h.host.cookie_name(COOKIE_NAME);
assert_eq!(name, "__Host-group_host_session");
let jar = format!("{name}={value}");
let as_from = async |origin: Option<&str>| {
let mut req = h
.http
.get(format!("{}/xrpc/{NS}.getViewer", h.url))
.header("cookie", &jar);
if let Some(o) = origin {
req = req.header("origin", o);
}
let said: Json_ = req.send().await.unwrap().json().await.unwrap();
said["actor"]["did"].as_str().map(String::from)
};
// From the console's own pages, or with no word of where from.
assert_eq!(as_from(None).await.as_deref(), Some(did.as_str()));
assert_eq!(as_from(Some(console)).await.as_deref(), Some(did.as_str()));
// From a page anywhere else, a group's site or a sandboxed page, it is
// as nobody's.
for elsewhere in [
"https://riders.groups.test",
"null",
"https://console.test:8443",
] {
assert_eq!(as_from(Some(elsewhere)).await, None, "{elsewhere}");
}
// The name before `__Host-` is nobody's here.
let (_, plain) = viewer(&h, &format!("{COOKIE_NAME}={value}")).await;
assert_eq!(plain.get("actor"), None);
// Nor does a page elsewhere sign anyone in to another account, or out.
for path in ["/console/switch", "/console/logout"] {
let res = browser()
.post(format!("{}{path}", h.url))
.header("cookie", &jar)
.header("origin", "https://riders.groups.test")
.form(&[("did", did.as_str())])
.send()
.await
.unwrap();
assert_eq!(res.status(), 403, "{path}");
assert_eq!(res.headers().get("set-cookie"), None, "{path}");
}
assert_eq!(as_from(None).await.as_deref(), Some(did.as_str()));
// The console's own page signs out, the cookie cleared as it was set.
let out = browser()
.post(format!("{}/console/logout", h.url))
.header("cookie", &jar)
.header("origin", console)
.send()
.await
.unwrap();
assert_eq!(out.status(), 303);
assert_eq!(
out.headers()["set-cookie"],
"__Host-group_host_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0; Secure"
);
assert_eq!(as_from(None).await, None);
}
crates/group-host/tests/group_config.rs+4−1
@@ -405,7 +405,10 @@ async fn image(
let cookie = h.host.session_cookie(&who.did, now);
req = req.header(
"cookie",
format!("{}={cookie}", group_host::console_login::COOKIE),
format!(
"{}={cookie}",
h.host.cookie_name(group_host::console_login::COOKIE)
),
);
}
let res = req.send().await.unwrap();
docs/design/signing-in.md+12−0
@@ -86,6 +86,18 @@ good for 30 days. Signing out records the time in `console_logout`, and
a cookie signed before a person's last sign-out names no one, in any
browser.
The cookie is HttpOnly and `SameSite=Lax`. Where the console is on https
(`CONSOLE_URL`), it is also Secure and named `__Host-group_host_session`,
as are the cookies beside it: a browser then keeps it as the console's
name's alone, for its whole path, and a page at a name beside the
console's, such as a group's address, cannot set one in its place. A
request whose `Origin` is not the console's names no one, whatever
cookie it carries, and signing in to another account
(`/console/switch`) or out (`/console/logout`) from such a page is
refused with 403. A page of the console's own, or a request saying no
`Origin`, as a browser's own navigations and the console's server do,
is answered as before.
Details:
- The sign-in under way is kept by its `state` for 15 minutes, and the
docs/design/sites.md+5−1
@@ -100,7 +100,11 @@ every group's pages for the same site as the console, at the host's own
name. Left alone, a page's scripts could set a cookie for the whole
domain, which the console would then receive. They could also send a
request or a form to the host that carried a member's console session,
since `SameSite` cookies only stop requests from other sites.
since `SameSite` cookies only stop requests from other sites. The host
names its console's cookies `__Host-`, so no page at a group's address
can set one in their place, and takes no cookie from a request whose
`Origin` is not the console's ([signing in](signing-in.md)); the sandbox
keeps a page's requests from carrying the cookie at all.
So every answer to a request for a site, redirects and errors included,
carries:
docs/reference/api.md+5−3
@@ -37,9 +37,11 @@ A method of the host's own knows its caller in one of two ways:
as `aud` (or `SERVICE_DID#<service>`, as a PDS proxying to the
host's `#opensocial` service names it) and the method's NSID as `lxm`. This is how an app, or the
`opensocial` command, calls as a person.
- **The console's cookie**: `group_host_session`, which the host signs
once someone signs in to the console ([signing in](../design/signing-in.md#signing-people-in-to-the-console)),
used only when no `Authorization` is sent.
- **The console's cookie**: `__Host-group_host_session` (`group_host_session`
where the console is not on https), which the host signs once someone
signs in to the console ([signing in](../design/signing-in.md#signing-people-in-to-the-console)),
used only when no `Authorization` is sent, and only from the console's
own pages: a request whose `Origin` is another is as nobody's.
What a caller may then do in a group is what their roles there allow
([membership](../design/membership.md)); a method's lexicon names the
docs/reference/config.md+1−1
@@ -21,7 +21,7 @@ trimmed of spaces and a trailing `/`.
| `HANDLE_RESOLVERS` | how a handle is resolved, tried in turn: `well-known:<scheme>` for its own `/.well-known/atproto-did`, or a service answering `com.atproto.identity.resolveHandle` (which reads its DNS record); a trailing `/` is dropped | `well-known:https,https://public.api.bsky.app` |
| `GROUP_FOUNDERS` | who the host starts groups for, comma-separated DIDs: by `createGroup`, `provisionGroup`, or moving a group or an account here | anyone |
| `BLOB_UPLOAD_LIMIT` | the most bytes one blob may be, uploaded, or brought with a group, an account or a space; `describeServer` answers it | 52428800 (50 MiB) |
| `CONSOLE_URL` | where the console is: where the host sends a member to approve an app or an MCP client (`/authorize`), the console's OAuth client id and callback when people sign in (`/console/…`), and, when `https`, whether the session cookie is `Secure` | `PUBLIC_URL` |
| `CONSOLE_URL` | where the console is: where the host sends a member to approve an app or an MCP client (`/authorize`), the console's OAuth client id and callback when people sign in (`/console/…`), the one `Origin` its session cookie is taken from, and, when `https`, whether that cookie is `Secure` and named `__Host-` | `PUBLIC_URL` |
| `FAVICONS` | where it asks a link's site's icon when an MCP client writes a new link to a group's profile: the link's address follows, encoded, and a PNG is answered; empty asks nowhere | `https://cardyb.bsky.app/v1/favicon?url=` |
| `PROVISIONING_CLIENTS` | the apps the host makes groups for with `provisionGroup`, comma-separated OAuth client ids, each matched as written, a trailing `/` included; `*` for any | none |
| `ACTOR_SEARCH` | where `searchActors` looks for a handle being typed: `plc`, the handles in `PLC_URL`'s own export, read a page at a time and kept a minute; or the URL of a service answering `tech.waow.typeahead.searchActors` | typeahead.waow.tech's, when `PLC_URL` is `https://plc.directory`; else `plc` |