From 379e97c2cb145bc3a495aa14746273d83b508214 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Sat, 19 Oct 2024 01:51:30 -0400 Subject: Unicode normalization on input. This normalizes the following values: * login names * passwords * channel names * message bodies, because why not The goal here is to have a canonical representation of these values, so that, for example, the service does not inadvertently host two channels whose names are semantically identical but differ in the specifics of how diacritics are encoded, or two users whose names are identical. Normalization is done on input from the wire, using Serde hooks, and when reading from the database. The `crate::nfc::String` type implements these normalizations (as well as normalizing whenever converted from a `std::string::String` generally). This change does not cover: * Trying to cope with passwords that were created as non-normalized strings, which are now non-verifiable as all the paths to verify passwords normalize the input. * Trying to ensure that non-normalized data in the database compares reasonably to normalized data. Fortunately, we don't _do_ very many string comparisons (I think only login names), so this isn't a huge deal at this stage. Login names will probably have to Get Fixed later on, when we figure out how to handle case folding for login name verification. --- src/message/app.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/message/app.rs') diff --git a/src/message/app.rs b/src/message/app.rs index 4e50513..af87553 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -2,7 +2,7 @@ use chrono::TimeDelta; use itertools::Itertools; use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Id, Message}; +use super::{repo::Provider as _, Body, Id, Message}; use crate::{ channel::{self, repo::Provider as _}, clock::DateTime, @@ -26,7 +26,7 @@ impl<'a> Messages<'a> { channel: &channel::Id, sender: &Login, sent_at: &DateTime, - body: &str, + body: &Body, ) -> Result { let mut tx = self.db.begin().await?; let channel = tx -- cgit v1.2.3 From 3f9648eed48cd8b6cd35d0ae2ee5bbe25fa735ac Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Mon, 21 Oct 2024 00:36:44 -0400 Subject: Canonicalize login and channel names. Canonicalization does two things: * It prevents duplicate names that differ only by case or only by normalization/encoding sequence; and * It makes certain name-based comparisons "case-insensitive" (generalizing via Unicode's case-folding rules). This change is complicated, as it means that every name now needs to be stored in two forms. Unfortunately, this is _very likely_ a breaking schema change. The migrations in this commit perform a best-effort attempt to canonicalize existing channel or login names, but it's likely any existing channels or logins with non-ASCII characters will not be canonicalize correctly. Since clients look at all channel names and all login names on boot, and since the code in this commit verifies canonicalization when reading from the database, this will effectively make the server un-usuable until any incorrectly-canonicalized values are either manually canonicalized, or removed It might be possible to do better with [the `icu` sqlite3 extension][icu], but (a) I'm not convinced of that and (b) this commit is already huge; adding database extension support would make it far larger. [icu]: https://sqlite.org/src/dir/ext/icu For some references on why it's worth storing usernames this way, see and the refernced talk, as well as . Bennett's treatment of this issue is, to my eye, much more readable than the referenced Unicode technical reports, and I'm inclined to trust his opinion given that he maintains a widely-used, internet-facing user registration library for Django. --- ...a9eb3578281dc70941faf05d53f8525034446ae52f.json | 50 ----- ...8ec70ecce6408cb241c9ac5f76bb484b214e720cb9.json | 56 ++++++ ...f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json | 12 ++ ...b0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c.json | 44 +++++ ...61b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e.json | 32 ---- ...cf421524e41055cddf76dd4e4016142f61e0a4903f.json | 12 ++ ...2e34ec512dfc9109b338eea475c209e5a005ae20c6.json | 50 ----- ...b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json | 12 ++ ...7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json | 26 +++ ...65327d32a68f41258a27249027f9200b2bbba047cb.json | 50 ----- ...72b013b1ac76a28471e63d0492132b9c12c63a1f9c.json | 12 -- ...0717bf42e5d43b041acb198710e75417ac40991ec6.json | 50 +++++ ...eb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659.json | 38 ---- ...f05ffc52cb1712545ff539df49bbd47df194012f79.json | 56 ++++++ ...c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json | 56 ++++++ ...4730699683e63ae1ea404418a17c6af60148f03fe8.json | 44 +++++ ...314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json | 20 -- ...90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e.json | 44 ----- ...d188879a394d36e66f90edb27d2665f081ff95087f.json | 44 +++++ ...bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87.json | 20 -- ...ae5ca13b72436960622863420d3f1d73a422fe5b42.json | 12 ++ ...3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f.json | 38 ---- ...c19a4eed48252247f15a046098d63359c6d9047c9a.json | 38 ---- ...ebb2c0efd1c5718e721fe906765c28d040e446acd7.json | 38 ---- ...79ae0758568f732d837c923cfe1b142181fb5d83f3.json | 38 ---- ...ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6.json | 50 ----- ...5518d6364c8dbfdb45f205fecf0734fe272be493b0.json | 12 ++ ...6c38657da87439340801d0765f8d9f64f8fbbbfb6b.json | 38 ++++ ...5010f2f77b943ec225244fcfc24013b12a48084a1e.json | 56 ++++++ Cargo.lock | 7 + Cargo.toml | 1 + docs/api/authentication.md | 19 +- docs/api/channels-messages.md | 12 ++ migrations/20241019191531_canonical_names.sql | 189 ++++++++++++++++++ src/boot/app.rs | 34 +++- src/channel/app.rs | 49 ++++- src/channel/mod.rs | 5 +- src/channel/name.rs | 30 --- src/channel/repo.rs | 212 +++++++++++++-------- src/channel/routes/post.rs | 3 +- src/channel/snapshot.rs | 4 +- src/db/mod.rs | 15 +- src/event/app.rs | 30 ++- src/event/routes/get.rs | 4 +- src/invite/app.rs | 3 +- src/invite/mod.rs | 4 +- src/invite/repo.rs | 3 +- src/invite/routes/invite/post.rs | 3 +- src/lib.rs | 3 +- src/login/app.rs | 3 +- src/login/mod.rs | 4 +- src/login/name.rs | 28 --- src/login/password.rs | 2 +- src/login/repo.rs | 98 +++++----- src/login/routes/login/post.rs | 3 +- src/login/routes/logout/test.rs | 1 - src/login/snapshot.rs | 3 +- src/message/app.rs | 13 ++ src/message/body.rs | 2 +- src/name.rs | 85 +++++++++ src/nfc.rs | 103 ---------- src/normalize/mod.rs | 36 ++++ src/normalize/string.rs | 112 +++++++++++ src/setup/app.rs | 3 +- src/setup/routes/post.rs | 3 +- src/test/fixtures/channel.rs | 3 +- src/test/fixtures/login.rs | 3 +- src/token/app.rs | 37 +++- src/token/repo/auth.rs | 68 ++++--- src/token/repo/mod.rs | 2 +- src/token/repo/token.rs | 68 +++++-- 71 files changed, 1463 insertions(+), 895 deletions(-) delete mode 100644 .sqlx/query-0caf898537dd38eea00322a9eb3578281dc70941faf05d53f8525034446ae52f.json create mode 100644 .sqlx/query-10a8d7ebb8a228c297f38e8ec70ecce6408cb241c9ac5f76bb484b214e720cb9.json create mode 100644 .sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json create mode 100644 .sqlx/query-2f4def5e6aa14d9bc4ca5db0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c.json delete mode 100644 .sqlx/query-4392eb4ec7257676acdce461b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e.json create mode 100644 .sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json delete mode 100644 .sqlx/query-48884b1c153cbf6e10eed72e34ec512dfc9109b338eea475c209e5a005ae20c6.json create mode 100644 .sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json create mode 100644 .sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json delete mode 100644 .sqlx/query-7f5bbd935941210ba2f25e65327d32a68f41258a27249027f9200b2bbba047cb.json delete mode 100644 .sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json create mode 100644 .sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json delete mode 100644 .sqlx/query-91df35ca0c610b05fb353eeb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659.json create mode 100644 .sqlx/query-947df87da285e68a710443f05ffc52cb1712545ff539df49bbd47df194012f79.json create mode 100644 .sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json create mode 100644 .sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json delete mode 100644 .sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json delete mode 100644 .sqlx/query-be33d1fb2f71093ed73efd90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e.json create mode 100644 .sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json delete mode 100644 .sqlx/query-c83af5b462071927d05664bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87.json create mode 100644 .sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json delete mode 100644 .sqlx/query-d693a55bf9394ea79a892c3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f.json delete mode 100644 .sqlx/query-d9c772a28d1b5b2ca3b0a2c19a4eed48252247f15a046098d63359c6d9047c9a.json delete mode 100644 .sqlx/query-db77e97937167d1edbbe88ebb2c0efd1c5718e721fe906765c28d040e446acd7.json delete mode 100644 .sqlx/query-dbbc785bc45173db773f9179ae0758568f732d837c923cfe1b142181fb5d83f3.json delete mode 100644 .sqlx/query-dd613246fc1e87039f0a12ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6.json create mode 100644 .sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json create mode 100644 .sqlx/query-e06cbe45408d593a081b566c38657da87439340801d0765f8d9f64f8fbbbfb6b.json create mode 100644 .sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json create mode 100644 migrations/20241019191531_canonical_names.sql delete mode 100644 src/channel/name.rs delete mode 100644 src/login/name.rs create mode 100644 src/name.rs delete mode 100644 src/nfc.rs create mode 100644 src/normalize/mod.rs create mode 100644 src/normalize/string.rs (limited to 'src/message/app.rs') diff --git a/.sqlx/query-0caf898537dd38eea00322a9eb3578281dc70941faf05d53f8525034446ae52f.json b/.sqlx/query-0caf898537dd38eea00322a9eb3578281dc70941faf05d53f8525034446ae52f.json deleted file mode 100644 index 8990436..0000000 --- a/.sqlx/query-0caf898537dd38eea00322a9eb3578281dc70941faf05d53f8525034446ae52f.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n channel.name as \"name: Name\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence <= $1, true)\n order by channel.name\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - }, - { - "name": "deleted_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "deleted_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - true, - false, - false, - true, - true - ] - }, - "hash": "0caf898537dd38eea00322a9eb3578281dc70941faf05d53f8525034446ae52f" -} diff --git a/.sqlx/query-10a8d7ebb8a228c297f38e8ec70ecce6408cb241c9ac5f76bb484b214e720cb9.json b/.sqlx/query-10a8d7ebb8a228c297f38e8ec70ecce6408cb241c9ac5f76bb484b214e720cb9.json new file mode 100644 index 0000000..f8dd228 --- /dev/null +++ b/.sqlx/query-10a8d7ebb8a228c297f38e8ec70ecce6408cb241c9ac5f76bb484b214e720cb9.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n channel.id as \"id: Id\",\n name.display_name as \"display_name: String\",\n name.canonical_name as \"canonical_name: String\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n left join message\n on channel.id = message.channel\n where channel.created_at < $1\n and message.id is null\n and deleted.id is null\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Null" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Null" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + true, + true, + false, + false, + true, + true + ] + }, + "hash": "10a8d7ebb8a228c297f38e8ec70ecce6408cb241c9ac5f76bb484b214e720cb9" +} diff --git a/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json b/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json new file mode 100644 index 0000000..2de9614 --- /dev/null +++ b/.sqlx/query-2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "2773f12ef58c251596dd00f0bd048975fb06f090a11622cc74ced47a3d7ad44a" +} diff --git a/.sqlx/query-2f4def5e6aa14d9bc4ca5db0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c.json b/.sqlx/query-2f4def5e6aa14d9bc4ca5db0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c.json new file mode 100644 index 0000000..c1da170 --- /dev/null +++ b/.sqlx/query-2f4def5e6aa14d9bc4ca5db0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c.json @@ -0,0 +1,44 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(created_sequence <= $1, true)\n order by created_sequence\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "2f4def5e6aa14d9bc4ca5db0d1f81953cd5f584b76ca59ece17d9ef2ce29ee9c" +} diff --git a/.sqlx/query-4392eb4ec7257676acdce461b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e.json b/.sqlx/query-4392eb4ec7257676acdce461b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e.json deleted file mode 100644 index 1dd685b..0000000 --- a/.sqlx/query-4392eb4ec7257676acdce461b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n token.id as \"token_id: Id\",\n login.id as \"login_id: login::Id\",\n login.name as \"login_name: Name\"\n from login\n join token on login.id = token.login\n where token.secret = $1\n ", - "describe": { - "columns": [ - { - "name": "token_id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "login_id: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "login_name: Name", - "ordinal": 2, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false - ] - }, - "hash": "4392eb4ec7257676acdce461b3bd7892ca01c2e3a2e0b1abfd8d7a57cbbf265e" -} diff --git a/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json b/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json new file mode 100644 index 0000000..ebddeb8 --- /dev/null +++ b/.sqlx/query-454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n delete from channel_name\n where id = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "454ca70caa83eee2dac585cf421524e41055cddf76dd4e4016142f61e0a4903f" +} diff --git a/.sqlx/query-48884b1c153cbf6e10eed72e34ec512dfc9109b338eea475c209e5a005ae20c6.json b/.sqlx/query-48884b1c153cbf6e10eed72e34ec512dfc9109b338eea475c209e5a005ae20c6.json deleted file mode 100644 index b8d7303..0000000 --- a/.sqlx/query-48884b1c153cbf6e10eed72e34ec512dfc9109b338eea475c209e5a005ae20c6.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n channel.name as \"name: Name\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where id = $1\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - }, - { - "name": "deleted_at?: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "deleted_sequence?: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - true, - false, - false, - false, - false - ] - }, - "hash": "48884b1c153cbf6e10eed72e34ec512dfc9109b338eea475c209e5a005ae20c6" -} diff --git a/.sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json b/.sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json new file mode 100644 index 0000000..8962098 --- /dev/null +++ b/.sqlx/query-4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert into channel_name (id, display_name, canonical_name)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "4c27c8f7ed9b6315433dc2b5f787a61d82693fe0426b46f9971fcde5e44f38b0" +} diff --git a/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json b/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json new file mode 100644 index 0000000..93a4093 --- /dev/null +++ b/.sqlx/query-6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91.json @@ -0,0 +1,26 @@ +{ + "db_name": "SQLite", + "query": "\n update token\n set last_used_at = $1\n where secret = $2\n returning\n id as \"token: Id\",\n login as \"login: login::Id\"\n ", + "describe": { + "columns": [ + { + "name": "token: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "login: login::Id", + "ordinal": 1, + "type_info": "Text" + } + ], + "parameters": { + "Right": 2 + }, + "nullable": [ + false, + false + ] + }, + "hash": "6d34d8232e7247155c697f7ef7a26f6b14e1d30c3fb44ece8fb149c92317fa91" +} diff --git a/.sqlx/query-7f5bbd935941210ba2f25e65327d32a68f41258a27249027f9200b2bbba047cb.json b/.sqlx/query-7f5bbd935941210ba2f25e65327d32a68f41258a27249027f9200b2bbba047cb.json deleted file mode 100644 index 83e730d..0000000 --- a/.sqlx/query-7f5bbd935941210ba2f25e65327d32a68f41258a27249027f9200b2bbba047cb.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n channel.id as \"id: Id\",\n channel.name as \"name: Name\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n left join message\n where channel.created_at < $1\n and message.id is null\n and deleted.id is null\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - }, - { - "name": "deleted_at?: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "deleted_sequence?: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - true, - false, - false, - false, - false - ] - }, - "hash": "7f5bbd935941210ba2f25e65327d32a68f41258a27249027f9200b2bbba047cb" -} diff --git a/.sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json b/.sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json deleted file mode 100644 index edd3825..0000000 --- a/.sqlx/query-873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n update token\n set last_used_at = $1\n where secret = $2\n ", - "describe": { - "columns": [], - "parameters": { - "Right": 2 - }, - "nullable": [] - }, - "hash": "873b8b58360d717ea2099272b013b1ac76a28471e63d0492132b9c12c63a1f9c" -} diff --git a/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json b/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json new file mode 100644 index 0000000..cf1afec --- /dev/null +++ b/.sqlx/query-903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6.json @@ -0,0 +1,50 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: login::Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\",\n password_hash as \"password_hash: StoredHash\"\n from login\n where canonical_name = $1\n ", + "describe": { + "columns": [ + { + "name": "id: login::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + }, + { + "name": "password_hash: StoredHash", + "ordinal": 5, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "903e7ec4fafd5ce124a0e40717bf42e5d43b041acb198710e75417ac40991ec6" +} diff --git a/.sqlx/query-91df35ca0c610b05fb353eeb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659.json b/.sqlx/query-91df35ca0c610b05fb353eeb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659.json deleted file mode 100644 index 6d2cb52..0000000 --- a/.sqlx/query-91df35ca0c610b05fb353eeb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name as \"name: Name\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(created_sequence <= $1, true)\n order by created_sequence\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "91df35ca0c610b05fb353eeb7b7ef2f4fca0cd1c43ef45f32c9ce069d37fe659" -} diff --git a/.sqlx/query-947df87da285e68a710443f05ffc52cb1712545ff539df49bbd47df194012f79.json b/.sqlx/query-947df87da285e68a710443f05ffc52cb1712545ff539df49bbd47df194012f79.json new file mode 100644 index 0000000..d4bb122 --- /dev/null +++ b/.sqlx/query-947df87da285e68a710443f05ffc52cb1712545ff539df49bbd47df194012f79.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name: String\",\n name.canonical_name as \"canonical_name: String\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence <= $1, true)\n order by name.canonical_name\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + true, + true, + false, + false, + true, + true + ] + }, + "hash": "947df87da285e68a710443f05ffc52cb1712545ff539df49bbd47df194012f79" +} diff --git a/.sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json b/.sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json new file mode 100644 index 0000000..647e5ad --- /dev/null +++ b/.sqlx/query-a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name: String\",\n name.canonical_name as \"canonical_name: String\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence > $1, true)\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + true, + true, + false, + false, + true, + true + ] + }, + "hash": "a40496319887752f5845c0c2e965e2294c1a6932d72a8b04d258d06d0f8938bd" +} diff --git a/.sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json b/.sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json new file mode 100644 index 0000000..7d9bbbc --- /dev/null +++ b/.sqlx/query-ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8.json @@ -0,0 +1,44 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(login.created_sequence > $1, true)\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "ac7ab464e44e4412cd83744730699683e63ae1ea404418a17c6af60148f03fe8" +} diff --git a/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json b/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json deleted file mode 100644 index 5825ce8..0000000 --- a/.sqlx/query-b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n insert into channel_deleted (id, deleted_at, deleted_sequence)\n values ($1, $2, $3)\n returning 1 as \"deleted: bool\"\n ", - "describe": { - "columns": [ - { - "name": "deleted: bool", - "ordinal": 0, - "type_info": "Null" - } - ], - "parameters": { - "Right": 3 - }, - "nullable": [ - null - ] - }, - "hash": "b1ba724a62135a6fbcb7ad314ba09dbe4e42fd49b2007e47bcfb07b5ba9001b0" -} diff --git a/.sqlx/query-be33d1fb2f71093ed73efd90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e.json b/.sqlx/query-be33d1fb2f71093ed73efd90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e.json deleted file mode 100644 index 4b69943..0000000 --- a/.sqlx/query-be33d1fb2f71093ed73efd90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n\t\t\t\tselect\n\t\t\t\t\tid as \"id: login::Id\",\n\t\t\t\t\tname as \"name: Name\",\n\t\t\t\t\tpassword_hash as \"password_hash: StoredHash\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n\t\t\t\tfrom login\n\t\t\t\twhere name = $1\n\t\t\t", - "describe": { - "columns": [ - { - "name": "id: login::Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "password_hash: StoredHash", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 4, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false, - false - ] - }, - "hash": "be33d1fb2f71093ed73efd90c8d4dfe599c70b36607a5dc436f28ba5b2ea9b2e" -} diff --git a/.sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json b/.sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json new file mode 100644 index 0000000..aa20875 --- /dev/null +++ b/.sqlx/query-c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f.json @@ -0,0 +1,44 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: login::Id\",\n display_name as \"display_name: String\",\n canonical_name as \"canonical_name: String\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where id = $1\n ", + "describe": { + "columns": [ + { + "name": "id: login::Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name: String", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "canonical_name: String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 3, + "type_info": "Integer" + }, + { + "name": "created_at: DateTime", + "ordinal": 4, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "c31c02aa8c4e615c463835d188879a394d36e66f90edb27d2665f081ff95087f" +} diff --git a/.sqlx/query-c83af5b462071927d05664bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87.json b/.sqlx/query-c83af5b462071927d05664bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87.json deleted file mode 100644 index 01bb071..0000000 --- a/.sqlx/query-c83af5b462071927d05664bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n update channel\n set name = null\n where id = $1\n returning 1 as \"updated: bool\"\n ", - "describe": { - "columns": [ - { - "name": "updated: bool", - "ordinal": 0, - "type_info": "Null" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - null - ] - }, - "hash": "c83af5b462071927d05664bb69067dd15b2e7602aafcfaf04aa1f41e118a1f87" -} diff --git a/.sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json b/.sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json new file mode 100644 index 0000000..658728c --- /dev/null +++ b/.sqlx/query-d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert\n into channel (id, created_at, created_sequence)\n values ($1, $2, $3)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 3 + }, + "nullable": [] + }, + "hash": "d1c869c323d1ab45216279ae5ca13b72436960622863420d3f1d73a422fe5b42" +} diff --git a/.sqlx/query-d693a55bf9394ea79a892c3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f.json b/.sqlx/query-d693a55bf9394ea79a892c3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f.json deleted file mode 100644 index 4291236..0000000 --- a/.sqlx/query-d693a55bf9394ea79a892c3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n insert\n into login (id, name, password_hash, created_sequence, created_at)\n values ($1, $2, $3, $4, $5)\n returning\n id as \"id: Id\",\n name as \"name: Name\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 5 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "d693a55bf9394ea79a892c3a5ed7d651ce7c5b3c7e8960458af03f1b533e3b1f" -} diff --git a/.sqlx/query-d9c772a28d1b5b2ca3b0a2c19a4eed48252247f15a046098d63359c6d9047c9a.json b/.sqlx/query-d9c772a28d1b5b2ca3b0a2c19a4eed48252247f15a046098d63359c6d9047c9a.json deleted file mode 100644 index 39e9231..0000000 --- a/.sqlx/query-d9c772a28d1b5b2ca3b0a2c19a4eed48252247f15a046098d63359c6d9047c9a.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n\t\t\t\tselect\n invite.id as \"invite_id: Id\",\n\t\t\t\t\tissuer.id as \"issuer_id: login::Id\",\n\t\t\t\t\tissuer.name as \"issuer_name\",\n\t\t\t\t\tinvite.issued_at as \"invite_issued_at: DateTime\"\n\t\t\t\tfrom invite\n\t\t\t\tjoin login as issuer on (invite.issuer = issuer.id)\n\t\t\t\twhere invite.id = $1\n\t\t\t", - "describe": { - "columns": [ - { - "name": "invite_id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "issuer_id: login::Id", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "issuer_name", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "invite_issued_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "d9c772a28d1b5b2ca3b0a2c19a4eed48252247f15a046098d63359c6d9047c9a" -} diff --git a/.sqlx/query-db77e97937167d1edbbe88ebb2c0efd1c5718e721fe906765c28d040e446acd7.json b/.sqlx/query-db77e97937167d1edbbe88ebb2c0efd1c5718e721fe906765c28d040e446acd7.json deleted file mode 100644 index 0f2045f..0000000 --- a/.sqlx/query-db77e97937167d1edbbe88ebb2c0efd1c5718e721fe906765c28d040e446acd7.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n insert\n into channel (id, name, created_at, created_sequence)\n values ($1, $2, $3, $4)\n returning\n id as \"id: Id\",\n name as \"name!: Name\", -- known non-null as we just set it\n created_at as \"created_at: DateTime\",\n created_sequence as \"created_sequence: Sequence\"\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name!: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 4 - }, - "nullable": [ - false, - true, - false, - false - ] - }, - "hash": "db77e97937167d1edbbe88ebb2c0efd1c5718e721fe906765c28d040e446acd7" -} diff --git a/.sqlx/query-dbbc785bc45173db773f9179ae0758568f732d837c923cfe1b142181fb5d83f3.json b/.sqlx/query-dbbc785bc45173db773f9179ae0758568f732d837c923cfe1b142181fb5d83f3.json deleted file mode 100644 index 7b5ac51..0000000 --- a/.sqlx/query-dbbc785bc45173db773f9179ae0758568f732d837c923cfe1b142181fb5d83f3.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n name as \"name: Name\",\n created_sequence as \"created_sequence: Sequence\",\n created_at as \"created_at: DateTime\"\n from login\n where coalesce(login.created_sequence > $1, true)\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 2, - "type_info": "Integer" - }, - { - "name": "created_at: DateTime", - "ordinal": 3, - "type_info": "Text" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - false, - false, - false - ] - }, - "hash": "dbbc785bc45173db773f9179ae0758568f732d837c923cfe1b142181fb5d83f3" -} diff --git a/.sqlx/query-dd613246fc1e87039f0a12ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6.json b/.sqlx/query-dd613246fc1e87039f0a12ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6.json deleted file mode 100644 index fe8be3f..0000000 --- a/.sqlx/query-dd613246fc1e87039f0a12ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "db_name": "SQLite", - "query": "\n select\n id as \"id: Id\",\n channel.name as \"name: Name\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence: Sequence\"\n from channel\n left join channel_deleted as deleted\n using (id)\n where coalesce(channel.created_sequence > $1, true)\n ", - "describe": { - "columns": [ - { - "name": "id: Id", - "ordinal": 0, - "type_info": "Text" - }, - { - "name": "name: Name", - "ordinal": 1, - "type_info": "Text" - }, - { - "name": "created_at: DateTime", - "ordinal": 2, - "type_info": "Text" - }, - { - "name": "created_sequence: Sequence", - "ordinal": 3, - "type_info": "Integer" - }, - { - "name": "deleted_at: DateTime", - "ordinal": 4, - "type_info": "Text" - }, - { - "name": "deleted_sequence: Sequence", - "ordinal": 5, - "type_info": "Integer" - } - ], - "parameters": { - "Right": 1 - }, - "nullable": [ - false, - true, - false, - false, - true, - true - ] - }, - "hash": "dd613246fc1e87039f0a12ca8e2fa7c9cee66d2dfc3e516064982609cdcb3ff6" -} diff --git a/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json b/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json new file mode 100644 index 0000000..4efac0c --- /dev/null +++ b/.sqlx/query-e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "\n insert\n into login (id, display_name, canonical_name, password_hash, created_sequence, created_at)\n values ($1, $2, $3, $4, $5, $6)\n ", + "describe": { + "columns": [], + "parameters": { + "Right": 6 + }, + "nullable": [] + }, + "hash": "e01508e57cc9cecc83640a5518d6364c8dbfdb45f205fecf0734fe272be493b0" +} diff --git a/.sqlx/query-e06cbe45408d593a081b566c38657da87439340801d0765f8d9f64f8fbbbfb6b.json b/.sqlx/query-e06cbe45408d593a081b566c38657da87439340801d0765f8d9f64f8fbbbfb6b.json new file mode 100644 index 0000000..662e8c2 --- /dev/null +++ b/.sqlx/query-e06cbe45408d593a081b566c38657da87439340801d0765f8d9f64f8fbbbfb6b.json @@ -0,0 +1,38 @@ +{ + "db_name": "SQLite", + "query": "\n\t\t\t\tselect\n invite.id as \"invite_id: Id\",\n\t\t\t\t\tissuer.id as \"issuer_id: login::Id\",\n\t\t\t\t\tissuer.display_name as \"issuer_name: nfc::String\",\n\t\t\t\t\tinvite.issued_at as \"invite_issued_at: DateTime\"\n\t\t\t\tfrom invite\n\t\t\t\tjoin login as issuer on (invite.issuer = issuer.id)\n\t\t\t\twhere invite.id = $1\n\t\t\t", + "describe": { + "columns": [ + { + "name": "invite_id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "issuer_id: login::Id", + "ordinal": 1, + "type_info": "Text" + }, + { + "name": "issuer_name: nfc::String", + "ordinal": 2, + "type_info": "Text" + }, + { + "name": "invite_issued_at: DateTime", + "ordinal": 3, + "type_info": "Text" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "e06cbe45408d593a081b566c38657da87439340801d0765f8d9f64f8fbbbfb6b" +} diff --git a/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json b/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json new file mode 100644 index 0000000..6700c43 --- /dev/null +++ b/.sqlx/query-e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e.json @@ -0,0 +1,56 @@ +{ + "db_name": "SQLite", + "query": "\n select\n id as \"id: Id\",\n name.display_name as \"display_name?: String\",\n name.canonical_name as \"canonical_name?: String\",\n channel.created_at as \"created_at: DateTime\",\n channel.created_sequence as \"created_sequence: Sequence\",\n deleted.deleted_at as \"deleted_at?: DateTime\",\n deleted.deleted_sequence as \"deleted_sequence?: Sequence\"\n from channel\n left join channel_name as name\n using (id)\n left join channel_deleted as deleted\n using (id)\n where id = $1\n ", + "describe": { + "columns": [ + { + "name": "id: Id", + "ordinal": 0, + "type_info": "Text" + }, + { + "name": "display_name?: String", + "ordinal": 1, + "type_info": "Null" + }, + { + "name": "canonical_name?: String", + "ordinal": 2, + "type_info": "Null" + }, + { + "name": "created_at: DateTime", + "ordinal": 3, + "type_info": "Text" + }, + { + "name": "created_sequence: Sequence", + "ordinal": 4, + "type_info": "Integer" + }, + { + "name": "deleted_at?: DateTime", + "ordinal": 5, + "type_info": "Text" + }, + { + "name": "deleted_sequence?: Sequence", + "ordinal": 6, + "type_info": "Integer" + } + ], + "parameters": { + "Right": 1 + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "e36d7cd00f040807c3994b5010f2f77b943ec225244fcfc24013b12a48084a1e" +} diff --git a/Cargo.lock b/Cargo.lock index c4454e3..1cb656d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -825,6 +825,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", + "unicode-casefold", "unicode-normalization", "uuid", ] @@ -2108,6 +2109,12 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" +[[package]] +name = "unicode-casefold" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f66b1c8f8caa2ab31dc6d3f35386f16efdab89668f93411e565ac368908e8f" + [[package]] name = "unicode-ident" version = "1.0.13" diff --git a/Cargo.toml b/Cargo.toml index fe8fdfd..30a209d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ sqlx = { version = "=0.8.2", features = ["chrono", "runtime-tokio", "sqlite"] } thiserror = "1.0.64" tokio = { version = "1.40.0", features = ["rt", "macros", "rt-multi-thread"] } tokio-stream = { version = "0.1.16", features = ["sync"] } +unicode-casefold = "0.2.0" unicode-normalization = "0.1.24" uuid = { version = "1.11.0", features = ["v4"] } diff --git a/docs/api/authentication.md b/docs/api/authentication.md index 7e05443..135e91b 100644 --- a/docs/api/authentication.md +++ b/docs/api/authentication.md @@ -13,6 +13,23 @@ stateDiagram-v2 Authentication associates each authenticated request with a login. +To create logins, see [initial setup](./initial-setup.md) and [invitations](./invitations.md). + + +## Names + + +The service handles login names using two separate forms. + +The first form is as given in the request used to create the login. This form of the login name is used throughout the API, and the service will preserve the name as entered (other than applying normalization), so that users' preferences around capitalization and accent marks are preserved. + +The second form is a "canonical" form, used internally by the service to control uniqueness and match names to logins. The canonical form is both case-folded and normalized. + +The canonical form is not available to API clients, but its use has practical consequences: + +* Names that differ only by case or only by code point sequence are treated as the same name. If the name is in use, changing the capitalization or changing the sequence of combining marks will not allow the creation of a second "identical" login. +* The login API accepts any name that canonicalizes to the form stored in the database, making login names effectively case-insensitive. + ## Identity tokens @@ -32,8 +49,6 @@ Unless the endpoint's documentation says otherwise, all endpoints require authen Authenticates the user using their login name and password. The login must exist before calling this endpoint. -To create logins, see [initial setup](./initial-setup.md) and [invitations](./invitations.md). - **This endpoint does not require an `identity` cookie.** ### Request diff --git a/docs/api/channels-messages.md b/docs/api/channels-messages.md index a441f52..9ef4e66 100644 --- a/docs/api/channels-messages.md +++ b/docs/api/channels-messages.md @@ -27,6 +27,18 @@ Messages allow logins to communicate with one another. Channels are the conversa Every channel has a unique name, chosen when the channel is created. +## Names + + +The service handles channel names using two separate forms. + +The first form is as given in the request used to create the channel. This form of the channel name is used throughout the API, and the service will preserve the name as entered (other than applying normalization), so that users' preferences around capitalization and accent marks are preserved. + +The second form is a "canonical" form, used internally by the service to control uniqueness and match names to channels. The canonical form is both case-folded and normalized. + +The canonical form is not available to API clients, but its use has practical consequences. Names that differ only by case or only by code point sequence are treated as the same name. If the name is in use, changing the capitalization or changing the sequence of combining marks will not allow the creation of a second "identical" channel. + + ## Expiry and purging Both channels and messages expire after a time. Messages expire 90 days after being sent. Channels expire 90 days after the last message sent to them, or after creation if no messages are sent in that time. diff --git a/migrations/20241019191531_canonical_names.sql b/migrations/20241019191531_canonical_names.sql new file mode 100644 index 0000000..ab7cbf4 --- /dev/null +++ b/migrations/20241019191531_canonical_names.sql @@ -0,0 +1,189 @@ +alter table login +rename to old_login; +alter table token +rename to old_token; +alter table invite +rename to old_invite; +alter table channel +rename to old_channel; +alter table channel_deleted +rename to old_channel_deleted; +alter table message +rename to old_message; +alter table message_deleted +rename to old_message_deleted; + +create table login ( + id text + not null + primary key, + display_name text + not null, + canonical_name text + not null + unique, + password_hash text + not null, + created_sequence bigint + unique + not null, + created_at text + not null +); + +insert into login (id, display_name, canonical_name, password_hash, created_sequence, created_at) +select + id, + -- This isn't strictly correct, as existing names are not guaranteed to be + -- normalized, and as sqlite's built-in `lower` only operates on ASCII, but + -- without any way to do case folding and normalization in sqlite3, and + -- without any way to call out into Rust to do the work, this is the best we + -- can do. Normalization issues will produce errors at runtime when the + -- relevant rows are loaded. + name as display_name, + lower(name) as canonical_name, + password_hash, + created_sequence, + created_at +from old_login; + +create table token ( + id text + not null + primary key, + secret text + not null + unique, + login text + not null + references login (id), + issued_at text + not null, + last_used_at text + not null +); + +insert into token (id, secret, login, issued_at, last_used_at) +select id, secret, login, issued_at, last_used_at from old_token; + +create table invite ( + id text + primary key + not null, + issuer text + not null + references login (id), + issued_at text + not null +); + +insert into invite (id, issuer, issued_at) +select id, issuer, issued_at +from old_invite; + +create table channel ( + id text + not null + primary key, + created_sequence bigint + unique + not null, + created_at text + not null +); + +create table channel_name ( + id text + not null + primary key + references channel (id), + display_name + not null, + canonical_name + not null + unique +); + +insert into channel (id, created_sequence, created_at) +select id, created_sequence, created_at from old_channel; + +insert into channel_name (id, display_name, canonical_name) +select + id, + -- This isn't strictly correct, for the same reasons as above. + name as display_name, + name as canonical_name +from old_channel +where name is not null; + +create table channel_deleted ( + id text + not null + primary key + references channel (id), + deleted_sequence bigint + unique + not null, + deleted_at text + not null +); + +insert into channel_deleted (id, deleted_sequence, deleted_at) +select id, deleted_sequence, deleted_at +from old_channel_deleted; + +create table message ( + id text + not null + primary key, + -- Starting from the code changes in this rev, values in this column will be + -- in NFC. However, we don't actually need to normalize historical values; + -- they're delivered to clients "verbatim" with respect to how they were sent, + -- which causes no harm. + channel text + not null + references channel (id), + sender text + not null + references login (id), + sent_sequence bigint + unique + not null, + sent_at text + not null, + body text + null +); + +insert into message (id, channel, sender, sent_sequence, sent_at, body) +select id, channel, sender, sent_sequence, sent_at, body +from old_message; + +create table message_deleted ( + id text + not null + primary key + references message (id), + deleted_sequence bigint + unique + not null, + deleted_at text + not null +); + +insert into message_deleted (id, deleted_sequence, deleted_at) +select id, deleted_sequence, deleted_at +from old_message_deleted; + +drop table old_message_deleted; +drop table old_message; +drop table old_channel_deleted; +drop table old_channel; +drop table old_invite; +drop table old_token; +drop table old_login; + +create index token_issued_at +on token (issued_at); +create index message_sent_at +on message (sent_at); diff --git a/src/boot/app.rs b/src/boot/app.rs index ef48b2f..1d88608 100644 --- a/src/boot/app.rs +++ b/src/boot/app.rs @@ -2,8 +2,11 @@ use sqlx::sqlite::SqlitePool; use super::Snapshot; use crate::{ - channel::repo::Provider as _, event::repo::Provider as _, login::repo::Provider as _, + channel::{self, repo::Provider as _}, + event::repo::Provider as _, + login::{self, repo::Provider as _}, message::repo::Provider as _, + name, }; pub struct Boot<'a> { @@ -15,7 +18,7 @@ impl<'a> Boot<'a> { Self { db } } - pub async fn snapshot(&self) -> Result { + pub async fn snapshot(&self) -> Result { let mut tx = self.db.begin().await?; let resume_point = tx.sequence().current().await?; @@ -48,3 +51,30 @@ impl<'a> Boot<'a> { }) } } + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum Error { + Name(#[from] name::Error), + Database(#[from] sqlx::Error), +} + +impl From for Error { + fn from(error: login::repo::LoadError) -> Self { + use login::repo::LoadError; + match error { + LoadError::Name(error) => error.into(), + LoadError::Database(error) => error.into(), + } + } +} + +impl From for Error { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Name(error) => error.into(), + LoadError::Database(error) => error.into(), + } + } +} diff --git a/src/channel/app.rs b/src/channel/app.rs index ea60943..b8ceeb0 100644 --- a/src/channel/app.rs +++ b/src/channel/app.rs @@ -2,12 +2,16 @@ use chrono::TimeDelta; use itertools::Itertools; use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Channel, History, Id, Name}; +use super::{ + repo::{LoadError, Provider as _}, + Channel, History, Id, +}; use crate::{ clock::DateTime, db::{Duplicate as _, NotFound as _}, event::{repo::Provider as _, Broadcaster, Event, Sequence}, message::repo::Provider as _, + name::{self, Name}, }; pub struct Channels<'a> { @@ -38,7 +42,7 @@ impl<'a> Channels<'a> { // This function is careless with respect to time, and gets you the channel as // it exists in the specific moment when you call it. - pub async fn get(&self, channel: &Id) -> Result, sqlx::Error> { + pub async fn get(&self, channel: &Id) -> Result, Error> { let mut tx = self.db.begin().await?; let channel = tx.channels().by_id(channel).await.optional()?; tx.commit().await?; @@ -88,7 +92,7 @@ impl<'a> Channels<'a> { Ok(()) } - pub async fn expire(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> { + pub async fn expire(&self, relative_to: &DateTime) -> Result<(), ExpireError> { // Somewhat arbitrarily, expire after 90 days. let expire_at = relative_to.to_owned() - TimeDelta::days(90); @@ -137,6 +141,17 @@ pub enum CreateError { DuplicateName(Name), #[error(transparent)] Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From for CreateError { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[derive(Debug, thiserror::Error)] @@ -147,4 +162,32 @@ pub enum Error { Deleted(Id), #[error(transparent)] Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From for Error { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ExpireError { + #[error(transparent)] + Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From for ExpireError { + fn from(error: LoadError) -> Self { + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } diff --git a/src/channel/mod.rs b/src/channel/mod.rs index fb13e92..eb8200b 100644 --- a/src/channel/mod.rs +++ b/src/channel/mod.rs @@ -2,11 +2,8 @@ pub mod app; pub mod event; mod history; mod id; -mod name; pub mod repo; mod routes; mod snapshot; -pub use self::{ - event::Event, history::History, id::Id, name::Name, routes::router, snapshot::Channel, -}; +pub use self::{event::Event, history::History, id::Id, routes::router, snapshot::Channel}; diff --git a/src/channel/name.rs b/src/channel/name.rs deleted file mode 100644 index fc82dec..0000000 --- a/src/channel/name.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::fmt; - -use crate::nfc; - -#[derive( - Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type, -)] -#[serde(transparent)] -#[sqlx(transparent)] -pub struct Name(nfc::String); - -impl fmt::Display for Name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let Self(name) = self; - name.fmt(f) - } -} - -impl From for Name { - fn from(name: String) -> Self { - Self(name.into()) - } -} - -impl From for String { - fn from(name: Name) -> Self { - let Name(name) = name; - name.into() - } -} diff --git a/src/channel/repo.rs b/src/channel/repo.rs index 3353bfd..4baa95b 100644 --- a/src/channel/repo.rs +++ b/src/channel/repo.rs @@ -1,9 +1,12 @@ +use futures::stream::{StreamExt as _, TryStreamExt as _}; use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ - channel::{Channel, History, Id, Name}, + channel::{Channel, History, Id}, clock::DateTime, + db::NotFound, event::{Instant, ResumePoint, Sequence}, + name::{self, Name}, }; pub trait Provider { @@ -21,132 +24,160 @@ pub struct Channels<'t>(&'t mut SqliteConnection); impl<'c> Channels<'c> { pub async fn create(&mut self, name: &Name, created: &Instant) -> Result { let id = Id::generate(); - let channel = sqlx::query!( + let name = name.clone(); + let display_name = name.display(); + let canonical_name = name.canonical(); + let created = *created; + + sqlx::query!( r#" insert - into channel (id, name, created_at, created_sequence) - values ($1, $2, $3, $4) - returning - id as "id: Id", - name as "name!: Name", -- known non-null as we just set it - created_at as "created_at: DateTime", - created_sequence as "created_sequence: Sequence" + into channel (id, created_at, created_sequence) + values ($1, $2, $3) "#, id, - name, created.at, created.sequence, ) - .map(|row| History { + .execute(&mut *self.0) + .await?; + + sqlx::query!( + r#" + insert into channel_name (id, display_name, canonical_name) + values ($1, $2, $3) + "#, + id, + display_name, + canonical_name, + ) + .execute(&mut *self.0) + .await?; + + let channel = History { channel: Channel { - id: row.id, - name: row.name, + id, + name: name.clone(), deleted_at: None, }, - created: Instant::new(row.created_at, row.created_sequence), + created, deleted: None, - }) - .fetch_one(&mut *self.0) - .await?; + }; Ok(channel) } - pub async fn by_id(&mut self, channel: &Id) -> Result { + pub async fn by_id(&mut self, channel: &Id) -> Result { let channel = sqlx::query!( r#" select id as "id: Id", - channel.name as "name: Name", + name.display_name as "display_name?: String", + name.canonical_name as "canonical_name?: String", channel.created_at as "created_at: DateTime", channel.created_sequence as "created_sequence: Sequence", deleted.deleted_at as "deleted_at?: DateTime", deleted.deleted_sequence as "deleted_sequence?: Sequence" from channel + left join channel_name as name + using (id) left join channel_deleted as deleted using (id) where id = $1 "#, channel, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name.unwrap_or_default(), - deleted_at: row.deleted_at, - }, - created: Instant::new(row.created_at, row.created_sequence), - deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) }) .fetch_one(&mut *self.0) - .await?; + .await??; Ok(channel) } - pub async fn all(&mut self, resume_at: ResumePoint) -> Result, sqlx::Error> { + pub async fn all(&mut self, resume_at: ResumePoint) -> Result, LoadError> { let channels = sqlx::query!( r#" select id as "id: Id", - channel.name as "name: Name", + name.display_name as "display_name: String", + name.canonical_name as "canonical_name: String", channel.created_at as "created_at: DateTime", channel.created_sequence as "created_sequence: Sequence", - deleted.deleted_at as "deleted_at: DateTime", - deleted.deleted_sequence as "deleted_sequence: Sequence" + deleted.deleted_at as "deleted_at?: DateTime", + deleted.deleted_sequence as "deleted_sequence?: Sequence" from channel + left join channel_name as name + using (id) left join channel_deleted as deleted using (id) where coalesce(channel.created_sequence <= $1, true) - order by channel.name + order by name.canonical_name "#, resume_at, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name.unwrap_or_default(), - deleted_at: row.deleted_at, - }, - created: Instant::new(row.created_at, row.created_sequence), - deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) } - pub async fn replay( - &mut self, - resume_at: Option, - ) -> Result, sqlx::Error> { + pub async fn replay(&mut self, resume_at: Option) -> Result, LoadError> { let channels = sqlx::query!( r#" select id as "id: Id", - channel.name as "name: Name", + name.display_name as "display_name: String", + name.canonical_name as "canonical_name: String", channel.created_at as "created_at: DateTime", channel.created_sequence as "created_sequence: Sequence", - deleted.deleted_at as "deleted_at: DateTime", - deleted.deleted_sequence as "deleted_sequence: Sequence" + deleted.deleted_at as "deleted_at?: DateTime", + deleted.deleted_sequence as "deleted_sequence?: Sequence" from channel + left join channel_name as name + using (id) left join channel_deleted as deleted using (id) where coalesce(channel.created_sequence > $1, true) "#, resume_at, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name.unwrap_or_default(), - deleted_at: row.deleted_at, - }, - created: Instant::new(row.created_at, row.created_sequence), - deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) @@ -156,19 +187,18 @@ impl<'c> Channels<'c> { &mut self, channel: &History, deleted: &Instant, - ) -> Result { + ) -> Result { let id = channel.id(); - sqlx::query_scalar!( + sqlx::query!( r#" insert into channel_deleted (id, deleted_at, deleted_sequence) values ($1, $2, $3) - returning 1 as "deleted: bool" "#, id, deleted.at, deleted.sequence, ) - .fetch_one(&mut *self.0) + .execute(&mut *self.0) .await?; // Small social responsibility hack here: when a channel is deleted, its name is @@ -179,16 +209,14 @@ impl<'c> Channels<'c> { // This also avoids the need for a separate name reservation table to ensure // that live channels have unique names, since the `channel` table's name field // is unique over non-null values. - sqlx::query_scalar!( + sqlx::query!( r#" - update channel - set name = null + delete from channel_name where id = $1 - returning 1 as "updated: bool" "#, id, ) - .fetch_one(&mut *self.0) + .execute(&mut *self.0) .await?; let channel = self.by_id(id).await?; @@ -230,38 +258,66 @@ impl<'c> Channels<'c> { Ok(()) } - pub async fn expired(&mut self, expired_at: &DateTime) -> Result, sqlx::Error> { + pub async fn expired(&mut self, expired_at: &DateTime) -> Result, LoadError> { let channels = sqlx::query!( r#" select channel.id as "id: Id", - channel.name as "name: Name", + name.display_name as "display_name: String", + name.canonical_name as "canonical_name: String", channel.created_at as "created_at: DateTime", channel.created_sequence as "created_sequence: Sequence", deleted.deleted_at as "deleted_at?: DateTime", deleted.deleted_sequence as "deleted_sequence?: Sequence" from channel + left join channel_name as name + using (id) left join channel_deleted as deleted using (id) left join message + on channel.id = message.channel where channel.created_at < $1 and message.id is null and deleted.id is null "#, expired_at, ) - .map(|row| History { - channel: Channel { - id: row.id, - name: row.name.unwrap_or_default(), - deleted_at: row.deleted_at, - }, - created: Instant::new(row.created_at, row.created_sequence), - deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + .map(|row| { + Ok::<_, name::Error>(History { + channel: Channel { + id: row.id, + name: Name::optional(row.display_name, row.canonical_name)?.unwrap_or_default(), + deleted_at: row.deleted_at, + }, + created: Instant::new(row.created_at, row.created_sequence), + deleted: Instant::optional(row.deleted_at, row.deleted_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; Ok(channels) } } + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl NotFound for Result { + type Ok = T; + type Error = LoadError; + + fn optional(self) -> Result, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } + } +} diff --git a/src/channel/routes/post.rs b/src/channel/routes/post.rs index d354f79..9781dd7 100644 --- a/src/channel/routes/post.rs +++ b/src/channel/routes/post.rs @@ -6,10 +6,11 @@ use axum::{ use crate::{ app::App, - channel::{app, Channel, Name}, + channel::{app, Channel}, clock::RequestedAt, error::Internal, login::Login, + name::Name, }; pub async fn handler( diff --git a/src/channel/snapshot.rs b/src/channel/snapshot.rs index dc2894d..129c0d6 100644 --- a/src/channel/snapshot.rs +++ b/src/channel/snapshot.rs @@ -1,8 +1,8 @@ use super::{ event::{Created, Event}, - Id, Name, + Id, }; -use crate::clock::DateTime; +use crate::{clock::DateTime, name::Name}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct Channel { diff --git a/src/db/mod.rs b/src/db/mod.rs index 6005813..e0522d4 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -130,14 +130,17 @@ pub enum Error { Rejected(String, String), } -pub trait NotFound { +pub trait NotFound: Sized { type Ok; type Error; fn not_found(self, map: F) -> Result where E: From, - F: FnOnce() -> E; + F: FnOnce() -> E, + { + self.optional()?.ok_or_else(map) + } fn optional(self) -> Result, Self::Error>; } @@ -153,14 +156,6 @@ impl NotFound for Result { Err(other) => Err(other), } } - - fn not_found(self, map: F) -> Result - where - E: From, - F: FnOnce() -> E, - { - self.optional()?.ok_or_else(map) - } } pub trait Duplicate { diff --git a/src/event/app.rs b/src/event/app.rs index 951ce25..c754388 100644 --- a/src/event/app.rs +++ b/src/event/app.rs @@ -11,6 +11,7 @@ use crate::{ channel::{self, repo::Provider as _}, login::{self, repo::Provider as _}, message::{self, repo::Provider as _}, + name, }; pub struct Events<'a> { @@ -26,7 +27,7 @@ impl<'a> Events<'a> { pub async fn subscribe( &self, resume_at: impl Into, - ) -> Result + std::fmt::Debug, sqlx::Error> { + ) -> Result + std::fmt::Debug, Error> { let resume_at = resume_at.into(); // Subscribe before retrieving, to catch messages broadcast while we're // querying the DB. We'll prune out duplicates later. @@ -81,3 +82,30 @@ impl<'a> Events<'a> { move |event| future::ready(filter(event)) } } + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum Error { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl From for Error { + fn from(error: login::repo::LoadError) -> Self { + use login::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} + +impl From for Error { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} diff --git a/src/event/routes/get.rs b/src/event/routes/get.rs index 357845a..22e8762 100644 --- a/src/event/routes/get.rs +++ b/src/event/routes/get.rs @@ -12,7 +12,7 @@ use futures::stream::{Stream, StreamExt as _}; use crate::{ app::App, error::{Internal, Unauthorized}, - event::{extract::LastEventId, Event, ResumePoint, Sequence, Sequenced as _}, + event::{app, extract::LastEventId, Event, ResumePoint, Sequence, Sequenced as _}, token::{app::ValidateError, extract::Identity}, }; @@ -69,7 +69,7 @@ impl TryFrom for sse::Event { #[derive(Debug, thiserror::Error)] #[error(transparent)] pub enum Error { - Database(#[from] sqlx::Error), + Subscribe(#[from] app::Error), Validate(#[from] ValidateError), } diff --git a/src/invite/app.rs b/src/invite/app.rs index 285a819..64ba753 100644 --- a/src/invite/app.rs +++ b/src/invite/app.rs @@ -6,7 +6,8 @@ use crate::{ clock::DateTime, db::{Duplicate as _, NotFound as _}, event::repo::Provider as _, - login::{repo::Provider as _, Login, Name, Password}, + login::{repo::Provider as _, Login, Password}, + name::Name, token::{repo::Provider as _, Secret}, }; diff --git a/src/invite/mod.rs b/src/invite/mod.rs index abf1c3a..d59fb9c 100644 --- a/src/invite/mod.rs +++ b/src/invite/mod.rs @@ -3,7 +3,7 @@ mod id; mod repo; mod routes; -use crate::{clock::DateTime, login}; +use crate::{clock::DateTime, login, normalize::nfc}; pub use self::{id::Id, routes::router}; @@ -17,6 +17,6 @@ pub struct Invite { #[derive(serde::Serialize)] pub struct Summary { pub id: Id, - pub issuer: String, + pub issuer: nfc::String, pub issued_at: DateTime, } diff --git a/src/invite/repo.rs b/src/invite/repo.rs index 643f5b7..02f4e42 100644 --- a/src/invite/repo.rs +++ b/src/invite/repo.rs @@ -4,6 +4,7 @@ use super::{Id, Invite, Summary}; use crate::{ clock::DateTime, login::{self, Login}, + normalize::nfc, }; pub trait Provider { @@ -70,7 +71,7 @@ impl<'c> Invites<'c> { select invite.id as "invite_id: Id", issuer.id as "issuer_id: login::Id", - issuer.name as "issuer_name", + issuer.display_name as "issuer_name: nfc::String", invite.issued_at as "invite_issued_at: DateTime" from invite join login as issuer on (invite.issuer = issuer.id) diff --git a/src/invite/routes/invite/post.rs b/src/invite/routes/invite/post.rs index 8160465..a41207a 100644 --- a/src/invite/routes/invite/post.rs +++ b/src/invite/routes/invite/post.rs @@ -9,7 +9,8 @@ use crate::{ clock::RequestedAt, error::{Internal, NotFound}, invite::app, - login::{Login, Name, Password}, + login::{Login, Password}, + name::Name, token::extract::IdentityToken, }; diff --git a/src/lib.rs b/src/lib.rs index 4d0d9b9..84b8dfc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,8 @@ mod id; mod invite; mod login; mod message; -mod nfc; +mod name; +mod normalize; mod setup; #[cfg(test)] mod test; diff --git a/src/login/app.rs b/src/login/app.rs index ebc1c00..37f1249 100644 --- a/src/login/app.rs +++ b/src/login/app.rs @@ -1,9 +1,10 @@ use sqlx::sqlite::SqlitePool; -use super::{repo::Provider as _, Login, Name, Password}; +use super::{repo::Provider as _, Login, Password}; use crate::{ clock::DateTime, event::{repo::Provider as _, Broadcaster, Event}, + name::Name, }; pub struct Logins<'a> { diff --git a/src/login/mod.rs b/src/login/mod.rs index 71d5bfc..98cc3d7 100644 --- a/src/login/mod.rs +++ b/src/login/mod.rs @@ -4,13 +4,11 @@ pub mod event; pub mod extract; mod history; mod id; -mod name; pub mod password; pub mod repo; mod routes; mod snapshot; pub use self::{ - event::Event, history::History, id::Id, name::Name, password::Password, routes::router, - snapshot::Login, + event::Event, history::History, id::Id, password::Password, routes::router, snapshot::Login, }; diff --git a/src/login/name.rs b/src/login/name.rs deleted file mode 100644 index d882ff9..0000000 --- a/src/login/name.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::fmt; - -use crate::nfc; - -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type)] -#[serde(transparent)] -#[sqlx(transparent)] -pub struct Name(nfc::String); - -impl fmt::Display for Name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let Self(name) = self; - name.fmt(f) - } -} - -impl From for Name { - fn from(name: String) -> Self { - Self(name.into()) - } -} - -impl From for String { - fn from(name: Name) -> Self { - let Name(name) = name; - name.into() - } -} diff --git a/src/login/password.rs b/src/login/password.rs index f9ecf37..c27c950 100644 --- a/src/login/password.rs +++ b/src/login/password.rs @@ -4,7 +4,7 @@ use argon2::Argon2; use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; use rand_core::OsRng; -use crate::nfc; +use crate::normalize::nfc; #[derive(sqlx::Type)] #[sqlx(transparent)] diff --git a/src/login/repo.rs b/src/login/repo.rs index 204329f..6021f26 100644 --- a/src/login/repo.rs +++ b/src/login/repo.rs @@ -1,9 +1,11 @@ +use futures::stream::{StreamExt as _, TryStreamExt as _}; use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ clock::DateTime, event::{Instant, ResumePoint, Sequence}, - login::{password::StoredHash, History, Id, Login, Name}, + login::{password::StoredHash, History, Id, Login}, + name::{self, Name}, }; pub trait Provider { @@ -26,43 +28,43 @@ impl<'c> Logins<'c> { created: &Instant, ) -> Result { let id = Id::generate(); + let display_name = name.display(); + let canonical_name = name.canonical(); - let login = sqlx::query!( + sqlx::query!( r#" insert - into login (id, name, password_hash, created_sequence, created_at) - values ($1, $2, $3, $4, $5) - returning - id as "id: Id", - name as "name: Name", - created_sequence as "created_sequence: Sequence", - created_at as "created_at: DateTime" + into login (id, display_name, canonical_name, password_hash, created_sequence, created_at) + values ($1, $2, $3, $4, $5, $6) "#, id, - name, + display_name, + canonical_name, password_hash, created.sequence, created.at, ) - .map(|row| History { + .execute(&mut *self.0) + .await?; + + let login = History { + created: *created, login: Login { - id: row.id, - name: row.name, + id, + name: name.clone(), }, - created: Instant::new(row.created_at, row.created_sequence), - }) - .fetch_one(&mut *self.0) - .await?; + }; Ok(login) } - pub async fn all(&mut self, resume_at: ResumePoint) -> Result, sqlx::Error> { - let channels = sqlx::query!( + pub async fn all(&mut self, resume_at: ResumePoint) -> Result, LoadError> { + let logins = sqlx::query!( r#" select id as "id: Id", - name as "name: Name", + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", created_at as "created_at: DateTime" from login @@ -71,24 +73,29 @@ impl<'c> Logins<'c> { "#, resume_at, ) - .map(|row| History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant::new(row.created_at, row.created_sequence), + .map(|row| { + Ok::<_, LoadError>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| res?) + .try_collect() .await?; - Ok(channels) + Ok(logins) } - pub async fn replay(&mut self, resume_at: ResumePoint) -> Result, sqlx::Error> { - let messages = sqlx::query!( + pub async fn replay(&mut self, resume_at: ResumePoint) -> Result, LoadError> { + let logins = sqlx::query!( r#" select id as "id: Id", - name as "name: Name", + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", created_at as "created_at: DateTime" from login @@ -96,22 +103,27 @@ impl<'c> Logins<'c> { "#, resume_at, ) - .map(|row| History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant::new(row.created_at, row.created_sequence), + .map(|row| { + Ok::<_, name::Error>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }) }) - .fetch_all(&mut *self.0) + .fetch(&mut *self.0) + .map(|res| Ok::<_, LoadError>(res??)) + .try_collect() .await?; - Ok(messages) + Ok(logins) } } -impl<'t> From<&'t mut SqliteConnection> for Logins<'t> { - fn from(tx: &'t mut SqliteConnection) -> Self { - Self(tx) - } +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), } diff --git a/src/login/routes/login/post.rs b/src/login/routes/login/post.rs index 7a685e2..20430db 100644 --- a/src/login/routes/login/post.rs +++ b/src/login/routes/login/post.rs @@ -8,7 +8,8 @@ use crate::{ app::App, clock::RequestedAt, error::Internal, - login::{Login, Name, Password}, + login::{Login, Password}, + name::Name, token::{app, extract::IdentityToken}, }; diff --git a/src/login/routes/logout/test.rs b/src/login/routes/logout/test.rs index 0e70e4c..91837fe 100644 --- a/src/login/routes/logout/test.rs +++ b/src/login/routes/logout/test.rs @@ -33,7 +33,6 @@ async fn successful() { assert_eq!(StatusCode::NO_CONTENT, response_status); // Verify the semantics - let error = app .tokens() .validate(&secret, &now) diff --git a/src/login/snapshot.rs b/src/login/snapshot.rs index 85800e4..e1eb96c 100644 --- a/src/login/snapshot.rs +++ b/src/login/snapshot.rs @@ -1,7 +1,8 @@ use super::{ event::{Created, Event}, - Id, Name, + Id, }; +use crate::name::Name; // This also implements FromRequestParts (see `./extract.rs`). As a result, it // can be used as an extractor for endpoints that want to require login, or for diff --git a/src/message/app.rs b/src/message/app.rs index af87553..852b958 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -9,6 +9,7 @@ use crate::{ db::NotFound as _, event::{repo::Provider as _, Broadcaster, Event, Sequence}, login::Login, + name, }; pub struct Messages<'a> { @@ -119,6 +120,18 @@ pub enum SendError { ChannelNotFound(channel::Id), #[error(transparent)] Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From for SendError { + fn from(error: channel::repo::LoadError) -> Self { + use channel::repo::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } } #[derive(Debug, thiserror::Error)] diff --git a/src/message/body.rs b/src/message/body.rs index a415f85..6dd224c 100644 --- a/src/message/body.rs +++ b/src/message/body.rs @@ -1,6 +1,6 @@ use std::fmt; -use crate::nfc; +use crate::normalize::nfc; #[derive( Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type, diff --git a/src/name.rs b/src/name.rs new file mode 100644 index 0000000..9187d33 --- /dev/null +++ b/src/name.rs @@ -0,0 +1,85 @@ +use std::fmt; + +use crate::normalize::{ident, nfc}; + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, sqlx::Type)] +#[serde(from = "String", into = "String")] +pub struct Name { + display: nfc::String, + canonical: ident::String, +} + +impl Name { + pub fn new(display: D, canonical: C) -> Result + where + D: AsRef, + C: AsRef, + { + let name = Self::from(display); + + if name.canonical.as_str() == canonical.as_ref() { + Ok(name) + } else { + Err(Error::CanonicalMismatch( + canonical.as_ref().into(), + name.canonical, + name.display, + )) + } + } + + pub fn optional(display: Option, canonical: Option) -> Result, Error> + where + D: AsRef, + C: AsRef, + { + display + .zip(canonical) + .map(|(display, canonical)| Self::new(display, canonical)) + .transpose() + } + + pub fn display(&self) -> &nfc::String { + &self.display + } + + pub fn canonical(&self) -> &ident::String { + &self.canonical + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("stored canonical form {0:#?} does not match computed canonical form {:#?} for name {:#?}", .1.as_str(), .2.as_str())] + CanonicalMismatch(String, ident::String, nfc::String), +} + +impl Default for Name { + fn default() -> Self { + Self::from(String::default()) + } +} + +impl fmt::Display for Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.display.fmt(f) + } +} + +impl From for Name +where + S: AsRef, +{ + fn from(name: S) -> Self { + let display = nfc::String::from(&name); + let canonical = ident::String::from(&name); + + Self { display, canonical } + } +} + +impl From for String { + fn from(name: Name) -> Self { + name.display.into() + } +} diff --git a/src/nfc.rs b/src/nfc.rs deleted file mode 100644 index 70e936c..0000000 --- a/src/nfc.rs +++ /dev/null @@ -1,103 +0,0 @@ -use std::{fmt, string::String as StdString}; - -use sqlx::{ - encode::{Encode, IsNull}, - Database, Decode, Type, -}; -use unicode_normalization::UnicodeNormalization as _; - -#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -#[serde(from = "StdString", into = "StdString")] -pub struct String(StdString); - -impl fmt::Display for String { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let Self(value) = self; - value.fmt(f) - } -} - -impl From for String { - fn from(value: StdString) -> Self { - let value = value.nfc().collect(); - - Self(value) - } -} - -impl From for StdString { - fn from(value: String) -> Self { - let String(value) = value; - value - } -} - -impl std::ops::Deref for String { - type Target = StdString; - - fn deref(&self) -> &Self::Target { - let Self(value) = self; - value - } -} - -// Type is manually implemented so that we can implement Decode to do -// normalization on read. Implementation is otherwise based on -// `#[derive(sqlx::Type)]` with the `#[sqlx(transparent)]` attribute. -impl Type for String -where - DB: Database, - StdString: Type, -{ - fn type_info() -> ::TypeInfo { - >::type_info() - } - - fn compatible(ty: &::TypeInfo) -> bool { - >::compatible(ty) - } -} - -impl<'r, DB> Decode<'r, DB> for String -where - DB: Database, - StdString: Decode<'r, DB>, -{ - fn decode(value: ::ValueRef<'r>) -> Result { - let value = StdString::decode(value)?; - let value = value.nfc().collect(); - Ok(Self(value)) - } -} - -impl<'q, DB> Encode<'q, DB> for String -where - DB: Database, - StdString: Encode<'q, DB>, -{ - fn encode_by_ref( - &self, - buf: &mut ::ArgumentBuffer<'q>, - ) -> Result { - let Self(value) = self; - value.encode_by_ref(buf) - } - - fn encode( - self, - buf: &mut ::ArgumentBuffer<'q>, - ) -> Result { - let Self(value) = self; - value.encode(buf) - } - - fn produces(&self) -> Option<::TypeInfo> { - let Self(value) = self; - value.produces() - } - - fn size_hint(&self) -> usize { - let Self(value) = self; - value.size_hint() - } -} diff --git a/src/normalize/mod.rs b/src/normalize/mod.rs new file mode 100644 index 0000000..6294201 --- /dev/null +++ b/src/normalize/mod.rs @@ -0,0 +1,36 @@ +mod string; + +pub mod nfc { + use std::string::String as StdString; + + use unicode_normalization::UnicodeNormalization as _; + + pub type String = super::string::String; + + #[derive(Clone, Debug, Default, Eq, PartialEq)] + pub struct Nfc; + + impl super::string::Normalize for Nfc { + fn normalize(&self, value: &str) -> StdString { + value.nfc().collect() + } + } +} + +pub mod ident { + use std::string::String as StdString; + + use unicode_casefold::UnicodeCaseFold as _; + use unicode_normalization::UnicodeNormalization as _; + + pub type String = super::string::String; + + #[derive(Clone, Debug, Default, Eq, PartialEq)] + pub struct Ident; + + impl super::string::Normalize for Ident { + fn normalize(&self, value: &str) -> StdString { + value.case_fold().nfkc().collect() + } + } +} diff --git a/src/normalize/string.rs b/src/normalize/string.rs new file mode 100644 index 0000000..a0d178c --- /dev/null +++ b/src/normalize/string.rs @@ -0,0 +1,112 @@ +use std::{fmt, string::String as StdString}; + +use sqlx::{ + encode::{Encode, IsNull}, + Database, Decode, Type, +}; + +pub trait Normalize: Clone + Default { + fn normalize(&self, value: &str) -> StdString; +} + +#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(into = "StdString", from = "StdString")] +#[serde(bound = "N: Normalize")] +pub struct String(StdString, N); + +impl fmt::Display for String { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self(value, _) = self; + value.fmt(f) + } +} + +impl From for String +where + S: AsRef, + N: Normalize, +{ + fn from(value: S) -> Self { + let normalizer = N::default(); + let value = normalizer.normalize(value.as_ref()); + + Self(value, normalizer) + } +} + +impl From> for StdString { + fn from(value: String) -> Self { + let String(value, _) = value; + value + } +} + +impl std::ops::Deref for String { + type Target = StdString; + + fn deref(&self) -> &Self::Target { + let Self(value, _) = self; + value + } +} + +// Type is manually implemented so that we can implement Decode to do +// normalization on read. Implementation is otherwise based on +// `#[derive(sqlx::Type)]` with the `#[sqlx(transparent)]` attribute. +impl Type for String +where + DB: Database, + StdString: Type, +{ + fn type_info() -> ::TypeInfo { + >::type_info() + } + + fn compatible(ty: &::TypeInfo) -> bool { + >::compatible(ty) + } +} + +impl<'r, DB, N> Decode<'r, DB> for String +where + DB: Database, + StdString: Decode<'r, DB>, + N: Normalize, +{ + fn decode(value: ::ValueRef<'r>) -> Result { + let value = StdString::decode(value)?; + Ok(Self::from(value)) + } +} + +impl<'q, DB, N> Encode<'q, DB> for String +where + DB: Database, + StdString: Encode<'q, DB>, +{ + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer<'q>, + ) -> Result { + let Self(value, _) = self; + value.encode_by_ref(buf) + } + + fn encode( + self, + buf: &mut ::ArgumentBuffer<'q>, + ) -> Result { + let Self(value, _) = self; + value.encode(buf) + } + + fn produces(&self) -> Option<::TypeInfo> { + let Self(value, _) = self; + value.produces() + } + + fn size_hint(&self) -> usize { + let Self(value, _) = self; + value.size_hint() + } +} diff --git a/src/setup/app.rs b/src/setup/app.rs index 9fbcf6d..030b5f6 100644 --- a/src/setup/app.rs +++ b/src/setup/app.rs @@ -4,7 +4,8 @@ use super::repo::Provider as _; use crate::{ clock::DateTime, event::{repo::Provider as _, Broadcaster, Event}, - login::{repo::Provider as _, Login, Name, Password}, + login::{repo::Provider as _, Login, Password}, + name::Name, token::{repo::Provider as _, Secret}, }; diff --git a/src/setup/routes/post.rs b/src/setup/routes/post.rs index 6a3fa11..fb2280a 100644 --- a/src/setup/routes/post.rs +++ b/src/setup/routes/post.rs @@ -8,7 +8,8 @@ use crate::{ app::App, clock::RequestedAt, error::Internal, - login::{Login, Name, Password}, + login::{Login, Password}, + name::Name, setup::app, token::extract::IdentityToken, }; diff --git a/src/test/fixtures/channel.rs b/src/test/fixtures/channel.rs index 024ac1b..3831c82 100644 --- a/src/test/fixtures/channel.rs +++ b/src/test/fixtures/channel.rs @@ -8,9 +8,10 @@ use rand; use crate::{ app::App, - channel::{self, Channel, Name}, + channel::{self, Channel}, clock::RequestedAt, event::Event, + name::Name, }; pub async fn create(app: &App, created_at: &RequestedAt) -> Channel { diff --git a/src/test/fixtures/login.rs b/src/test/fixtures/login.rs index 0a42320..714b936 100644 --- a/src/test/fixtures/login.rs +++ b/src/test/fixtures/login.rs @@ -4,7 +4,8 @@ use uuid::Uuid; use crate::{ app::App, clock::RequestedAt, - login::{self, Login, Name, Password}, + login::{self, Login, Password}, + name::Name, }; pub async fn create_with_password(app: &App, created_at: &RequestedAt) -> (Login, Password) { diff --git a/src/token/app.rs b/src/token/app.rs index d4dd1a0..c19d6a0 100644 --- a/src/token/app.rs +++ b/src/token/app.rs @@ -7,12 +7,14 @@ use futures::{ use sqlx::sqlite::SqlitePool; use super::{ - repo::auth::Provider as _, repo::Provider as _, Broadcaster, Event as TokenEvent, Id, Secret, + repo::{self, auth::Provider as _, Provider as _}, + Broadcaster, Event as TokenEvent, Id, Secret, }; use crate::{ clock::DateTime, db::NotFound as _, - login::{Login, Name, Password}, + login::{Login, Password}, + name::{self, Name}, }; pub struct Tokens<'a> { @@ -65,14 +67,16 @@ impl<'a> Tokens<'a> { used_at: &DateTime, ) -> Result<(Id, Login), ValidateError> { let mut tx = self.db.begin().await?; - let login = tx + let (token, login) = tx .tokens() .validate(secret, used_at) .await .not_found(|| ValidateError::InvalidToken)?; tx.commit().await?; - Ok(login) + let login = login.as_snapshot().ok_or(ValidateError::LoginDeleted)?; + + Ok((token, login)) } pub async fn limit_stream( @@ -162,15 +166,40 @@ pub enum LoginError { #[error(transparent)] Database(#[from] sqlx::Error), #[error(transparent)] + Name(#[from] name::Error), + #[error(transparent)] PasswordHash(#[from] password_hash::Error), } +impl From for LoginError { + fn from(error: repo::auth::LoadError) -> Self { + use repo::auth::LoadError; + match error { + LoadError::Database(error) => error.into(), + LoadError::Name(error) => error.into(), + } + } +} + #[derive(Debug, thiserror::Error)] pub enum ValidateError { #[error("invalid token")] InvalidToken, + #[error("login deleted")] + LoginDeleted, #[error(transparent)] Database(#[from] sqlx::Error), + #[error(transparent)] + Name(#[from] name::Error), +} + +impl From for ValidateError { + fn from(error: repo::LoadError) -> Self { + match error { + repo::LoadError::Database(error) => error.into(), + repo::LoadError::Name(error) => error.into(), + } + } } #[derive(Debug)] diff --git a/src/token/repo/auth.rs b/src/token/repo/auth.rs index c621b65..bdc4c33 100644 --- a/src/token/repo/auth.rs +++ b/src/token/repo/auth.rs @@ -2,8 +2,10 @@ use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use crate::{ clock::DateTime, + db::NotFound, event::{Instant, Sequence}, - login::{self, password::StoredHash, History, Login, Name}, + login::{self, password::StoredHash, History, Login}, + name::{self, Name}, }; pub trait Provider { @@ -19,35 +21,53 @@ impl<'c> Provider for Transaction<'c, Sqlite> { pub struct Auth<'t>(&'t mut SqliteConnection); impl<'t> Auth<'t> { - pub async fn for_name(&mut self, name: &Name) -> Result<(History, StoredHash), sqlx::Error> { - let found = sqlx::query!( + pub async fn for_name(&mut self, name: &Name) -> Result<(History, StoredHash), LoadError> { + let name = name.canonical(); + let row = sqlx::query!( r#" - select - id as "id: login::Id", - name as "name: Name", - password_hash as "password_hash: StoredHash", + select + id as "id: login::Id", + display_name as "display_name: String", + canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", - created_at as "created_at: DateTime" - from login - where name = $1 - "#, + created_at as "created_at: DateTime", + password_hash as "password_hash: StoredHash" + from login + where canonical_name = $1 + "#, name, ) - .map(|row| { - ( - History { - login: Login { - id: row.id, - name: row.name, - }, - created: Instant::new(row.created_at, row.created_sequence), - }, - row.password_hash, - ) - }) .fetch_one(&mut *self.0) .await?; - Ok(found) + let login = History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, + }, + created: Instant::new(row.created_at, row.created_sequence), + }; + + Ok((login, row.password_hash)) + } +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl NotFound for Result { + type Ok = T; + type Error = LoadError; + + fn optional(self) -> Result, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } } } diff --git a/src/token/repo/mod.rs b/src/token/repo/mod.rs index 9169743..d8463eb 100644 --- a/src/token/repo/mod.rs +++ b/src/token/repo/mod.rs @@ -1,4 +1,4 @@ pub mod auth; mod token; -pub use self::token::Provider; +pub use self::token::{LoadError, Provider}; diff --git a/src/token/repo/token.rs b/src/token/repo/token.rs index 960bb72..35ea385 100644 --- a/src/token/repo/token.rs +++ b/src/token/repo/token.rs @@ -3,7 +3,10 @@ use uuid::Uuid; use crate::{ clock::DateTime, - login::{self, History, Login, Name}, + db::NotFound, + event::{Instant, Sequence}, + login::{self, History, Login}, + name::{self, Name}, token::{Id, Secret}, }; @@ -100,53 +103,78 @@ impl<'c> Tokens<'c> { } // Validate a token by its secret, retrieving the associated Login record. - // Will return [None] if the token is not valid. The token's last-used - // timestamp will be set to `used_at`. + // Will return an error if the token is not valid. If successful, the + // retrieved token's last-used timestamp will be set to `used_at`. pub async fn validate( &mut self, secret: &Secret, used_at: &DateTime, - ) -> Result<(Id, Login), sqlx::Error> { + ) -> Result<(Id, History), LoadError> { // I would use `update … returning` to do this in one query, but // sqlite3, as of this writing, does not allow an update's `returning` // clause to reference columns from tables joined into the update. Two // queries is fine, but it feels untidy. - sqlx::query!( + let (token, login) = sqlx::query!( r#" update token set last_used_at = $1 where secret = $2 + returning + id as "token: Id", + login as "login: login::Id" "#, used_at, secret, ) - .execute(&mut *self.0) + .map(|row| (row.token, row.login)) + .fetch_one(&mut *self.0) .await?; let login = sqlx::query!( r#" select - token.id as "token_id: Id", - login.id as "login_id: login::Id", - login.name as "login_name: Name" + id as "id: login::Id", + display_name as "display_name: String", + canonical_name as "canonical_name: String", + created_sequence as "created_sequence: Sequence", + created_at as "created_at: DateTime" from login - join token on login.id = token.login - where token.secret = $1 + where id = $1 "#, - secret, + login, ) .map(|row| { - ( - row.token_id, - Login { - id: row.login_id, - name: row.login_name, + Ok::<_, name::Error>(History { + login: Login { + id: row.id, + name: Name::new(row.display_name, row.canonical_name)?, }, - ) + created: Instant::new(row.created_at, row.created_sequence), + }) }) .fetch_one(&mut *self.0) - .await?; + .await??; + + Ok((token, login)) + } +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum LoadError { + Database(#[from] sqlx::Error), + Name(#[from] name::Error), +} + +impl NotFound for Result { + type Ok = T; + type Error = LoadError; - Ok(login) + fn optional(self) -> Result, LoadError> { + match self { + Ok(value) => Ok(Some(value)), + Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), + Err(other) => Err(other), + } } } -- cgit v1.2.3