From bf41400348c723965b1c6a6880c038f1cdcbc647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 09:35:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20sign=20in=20through=20im:?= =?UTF-8?q?=20OIDC=20client,=20local=20sessions,=20back-channel=20logout,?= =?UTF-8?q?=20directory=20mirror,=20avatar=20proxy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 355 ++++++- Cargo.toml | 3 + config/in.example.toml | 6 +- .../migrations/0002_session_id_token.sql | 5 + crates/in-core/src/config.rs | 5 + crates/in-core/src/quota.rs | 4 + crates/in-core/src/store/migrate.rs | 8 +- crates/in-core/src/store/sessions.rs | 14 +- crates/in-web/Cargo.toml | 17 +- crates/in-web/src/auth.rs | 229 +++++ crates/in-web/src/boot.rs | 24 +- crates/in-web/src/directory.rs | 418 ++++++++ crates/in-web/src/i18n/shell.rs | 60 +- crates/in-web/src/main.rs | 3 + crates/in-web/src/oidc.rs | 905 ++++++++++++++++++ crates/in-web/src/pages/backchannel.rs | 223 +++++ crates/in-web/src/pages/home.rs | 42 +- crates/in-web/src/pages/mod.rs | 5 +- crates/in-web/src/pages/photo.rs | 248 +++++ crates/in-web/src/pages/sign_in.rs | 385 ++++++++ crates/in-web/src/state.rs | 6 +- crates/in-web/src/views/mod.rs | 18 +- 22 files changed, 2954 insertions(+), 29 deletions(-) create mode 100644 crates/in-core/migrations/0002_session_id_token.sql create mode 100644 crates/in-web/src/auth.rs create mode 100644 crates/in-web/src/directory.rs create mode 100644 crates/in-web/src/oidc.rs create mode 100644 crates/in-web/src/pages/backchannel.rs create mode 100644 crates/in-web/src/pages/photo.rs create mode 100644 crates/in-web/src/pages/sign_in.rs diff --git a/Cargo.lock b/Cargo.lock index 0b78b16..bb4bd51 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -270,6 +270,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" @@ -636,6 +642,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -768,6 +780,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -808,6 +832,33 @@ dependencies = [ "cmov", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling" version = "0.24.1" @@ -854,6 +905,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -870,6 +932,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -881,7 +944,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -909,12 +972,71 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "elsa" version = "1.11.2" @@ -1030,6 +1152,22 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1178,6 +1316,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -1262,6 +1401,17 @@ dependencies = [ "rand 0.8.8", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "h2" version = "0.4.20" @@ -1739,13 +1889,21 @@ dependencies = [ name = "in-web" version = "0.1.0" dependencies = [ + "base64 0.23.1", + "ed25519-dalek", "futures-util", "grass", "hex", "http", "in-core", + "jsonwebtoken", + "rand 0.10.3", + "reqwest", + "serde", + "serde_json", "sha2 0.11.1", "tempfile", + "thiserror", "tokio", "topcoat", "tracing", @@ -1924,6 +2082,28 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "11.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1" +dependencies = [ + "base64 0.22.1", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac 0.12.1", + "js-sys", + "p256", + "p384", + "rand 0.8.8", + "rsa", + "serde", + "serde_json", + "sha2 0.10.9", + "signature", + "zeroize", +] + [[package]] name = "lasso" version = "0.7.3" @@ -1938,6 +2118,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin 0.9.9", +] [[package]] name = "lazycell" @@ -2277,6 +2460,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2292,6 +2491,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2299,6 +2508,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -2397,6 +2607,30 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + [[package]] name = "pack1" version = "1.1.0" @@ -2445,6 +2679,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2510,6 +2753,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2598,6 +2862,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -2945,6 +3218,8 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_urlencoded", "sync_wrapper", "tokio", "tokio-rustls", @@ -2959,6 +3234,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -2983,6 +3268,26 @@ dependencies = [ "byteorder", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rust-stemmers" version = "1.2.0" @@ -3167,6 +3472,20 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -3361,6 +3680,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3441,6 +3770,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -5147,6 +5486,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 0e5a968..5685138 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ async-trait = "0.1.92" base64 = "0.23.1" bytes = "1.12.1" chacha20poly1305 = "0.11.0" +ed25519-dalek = "2.1.1" futures-util = "0.3.34" grass = "0.13.4" hex = "0.4.3" @@ -52,8 +53,10 @@ hmac = "0.13.0" http = "1.5.0" in-core = { path = "crates/in-core" } ipnet = "2.12.2" +jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } object_store = { version = "0.14.2", features = ["aws"] } rand = "0.10.3" +reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] } serde = "1.0.229" serde_json = "1.0.154" sha2 = "0.11.1" diff --git a/config/in.example.toml b/config/in.example.toml index 39ad7de..498f732 100644 --- a/config/in.example.toml +++ b/config/in.example.toml @@ -13,10 +13,12 @@ base_url = "http://127.0.0.1:7655" # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. trusted_proxies = [] -# Sign-in through im. Placeholder for development: point issuer at the im instance you run. +# Sign-in through im (OpenID Connect). Point issuer at the im instance you run (its origin, no +# trailing slash). The client secret is read from client_secret_file at boot; it is never in this file. [oidc] -issuer = "http://127.0.0.1:7600" +issuer = "http://127.0.0.1:7650" client_id = "in" +client_secret_file = "data/oidc_client_secret" [storage] backend = "local" diff --git a/crates/in-core/migrations/0002_session_id_token.sql b/crates/in-core/migrations/0002_session_id_token.sql new file mode 100644 index 0000000..f27580a --- /dev/null +++ b/crates/in-core/migrations/0002_session_id_token.sql @@ -0,0 +1,5 @@ +-- 0002: keeps the sealed ID token of each sign-in session. RP-initiated logout needs it as the +-- `id_token_hint`. It is sealed with the instance key (secret.rs), and it is NULL for sessions made +-- before this migration, which then sign out without a hint. + +ALTER TABLE sessions ADD COLUMN id_token_sealed TEXT; diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index ee1b2d8..b03d87d 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -60,6 +60,8 @@ pub struct Oidc { pub issuer: String, /// The OAuth client id registered for `in` in `im`. pub client_id: String, + /// File holding the client secret, readable only by the service user. Read at boot. + pub client_secret_file: PathBuf, } /// The `[storage]` table. @@ -163,6 +165,9 @@ impl Config { "oidc.client_id must be a non-empty plain string", )); } + if oidc.client_secret_file.as_os_str().is_empty() { + return Err(config_err("oidc.client_secret_file must not be empty")); + } } self.storage.validate()?; if let Some(backup) = &self.backup { diff --git a/crates/in-core/src/quota.rs b/crates/in-core/src/quota.rs index bfb732c..91f47e5 100644 --- a/crates/in-core/src/quota.rs +++ b/crates/in-core/src/quota.rs @@ -5,6 +5,10 @@ //! those bytes are promised to be written, so a new upload cannot take them. Everything saturates, so //! an over-full account has zero headroom instead of a negative one. +/// Quota of a person who has none set yet: 10 GiB. Used when a person first appears, from a sign-in or +/// from the directory. The admin page changes it per person later. +pub const DEFAULT_MEMBER_QUOTA: i64 = 10 * 1024 * 1024 * 1024; + /// Bytes a new upload may still use: the quota less what is stored and what is promised to uploads /// in progress. Never negative. pub fn headroom(quota: i64, used: i64, staged_claims: i64) -> i64 { diff --git a/crates/in-core/src/store/migrate.rs b/crates/in-core/src/store/migrate.rs index 23bf973..41626c8 100644 --- a/crates/in-core/src/store/migrate.rs +++ b/crates/in-core/src/store/migrate.rs @@ -9,7 +9,13 @@ use crate::store::fetch_all; use crate::time::now_stamp; /// `(version, sql)` in ascending order. Never edit a migration that has been applied; add a new one. -pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; +pub const MIGRATIONS: &[(u32, &str)] = &[ + (1, include_str!("../../migrations/0001_init.sql")), + ( + 2, + include_str!("../../migrations/0002_session_id_token.sql"), + ), +]; fn migration_err(e: turso::Error) -> Error { Error::Migration(e.to_string()) diff --git a/crates/in-core/src/store/sessions.rs b/crates/in-core/src/store/sessions.rs index 1d27daa..f443c11 100644 --- a/crates/in-core/src/store/sessions.rs +++ b/crates/in-core/src/store/sessions.rs @@ -10,7 +10,7 @@ use crate::time::now_stamp; /// Column list for [`map_session`]. Keep the two in step. pub const SESSION_COLS: &str = "id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ - last_seen_at, ip, user_agent"; + last_seen_at, ip, user_agent, id_token_sealed"; /// One row of the `sessions` table. The token itself is not in here. #[derive(Debug, Clone, PartialEq, Eq)] @@ -35,6 +35,9 @@ pub struct Session { pub ip: Option, /// User agent at sign-in, when sent. pub user_agent: Option, + /// The sealed ID token of the sign-in, used as the `id_token_hint` of logout. Absent for sessions + /// made before migration 2. + pub id_token_sealed: Option, } /// What a new session needs. The id and timestamps are made by the store. @@ -54,6 +57,8 @@ pub struct NewSession { pub ip: Option, /// User agent, when sent. pub user_agent: Option, + /// The sealed ID token of the sign-in. Sealed by the caller with the instance key. + pub id_token_sealed: Option, } /// Maps a row selected with [`SESSION_COLS`]. @@ -69,6 +74,7 @@ pub fn map_session(row: &turso::Row) -> Result { last_seen_at: col_text(row, 7)?, ip: col_opt_text(row, 8)?, user_agent: col_opt_text(row, 9)?, + id_token_sealed: col_opt_text(row, 10)?, }) } @@ -80,7 +86,8 @@ impl Store { let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO sessions (id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ - last_seen_at, ip, user_agent) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9)", + last_seen_at, ip, user_agent, id_token_sealed) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10)", ( id.clone(), new.sub.clone(), @@ -91,6 +98,7 @@ impl Store { new.expires_at.clone(), new.ip.clone(), new.user_agent.clone(), + new.id_token_sealed.clone(), ), ) .await @@ -106,6 +114,7 @@ impl Store { last_seen_at: now, ip: new.ip, user_agent: new.user_agent, + id_token_sealed: new.id_token_sealed, }) } @@ -224,6 +233,7 @@ mod tests { expires_at: stamp_after(Duration::from_secs(3600)), ip: None, user_agent: None, + id_token_sealed: None, }) .await .unwrap(); diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml index a2da846..1a37ce0 100644 --- a/crates/in-web/Cargo.toml +++ b/crates/in-web/Cargo.toml @@ -11,17 +11,28 @@ name = "in" path = "src/main.rs" [dependencies] +base64.workspace = true futures-util.workspace = true http.workspace = true in-core.workspace = true -# `net` and `signal` for the listener and the shutdown signals, `time` for the probe deadlines, and -# `rt-multi-thread` and `macros` for the async entry point and `join!`. -tokio = { workspace = true, features = ["net", "signal", "time", "rt-multi-thread", "macros"] } +jsonwebtoken.workspace = true +rand.workspace = true +reqwest.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +sha2.workspace = true +thiserror.workspace = true +# `net` and `signal` for the listener and the shutdown signals, `time` for the probe deadlines and the +# retry delays, `sync` for the token and key caches, `fs` for the photo cache, and `rt-multi-thread` +# and `macros` for the async entry point and `join!`/`select!`. +tokio = { workspace = true, features = ["net", "signal", "time", "sync", "fs", "io-util", "rt-multi-thread", "macros"] } topcoat.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } [dev-dependencies] +# jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version. +ed25519-dalek = { workspace = true, features = ["pkcs8"] } tempfile.workspace = true [build-dependencies] diff --git a/crates/in-web/src/auth.rs b/crates/in-web/src/auth.rs new file mode 100644 index 0000000..909bd04 --- /dev/null +++ b/crates/in-web/src/auth.rs @@ -0,0 +1,229 @@ +//! Who the viewer of a request is, and the checks that gate pages and forms. +//! +//! A signed-in viewer has a local session: a cookie with a random token, of which the database keeps only +//! the SHA-256 (conventions section 5). Every check reads the store, never `im`, so pages keep working +//! while `im` is down (contracts section 1.1). This module also owns the redirect target check, +//! [`safe_next`], which every return path uses. +//! +//! The helpers here are called by the sign-in pages, the logout form, the photo proxy and the home +//! page. The pages that come next (drive, admin) use [`require_member`], [`require_admin`] and +//! [`require_csrf`] too. + +use std::time::Duration; + +use in_core::store::members::Member; +use in_core::store::sessions::Session; +use in_core::time::stamp_before; +use in_core::token::{constant_time_eq, hash_token}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::error::{forbidden, not_found, see_other}; +use topcoat::router::request::uri; + +use crate::oidc::percent_encode; +use crate::state::AppState; + +/// Cookie of the local session. The `__Host-` prefix pins it to this origin, to path `/`, and to HTTPS. +pub const SESSION_COOKIE: &str = "__Host-in_session"; + +/// Cookie of a sign-in in progress: the sealed state, nonce, PKCE verifier and `next` target. +pub const FLIGHT_COOKIE: &str = "__Host-in_flight"; + +/// Absolute age of a local session. Contracts section 2.4 caps it at 12 hours. +pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60); + +/// How long a sign-in may take from the redirect to `im` to the callback. +pub const FLIGHT_TTL: Duration = Duration::from_secs(10 * 60); + +/// Longest `next` target accepted. Longer ones are refused rather than cut. +pub const MAX_NEXT_BYTES: usize = 2048; + +/// How often `last_seen_at` is written. Writing it on every page view would make every read a write. +const TOUCH_EVERY: Duration = Duration::from_secs(5 * 60); + +/// A request's signed-in person: the session that was presented and the member it belongs to. +pub struct Viewer { + /// The session. Its CSRF token checks the forms of this viewer. + pub session: Session, + /// The member the session belongs to. Disabled members never get here. + pub member: Member, +} + +/// Returns `candidate` when it is a safe place to redirect to, and `None` otherwise. +/// +/// A safe target is a single absolute path on this origin: it starts with one `/`, the next character is +/// not `/` or `\` (browsers read `/\evil` as `//evil`), it has no control characters (no line breaks to +/// inject headers) and no backslash anywhere, and it is at most [`MAX_NEXT_BYTES`] long. Anything that +/// is not a path, such as a scheme, a percent-encoded slash or an empty string, is refused. +pub fn safe_next(candidate: &str) -> Option<&str> { + if candidate.len() > MAX_NEXT_BYTES { + return None; + } + let mut chars = candidate.chars(); + if chars.next() != Some('/') { + return None; + } + if matches!(chars.next(), Some('/' | '\\')) { + return None; + } + if candidate.chars().any(|c| c.is_control() || c == '\\') { + return None; + } + Some(candidate) +} + +/// The redirect target for an optional `next` value: the value when it is safe, else the start page. +pub fn next_or_home(candidate: &str) -> String { + safe_next(candidate).unwrap_or("/").to_owned() +} + +/// The sign-in page URL that returns to `next` after sign-in. +pub fn login_path(next: &str) -> String { + format!("/auth/login?next={}", percent_encode(next)) +} + +/// Sets a cookie that only this origin's root path can read, sent over HTTPS, and hidden from scripts. +/// `SameSite=Lax` lets it arrive on the redirect back from `im`. A zero `ttl` deletes the cookie. +pub fn set_cookie(cx: &Cx, name: &'static str, value: String, ttl: Duration) { + let max_age = time::Duration::seconds(i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX)); + let cookie = Cookie::build((name, value)) + .path("/") + .http_only(true) + .secure(true) + .same_site(SameSite::Lax) + .max_age(max_age) + .build(); + cookies(cx).add(cookie); +} + +/// Reads a cookie's value, when it is present. +pub fn cookie_value(cx: &Cx, name: &str) -> Option { + cookies(cx) + .get(name) + .map(|cookie| cookie.value().to_owned()) +} + +/// The local session that the request presents, when it is still live. The store filters out expired +/// sessions and sessions of disabled members. Touches `last_seen_at` at most every [`TOUCH_EVERY`]. +pub async fn current_session(cx: &Cx) -> Result> { + let Some(token) = cookie_value(cx, SESSION_COOKIE) else { + return Ok(None); + }; + let state = app_context::(cx); + let Some(session) = state + .store + .session_by_token_hash(&hash_token(&token)) + .await? + else { + return Ok(None); + }; + if session.last_seen_at < stamp_before(TOUCH_EVERY) { + state.store.touch_session(&session.id).await?; + } + Ok(Some(session)) +} + +/// The signed-in person of the request, if any. +pub async fn current_member(cx: &Cx) -> Result> { + let Some(session) = current_session(cx).await? else { + return Ok(None); + }; + let state = app_context::(cx); + let Some(member) = state.store.member(&session.sub).await? else { + return Ok(None); + }; + if member.disabled { + return Ok(None); + } + Ok(Some(Viewer { session, member })) +} + +/// The signed-in person, or a redirect to sign-in that returns to this request's path and query. +pub async fn require_member(cx: &Cx) -> Result { + match current_member(cx).await? { + Some(viewer) => Ok(viewer), + None => { + let here = uri(cx) + .path_and_query() + .map_or("/", |path_and_query| path_and_query.as_str()); + Err(see_other(login_path(here)).into()) + } + } +} + +/// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not +/// reveal that they exist. +#[allow(dead_code)] // The admin pages that come next are the first callers. +pub async fn require_admin(cx: &Cx) -> Result { + let viewer = require_member(cx).await?; + if !viewer.member.is_admin { + return Err(not_found().into()); + } + Ok(viewer) +} + +/// Whether `submitted` is the CSRF token of `session`. The comparison is constant-time, and an empty +/// stored token never matches, not even an empty submission. +pub fn csrf_matches(session: &Session, submitted: &str) -> bool { + !session.csrf_token.is_empty() + && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) +} + +/// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to +/// sign-in; a wrong or missing token is `403`. Run it before any side effect. +#[allow(dead_code)] // The first state-changing form that is not logout calls it. +pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { + let viewer = require_member(cx).await?; + if !csrf_matches(&viewer.session, submitted) { + return Err(forbidden().into()); + } + Ok(viewer) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn safe_next_accepts_local_paths() { + assert_eq!(safe_next("/"), Some("/")); + assert_eq!( + safe_next("/drive/abc?sort=name"), + Some("/drive/abc?sort=name") + ); + assert_eq!(next_or_home(""), "/"); + assert_eq!(next_or_home("https://evil.example"), "/"); + } + + #[test] + fn safe_next_refuses_attack_strings() { + let attacks = [ + "//evil.example", + "/\\evil.example", + "\\\\evil.example", + "/\\/evil.example", + "https://evil.example", + "http://evil.example", + "javascript:alert(1)", + "%2f%2fevil.example", + "/\nSet-Cookie: x=1", + "/\r\nLocation: https://evil.example", + "/\t/evil.example", + "/a\u{0}b", + " //evil.example", + "drive", + "", + ]; + for attack in attacks { + assert_eq!(safe_next(attack), None, "accepted {attack:?}"); + } + } + + #[test] + fn safe_next_limits_the_length() { + let longest = format!("/{}", "a".repeat(MAX_NEXT_BYTES - 1)); + assert_eq!(safe_next(&longest), Some(longest.as_str())); + assert_eq!(safe_next(&format!("{longest}a")), None); + } +} diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index cff95c2..a5b5668 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -23,7 +23,9 @@ use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; +use crate::directory; use crate::live::LiveHub; +use crate::oidc::OidcClient; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; @@ -39,6 +41,11 @@ pub async fn serve(config_path: &Path) -> Result<()> { let config = Config::load(config_path)?; let listen = config.listen; let state = open_state(config).await?; + // One stop flag. The signal task sets it; the server and every worker watch it and then drain. + let (stop_tx, stop_rx) = watch::channel(false); + if state.oidc.is_some() { + tokio::spawn(directory::run(state.clone(), stop_rx.clone())); + } let listener = TcpListener::bind(listen).await.map_err(|error| { std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) @@ -51,8 +58,6 @@ pub async fn serve(config_path: &Path) -> Result<()> { "in starting" ); - // One stop flag. The signal task sets it; the server watches it and then drains. - let (stop_tx, stop_rx) = watch::channel(false); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -86,12 +91,24 @@ async fn open_state(config: Config) -> Result { let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; let blobs = open_blobs(&config, &data_dir)?; + let oidc = match &config.oidc { + Some(oidc) => { + let client_secret = read_secret(&oidc.client_secret_file)?; + Some(Arc::new(OidcClient::new( + oidc, + &config.base_url, + client_secret, + )?)) + } + None => None, + }; Ok(AppState { config: Arc::new(config), store, blobs, key: Arc::new(key), live: Arc::new(LiveHub::default()), + oidc, }) } @@ -191,8 +208,8 @@ pub(crate) use tests::test_state; #[cfg(test)] mod tests { use super::*; - use std::net::SocketAddr; use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; + use std::net::SocketAddr; use topcoat::router::response::Response; use topcoat::router::{Body, to_bytes}; @@ -215,6 +232,7 @@ mod tests { blobs, key: Arc::new(key), live: Arc::new(LiveHub::default()), + oidc: None, }; (dir, state) } diff --git a/crates/in-web/src/directory.rs b/crates/in-web/src/directory.rs new file mode 100644 index 0000000..f05c2f8 --- /dev/null +++ b/crates/in-web/src/directory.rs @@ -0,0 +1,418 @@ +//! The members mirror: a local copy of the people directory of `im` (contracts section 3), kept current by +//! a stream, so pages show a name or an avatar without calling `im`. +//! +//! The worker does a full fetch when it has no cursor yet, then follows the event stream from the cursor +//! it stored in the `settings` table. A `resync` event means the cursor is too old: the next round does a +//! full fetch. A `deleted` event, a `disabled` member, and a person missing from a full fetch all end the +//! person's local sessions, which is the second of the two paths in contracts section 2.5. +//! +//! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random +//! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends +//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second. + +use std::collections::HashSet; +use std::time::Duration; + +use futures_util::StreamExt; +use http::header::ACCEPT; +use in_core::quota::DEFAULT_MEMBER_QUOTA; +use in_core::store::members::MemberFields; +use in_core::time::now_stamp; +use serde::Deserialize; +use tokio::sync::watch; + +use crate::oidc::{OidcClient, OidcError}; +use crate::state::AppState; + +/// The `settings` key of the directory cursor. +pub const CURSOR_KEY: &str = "directory_cursor"; + +/// The first wait after a failure. +const BACKOFF_FIRST: Duration = Duration::from_secs(1); + +/// The longest wait between attempts after failures. +const BACKOFF_MAX: Duration = Duration::from_secs(60); + +/// The pause after a stream that ended cleanly, before it is reconnected. +const CLEAN_PAUSE: Duration = Duration::from_secs(1); + +/// Why one round of syncing failed. +#[derive(Debug, thiserror::Error)] +enum SyncError { + /// A token could not be had from `im`. + #[error(transparent)] + Oidc(#[from] OidcError), + /// A local write failed. + #[error(transparent)] + Store(#[from] in_core::error::Error), + /// The request to `im` failed on the way. + #[error("the request to im failed: {0}")] + Transport(String), + /// `im` answered with a non-success status. + #[error("im answered {0}")] + Status(reqwest::StatusCode), + /// The full directory could not be read. + #[error("the directory listing is not what the contracts describe")] + Listing, +} + +/// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored. +#[derive(Debug, Deserialize)] +struct WireMember { + sub: String, + #[serde(default)] + email: String, + #[serde(default)] + name: String, + #[serde(default)] + admin: bool, + #[serde(default)] + disabled: bool, + #[serde(default)] + locale: String, + #[serde(default)] + zoneinfo: String, + #[serde(default)] + picture_version: i64, + #[serde(default)] + updated_at: String, +} + +/// The full listing (contracts section 3.2). +#[derive(Debug, Deserialize)] +struct Listing { + #[serde(default)] + members: Vec, + #[serde(default)] + cursor: String, +} + +/// The data of a `deleted` event. +#[derive(Debug, Deserialize)] +struct DeletedEvent { + sub: String, +} + +/// One server-sent event: its id (the cursor), its name and its data. +#[derive(Debug, Clone, PartialEq, Eq)] +struct SseEvent { + id: Option, + event: String, + data: String, +} + +/// Incremental parser of `text/event-stream`. Bytes go in in any split; complete events come out. +#[derive(Debug, Default)] +struct SseParser { + buffer: Vec, + id: Option, + event: String, + data: Vec, +} + +impl SseParser { + /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start + /// with `:` are comments (keep-alives) and are skipped. + fn push(&mut self, chunk: &[u8]) -> Vec { + self.buffer.extend_from_slice(chunk); + let mut events = Vec::new(); + while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') { + let raw: Vec = self.buffer.drain(..=end).collect(); + let line = String::from_utf8_lossy(&raw); + let line = line.trim_end_matches(['\n', '\r']); + if line.is_empty() { + if !self.data.is_empty() { + events.push(SseEvent { + id: self.id.take(), + event: if self.event.is_empty() { + "message".to_owned() + } else { + std::mem::take(&mut self.event) + }, + data: self.data.join("\n"), + }); + self.data.clear(); + } + self.event.clear(); + continue; + } + if line.starts_with(':') { + continue; + } + let (field, value) = match line.split_once(':') { + Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), + None => (line, ""), + }; + match field { + "event" => self.event = value.to_owned(), + "data" => self.data.push(value.to_owned()), + "id" => self.id = Some(value.to_owned()), + _ => {} + } + } + events + } +} + +/// What a stream connection did when it stopped on its own. +enum Ended { + /// The server asked for a full fetch. + Resync, + /// The stream closed (the server's 50-minute close, or a stop). + Closed, +} + +/// Runs the mirror until `stop` is set. Does nothing without an OIDC client. +pub async fn run(state: AppState, mut stop: watch::Receiver) { + let Some(oidc) = state.oidc.clone() else { + return; + }; + let mut needs_full = matches!(state.store.get_setting(CURSOR_KEY).await, Ok(None) | Err(_)); + let mut backoff = BACKOFF_FIRST; + loop { + if *stop.borrow() { + return; + } + let pause = match round(&state, &oidc, needs_full, &mut stop).await { + Ok(Ended::Resync) => { + needs_full = true; + backoff = BACKOFF_FIRST; + CLEAN_PAUSE + } + Ok(Ended::Closed) => { + backoff = BACKOFF_FIRST; + CLEAN_PAUSE + } + Err(error) => { + tracing::warn!(error = %error, "directory: sync failed, retrying"); + needs_full = true; + let pause = jittered(backoff); + backoff = (backoff * 2).min(BACKOFF_MAX); + pause + } + }; + tokio::select! { + _ = stop.wait_for(|stopped| *stopped) => return, + () = tokio::time::sleep(pause) => {} + } + } +} + +/// One round: a full fetch when one is due, then the stream from the stored cursor. +async fn round( + state: &AppState, + oidc: &OidcClient, + needs_full: bool, + stop: &mut watch::Receiver, +) -> Result { + if needs_full { + full_sync(state, oidc).await?; + } + follow(state, oidc, stop).await +} + +/// Fetches the whole directory, applies it, and stores its cursor. People the listing does not name any +/// more are marked deleted, and their sessions end. +async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> { + let token = oidc.service_token().await?; + let response = oidc + .http() + .get(format!("{}/api/v1/directory", oidc.issuer())) + .bearer_auth(token) + .header(ACCEPT, "application/json") + .send() + .await + .map_err(|e| SyncError::Transport(e.to_string()))?; + if !response.status().is_success() { + return Err(SyncError::Status(response.status())); + } + let bytes = response + .bytes() + .await + .map_err(|e| SyncError::Transport(e.to_string()))?; + let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; + + let mut named = HashSet::new(); + for member in listing.members { + named.insert(member.sub.clone()); + apply_member(state, member).await?; + } + for local in state.store.list_members().await? { + if !named.contains(&local.sub) && !local.disabled { + end_person(state, &local.sub).await?; + } + } + if !listing.cursor.is_empty() { + state.store.set_setting(CURSOR_KEY, &listing.cursor).await?; + } + tracing::info!(members = named.len(), "directory: full sync applied"); + Ok(()) +} + +/// Opens the event stream from the stored cursor and applies events until the stream ends, a `resync` +/// arrives, or `stop` is set. +async fn follow( + state: &AppState, + oidc: &OidcClient, + stop: &mut watch::Receiver, +) -> Result { + let cursor = state.store.get_setting(CURSOR_KEY).await?; + let token = oidc.service_token().await?; + let mut request = oidc + .stream_http() + .get(format!("{}/api/v1/directory/stream", oidc.issuer())) + .bearer_auth(token) + .header(ACCEPT, "text/event-stream"); + if let Some(cursor) = &cursor { + request = request.header("Last-Event-ID", cursor.as_str()); + } + let response = request + .send() + .await + .map_err(|e| SyncError::Transport(e.to_string()))?; + if !response.status().is_success() { + return Err(SyncError::Status(response.status())); + } + tracing::info!("directory: stream connected"); + + let mut body = response.bytes_stream(); + let mut parser = SseParser::default(); + loop { + let chunk = tokio::select! { + chunk = body.next() => chunk, + _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Closed), + }; + let Some(chunk) = chunk else { + return Ok(Ended::Closed); + }; + let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; + for event in parser.push(&chunk) { + if let Some(ended) = apply_event(state, event).await? { + return Ok(ended); + } + } + } +} + +/// Applies one stream event. `Some` means the stream must stop: a `resync`. An event that cannot be read +/// is logged and skipped, so one bad event cannot stall the mirror forever. +async fn apply_event(state: &AppState, event: SseEvent) -> Result, SyncError> { + match event.event.as_str() { + "member" => match serde_json::from_str::(&event.data) { + Ok(member) => apply_member(state, member).await?, + Err(_) => tracing::warn!("directory: a member event could not be read"), + }, + "deleted" => match serde_json::from_str::(&event.data) { + Ok(deleted) => end_person(state, &deleted.sub).await?, + Err(_) => tracing::warn!("directory: a deleted event could not be read"), + }, + "resync" => return Ok(Some(Ended::Resync)), + _ => {} + } + if let Some(id) = &event.id { + state.store.set_setting(CURSOR_KEY, id).await?; + } + Ok(None) +} + +/// Writes one member from the directory. A disabled member's sessions end as well. +async fn apply_member(state: &AppState, member: WireMember) -> Result<(), SyncError> { + if !valid_sub(&member.sub) { + tracing::warn!("directory: a member has an invalid id and is skipped"); + return Ok(()); + } + let name = if member.name.trim().is_empty() { + member.email.clone() + } else { + member.name + }; + let fields = MemberFields { + sub: member.sub.clone(), + email: member.email, + name, + is_admin: member.admin, + locale: if member.locale.is_empty() { + "en".to_owned() + } else { + member.locale + }, + zoneinfo: if member.zoneinfo.is_empty() { + "UTC".to_owned() + } else { + member.zoneinfo + }, + picture_version: member.picture_version.max(0), + im_updated_at: if member.updated_at.is_empty() { + now_stamp() + } else { + member.updated_at + }, + }; + let stored = state + .store + .apply_directory_member(&fields, member.disabled, DEFAULT_MEMBER_QUOTA) + .await?; + if stored.disabled { + state.store.delete_sessions_by_sub(&stored.sub).await?; + } + Ok(()) +} + +/// Marks a person deleted and ends their sessions. +async fn end_person(state: &AppState, sub: &str) -> Result<(), SyncError> { + if !valid_sub(sub) { + return Ok(()); + } + state.store.mark_member_deleted(sub).await?; + state.store.delete_sessions_by_sub(sub).await?; + Ok(()) +} + +/// Whether `sub` is a plain identifier. Subjects are ULIDs; anything else is not stored. +fn valid_sub(sub: &str) -> bool { + !sub.is_empty() + && sub.len() <= 64 + && sub + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// A random wait between half of `base` and `base`, so that retries spread out. +fn jittered(base: Duration) -> Duration { + let half = base / 2; + let span = u64::try_from(half.as_millis()).unwrap_or(u64::MAX); + let mut bytes = [0u8; 8]; + rand::fill(&mut bytes); + let offset = u64::from_le_bytes(bytes) % span.saturating_add(1); + half + Duration::from_millis(offset) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn events_are_parsed_across_chunks_and_comments_are_skipped() { + let mut parser = SseParser::default(); + assert!(parser.push(b": keep-alive\nid: 7\nevent: mem").is_empty()); + let events = parser.push(b"ber\ndata: {\"sub\":\"a\"}\n\n"); + assert_eq!( + events, + vec![SseEvent { + id: Some("7".into()), + event: "member".into(), + data: "{\"sub\":\"a\"}".into(), + }] + ); + let events = parser.push(b"event: resync\ndata: {}\r\n\r\n"); + assert_eq!(events[0].event, "resync"); + } + + #[test] + fn jitter_stays_in_the_upper_half_of_the_step() { + for _ in 0..50 { + let wait = jittered(Duration::from_secs(8)); + assert!(wait >= Duration::from_secs(4) && wait <= Duration::from_secs(8)); + } + } +} diff --git a/crates/in-web/src/i18n/shell.rs b/crates/in-web/src/i18n/shell.rs index 8b40143..38a57eb 100644 --- a/crates/in-web/src/i18n/shell.rs +++ b/crates/in-web/src/i18n/shell.rs @@ -24,6 +24,32 @@ pub enum K { SignedOutTitle, /// The sentence under the signed-out heading on the start page. SignedOutBody, + /// The button that starts sign-in. + SignIn, + /// The placeholder under the greeting until the drive exists. + DriveComesNext, + /// The button in the user menu that ends the session. + SignOut, + /// Heading of the page that explains a sign-in that did not finish. + ProblemFailedTitle, + /// Text of that page. + ProblemFailedBody, + /// Heading of the page shown when `im` cannot be reached. + ProblemUnavailableTitle, + /// Text of that page. + ProblemUnavailableBody, + /// Heading of the page shown to a disabled or refused account. + ProblemDeniedTitle, + /// Text of that page. + ProblemDeniedBody, +} + +/// The greeting for a signed-in person. The name is inserted as text; the view escapes it. +pub fn greeting(lang: Lang, name: &str) -> String { + match lang { + Lang::En => format!("Hello, {name}."), + Lang::Tr => format!("Merhaba, {name}."), + } } /// The text of `key` in `lang`. @@ -45,7 +71,37 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SkipToContent, Lang::Tr) => "İçeriğe geç", (K::SignedOutTitle, Lang::En) => "Sign in to open your files", (K::SignedOutTitle, Lang::Tr) => "Dosyalarınızı açmak için oturum açın", - (K::SignedOutBody, Lang::En) => "You are signed out. Sign-in is not part of this build yet.", - (K::SignedOutBody, Lang::Tr) => "Oturumunuz kapalı. Oturum açma bu sürümde henüz yok.", + (K::SignedOutBody, Lang::En) => "Sign in with your family account to open your files.", + (K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.", + (K::SignIn, Lang::En) => "Sign in", + (K::SignIn, Lang::Tr) => "Oturum aç", + (K::DriveComesNext, Lang::En) => "The drive comes next. Your files will appear here.", + (K::DriveComesNext, Lang::Tr) => "Sürücü sıradaki adım. Dosyalarınız burada görünecek.", + (K::SignOut, Lang::En) => "Sign out", + (K::SignOut, Lang::Tr) => "Oturumu kapat", + (K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish", + (K::ProblemFailedTitle, Lang::Tr) => "Oturum açma tamamlanamadı", + (K::ProblemFailedBody, Lang::En) => { + "The sign-in was cancelled or expired. Start again from the start page." + } + (K::ProblemFailedBody, Lang::Tr) => { + "Oturum açma iptal edildi ya da süresi doldu. Başlangıç sayfasından yeniden deneyin." + } + (K::ProblemUnavailableTitle, Lang::En) => "Sign-in is unavailable", + (K::ProblemUnavailableTitle, Lang::Tr) => "Oturum açma şu an kullanılamıyor", + (K::ProblemUnavailableBody, Lang::En) => { + "The account service cannot be reached. Try again in a few minutes." + } + (K::ProblemUnavailableBody, Lang::Tr) => { + "Hesap servisine ulaşılamıyor. Birkaç dakika içinde yeniden deneyin." + } + (K::ProblemDeniedTitle, Lang::En) => "This account cannot sign in", + (K::ProblemDeniedTitle, Lang::Tr) => "Bu hesapla oturum açılamaz", + (K::ProblemDeniedBody, Lang::En) => { + "Ask the administrator of this instance to check the account." + } + (K::ProblemDeniedBody, Lang::Tr) => { + "Bu sunucunun yöneticisine hesabı kontrol etmesini isteyin." + } } } diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 4e9b37e..324ab51 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -5,10 +5,13 @@ //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. mod assets; +mod auth; mod boot; +mod directory; mod health; mod i18n; mod live; +mod oidc; mod pages; mod security; mod state; diff --git a/crates/in-web/src/oidc.rs b/crates/in-web/src/oidc.rs new file mode 100644 index 0000000..42aacbd --- /dev/null +++ b/crates/in-web/src/oidc.rs @@ -0,0 +1,905 @@ +//! The OpenID Connect client of `in`, a relying party of `im` (docs/contracts.md section 2). +//! +//! It does four things and nothing more. It finds `im`'s endpoints (discovery, cached, with the +//! standard paths as a fallback). It keeps `im`'s signing keys (JWKS, cached for an hour, refetched at +//! most once a minute when a token names an unknown key). It verifies the three kinds of token `in` +//! receives: ID tokens, logout tokens and access tokens. And it makes the calls `in` sends to `im`: the +//! code exchange and the client-credentials token that the directory and the photos need. +//! +//! The verification rules are pure functions over a [`KeySet`], so they are tested without a network. +//! Only EdDSA is accepted. The algorithm is checked on the raw header before any library parses it, so +//! `none` and every other algorithm are refused with the same answer. + +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; +use in_core::config::Oidc; +use in_core::error::{Error as CoreError, Result as CoreResult}; +use in_core::token::constant_time_eq; +use jsonwebtoken::errors::ErrorKind; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use serde::Deserialize; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use tokio::sync::Mutex; + +/// Seconds of clock skew allowed on `exp`. The contracts do not name a value; `in` uses 60 s. +pub const CLOCK_LEEWAY_SECS: i64 = 60; + +/// Seconds an `iat` may lie in the future. Contracts section 2.3 says five minutes. +pub const MAX_FUTURE_IAT_SECS: i64 = 300; + +/// How long a fetched key set is used before it is fetched again (contracts section 2.2). +pub const JWKS_MAX_AGE: Duration = Duration::from_secs(60 * 60); + +/// The shortest gap between two key fetches caused by an unknown `kid`. Protects `im` from a flood of +/// tokens that name keys that do not exist. +pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); + +/// How long a failed discovery is not retried. Until it succeeds the standard paths are used. +const DISCOVERY_RETRY_GAP: Duration = Duration::from_secs(60); + +/// Time limit of every call to `im`, except the directory stream. +pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); + +/// Longest silence on the directory stream before the connection is given up. The server sends a +/// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. +const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); + +/// A service token is refreshed this long before its stated end (contracts section 2.6). +const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); + +/// The event name that marks a logout token (OIDC Back-Channel Logout 1.0). +pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; + +/// The family key of `im`. Client-credentials tokens that `in` asks for carry it as `aud`. +pub const IM_KEY: &str = "im"; + +/// The scope that reads the people directory and photos at `im`. +pub const DIRECTORY_SCOPE: &str = "directory.read"; + +/// Why a token was refused. Every variant is a refusal; none of them says more than the cause. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TokenError { + /// The token is not three base64url segments with a JSON header and claims. + #[error("the token is malformed")] + Malformed, + /// The header names an algorithm other than EdDSA, or none at all. + #[error("the token is not signed with EdDSA")] + Algorithm, + /// The header has no `kid`, so the key cannot be chosen. + #[error("the token has no key id")] + NoKeyId, + /// The `kid` is not in the published key set. The caller may refetch the keys once. + #[error("the token names an unknown key")] + UnknownKey, + /// The signature does not verify with the named key. + #[error("the signature does not verify")] + Signature, + /// `exp` is in the past, beyond the leeway. + #[error("the token has expired")] + Expired, + /// A claim is missing, has the wrong type, or has the wrong value. + #[error("the claim {0} is missing or wrong")] + Claim(&'static str), + /// The nonce does not equal the one this sign-in sent. + #[error("the nonce does not match")] + Nonce, +} + +/// Why a call to `im` failed. +#[derive(Debug, thiserror::Error)] +pub enum OidcError { + /// A token did not verify. + #[error(transparent)] + Token(#[from] TokenError), + /// `im` could not be reached, or answered something that is not what the contracts describe. + #[error("the identity provider is unavailable: {0}")] + Unavailable(String), + /// `im` answered with a refusal, such as a rejected code or a wrong client secret. + #[error("the identity provider refused the request")] + Refused, +} + +/// The claims of an ID token that `in` uses. Each field is checked by [`verify_id_token`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdClaims { + /// The person's stable id (a ULID). + pub sub: String, + /// The `im` browser session the sign-in belongs to. Back-channel logout names it. + pub sid: String, + /// The person's email address. + pub email: String, + /// The display name. The email address when the claim is empty. + pub name: String, + /// Whether the person administers the family instance. + pub admin: bool, + /// `en` or `tr`. Anything else from `im` is read as `en`. + pub locale: String, + /// IANA time zone name. + pub zoneinfo: String, + /// Photo version; bumps when the photo changes. + pub picture_version: i64, +} + +/// The claims of a back-channel logout token that `in` uses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LogoutClaims { + /// Unique id of the token. A replayed id is refused for ten minutes. + pub jti: String, + /// The `im` session that ended, when the token names one. + pub sid: Option, + /// The person, when the token names one. A token with only `sub` ends every session of the person. + pub sub: Option, +} + +/// The endpoints of `im` that `in` calls. Discovery provides them; the standard paths replace them +/// when discovery cannot be fetched. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Endpoints { + /// The sign-in page, `/authorize`. + pub authorization: String, + /// The token endpoint, `/token`. + pub token: String, + /// The signing keys, `/jwks.json`. + pub jwks: String, + /// The end-session page, `/logout`. + pub end_session: String, +} + +/// The fields of the discovery document that `in` reads. +#[derive(Debug, Deserialize)] +struct DiscoveryDocument { + issuer: String, + authorization_endpoint: String, + token_endpoint: String, + jwks_uri: String, + end_session_endpoint: Option, +} + +/// One key of the published JWKS, as far as `in` reads it. +#[derive(Debug, Deserialize)] +pub struct Jwk { + #[serde(default)] + kty: String, + #[serde(default)] + crv: String, + #[serde(default)] + x: String, + #[serde(default)] + kid: String, + #[serde(default)] + alg: String, + #[serde(default, rename = "use")] + usage: String, +} + +/// The JWKS document. +#[derive(Debug, Deserialize)] +pub struct Jwks { + keys: Vec, +} + +/// The usable Ed25519 keys of `im`, by `kid`. +pub struct KeySet { + keys: Vec<(String, DecodingKey)>, +} + +impl KeySet { + /// Keeps the keys that `in` can use: Ed25519 (`OKP`) signing keys whose algorithm, when named, is + /// EdDSA. Anything else in the document is skipped, not an error. + pub fn from_jwks(jwks: &Jwks) -> KeySet { + let keys = jwks + .keys + .iter() + .filter(|key| key.kty == "OKP" && key.crv == "Ed25519") + .filter(|key| key.alg.is_empty() || key.alg == "EdDSA") + .filter(|key| key.usage.is_empty() || key.usage == "sig") + .filter(|key| !key.kid.is_empty()) + .filter_map(|key| { + DecodingKey::from_ed_components(&key.x) + .ok() + .map(|decoding| (key.kid.clone(), decoding)) + }) + .collect(); + KeySet { keys } + } + + /// The key with this `kid`, if it is published. + fn get(&self, kid: &str) -> Option<&DecodingKey> { + self.keys + .iter() + .find(|(known, _)| known == kid) + .map(|(_, key)| key) + } +} + +/// The current time in whole seconds since the Unix epoch. +pub fn now_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) +} + +/// Reads a non-empty string claim. +fn text_claim<'a>( + claims: &'a Map, + name: &'static str, +) -> Result<&'a str, TokenError> { + claims + .get(name) + .and_then(Value::as_str) + .filter(|value| !value.trim().is_empty()) + .ok_or(TokenError::Claim(name)) +} + +/// Reads an optional non-empty string claim. A present but empty value counts as absent. +fn optional_text_claim<'a>(claims: &'a Map, name: &str) -> Option<&'a str> { + claims + .get(name) + .and_then(Value::as_str) + .filter(|value| !value.trim().is_empty()) +} + +/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. +/// Contracts require an exact `client_id` for ID tokens, so a longer audience list is refused. +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { + match aud { + Some(Value::String(single)) => single == expected, + Some(Value::Array(items)) => { + items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) + } + _ => false, + } +} + +/// Refuses an `iat` that is missing or more than [`MAX_FUTURE_IAT_SECS`] ahead of `now`. +fn check_iat(claims: &Map, now: i64) -> Result<(), TokenError> { + let iat = claims + .get("iat") + .and_then(Value::as_i64) + .ok_or(TokenError::Claim("iat"))?; + if iat > now + MAX_FUTURE_IAT_SECS { + return Err(TokenError::Claim("iat")); + } + Ok(()) +} + +/// Checks the algorithm, the key id, the signature, the issuer and the expiry, and returns the claims. +/// Audience, nonce and the rest are the job of the callers, which know what they expect. +/// +/// The algorithm is read from the raw header first, so `none` and any other algorithm are refused +/// before a library sees the token. +pub fn verify_signed( + keys: &KeySet, + token: &str, + issuer: &str, +) -> Result, TokenError> { + let first_segment = token.split('.').next().ok_or(TokenError::Malformed)?; + let header_bytes = BASE64_URL_SAFE_NO_PAD + .decode(first_segment) + .map_err(|_| TokenError::Malformed)?; + let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; + if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { + return Err(TokenError::Algorithm); + } + let parsed = decode_header(token).map_err(|_| TokenError::Malformed)?; + let kid = parsed.kid.ok_or(TokenError::NoKeyId)?; + let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; + + let mut validation = Validation::new(Algorithm::EdDSA); + validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); + validation.validate_exp = true; + // Audience is checked by the callers, because the rule differs by token kind. + validation.validate_aud = false; + validation.set_issuer(&[issuer]); + // `sub` is not required here: a back-channel token may carry only `sid`, and each caller checks + // the subject it needs. + validation.set_required_spec_claims(&["exp", "iss", "iat"]); + let data = + decode::>(token, key, &validation).map_err(|error| { + match error.kind() { + ErrorKind::ExpiredSignature => TokenError::Expired, + ErrorKind::InvalidSignature => TokenError::Signature, + ErrorKind::InvalidIssuer => TokenError::Claim("iss"), + ErrorKind::InvalidAlgorithm => TokenError::Algorithm, + ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), + _ => TokenError::Malformed, + } + })?; + Ok(data.claims) +} + +/// Verifies an ID token from the code exchange: signature, issuer, `aud` equal to `client_id`, `exp`, +/// `iat`, and the `nonce` this sign-in sent. Returns the claims `in` keeps about the person. +pub fn verify_id_token( + keys: &KeySet, + token: &str, + issuer: &str, + client_id: &str, + nonce: &str, +) -> Result { + let claims = verify_signed(keys, token, issuer)?; + if !audience_is(claims.get("aud"), client_id) { + return Err(TokenError::Claim("aud")); + } + check_iat(&claims, now_secs())?; + let sent = text_claim(&claims, "nonce")?; + if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { + return Err(TokenError::Nonce); + } + let sub = text_claim(&claims, "sub")?.to_owned(); + let sid = text_claim(&claims, "sid")?.to_owned(); + let email = text_claim(&claims, "email")?.to_owned(); + let name = optional_text_claim(&claims, "name") + .unwrap_or(&email) + .to_owned(); + let locale = match optional_text_claim(&claims, "locale") { + Some("tr") => "tr".to_owned(), + _ => "en".to_owned(), + }; + Ok(IdClaims { + sub, + sid, + email, + name, + admin: claims + .get("admin") + .and_then(Value::as_bool) + .unwrap_or(false), + locale, + zoneinfo: optional_text_claim(&claims, "zoneinfo") + .unwrap_or("UTC") + .to_owned(), + picture_version: claims + .get("picture_version") + .and_then(Value::as_i64) + .unwrap_or(0) + .max(0), + }) +} + +/// Verifies a back-channel logout token (contracts section 2.5): signature, issuer, `aud` equal to +/// `client_id`, `iat`, `exp`, the logout event, a `jti`, a `sid` or `sub`, and no `nonce`. +pub fn verify_logout_token( + keys: &KeySet, + token: &str, + issuer: &str, + client_id: &str, +) -> Result { + let claims = verify_signed(keys, token, issuer)?; + if !audience_is(claims.get("aud"), client_id) { + return Err(TokenError::Claim("aud")); + } + check_iat(&claims, now_secs())?; + if claims.contains_key("nonce") { + return Err(TokenError::Claim("nonce")); + } + let has_event = claims + .get("events") + .and_then(Value::as_object) + .and_then(|events| events.get(LOGOUT_EVENT)) + .is_some_and(Value::is_object); + if !has_event { + return Err(TokenError::Claim("events")); + } + let jti = text_claim(&claims, "jti")?.to_owned(); + let sid = optional_text_claim(&claims, "sid").map(str::to_owned); + let sub = optional_text_claim(&claims, "sub").map(str::to_owned); + if sid.is_none() && sub.is_none() { + return Err(TokenError::Claim("sub")); + } + Ok(LogoutClaims { jti, sid, sub }) +} + +/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]) that grants +/// `required_scope`. Returns the caller's family key (`svc`) and its subject. +/// +/// Nothing calls this yet; the object API that accepts service calls comes next. +#[allow(dead_code)] // The object API that accepts other family apps' calls is the first caller. +pub fn verify_access_token( + keys: &KeySet, + token: &str, + issuer: &str, + audience: &str, + required_scope: &str, +) -> Result<(String, String), TokenError> { + let claims = verify_signed(keys, token, issuer)?; + if !audience_is(claims.get("aud"), audience) { + return Err(TokenError::Claim("aud")); + } + check_iat(&claims, now_secs())?; + let scope = text_claim(&claims, "scope")?; + if !scope.split(' ').any(|granted| granted == required_scope) { + return Err(TokenError::Claim("scope")); + } + let sub = text_claim(&claims, "sub")?.to_owned(); + let svc = text_claim(&claims, "svc")?.to_owned(); + Ok((sub, svc)) +} + +/// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). +pub fn pkce_challenge(verifier: &str) -> String { + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +/// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): +/// unreserved characters pass, everything else becomes `%XX`. +pub fn percent_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +/// The body of a successful token response. Only the fields `in` reads are named. +#[derive(Debug, Deserialize)] +struct TokenResponse { + #[serde(default)] + id_token: Option, + #[serde(default)] + access_token: Option, + #[serde(default)] + expires_in: Option, +} + +/// Cached state of the client. Every field is behind one lock, and no method holds it while it +/// takes it again. +#[derive(Default)] +struct Cache { + /// The endpoints from discovery, once fetched. + endpoints: Option>, + /// When the last discovery failed. Until [`DISCOVERY_RETRY_GAP`] has passed, the standard paths + /// are used without asking again. + discovery_failed_at: Option, + /// The key set and when it was fetched. + keys: Option<(Instant, Arc)>, + /// When the keys were last fetched for an unknown `kid`. Limits those fetches. + keys_refresh_at: Option, + /// The client-credentials token for `im`, and the instant it stops being used. + service: Option<(String, Instant)>, +} + +/// The OpenID Connect client. One per process, shared through the app state. +pub struct OidcClient { + issuer: String, + client_id: String, + client_secret: String, + redirect_uri: String, + http: reqwest::Client, + stream_http: reqwest::Client, + cache: Mutex, +} + +impl OidcClient { + /// Builds the client from the `[oidc]` table, the public base URL and the client secret read from + /// its file. No request is made here. + pub fn new(config: &Oidc, base_url: &str, client_secret: String) -> CoreResult { + let http = reqwest::Client::builder() + .timeout(HTTP_TIMEOUT) + .connect_timeout(HTTP_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|e| CoreError::Config(format!("cannot build the HTTP client: {e}")))?; + // The directory stream lasts for minutes, so it gets no total time limit, only a read limit. + let stream_http = reqwest::Client::builder() + .connect_timeout(HTTP_TIMEOUT) + .read_timeout(STREAM_READ_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|e| CoreError::Config(format!("cannot build the stream client: {e}")))?; + Ok(Self { + issuer: config.issuer.clone(), + client_id: config.client_id.clone(), + client_secret, + redirect_uri: format!("{base_url}/auth/callback"), + http, + stream_http, + cache: Mutex::new(Cache::default()), + }) + } + + /// The issuer URL of `im`, which is also the origin of its API. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// The HTTP client for calls to `im` with a time limit. + pub fn http(&self) -> &reqwest::Client { + &self.http + } + + /// The HTTP client for the directory stream, which has no total time limit. + pub fn stream_http(&self) -> &reqwest::Client { + &self.stream_http + } + + /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths + /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`]. + pub async fn endpoints(&self) -> Arc { + let mut cache = self.cache.lock().await; + if let Some(endpoints) = &cache.endpoints { + return Arc::clone(endpoints); + } + let recently_failed = cache + .discovery_failed_at + .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP); + if !recently_failed { + match self.fetch_discovery().await { + Ok(endpoints) => { + let endpoints = Arc::new(endpoints); + cache.endpoints = Some(Arc::clone(&endpoints)); + cache.discovery_failed_at = None; + return endpoints; + } + Err(error) => { + tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); + cache.discovery_failed_at = Some(Instant::now()); + } + } + } + Arc::new(self.standard_endpoints()) + } + + /// The paths of contracts section 2.1, under the issuer. + fn standard_endpoints(&self) -> Endpoints { + Endpoints { + authorization: format!("{}/authorize", self.issuer), + token: format!("{}/token", self.issuer), + jwks: format!("{}/jwks.json", self.issuer), + end_session: format!("{}/logout", self.issuer), + } + } + + /// Fetches and checks the discovery document. Its `issuer` must equal the configured one exactly. + async fn fetch_discovery(&self) -> Result { + let url = format!("{}/.well-known/openid-configuration", self.issuer); + let document: DiscoveryDocument = self.get_json(&url).await?; + if document.issuer != self.issuer { + return Err(OidcError::Unavailable( + "discovery names another issuer".to_owned(), + )); + } + let end_session = document + .end_session_endpoint + .unwrap_or_else(|| format!("{}/logout", self.issuer)); + Ok(Endpoints { + authorization: document.authorization_endpoint, + token: document.token_endpoint, + jwks: document.jwks_uri, + end_session, + }) + } + + /// GETs a JSON document. A non-2xx answer is unavailable: the caller cannot do anything with it. + async fn get_json(&self, url: &str) -> Result { + let response = self + .http + .get(url) + .send() + .await + .map_err(|e| OidcError::Unavailable(e.to_string()))?; + if !response.status().is_success() { + return Err(OidcError::Unavailable(format!( + "{url} answered {}", + response.status() + ))); + } + let bytes = response + .bytes() + .await + .map_err(|e| OidcError::Unavailable(e.to_string()))?; + serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) + } + + /// The key set in use. A fresh cache is used as it is; an expired one is refetched, and a failed + /// refetch keeps the old set, because a stale key still verifies tokens that were signed with it. + async fn load_keys(&self, force: bool) -> Result, OidcError> { + let endpoints = self.endpoints().await; + let mut cache = self.cache.lock().await; + let fresh = cache + .keys + .as_ref() + .is_some_and(|(at, _)| at.elapsed() < JWKS_MAX_AGE); + if fresh + && !force + && let Some((_, keys)) = &cache.keys + { + return Ok(Arc::clone(keys)); + } + // A forced refetch (unknown kid) is rate limited. Within the gap the old set is the answer. + let refreshed_recently = cache + .keys_refresh_at + .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); + if force + && refreshed_recently + && let Some((_, keys)) = &cache.keys + { + return Ok(Arc::clone(keys)); + } + cache.keys_refresh_at = Some(Instant::now()); + match self.get_json::(&endpoints.jwks).await { + Ok(jwks) => { + let keys = Arc::new(KeySet::from_jwks(&jwks)); + cache.keys = Some((Instant::now(), Arc::clone(&keys))); + Ok(keys) + } + Err(error) => match &cache.keys { + Some((_, keys)) => { + tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); + Ok(Arc::clone(keys)) + } + None => Err(error), + }, + } + } + + /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. + async fn verify_with( + &self, + check: impl Fn(&KeySet) -> Result, + ) -> Result { + let keys = self.load_keys(false).await?; + match check(&keys) { + Err(TokenError::UnknownKey) => { + let keys = self.load_keys(true).await?; + Ok(check(&keys)?) + } + outcome => Ok(outcome?), + } + } + + /// Verifies an ID token of this sign-in. See [`verify_id_token`]. + pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result { + self.verify_with(|keys| verify_id_token(keys, token, &self.issuer, &self.client_id, nonce)) + .await + } + + /// Verifies a back-channel logout token. See [`verify_logout_token`]. + pub async fn verify_logout_token(&self, token: &str) -> Result { + self.verify_with(|keys| verify_logout_token(keys, token, &self.issuer, &self.client_id)) + .await + } + + /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1). + pub async fn authorize_url( + &self, + state: &str, + nonce: &str, + challenge: &str, + ) -> Result { + let endpoints = self.endpoints().await; + let mut url = reqwest::Url::parse(&endpoints.authorization) + .map_err(|e| OidcError::Unavailable(format!("bad authorization endpoint: {e}")))?; + url.query_pairs_mut() + .append_pair("response_type", "code") + .append_pair("client_id", &self.client_id) + .append_pair("redirect_uri", &self.redirect_uri) + .append_pair("scope", "openid profile email") + .append_pair("state", state) + .append_pair("nonce", nonce) + .append_pair("code_challenge", challenge) + .append_pair("code_challenge_method", "S256"); + Ok(url.to_string()) + } + + /// The URL that ends the `im` session (RP-initiated logout, contracts section 2.5). + pub async fn end_session_url( + &self, + id_token_hint: &str, + post_logout_redirect: &str, + state: &str, + ) -> Result { + let endpoints = self.endpoints().await; + let mut url = reqwest::Url::parse(&endpoints.end_session) + .map_err(|e| OidcError::Unavailable(format!("bad end-session endpoint: {e}")))?; + url.query_pairs_mut() + .append_pair("id_token_hint", id_token_hint) + .append_pair("post_logout_redirect_uri", post_logout_redirect) + .append_pair("state", state); + Ok(url.to_string()) + } + + /// Exchanges the authorization code for the ID token (contracts section 2.3, step 3). The access + /// and refresh tokens are not kept: this family does not use them. + pub async fn exchange_code(&self, code: &str, verifier: &str) -> Result { + let endpoints = self.endpoints().await; + let response = self + .token_request( + &endpoints.token, + &[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", &self.redirect_uri), + ("code_verifier", verifier), + ], + ) + .await?; + response + .id_token + .ok_or(OidcError::Token(TokenError::Claim("id_token"))) + } + + /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until + /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends. + pub async fn service_token(&self) -> Result { + let endpoints = self.endpoints().await; + let mut cache = self.cache.lock().await; + if let Some((token, until)) = &cache.service + && Instant::now() < *until + { + return Ok(token.clone()); + } + let response = self + .token_request( + &endpoints.token, + &[ + ("grant_type", "client_credentials"), + ("scope", DIRECTORY_SCOPE), + ("audience", IM_KEY), + ], + ) + .await?; + let token = response + .access_token + .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; + let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); + let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); + cache.service = Some((token.clone(), until)); + Ok(token) + } + + /// Posts a form to a token endpoint with client_secret_basic authentication (RFC 6749 section + /// 2.3.1). A 4xx answer is a refusal; anything else that is not a success is unavailable. + async fn token_request( + &self, + url: &str, + form: &[(&str, &str)], + ) -> Result { + let credentials = format!( + "{}:{}", + percent_encode(&self.client_id), + percent_encode(&self.client_secret) + ); + let response = self + .http + .post(url) + .header( + reqwest::header::AUTHORIZATION, + format!("Basic {}", BASE64_STANDARD.encode(credentials)), + ) + .header(reqwest::header::ACCEPT, "application/json") + .form(form) + .send() + .await + .map_err(|e| OidcError::Unavailable(e.to_string()))?; + let status = response.status(); + if status.is_client_error() { + tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); + return Err(OidcError::Refused); + } + if !status.is_success() { + return Err(OidcError::Unavailable(format!( + "token endpoint answered {status}" + ))); + } + let bytes = response + .bytes() + .await + .map_err(|e| OidcError::Unavailable(e.to_string()))?; + serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::SigningKey; + use ed25519_dalek::pkcs8::EncodePrivateKey; + use jsonwebtoken::{EncodingKey, Header, encode}; + use serde_json::json; + + const ISSUER: &str = "https://im.example.test"; + const CLIENT: &str = "in"; + const KID: &str = "k1"; + const NONCE: &str = "nonce-value"; + + /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. + fn test_key() -> (Vec, KeySet) { + let mut seed = [0u8; 32]; + rand::fill(&mut seed); + let signing = SigningKey::from_bytes(&seed); + let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); + let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); + let jwks: Jwks = serde_json::from_value(json!({ + "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] + })) + .expect("jwks"); + (der, KeySet::from_jwks(&jwks)) + } + + /// Signs `claims` with `der` under `kid`. + fn sign(der: &[u8], claims: &Value) -> String { + let mut header = Header::new(Algorithm::EdDSA); + header.kid = Some(KID.to_owned()); + encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") + } + + fn id_claims(now: i64) -> Value { + json!({ + "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, + "nonce": NONCE, "sid": "im-session-1", "email": "ann@example.test", "name": "Ann", + }) + } + + #[test] + fn a_valid_id_token_is_accepted() { + let (der, keys) = test_key(); + let token = sign(&der, &id_claims(now_secs())); + let claims = verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).expect("valid"); + assert_eq!(claims.sub, "01JTESTSUB"); + assert_eq!(claims.sid, "im-session-1"); + assert_eq!(claims.locale, "en"); + } + + #[test] + fn an_unsigned_alg_none_token_is_refused() { + let (_der, keys) = test_key(); + let header = BASE64_URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1","typ":"JWT"}"#); + let payload = BASE64_URL_SAFE_NO_PAD.encode(id_claims(now_secs()).to_string()); + let token = format!("{header}.{payload}."); + assert_eq!( + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), + Some(TokenError::Algorithm) + ); + } + + #[test] + fn a_token_for_another_audience_is_refused() { + let (der, keys) = test_key(); + let mut claims = id_claims(now_secs()); + claims["aud"] = json!("iz"); + let token = sign(&der, &claims); + assert_eq!( + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), + Some(TokenError::Claim("aud")) + ); + } + + #[test] + fn an_expired_token_is_refused_beyond_the_leeway() { + let (der, keys) = test_key(); + let now = now_secs(); + let mut claims = id_claims(now); + claims["exp"] = json!(now - 3 * CLOCK_LEEWAY_SECS); + let token = sign(&der, &claims); + assert_eq!( + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), + Some(TokenError::Expired) + ); + } + + #[test] + fn a_wrong_nonce_is_refused() { + let (der, keys) = test_key(); + let token = sign(&der, &id_claims(now_secs())); + assert_eq!( + verify_id_token(&keys, &token, ISSUER, CLIENT, "another-nonce").err(), + Some(TokenError::Nonce) + ); + } + + #[test] + fn the_pkce_challenge_matches_the_rfc_7636_vector() { + assert_eq!( + pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } +} diff --git a/crates/in-web/src/pages/backchannel.rs b/crates/in-web/src/pages/backchannel.rs new file mode 100644 index 0000000..fdfd171 --- /dev/null +++ b/crates/in-web/src/pages/backchannel.rs @@ -0,0 +1,223 @@ +//! The back-channel logout endpoint (contracts section 2.5). `im` POSTs a logout token here when a session +//! of ours has to end: on sign-out, admin revoke, password change, or a disabled or deleted person. +//! +//! The endpoint is for machines, so it has no CSRF token. Its protection is the token itself: the +//! signature, the issuer, the audience, the event and the `jti` replay guard. The body is capped at 16 KiB. +//! Every answer that is not success is an error with a JSON body, which `im` reads as a failed delivery and +//! retries. +//! +//! It is served at `/auth/backchannel-logout`, the path architecture.md names. + +use http::header::CONTENT_TYPE; +use http::{HeaderMap, HeaderValue}; +use in_core::error::Result as CoreResult; +use in_core::store::Store; +use in_core::time::stamp_after; +use serde::Deserialize; +use std::time::Duration; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::ContentTooLargeError; +use topcoat::router::{Body, StatusCode, route, to_bytes}; + +use crate::oidc::{LogoutClaims, OidcError}; +use crate::state::AppState; + +/// The largest body the endpoint reads. A logout form is a few kilobytes; this is generous. +pub const BODY_LIMIT: usize = 16 * 1024; + +/// How long a logout token's `jti` is remembered. Contracts section 2.5 says ten minutes, which is longer +/// than the token's own two-minute life. +pub const REPLAY_WINDOW: Duration = Duration::from_secs(10 * 60); + +/// What the endpoint answers: status, headers and body. +pub type Answer = (StatusCode, HeaderMap, String); + +/// The form body of a delivery: the one field `im` sends. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct LogoutTokenForm { + logout_token: String, +} + +/// What ending the sessions for one token did. +#[derive(Debug, PartialEq, Eq)] +pub enum Outcome { + /// The token was new. This many sessions ended (possibly none). + Ended(u64), + /// The `jti` was seen before. The token is refused and nothing is ended. + Replayed, +} + +/// Ends the sessions a verified logout token names, after recording its `jti`. +/// +/// The `jti` is recorded first, and the insert decides: two deliveries of one token cannot both be +/// acted on, and a replay ends nothing. The `sid` names one `im` session; a token with only `sub` ends +/// every session of the person. +pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> CoreResult { + if !store + .seen_jti(&claims.jti, &stamp_after(REPLAY_WINDOW)) + .await? + { + return Ok(Outcome::Replayed); + } + let ended = match (&claims.sid, &claims.sub) { + (Some(sid), _) => store.delete_sessions_by_im_sid(sid).await?, + (None, Some(sub)) => store.delete_sessions_by_sub(sub).await?, + (None, None) => 0, + }; + Ok(Outcome::Ended(ended)) +} + +/// A JSON error answer, in the shape of contracts section 7. +pub fn json_error(status: StatusCode, code: &str, message: &str) -> Answer { + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + let body = serde_json::json!({ "error": code, "message": message }).to_string(); + (status, headers, body) +} + +/// The answer of a successful delivery: `200` with an empty body. +fn accepted() -> Answer { + (StatusCode::OK, HeaderMap::new(), String::new()) +} + +/// Runs one delivery from start to answer. +async fn deliver(cx: &Cx, body: Body) -> Answer { + let state = app_context::(cx); + let bytes = match to_bytes(body, BODY_LIMIT).await { + Ok(bytes) => bytes, + Err(error) if error.downcast_ref::().is_some() => { + return json_error( + StatusCode::PAYLOAD_TOO_LARGE, + "too_large", + "The logout request body is too large.", + ); + } + Err(_) => { + return json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "The logout request body cannot be read.", + ); + } + }; + let token = match Form::::from_bytes(&bytes) { + Ok(Form(form)) if !form.logout_token.is_empty() => form.logout_token, + _ => { + return json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "The logout_token field is missing.", + ); + } + }; + let Some(oidc) = state.oidc.as_ref() else { + return json_error( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "Sign-in is not configured on this instance.", + ); + }; + let claims = match oidc.verify_logout_token(&token).await { + Ok(claims) => claims, + Err(OidcError::Unavailable(_)) => { + return json_error( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "The signing keys cannot be fetched right now.", + ); + } + Err(error) => { + tracing::warn!(error = %error, "backchannel: logout token refused"); + return json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "The logout token is not valid.", + ); + } + }; + match end_sessions(&state.store, &claims).await { + Ok(Outcome::Ended(count)) => { + tracing::info!(sessions = count, "backchannel: logout applied"); + accepted() + } + Ok(Outcome::Replayed) => json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "The logout token was already used.", + ), + Err(error) => { + tracing::error!(error = %error, "backchannel: could not end the sessions"); + json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + "The sessions could not be ended.", + ) + } + } +} + +/// `POST /auth/backchannel-logout`. +#[route(POST "/auth/backchannel-logout")] +async fn backchannel(cx: &Cx, body: Body) -> Result { + Ok(deliver(cx, body).await) +} + +#[cfg(test)] +mod tests { + use super::*; + use in_core::store::members::MemberFields; + use in_core::store::sessions::NewSession; + use in_core::time::stamp_after; + + #[tokio::test] + async fn a_replayed_jti_ends_nothing_the_second_time() { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("in.db")).await.expect("store"); + store + .upsert_member_from_claims( + &MemberFields { + sub: "ann".into(), + email: "ann@example.test".into(), + name: "Ann".into(), + is_admin: false, + locale: "en".into(), + zoneinfo: "UTC".into(), + picture_version: 0, + im_updated_at: String::new(), + }, + 1024, + ) + .await + .expect("member"); + store + .create_session(NewSession { + sub: "ann".into(), + token_hash: "h-ann".into(), + csrf_token: "c".into(), + im_sid: "im-1".into(), + expires_at: stamp_after(Duration::from_secs(3600)), + ip: None, + user_agent: None, + id_token_sealed: None, + }) + .await + .expect("session"); + + let claims = LogoutClaims { + jti: "jti-1".into(), + sid: Some("im-1".into()), + sub: None, + }; + assert_eq!( + end_sessions(&store, &claims).await.expect("first"), + Outcome::Ended(1) + ); + assert_eq!( + end_sessions(&store, &claims).await.expect("replay"), + Outcome::Replayed + ); + } +} diff --git a/crates/in-web/src/pages/home.rs b/crates/in-web/src/pages/home.rs index 66883e4..fae16c7 100644 --- a/crates/in-web/src/pages/home.rs +++ b/crates/in-web/src/pages/home.rs @@ -1,25 +1,51 @@ -//! The start page. For now it is a placeholder that shows the signed-out state; it becomes the -//! account home (the drive redirect) once sign-in exists. +//! The start page. Signed out, it offers sign-in. Signed in, it greets the person; the drive that +//! follows it is not built yet, so it says so. use topcoat::Result; use topcoat::context::Cx; use topcoat::router::page; use topcoat::view::{View, view}; +use crate::auth::current_member; use crate::i18n::lang; -use crate::i18n::shell::{K, t}; -use crate::views::{notice, shell}; +use crate::i18n::shell::{K, greeting, t}; +use crate::views::{ViewerInfo, shell}; /// `GET /`. #[page("/")] async fn home(cx: &Cx) -> Result { - let lang = lang(cx, None); + let viewer = current_member(cx).await?; + // The language follows the stored override, else the one `im` reports, else the request. + let lang = lang( + cx, + viewer.as_ref().map(|viewer| { + viewer + .member + .locale_override + .as_deref() + .unwrap_or(viewer.member.locale.as_str()) + }), + ); + let info = viewer.map(|viewer| ViewerInfo { + name: viewer.member.name, + is_admin: viewer.member.is_admin, + csrf: viewer.session.csrf_token, + }); + let heading = match &info { + Some(info) => greeting(lang, &info.name), + None => t(lang, K::SignedOutTitle).to_owned(), + }; Ok(view! { - shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: None, + shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(),

"in"

-

(t(lang, K::SignedOutTitle))

- notice(message: t(lang, K::SignedOutBody)) +

(heading.as_str())

+ if info.is_some() { +

(t(lang, K::DriveComesNext))

+ } else { +

(t(lang, K::SignedOutBody))

+ (t(lang, K::SignIn)) + }
) }) diff --git a/crates/in-web/src/pages/mod.rs b/crates/in-web/src/pages/mod.rs index 2f18c8a..700b695 100644 --- a/crates/in-web/src/pages/mod.rs +++ b/crates/in-web/src/pages/mod.rs @@ -1,4 +1,7 @@ -//! The pages and the page-level layers. One file per page. +//! The pages and the page-level layers. One file per page or per closely related group of pages. +pub mod backchannel; pub mod home; pub mod not_found; +pub mod photo; +pub mod sign_in; diff --git a/crates/in-web/src/pages/photo.rs b/crates/in-web/src/pages/photo.rs new file mode 100644 index 0000000..cde51a7 --- /dev/null +++ b/crates/in-web/src/pages/photo.rs @@ -0,0 +1,248 @@ +//! `GET /avatar/{sub}`: a member's photo, served by `in` to signed-in members only. +//! +//! A browser never talks to `im` for a photo (contracts section 3). On a miss, `in` fetches the photo from +//! `im` with its service token and keeps it on disk under `data_dir/photos//`, so a +//! photo is fetched once per version. The bytes go out with an ETag of the version (`"p"`), +//! `nosniff`, and a content type from a short allowlist. Anything else `im` sends is not served. +//! +//! A signed-out viewer, an unknown person and an unknown sub all get `404`: the answer does not say +//! which of them it was. + +use std::path::{Path, PathBuf}; + +use http::header::{CONTENT_TYPE, ETAG, IF_NONE_MATCH}; +use http::{HeaderMap, HeaderValue}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::{not_found, service_unavailable}; +use topcoat::router::request::{headers, uri}; +use topcoat::router::{StatusCode, route}; + +use crate::auth::current_member; +use crate::oidc::OidcClient; +use crate::state::AppState; + +/// The image types a photo may be served as. `im` may store others; they are not served. +const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; + +/// The largest photo kept or served. Larger ones from `im` are not served. +const MAX_PHOTO_BYTES: usize = 5 * 1024 * 1024; + +/// Seconds a client is told to wait when a photo cannot be fetched. +const PHOTO_RETRY_SECS: u64 = 30; + +/// Directory under the data directory that holds the photo cache. +const PHOTO_DIR: &str = "photos"; + +/// The answer of a photo request: status, headers and the image bytes. +type PhotoAnswer = (StatusCode, HeaderMap, Vec); + +/// The allowlisted content type that `raw` names, ignoring parameters such as `; charset=...`. +fn allowed_type(raw: &str) -> Option<&'static str> { + let essence = raw.split(';').next()?.trim().to_ascii_lowercase(); + ALLOWED_TYPES + .into_iter() + .find(|allowed| *allowed == essence) +} + +/// A subject from the path. It must be a short id of ASCII letters, digits, `-` and `_`, so that it can +/// be a directory name and never a path. +fn valid_sub(sub: &str) -> bool { + !sub.is_empty() + && sub.len() <= 64 + && sub + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// The cache files of one photo version: the bytes and their content type. +fn cache_paths(photo_dir: &Path, sub: &str, version: i64) -> (PathBuf, PathBuf) { + let dir = photo_dir.join(sub); + ( + dir.join(format!("{version}.bin")), + dir.join(format!("{version}.type")), + ) +} + +/// Reads a cached photo. A missing or incomplete entry is `None`, and the photo is fetched again. +async fn read_cache(photo_dir: &Path, sub: &str, version: i64) -> Option<(&'static str, Vec)> { + let (bytes_path, type_path) = cache_paths(photo_dir, sub, version); + let content_type = allowed_type(&tokio::fs::read_to_string(type_path).await.ok()?)?; + let bytes = tokio::fs::read(bytes_path).await.ok()?; + Some((content_type, bytes)) +} + +/// Stores a photo in the cache: the type first, then the bytes, each through a temporary file and a +/// rename, so a reader never sees half of a photo. A failure is logged; the photo is still served. +async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &str, bytes: &[u8]) { + let (bytes_path, type_path) = cache_paths(photo_dir, sub, version); + let Some(dir) = bytes_path.parent() else { + return; + }; + let written = async { + tokio::fs::create_dir_all(dir).await?; + write_atomically(&type_path, content_type.as_bytes()).await?; + write_atomically(&bytes_path, bytes).await + } + .await; + if let Err(error) = written { + tracing::error!(error = %error, "photo: cannot write the cache"); + } +} + +/// Writes `bytes` to `path` through a sibling temporary file and a rename. +async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let temporary = path.with_extension("tmp"); + tokio::fs::write(&temporary, bytes).await?; + tokio::fs::rename(&temporary, path).await +} + +/// Fetches a photo from `im` with the service token. `Ok(None)` means `im` has no photo, or one of a +/// type or size that is not served. +async fn fetch_photo( + oidc: &OidcClient, + sub: &str, + version: i64, +) -> Result)>> { + let token = match oidc.service_token().await { + Ok(token) => token, + Err(error) => { + tracing::warn!(error = %error, "photo: no service token"); + return Err(unavailable()); + } + }; + let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer()); + let response = match oidc.http().get(url).bearer_auth(token).send().await { + Ok(response) => response, + Err(error) => { + tracing::warn!(error = %error, "photo: im could not be reached"); + return Err(unavailable()); + } + }; + match response.status() { + status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None), + status if !status.is_success() => { + tracing::warn!(status = %status, "photo: im refused the photo"); + return Err(unavailable()); + } + _ => {} + } + let content_type = response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .and_then(allowed_type); + let Some(content_type) = content_type else { + return Ok(None); + }; + if response + .content_length() + .is_some_and(|length| length > MAX_PHOTO_BYTES as u64) + { + return Ok(None); + } + let bytes = match response.bytes().await { + Ok(bytes) if bytes.len() <= MAX_PHOTO_BYTES => bytes.to_vec(), + Ok(_) => return Ok(None), + Err(error) => { + tracing::warn!(error = %error, "photo: the body could not be read"); + return Err(unavailable()); + } + }; + Ok(Some((content_type, bytes))) +} + +/// The error of a photo that cannot be had right now: `503` with a retry hint. +fn unavailable() -> topcoat::Error { + service_unavailable(PHOTO_RETRY_SECS).into() +} + +/// The answer that carries a photo: the bytes, the type, the version ETag, and the cache policy. +/// `private, no-cache` makes the browser ask again, and the ETag makes that ask cheap. +fn photo_answer(content_type: &'static str, etag: &str, bytes: Vec) -> PhotoAnswer { + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, HeaderValue::from_static(content_type)); + headers.insert( + http::header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert( + http::header::CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + if let Ok(value) = HeaderValue::from_str(etag) { + headers.insert(ETAG, value); + } + (StatusCode::OK, headers, bytes) +} + +/// `GET /avatar/{sub}`. +#[route(GET "/avatar/{sub}")] +async fn photo(cx: &Cx) -> Result { + let state = app_context::(cx); + let segments: Vec<&str> = uri(cx).path().split('/').collect(); + let sub = match segments.as_slice() { + ["", "people", sub, "photo"] if valid_sub(sub) => *sub, + _ => return Err(not_found().into()), + }; + if current_member(cx).await?.is_none() { + return Err(not_found().into()); + } + let Some(member) = state.store.member(sub).await? else { + return Err(not_found().into()); + }; + let version = member.picture_version; + let etag = format!("\"p{version}\""); + if headers(cx) + .get(IF_NONE_MATCH) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value == etag) + { + let mut headers = HeaderMap::new(); + if let Ok(value) = HeaderValue::from_str(&etag) { + headers.insert(ETAG, value); + } + headers.insert( + http::header::CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); + } + + let photo_dir = state.config.data_dir.join(PHOTO_DIR); + if let Some((content_type, bytes)) = read_cache(&photo_dir, sub, version).await { + return Ok(photo_answer(content_type, &etag, bytes)); + } + let Some(oidc) = state.oidc.as_ref() else { + return Err(unavailable()); + }; + let Some((content_type, bytes)) = fetch_photo(oidc, sub, version).await? else { + return Err(not_found().into()); + }; + write_cache(&photo_dir, sub, version, content_type, &bytes).await; + Ok(photo_answer(content_type, &etag, bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_allowlisted_image_types_are_served() { + assert_eq!( + allowed_type("image/jpeg; charset=binary"), + Some("image/jpeg") + ); + assert_eq!(allowed_type("IMAGE/PNG"), Some("image/png")); + assert_eq!(allowed_type("image/svg+xml"), None); + assert_eq!(allowed_type("text/html"), None); + assert_eq!(allowed_type(""), None); + } + + #[test] + fn subjects_are_plain_identifiers() { + assert!(valid_sub("01JABCDEF0123456789ABCDEFG")); + assert!(!valid_sub("../etc")); + assert!(!valid_sub("")); + } +} diff --git a/crates/in-web/src/pages/sign_in.rs b/crates/in-web/src/pages/sign_in.rs new file mode 100644 index 0000000..da3f3e0 --- /dev/null +++ b/crates/in-web/src/pages/sign_in.rs @@ -0,0 +1,385 @@ +//! The sign-in pages: `/auth/login` starts sign-in, `/auth/callback` finishes it, `/auth/logout` ends the local +//! session and the `im` session, and `/sign-in/problem` explains a sign-in that did not finish. +//! +//! The flow is contracts section 2.3. The state of a sign-in in progress (the state, nonce, PKCE verifier +//! and the safe `next` target) lives in one sealed cookie, `__Host-in_flight`, for ten minutes. It is cleared +//! on every outcome, so it is single use. After the callback the local session is created (section 2.4). +//! Failures redirect to the problem page with a fixed reason word; no text from the request is reflected. + +use std::sync::Arc; +use std::time::Duration; + +use http::header::USER_AGENT; +use in_core::error::{Error as CoreError, Result as CoreResult}; +use in_core::quota::DEFAULT_MEMBER_QUOTA; +use in_core::secret; +use in_core::store::members::MemberFields; +use in_core::store::sessions::NewSession; +use in_core::time::stamp_after; +use in_core::token::{constant_time_eq, generate_token, hash_token}; +use serde::{Deserialize, Serialize}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, forbidden, see_other}; +use topcoat::router::page; +use topcoat::router::request::{client_ip, headers}; +use topcoat::router::{StatusCode, route}; +use topcoat::view::{View, view}; + +use crate::auth::{ + FLIGHT_COOKIE, FLIGHT_TTL, SESSION_COOKIE, SESSION_TTL, cookie_value, csrf_matches, + current_session, next_or_home, set_cookie, +}; +use crate::i18n::lang; +use crate::i18n::shell::{K, t}; +use crate::oidc::{OidcClient, OidcError, now_secs, pkce_challenge}; +use crate::state::AppState; +use crate::views::shell; + +/// The reason word for a sign-in that did not finish: a refusal, a bad state, an expired flight. +const REASON_FAILED: &str = "failed"; +/// The reason word for `im` being unreachable. +const REASON_UNAVAILABLE: &str = "unavailable"; +/// The reason word for an account that may not sign in. +const REASON_DENIED: &str = "denied"; + +/// The longest User-Agent kept with a session. Longer values are cut. +const MAX_USER_AGENT_CHARS: usize = 256; + +/// The query of `/auth/login`. An absent or empty `next` means the start page. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct LoginQuery { + next: String, +} + +/// The query of `/auth/callback`, as `im` sends it. Only the fields `in` reads are named. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct CallbackQuery { + code: String, + state: String, + error: String, +} + +/// The form of `/auth/logout`: the CSRF token of the session. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct LogoutForm { + csrf: String, +} + +/// The sealed content of the flight cookie. +#[derive(Debug, Serialize, Deserialize)] +struct Flight { + state: String, + nonce: String, + verifier: String, + next: String, + /// When the flight stops being valid, in Unix seconds. + expires_at: i64, +} + +/// Redirects to the problem page with one of the fixed reason words. +fn problem(reason: &str) -> SeeOther { + see_other(format!("/sign-in/problem?reason={reason}")) +} + +/// The problem a failed call to `im` leads to: unreachable is its own page, anything else is a +/// sign-in that did not finish. +fn problem_for(error: &OidcError) -> SeeOther { + match error { + OidcError::Unavailable(_) => problem(REASON_UNAVAILABLE), + OidcError::Token(_) | OidcError::Refused => problem(REASON_FAILED), + } +} + +/// The client, when the configuration has one. +fn client(state: &AppState) -> Option> { + state.oidc.clone() +} + +/// Seals `bytes` with the instance key. +fn seal(state: &AppState, bytes: &[u8]) -> CoreResult { + secret::seal(&state.key, bytes) +} + +/// Opens a sealed value. Any failure reads as "not there", which the callers treat as a refusal. +fn open(state: &AppState, sealed: &str) -> Option> { + secret::open(&state.key, sealed).ok() +} + +/// Reads the flight cookie. An unreadable, malformed or expired flight is `None`. +fn read_flight(state: &AppState, sealed: &str) -> Option { + let bytes = open(state, sealed)?; + let flight: Flight = serde_json::from_slice(&bytes).ok()?; + (flight.expires_at > now_secs()).then_some(flight) +} + +/// `GET /auth/login?next=`. Creates the flight, then sends the browser to `im` to sign in. +#[route(GET "/auth/login")] +async fn login(cx: &Cx, query: Option>) -> Result { + let state = app_context::(cx); + let Some(oidc) = client(state) else { + return Ok(problem(REASON_UNAVAILABLE)); + }; + let requested = query.map(|Form(query)| query.next).unwrap_or_default(); + let flight = Flight { + state: generate_token(), + nonce: generate_token(), + verifier: generate_token(), + next: next_or_home(&requested), + expires_at: now_secs() + i64::try_from(FLIGHT_TTL.as_secs()).unwrap_or(0), + }; + let url = match oidc + .authorize_url( + &flight.state, + &flight.nonce, + &pkce_challenge(&flight.verifier), + ) + .await + { + Ok(url) => url, + Err(error) => { + tracing::warn!(error = %error, "sign-in: cannot start the flow"); + return Ok(problem(REASON_UNAVAILABLE)); + } + }; + let bytes = serde_json::to_vec(&flight).map_err(|e| CoreError::Crypto(e.to_string()))?; + set_cookie(cx, FLIGHT_COOKIE, seal(state, &bytes)?, FLIGHT_TTL); + Ok(see_other(url)) +} + +/// `GET /auth/callback`. Checks the state, exchanges the code, verifies the ID token, records the member +/// and starts the local session. +#[route(GET "/auth/callback")] +async fn callback(cx: &Cx, query: Option>) -> Result { + let state = app_context::(cx); + let sealed_flight = cookie_value(cx, FLIGHT_COOKIE); + // The flight is single use. It is cleared whatever the outcome. + set_cookie(cx, FLIGHT_COOKIE, String::new(), Duration::ZERO); + + let query = query.map(|Form(query)| query).unwrap_or_default(); + // `im` reported an error. Its text is not shown or reflected; the reason word is fixed. + if !query.error.is_empty() { + return Ok(problem(REASON_FAILED)); + } + let Some(oidc) = client(state) else { + return Ok(problem(REASON_UNAVAILABLE)); + }; + let Some(flight) = sealed_flight.and_then(|sealed| read_flight(state, &sealed)) else { + return Ok(problem(REASON_FAILED)); + }; + if query.code.is_empty() || !constant_time_eq(query.state.as_bytes(), flight.state.as_bytes()) { + return Ok(problem(REASON_FAILED)); + } + + let id_token = match oidc.exchange_code(&query.code, &flight.verifier).await { + Ok(token) => token, + Err(error) => return Ok(problem_for(&error)), + }; + let claims = match oidc.verify_id_token(&id_token, &flight.nonce).await { + Ok(claims) => claims, + Err(error) => return Ok(problem_for(&error)), + }; + + let member = state + .store + .upsert_member_from_claims( + &MemberFields { + sub: claims.sub.clone(), + email: claims.email, + name: claims.name, + is_admin: claims.admin, + locale: claims.locale, + zoneinfo: claims.zoneinfo, + picture_version: claims.picture_version, + // Sign-in claims carry no directory timestamp, so the store uses the sign-in time. + im_updated_at: String::new(), + }, + DEFAULT_MEMBER_QUOTA, + ) + .await?; + if member.disabled { + return Ok(problem(REASON_DENIED)); + } + + // A new sign-in replaces the session it started from, so an old token cannot stay alive. + if let Some(old) = cookie_value(cx, SESSION_COOKIE) + && let Some(session) = state.store.session_by_token_hash(&hash_token(&old)).await? + { + state.store.delete_session(&session.id).await?; + } + + let token = generate_token(); + let id_token_sealed = seal(state, id_token.as_bytes())?; + let user_agent = headers(cx) + .get(USER_AGENT) + .and_then(|value| value.to_str().ok()) + .map(|value| value.chars().take(MAX_USER_AGENT_CHARS).collect()); + state + .store + .create_session(NewSession { + sub: claims.sub, + token_hash: hash_token(&token), + csrf_token: generate_token(), + im_sid: claims.sid, + expires_at: stamp_after(SESSION_TTL), + ip: client_ip(cx).map(|ip| ip.to_string()), + user_agent, + id_token_sealed: Some(id_token_sealed), + }) + .await?; + set_cookie(cx, SESSION_COOKIE, token, SESSION_TTL); + Ok(see_other(next_or_home(&flight.next))) +} + +/// `POST /auth/logout`. Ends the local session, then ends the `im` session with RP-initiated logout. +/// +/// Without a session there is nothing to end, so the answer is the start page. A session with a missing +/// or wrong CSRF token is refused with `403` before anything changes. +#[route(POST "/auth/logout")] +async fn logout(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let Some(session) = current_session(cx).await? else { + set_cookie(cx, SESSION_COOKIE, String::new(), Duration::ZERO); + return Ok(see_other("/")); + }; + if !csrf_matches(&session, &form.csrf) { + return Err(forbidden().into()); + } + state.store.delete_session(&session.id).await?; + set_cookie(cx, SESSION_COOKIE, String::new(), Duration::ZERO); + + let hint = session + .id_token_sealed + .as_deref() + .and_then(|sealed| open(state, sealed)) + .and_then(|bytes| String::from_utf8(bytes).ok()); + let (Some(oidc), Some(hint)) = (client(state), hint) else { + return Ok(see_other("/")); + }; + let post_logout = format!("{}/", state.config.base_url); + match oidc + .end_session_url(&hint, &post_logout, &generate_token()) + .await + { + Ok(url) => Ok(see_other(url)), + Err(error) => { + tracing::warn!(error = %error, "logout: cannot build the im logout URL"); + Ok(see_other("/")) + } + } +} + +/// The query of the problem page. The reason is matched against the fixed words; anything else is a +/// failed sign-in. +#[topcoat::router::query_params] +pub struct ProblemQuery { + /// One of the reason words above. + pub reason: Option, +} + +/// `GET /sign-in/problem?reason=`. Explains a sign-in that did not finish, with a way back. +#[page("/sign-in/problem")] +async fn problem_page(cx: &Cx) -> Result { + let lang = lang(cx, None); + let reason = topcoat::router::query_params::(cx) + .ok() + .and_then(|query| query.reason.as_deref()) + .unwrap_or(REASON_FAILED); + let (status, title, body) = match reason { + REASON_UNAVAILABLE => ( + StatusCode::SERVICE_UNAVAILABLE, + K::ProblemUnavailableTitle, + K::ProblemUnavailableBody, + ), + REASON_DENIED => ( + StatusCode::FORBIDDEN, + K::ProblemDeniedTitle, + K::ProblemDeniedBody, + ), + _ => ( + StatusCode::BAD_REQUEST, + K::ProblemFailedTitle, + K::ProblemFailedBody, + ), + }; + Ok(view! { + (status) + shell(title: t(lang, title), lang: lang, viewer: None, +
+

"in"

+

(t(lang, title))

+

(t(lang, body))

+ (t(lang, K::BackHome)) +
+ ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::{CONTENT_TYPE, COOKIE}; + use in_core::store::members::MemberFields; + use topcoat::router::Body; + + #[tokio::test] + async fn logout_without_the_csrf_token_is_refused_and_ends_nothing() { + let (_dir, state) = test_state().await; + state + .store + .upsert_member_from_claims( + &MemberFields { + sub: "01JANN".into(), + email: "ann@example.test".into(), + name: "Ann".into(), + is_admin: false, + locale: "en".into(), + zoneinfo: "UTC".into(), + picture_version: 0, + im_updated_at: String::new(), + }, + DEFAULT_MEMBER_QUOTA, + ) + .await + .expect("member"); + let token = "session-token-for-the-test"; + state + .store + .create_session(NewSession { + sub: "01JANN".into(), + token_hash: hash_token(token), + csrf_token: "the-real-csrf-token".into(), + im_sid: "im-session".into(), + expires_at: stamp_after(SESSION_TTL), + ip: None, + user_agent: None, + id_token_sealed: None, + }) + .await + .expect("session"); + + let request = Request::post("/auth/logout") + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from("")) + .expect("request"); + let response = router(state.clone()).handle(request).await; + + assert_eq!(response.status(), 403); + assert!( + state + .store + .session_by_token_hash(&hash_token(token)) + .await + .expect("lookup") + .is_some(), + "a refused logout must leave the session alone" + ); + } +} diff --git a/crates/in-web/src/state.rs b/crates/in-web/src/state.rs index db45074..1f45e2b 100644 --- a/crates/in-web/src/state.rs +++ b/crates/in-web/src/state.rs @@ -7,9 +7,10 @@ use in_core::config::Config; use in_core::store::Store; use crate::live::LiveHub; +use crate::oidc::OidcClient; /// Everything a request handler reaches through the app context. Every field is cheap to clone. -#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. +#[allow(dead_code)] // The live hub is read by the live pages, which come after sign-in. #[derive(Clone)] pub struct AppState { /// The configuration the process booted with. @@ -22,4 +23,7 @@ pub struct AppState { pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, + /// The OpenID Connect client of `im`. `None` when the configuration has no `[oidc]` table, in which + /// case nobody can sign in and the sign-in routes say so. + pub oidc: Option>, } diff --git a/crates/in-web/src/views/mod.rs b/crates/in-web/src/views/mod.rs index f28f490..a8d50df 100644 --- a/crates/in-web/src/views/mod.rs +++ b/crates/in-web/src/views/mod.rs @@ -10,21 +10,23 @@ use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; use crate::i18n::Lang; use crate::i18n::shell::{K, t}; -/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page -/// is built for an anonymous viewer. -#[allow(dead_code)] // Built by the sign-in code, which comes next. +/// What the shell shows about the signed-in person: the name, the administrator badge, and the CSRF +/// token of the session for the sign-out form. pub struct ViewerInfo { /// The name shown in the topbar. pub name: String, /// Whether the topbar shows the administrator badge. pub is_admin: bool, + /// The session's CSRF token, which the sign-out form sends. + pub csrf: String, } /// The HTML document around a page. `title` is the page's own title; the document title adds the /// app name. `child` is the page, placed in `
`. /// /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and -/// the viewer's name on the right. `nav.js` reads the restart text from ``. +/// the viewer's user menu on the right. The menu's sign-out form opts out of soft navigation, because +/// it ends in a redirect to `im`. `nav.js` reads the restart text from ``. #[component] pub async fn shell( title: &str, @@ -51,7 +53,13 @@ pub async fn shell(
if let Some(viewer) = viewer { - (viewer.name.as_str()) +
+ (viewer.name.as_str()) +
+ + +
+
if viewer.is_admin { (t(lang, K::Admin)) }