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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ uuid = { version = "1", features = ["v4", "v7", "serde"] }
time = { version = "0.3", features = ["serde", "serde-well-known", "formatting", "parsing", "macros"] }
base64 = "0.22"
hex = "0.4"
form_urlencoded = "1"
bytes = "1"

# crypto
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Shared canvases (live Yjs rooms, chat, mentions, invites, share links) are serve
proxies the unchanged canvas API to it as the signed-in user, so Coppers need no update. See
[docs/canvas-link.md](docs/canvas-link.md); upgrading a 0.10.x (or older) instance with canvases:
[docs/canvas-migration.md](docs/canvas-migration.md).
People who are not on Copper open shared canvases in any browser at `https://HOST/canvas/`
([Canvas App](https://github.com/copper-browser/canvas-app)), and share links offer it too
([docs/canvas.md](docs/canvas.md#canvas-app-canvas)).

People can join with **company single sign-on** (Google Workspace or any OpenID Connect
provider): share one `https://HOST/start` page, they install Copper and click *Continue with
Expand Down
9 changes: 6 additions & 3 deletions crates/canvas-link/src/landing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//! the old canvas crate. It is merged at the application root (outside `/v1`, so no instance
//! key is needed) and deliberately touches neither the database nor Canvas Cloud: it only
//! checks the token's shape and hands it to Copper as
//! `copper://canvas/join/{token}?cloud={host}`.
//! `copper://canvas/join/{token}?cloud={host}`, or to Canvas App in the browser as
//! `/canvas/#/join/{token}` (`copper_cloud::canvas_app`).

use axum::extract::Path;
use axum::http::{header, HeaderMap, HeaderValue, Uri};
Expand Down Expand Up @@ -108,9 +109,11 @@ pub async fn join_landing(Path(token): Path<String>, uri: Uri, headers: HeaderMa
})
});
let html = match href {
// Not on Copper: Canvas App, which this server serves at `/canvas/`, joins in the browser.
Some(href) => format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Open canvas in Copper</title><style>body{{margin:0;min-height:100vh;display:grid;place-items:center;background:#f7f7f5;color:#171717;font:16px system-ui,sans-serif}}main{{max-width:28rem;padding:2rem;text-align:center}}a{{display:inline-block;padding:.75rem 1.1rem;border-radius:.5rem;background:#171717;color:#fff;text-decoration:none}}a:focus-visible{{outline:3px solid #6d5dfc;outline-offset:3px}}</style></head><body><main><h1>Canvas share link</h1><p>Open this canvas in Copper to continue.</p><a href=\"{}\">Open this canvas in Copper</a></main></body></html>",
escape_html(&href)
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Open canvas in Copper</title><style>body{{margin:0;min-height:100vh;display:grid;place-items:center;background:#f7f7f5;color:#171717;font:16px system-ui,sans-serif}}main{{max-width:28rem;padding:2rem;text-align:center}}a{{display:inline-block;padding:.75rem 1.1rem;border-radius:.5rem;background:#171717;color:#fff;text-decoration:none}}a.web{{margin-top:.75rem;background:none;color:#171717;text-decoration:underline}}a:focus-visible{{outline:3px solid #6d5dfc;outline-offset:3px}}</style></head><body><main><h1>Canvas share link</h1><p>Open this canvas in Copper to continue.</p><a href=\"{}\">Open this canvas in Copper</a><br><a class=\"web\" href=\"/canvas/#/join/{}\">Not on Copper? Open it in your browser</a></main></body></html>",
escape_html(&href),
escape_html(&percent_encode_component(&token))
),
None => "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Open canvas in Copper</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f7f7f5;color:#171717;font:16px system-ui,sans-serif}main{max-width:28rem;padding:2rem;text-align:center}</style></head><body><main><h1>Canvas share link</h1><p>Open this link in Copper to continue.</p></main></body></html>".to_owned(),
};
Expand Down
21 changes: 18 additions & 3 deletions crates/canvas-link/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,18 @@ pub(crate) fn is_ws_path(path: &str) -> bool {
.is_some_and(|id| !id.is_empty() && !id.contains('/'))
}

/// The query string minus every `token=` parameter (Copper's session token for WebSocket
/// tooling); `None` when nothing is left.
/// The query string minus Copper's own credentials, which never go to Canvas Cloud: every
/// `token=` (the session token, for WebSocket tooling and browsers) and `instance=` (the gate
/// credential a browser's room socket carries, `copper_cloud_core::app::INSTANCE_QUERY`);
/// `None` when nothing is left.
pub(crate) fn forwarded_query(query: Option<&str>) -> Option<String> {
let ours = |kv: &str| {
let key = kv.split_once('=').map_or(kv, |(k, _)| k);
key == "token" || key == copper_cloud_core::app::INSTANCE_QUERY
};
let kept: Vec<&str> = query?
.split('&')
.filter(|kv| !kv.is_empty() && *kv != "token" && !kv.starts_with("token="))
.filter(|kv| !kv.is_empty() && !ours(kv))
.collect();
(!kept.is_empty()).then(|| kept.join("&"))
}
Expand All @@ -301,6 +307,15 @@ mod tests {
Some("tokens=1&x=%20")
);
assert_eq!(forwarded_query(Some("token&q=1")).as_deref(), Some("q=1"));
// A browser's room socket: neither the session nor the gate credential goes upstream.
assert_eq!(
forwarded_query(Some("token=t&instance=ck_x")).as_deref(),
None
);
assert_eq!(
forwarded_query(Some("instance=k&full=true&instances=2")).as_deref(),
Some("full=true&instances=2")
);
}

#[test]
Expand Down
1 change: 1 addition & 0 deletions crates/copper-cloud/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ uuid.workspace = true
zeroize.workspace = true

[dev-dependencies]
form_urlencoded.workspace = true
futures.workspace = true
reqwest.workspace = true
tokio-tungstenite.workspace = true
Expand Down
94 changes: 94 additions & 0 deletions crates/copper-cloud/assets/canvas-app.html

Large diffs are not rendered by default.

49 changes: 49 additions & 0 deletions crates/copper-cloud/src/canvas_app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//! Canvas App at `/canvas/`: the canvas in any browser, for people who are not on Copper
//! (`copper-browser/canvas-app`, its `dist/web/index.html`, vendored as `assets/canvas-app.html`
//! by `packaging/sync-canvas-app.sh`). Served from the server's own origin so its REST calls
//! need no CORS (the server grants none, and the gate would refuse a preflight); it reaches
//! the linked Canvas Cloud through the same `/v1/canvases…` proxy Copper uses, and its room
//! socket carries the gate credential as `?instance=`
//! (`copper_cloud_core::app::INSTANCE_QUERY`), since a browser cannot set headers on a
//! WebSocket. The page is one self-contained file with its own CSP in a `<meta>` tag.

use axum::http::{header, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::get;
use axum::Router;
use copper_cloud_core::state::SharedState;

/// The vendored page.
pub static PAGE: &[u8] = include_bytes!("../assets/canvas-app.html");

/// `/canvas` → `/canvas/`, and the page at `/canvas/`.
pub fn router() -> Router<SharedState> {
Router::new()
.route("/canvas", get(|| async { Redirect::permanent("/canvas/") }))
.route("/canvas/", get(page))
}

async fn page() -> Response {
let mut resp = (StatusCode::OK, PAGE).into_response();
let h = resp.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
// Revalidate, so an upgraded server serves its new page at once.
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
h.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
h.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
// Only framing is restricted here; everything else is the page's own `<meta>` policy.
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("frame-ancestors 'none'"),
);
resp
}
5 changes: 4 additions & 1 deletion crates/copper-cloud/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod admin;
pub mod admin_addons;
pub mod admin_addons_cli;
pub mod admin_api;
pub mod canvas_app;
pub mod cli;
pub mod doctor;
pub mod portal;
Expand All @@ -17,7 +18,8 @@ use copper_cloud_core::state::SharedState;

/// The full HTTP app: core (`/healthz`, `/v1` auth/pairing/devices/sync) + the canvas API
/// proxied to the linked Canvas Cloud behind the instance gate, the admin API at
/// `/admin/api` (cookie sessions, not gated), the `/join/{token}` share-link landing page, the
/// `/admin/api` (cookie sessions, not gated), the `/join/{token}` share-link landing page,
/// Canvas App at `/canvas/` (the canvas in any browser), the
/// SSO onboarding page at `/start` and the embedded admin portal for every other path; auth
/// rate limiters and request tracing/metrics around everything. Starts the canvas link's
/// background tasks (event bridge, user reconcile, outbox) when called inside a tokio runtime.
Expand All @@ -31,6 +33,7 @@ pub fn build_app_with_link(state: SharedState) -> (Router, CanvasLink) {
let root = Router::new()
.nest("/admin/api", admin_api::router())
.merge(CanvasLink::landing_router())
.merge(canvas_app::router())
.route("/start", axum::routing::get(start::start))
.fallback(portal::serve);
let app = copper_cloud_core::app_with(state, link.router(), root)
Expand Down
30 changes: 30 additions & 0 deletions crates/copper-cloud/tests/canvas_app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! Canvas App at `/canvas/`: the vendored page, ungated, its own headers, never the portal.

mod common;

use common::*;

#[tokio::test]
async fn serves_canvas_app() {
let s = start().await;
let r = s.http.get(s.url("/canvas/")).send().await.unwrap();
assert_eq!(r.status(), 200);
let h = r.headers().clone();
assert_eq!(h["content-type"], "text/html; charset=utf-8");
assert_eq!(h["cache-control"], "no-cache");
assert_eq!(h["x-content-type-options"], "nosniff");
assert_eq!(h["referrer-policy"], "no-referrer");
// Only framing is restricted by the server; the page's <meta> CSP does the rest.
assert_eq!(h["content-security-policy"], "frame-ancestors 'none'");
let body = r.text().await.unwrap();
assert!(body.contains("id=\"web-root\""), "the Canvas App build");
assert_eq!(body.len(), copper_cloud::canvas_app::PAGE.len());

let no_redirect = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let r = no_redirect.get(s.url("/canvas")).send().await.unwrap();
assert_eq!(r.status(), 308);
assert_eq!(r.headers()["location"], "/canvas/");
}
42 changes: 42 additions & 0 deletions crates/copper-cloud/tests/canvas_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,43 @@ async fn next_data(ws: &mut Ws) -> Message {
}
}

/// Canvas App's room socket: a browser cannot set headers on a WebSocket, so the session
/// and the gate credential both ride in the query.
#[tokio::test]
async fn browser_websocket_carries_the_gate_credential_in_the_query() {
let (s, _c, m, ana, _bob) = setup().await;
let key: String = form_urlencoded::byte_serialize(s.key().as_bytes()).collect();
let url = |q: &str| format!("ws://{}/v1/canvases/c1/ws?{q}", s.addr);

let (mut ws, _) =
tokio_tungstenite::connect_async(url(&format!("token={}&instance={key}", ana.token)))
.await
.expect("browser socket accepted");
// Neither the session nor the gate credential goes upstream.
let last = m.st.requests_for("/v1/canvases/c1/ws").pop().unwrap();
assert_eq!(last.query, None, "token= and instance= stripped");
assert_eq!(last.headers["x-canvas-user"], ana.user_id);
ws.send(Message::Binary(vec![1, 2, 3].into()))
.await
.unwrap();
assert_eq!(
next_data(&mut ws).await,
Message::Binary(vec![1, 2, 3].into())
);
drop(ws);

// No credential, or a wrong one, is the gate's 401 as with a header.
for q in [
format!("token={}", ana.token),
format!("token={}&instance=ck_nope", ana.token),
] {
let (status, body) =
http_error(tokio_tungstenite::connect_async(url(&q)).await.unwrap_err());
assert_eq!(status, 401, "{q}");
assert_eq!(body["error"], "instance_key");
}
}

#[tokio::test]
async fn websocket_pipe() {
let (s, _c, m, ana, _bob) = setup().await;
Expand Down Expand Up @@ -1107,4 +1144,9 @@ async fn join_landing_page_is_public() {
assert_eq!(r.headers()["cache-control"], "no-store");
let html = r.text().await.unwrap();
assert!(html.contains(&format!("copper://canvas/join/{token}")));
// People who are not on Copper join in the browser, with Canvas App at /canvas/.
assert!(
html.contains(&format!("href=\"/canvas/#/join/{token}\"")),
"{html}"
);
}
1 change: 1 addition & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ uuid.workspace = true
time.workspace = true
base64.workspace = true
hex.workspace = true
form_urlencoded.workspace = true
aes-gcm.workspace = true
argon2.workspace = true
sha2.workspace = true
Expand Down
68 changes: 58 additions & 10 deletions crates/core/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use axum::extract::{OriginalUri, Request, State};
use axum::http::HeaderValue;
use axum::middleware::{from_fn_with_state, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
Expand All @@ -26,6 +25,11 @@ pub const INSTANCE_HEADER: &str = "x-copper-instance";
/// [`crate::agents::AGENT_PAIR_PATH`] are ungated too.
pub const PAIR_PATH: &str = "/v1/auth/pair";

/// Query parameter that may carry the gate credential on a canvas room socket
/// (`/v1/canvases/{id}/ws`) instead of [`INSTANCE_HEADER`]: a browser cannot set headers on a
/// WebSocket (Canvas App, `/canvas/`). Nowhere else; request logs never record query strings.
pub const INSTANCE_QUERY: &str = "instance";

/// The admin login route (rate limited with its own per-IP bucket).
pub const ADMIN_LOGIN_PATH: &str = "/admin/api/login";

Expand Down Expand Up @@ -132,24 +136,42 @@ pub fn is_gated(path: &str) -> bool {
&& !crate::sso::is_sso_path(path)
}

/// Whether `path` is a canvas room socket, `/v1/canvases/{id}/ws`.
pub fn is_canvas_socket(path: &str) -> bool {
path.strip_prefix("/v1/canvases/")
.and_then(|rest| rest.strip_suffix("/ws"))
.is_some_and(|id| !id.is_empty() && !id.contains('/'))
}

/// The [`INSTANCE_QUERY`] value of a query string, percent-decoded.
fn query_credential(query: Option<&str>) -> Option<String> {
form_urlencoded::parse(query?.as_bytes())
.find(|(k, _)| k == INSTANCE_QUERY)
.map(|(_, v)| v.into_owned())
}

/// Middleware: every gated path (see [`is_gated`]) must present a valid credential in
/// `X-Copper-Instance` — the shared instance key (only while `access_mode = open`, compared
/// in constant time) or a valid access key — else 401 `{"error":"instance_key"}`. The
/// accepted credential is attached as a [`GateIdentity`] extension.
/// in constant time) or a valid access key — else 401 `{"error":"instance_key"}`. A canvas
/// room socket without the header may carry it as `?instance=` instead ([`INSTANCE_QUERY`]).
/// The accepted credential is attached as a [`GateIdentity`] extension.
pub async fn instance_gate(
State(state): State<SharedState>,
mut req: Request,
next: Next,
) -> Response {
if !is_gated(req.uri().path()) {
let path = req.uri().path();
if !is_gated(path) {
return next.run(req).await;
}
let presented = req
.headers()
.get(INSTANCE_HEADER)
.map(HeaderValue::as_bytes)
.unwrap_or_default();
match gate_identity(&state, presented).await {
let presented: Vec<u8> = match req.headers().get(INSTANCE_HEADER) {
Some(value) => value.as_bytes().to_vec(),
None if is_canvas_socket(path) => query_credential(req.uri().query())
.unwrap_or_default()
.into_bytes(),
None => Vec::new(),
};
match gate_identity(&state, &presented).await {
Ok(Some(identity)) => {
req.extensions_mut().insert(identity);
next.run(req).await
Expand Down Expand Up @@ -290,6 +312,32 @@ mod tests {
assert!(!instance_key_matches(b"abcd", b"abc"));
}

#[test]
fn canvas_sockets() {
assert!(is_canvas_socket("/v1/canvases/0192aa/ws"));
assert!(is_canvas_socket("/v1/canvases/personal/ws"));
for p in [
"/v1/canvases/ws",
"/v1/canvases//ws",
"/v1/canvases/a/b/ws",
"/v1/canvases/a/state",
"/v1/canvases",
"/v1/sync/ws",
] {
assert!(!is_canvas_socket(p), "{p}");
}
}

#[test]
fn instance_from_query() {
assert_eq!(
query_credential(Some("token=t&instance=ck_a%2Bb")).as_deref(),
Some("ck_a+b")
);
assert_eq!(query_credential(Some("token=t")), None);
assert_eq!(query_credential(None), None);
}

#[test]
fn gated_paths() {
for p in [
Expand Down
Loading
Loading