From 07d22dc98ef4eeea0e4b237095b8e05a014212e7 Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 08:29:46 +0100 Subject: [PATCH 01/25] GO1: model: own identity provider (OAuth) settings An OAuth provider of the owner's own (`OAuthProvider::Custom`) with its issuer, sign-in, token and revocation addresses, extra scopes, SASL mechanism, redirect port and whether a client secret is kept, all saved with the account. Microsoft's and Google's built-in values move to the model (`OAuthProvider::defaults`, `OAuth::effective`) so that settings show what is used; `OAuth::check` refuses anything that can't be sent and keeps Microsoft's and Google's values unchangeable. A provider a file names that this version doesn't know reads as an own provider with nothing set up, never as Microsoft. An IMAP account that signs in with an own provider is written with a kind earlier versions don't know, so that they keep it whole instead of failing to open the mailbox. A token from an own provider goes only to the account's own IMAP and SMTP servers, never to Microsoft's or Google's. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- apps/mailcraft-cli/src/main.rs | 8 +- crates/engine/src/cmd/account.rs | 13 +- crates/engine/src/sync_driver/credentials.rs | 2 + crates/i18n/po/cs.po | 49 +++ crates/i18n/po/de.po | 49 +++ crates/i18n/po/es.po | 49 +++ crates/i18n/po/fr.po | 49 +++ crates/i18n/po/hu.po | 49 +++ crates/i18n/po/it.po | 49 +++ crates/i18n/po/ka.po | 49 +++ crates/i18n/po/messages.pot | 49 +++ crates/i18n/po/nl.po | 49 +++ crates/i18n/po/pl.po | 49 +++ crates/i18n/po/ro.po | 49 +++ crates/i18n/po/zh_CN.po | 49 +++ crates/model/src/lib.rs | 2 + crates/model/src/mailbox.rs | 66 +++- crates/model/src/mailbox_tests.rs | 9 +- crates/model/src/oauth.rs | 336 +++++++++++++++++++ crates/model/src/oauth_custom_tests.rs | 208 ++++++++++++ crates/net/src/oauth.rs | 18 +- crates/net/src/sync.rs | 19 ++ crates/net/src/tests.rs | 1 + crates/net/tests/token_hosts.rs | 39 ++- 24 files changed, 1286 insertions(+), 23 deletions(-) create mode 100644 crates/model/src/oauth.rs create mode 100644 crates/model/src/oauth_custom_tests.rs diff --git a/apps/mailcraft-cli/src/main.rs b/apps/mailcraft-cli/src/main.rs index baab0afe7b..8a9b4b5486 100644 --- a/apps/mailcraft-cli/src/main.rs +++ b/apps/mailcraft-cli/src/main.rs @@ -511,8 +511,12 @@ fn run(args: &[String]) -> Result<(), Failure> { mailcraft_model::OAuthProvider::Google => { ("MAILCRAFT_GOOGLE_CLIENT_ID", option_env!("MAILCRAFT_GOOGLE_CLIENT_ID").unwrap_or_default()) } + // (Its client id is the account's own setting: there is no other.) + mailcraft_model::OAuthProvider::Custom => ("", ""), }; - oauth.client_id = std::env::var(variable).unwrap_or_else(|_| built_in.to_string()); + if !variable.is_empty() { + oauth.client_id = std::env::var(variable).unwrap_or_else(|_| built_in.to_string()); + } } let open = |url: &str| { eprintln!( @@ -522,7 +526,7 @@ fn run(args: &[String]) -> Result<(), Failure> { }; let cancel = std::sync::atomic::AtomicBool::new(false); let signed_in = match oauth.provider { - mailcraft_model::OAuthProvider::Microsoft => { + mailcraft_model::OAuthProvider::Microsoft | mailcraft_model::OAuthProvider::Custom => { mailcraft_net::oauth::sign_in(&oauth, &request.account.email, &open, &cancel) } mailcraft_model::OAuthProvider::Google => { diff --git a/crates/engine/src/cmd/account.rs b/crates/engine/src/cmd/account.rs index 8d7223a6c4..eac696d155 100644 --- a/crates/engine/src/cmd/account.rs +++ b/crates/engine/src/cmd/account.rs @@ -104,7 +104,10 @@ fn sign_in(a: &mut Account, v: &Value) -> Result<(), CmdError> { Some(_) => return Err(bad("`auth` is password or oauth2")), } let provider = match p::str(v, "provider") { - Some(name) => Some(OAuthProvider::parse(name).ok_or_else(|| bad("`provider` is microsoft or google"))?), + // (An own identity provider is set up with its own fields, which this doesn't take yet.) + Some(name) => { + Some(OAuthProvider::parse(name).filter(|p| *p != OAuthProvider::Custom).ok_or_else(|| bad("`provider` is microsoft or google"))?) + } None => None, }; let (client_id, tenant) = (word("clientId", 200)?, word("tenant", 64)?); @@ -147,7 +150,7 @@ fn preset(_: &mut Session, v: &Value) -> CmdResult { _ => return Err(bad(format!("\"{email}\" isn't an e-mail address"))), }; let asked = match p::str(v, "provider") { - Some(name) => Some(OAuthProvider::parse(name).ok_or_else(|| bad("`provider` is microsoft or google"))?), + Some(name) => Some(OAuthProvider::parse(name).ok_or_else(|| bad("`provider` is microsoft, google or custom"))?), None => None, }; // The owner says whose the account is: that settles it. @@ -164,6 +167,8 @@ fn preset(_: &mut Session, v: &Value) -> CmdResult { // Explicitly choosing Google OAuth beats an app-password provider preset. // Ordinary discovery without that choice keeps the password flow. (Some(OAuthProvider::Google), own) => (Some(provider::google(own.is_some_and(|p| p.service == "Gmail"))), "asked"), + // An own identity provider: the servers are found as for a domain nobody here knows. + (Some(OAuthProvider::Custom), _) => (None, "asked"), _ if named.is_some() => (named, "asked"), // Said to be Microsoft's: Outlook.com when the domain is, work or school mail otherwise. (Some(OAuthProvider::Microsoft), own) => { @@ -203,8 +208,8 @@ fn preset(_: &mut Session, v: &Value) -> CmdResult { "known": known, "via": via, "service": preset.service, - "auth": if preset.oauth.is_some() { "oauth2" } else { "password" }, - "provider": preset.oauth.map(OAuthProvider::code), + "auth": if preset.oauth.is_some() || asked == Some(OAuthProvider::Custom) { "oauth2" } else { "password" }, + "provider": if asked == Some(OAuthProvider::Custom) { Some(OAuthProvider::Custom.code()) } else { preset.oauth.map(OAuthProvider::code) }, "username": username, "incoming": server(incoming.as_ref().map(|(s, _)| s).unwrap_or(&preset.incoming), if known { via } else { incoming_via }), "outgoing": server(outgoing.as_ref().map(|(s, _)| s).unwrap_or(&preset.outgoing), if known { via } else { outgoing_via }), diff --git a/crates/engine/src/sync_driver/credentials.rs b/crates/engine/src/sync_driver/credentials.rs index 3a9b977422..0197308840 100644 --- a/crates/engine/src/sync_driver/credentials.rs +++ b/crates/engine/src/sync_driver/credentials.rs @@ -24,6 +24,8 @@ pub fn effective_oauth(mut oauth: OAuth, ids: &ClientIds) -> OAuth { let (chosen, built_in) = match oauth.provider { OAuthProvider::Microsoft => (ids.microsoft_chosen, ids.microsoft_built_in), OAuthProvider::Google => (ids.google_chosen, ids.google_built_in), + // (An own identity provider has no id but the one registered there.) + OAuthProvider::Custom => return oauth, }; oauth.client_id = if chosen.is_empty() { built_in } else { chosen }.to_string(); } diff --git a/crates/i18n/po/cs.po b/crates/i18n/po/cs.po index a5cb795630..d1e125b748 100644 --- a/crates/i18n/po/cs.po +++ b/crates/i18n/po/cs.po @@ -27662,3 +27662,52 @@ msgstr "−Řádky" #~ msgid "Show a notification when a calendar reminder falls due. Off, none is shown; the reminders themselves stay in the calendar." #~ msgstr "Zobrazit oznámení, když nastane čas připomenutí v kalendáři. Pokud je vypnuto, nezobrazí se žádné; samotná připomenutí zůstávají v kalendáři." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/de.po b/crates/i18n/po/de.po index a8e052336c..0ac7003972 100644 --- a/crates/i18n/po/de.po +++ b/crates/i18n/po/de.po @@ -26129,3 +26129,52 @@ msgstr "−Zeilen" #~ msgstr[0] "{n} Nachricht wird endgültig gelöscht." #~ msgstr[1] "{n} Nachrichten werden endgültig gelöscht." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/es.po b/crates/i18n/po/es.po index 6671afaa54..4fe5c32b24 100644 --- a/crates/i18n/po/es.po +++ b/crates/i18n/po/es.po @@ -27686,3 +27686,52 @@ msgstr "−Líneas" #~ msgstr[0] "{n} mensaje se eliminará de forma definitiva." #~ msgstr[1] "{n} mensajes se eliminarán de forma definitiva." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/fr.po b/crates/i18n/po/fr.po index 83d761a9c7..1a3bf28770 100644 --- a/crates/i18n/po/fr.po +++ b/crates/i18n/po/fr.po @@ -27587,3 +27587,52 @@ msgstr "−Lignes" #~ msgstr[0] "{n} message sera définitivement supprimé." #~ msgstr[1] "{n} messages seront définitivement supprimés." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/hu.po b/crates/i18n/po/hu.po index c8345a3dc4..4e16501a37 100644 --- a/crates/i18n/po/hu.po +++ b/crates/i18n/po/hu.po @@ -27532,3 +27532,52 @@ msgstr "−Sorok" #~ msgid "This build has no application id to sign in with." #~ msgstr "A MailCraft ezen verziójában nincs alkalmazásazonosító a bejelentkezéshez." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/it.po b/crates/i18n/po/it.po index a3391d8b76..1efcb8edb3 100644 --- a/crates/i18n/po/it.po +++ b/crates/i18n/po/it.po @@ -27668,3 +27668,52 @@ msgstr "−Righe" #~ msgstr[0] "{n} messaggio verrà eliminato definitivamente." #~ msgstr[1] "{n} messaggi verranno eliminati definitivamente." +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/ka.po b/crates/i18n/po/ka.po index 44718e8696..e3a92a57c9 100644 --- a/crates/i18n/po/ka.po +++ b/crates/i18n/po/ka.po @@ -27452,3 +27452,52 @@ msgstr "" #~ msgid "{not_sending_yet}: send this message from another account, or save it as a draft" #~ msgstr "{not_sending_yet}: ეს წერილი სხვა ანგარიშიდან გაგზავნეთ ან მონახაზად შეინახეთ" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/messages.pot b/crates/i18n/po/messages.pot index 72ad3a2d20..ff1405bf50 100644 --- a/crates/i18n/po/messages.pot +++ b/crates/i18n/po/messages.pot @@ -22678,3 +22678,52 @@ msgstr "" msgid "−Lines" msgstr "" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/nl.po b/crates/i18n/po/nl.po index 43def5f30d..8606b7ad04 100644 --- a/crates/i18n/po/nl.po +++ b/crates/i18n/po/nl.po @@ -27080,3 +27080,52 @@ msgstr "−Regels" #~ msgid "Scheduling Assistant" #~ msgstr "Planningassistent" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/pl.po b/crates/i18n/po/pl.po index f12555a36b..641ce07104 100644 --- a/crates/i18n/po/pl.po +++ b/crates/i18n/po/pl.po @@ -27717,3 +27717,52 @@ msgstr "−Wiersze" #~ msgid "the mailbox has no calendar" #~ msgstr "skrzynka pocztowa nie ma kalendarza" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/ro.po b/crates/i18n/po/ro.po index 6045fa226a..afcdf855e0 100644 --- a/crates/i18n/po/ro.po +++ b/crates/i18n/po/ro.po @@ -27745,3 +27745,52 @@ msgstr "−Linii" #~ msgid "The draft stays in Drafts. {why}" #~ msgstr "Ciorna rămâne în Ciorne. {why}" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/i18n/po/zh_CN.po b/crates/i18n/po/zh_CN.po index 96e0f63367..b546fc3ffc 100644 --- a/crates/i18n/po/zh_CN.po +++ b/crates/i18n/po/zh_CN.po @@ -27381,3 +27381,52 @@ msgstr "−行" #~ msgid "The draft stays in Drafts. {why}" #~ msgstr "草稿保留在“草稿”中。{why}" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only sent to a mail server on this computer in a test" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "a sign-in with your identity provider is only used with this account's own mail servers" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "enter the client id registered for MailCraft at your identity provider" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "find your identity provider's sign-in addresses (Discover), or enter them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the client id can only be letters, digits and punctuation, at most 200 of them" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the identity provider (issuer) address can't have a query or a fragment" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "the redirect port must be between 1 and 65535, or automatic" +msgstr "" + +#. what a command says +#: crates/model/src/oauth.rs +msgid "use common, consumers, organizations, or a directory's id or domain as the tenant" +msgstr "" + +#. name +#: crates/model/src/mailbox.rs +msgid "your identity provider" +msgstr "" diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 45c399a283..fc962b60b2 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -33,6 +33,7 @@ pub mod messages; #[cfg(test)] mod messages_tests; mod note; +pub mod oauth; mod offline; pub mod outlook_colors; pub mod pictures; @@ -97,6 +98,7 @@ pub use message::{ }; pub use messages::Messages; pub use note::{JournalEntry, Note}; +pub use oauth::{OAuthDefaults, SaslChoice}; pub use offline::{KeepOffline, OfflineWindow}; pub use outlook_colors::preset_category_color; pub use remote::{AccountChoice, Origin}; diff --git a/crates/model/src/mailbox.rs b/crates/model/src/mailbox.rs index 530be38630..9a5c3f126a 100644 --- a/crates/model/src/mailbox.rs +++ b/crates/model/src/mailbox.rs @@ -18,6 +18,7 @@ mod followup; mod snooze; #[path = "category_sweep.rs"] mod sweep; +use crate::oauth::SaslChoice; use crate::sync::{RemoteFlags, same_category}; use crate::{ Action, Answers, Calendar, Contact, DavServer, Event, EwsServer, Id, JmapServer, KeepOffline, Message, ModelError, Rgb, Rule, Signature, Task, @@ -681,7 +682,14 @@ struct Identity { fn read_accounts<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { let written = crate::load_limit::capped_vec::<_, serde_json::Value>(deserializer)?; let mut accounts = Vec::with_capacity(written.len()); - for value in written { + for mut value in written { + // (An IMAP account that signs in with an own identity provider is written with a kind of + // its own, which earlier versions don't know and so keep whole: it is an IMAP account.) + if value.get("kind").and_then(serde_json::Value::as_str) == Some(crate::oauth::OWN_SIGN_IN_KIND) + && let Some(fields) = value.as_object_mut() + { + fields.insert("kind".into(), serde_json::Value::String("imap".into())); + } // (Only an object has a `kind`; one without says nothing, which is a local account.) let unknown = value.get("kind").is_some_and(|kind| AccountKind::deserialize(kind).unwrap_or(AccountKind::Unknown) == AccountKind::Unknown); if !unknown { @@ -720,6 +728,13 @@ fn write_accounts(accounts: &[Account], serializer: S) -> fields.insert("id".into(), account.id.into()); list.serialize_element(&fields)?; } + None if account.signs_in_with_own_provider() => { + let mut value = serde_json::to_value(account).map_err(serde::ser::Error::custom)?; + if let Some(fields) = value.as_object_mut() { + fields.insert("kind".into(), serde_json::Value::String(crate::oauth::OWN_SIGN_IN_KIND.into())); + } + list.serialize_element(&value)?; + } None => list.serialize_element(account)?, } } @@ -876,6 +891,12 @@ impl Account { if user.is_empty() { self.email.trim() } else { user } } + /// Whether it signs in with an identity provider of the owner's own + /// ([`OAuthProvider::Custom`]). + pub fn signs_in_with_own_provider(&self) -> bool { + self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom) + } + /// A Microsoft account (it signs in with Microsoft) that is still kept in step by IMAP and /// SMTP: one that can switch to Microsoft Graph (R3.7). pub fn on_imap_with_microsoft(&self) -> bool { @@ -892,6 +913,11 @@ pub enum OAuthProvider { Microsoft, /// Gmail and Google Workspace over IMAP/SMTP XOAUTH2. Google, + /// The owner's own identity provider (an OpenID Connect or OAuth 2.0 server such as Keycloak + /// or Authentik) in front of their own IMAP and SMTP servers: its addresses, the client id + /// registered there and the rest are the account's own settings ([`OAuth::issuer`] and on), + /// not built in. Only an IMAP account signs in with one. + Custom, } impl OAuth { @@ -915,6 +941,7 @@ impl OAuthProvider { match s.trim().to_ascii_lowercase().as_str() { "microsoft" | "outlook" | "office365" | "microsoft365" => Some(OAuthProvider::Microsoft), "google" | "gmail" | "googleworkspace" => Some(OAuthProvider::Google), + "custom" | "generic" | "oidc" | "own" => Some(OAuthProvider::Custom), _ => None, } } @@ -923,6 +950,7 @@ impl OAuthProvider { match self { OAuthProvider::Microsoft => "microsoft", OAuthProvider::Google => "google", + OAuthProvider::Custom => "custom", } } @@ -930,6 +958,7 @@ impl OAuthProvider { match self { OAuthProvider::Microsoft => "Microsoft", OAuthProvider::Google => "Google", + OAuthProvider::Custom => "your identity provider", } } } @@ -939,6 +968,10 @@ impl OAuthProvider { #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct OAuth { + /// Who signs the owner in. A file that names one this version doesn't know reads as + /// [`OAuthProvider::Custom`] with no addresses, which signs in nowhere until it is set up + /// again: never as Microsoft, whose page and hosts it would otherwise be given. + #[serde(deserialize_with = "crate::oauth::provider_read")] pub provider: OAuthProvider, /// The application (client) id presented to the provider; empty means the build's own. #[serde(skip_serializing_if = "String::is_empty")] @@ -951,6 +984,37 @@ pub struct OAuth { /// never the directory's id. #[serde(skip_serializing_if = "Directory::is_unknown", deserialize_with = "crate::sync::lenient_or_default")] pub directory: Directory, + /// [`OAuthProvider::Custom`]: the identity provider's own address (its issuer), from which + /// its sign-in and token addresses are found (OpenID Connect Discovery, RFC 8414). Empty when + /// the two addresses were typed by hand instead. + #[serde(skip_serializing_if = "String::is_empty", deserialize_with = "crate::sync::lenient_or_default")] + pub issuer: String, + /// [`OAuthProvider::Custom`]: the page the owner signs in on (the authorization endpoint), + /// as found from the issuer or typed. + #[serde(skip_serializing_if = "String::is_empty", deserialize_with = "crate::sync::lenient_or_default")] + pub authorize: String, + /// [`OAuthProvider::Custom`]: where a code or a refresh token is traded for tokens. + #[serde(skip_serializing_if = "String::is_empty", deserialize_with = "crate::sync::lenient_or_default")] + pub token: String, + /// [`OAuthProvider::Custom`]: where a refresh token is given back when the account is + /// removed (RFC 7009); empty for none. + #[serde(skip_serializing_if = "String::is_empty", deserialize_with = "crate::sync::lenient_or_default")] + pub revoke: String, + /// [`OAuthProvider::Custom`]: what the tokens are asked for on top of + /// [`crate::oauth::CUSTOM_SCOPE`], separated by spaces; empty for nothing more. + #[serde(skip_serializing_if = "String::is_empty", deserialize_with = "crate::sync::lenient_or_default")] + pub scopes: String, + /// [`OAuthProvider::Custom`]: how the mail servers are given the token. + #[serde(skip_serializing_if = "SaslChoice::is_auto", deserialize_with = "crate::sync::lenient_or_default")] + pub mechanism: SaslChoice, + /// The port on this computer the provider's page sends the owner back to; `None` for any + /// free one (what a provider that follows RFC 8252 §7.3 allows). + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "crate::sync::lenient")] + pub redirect_port: Option, + /// [`OAuthProvider::Custom`]: whether a client secret for it is kept in the system's + /// credential store. Never the secret itself. + #[serde(skip_serializing_if = "std::ops::Not::not", deserialize_with = "crate::sync::lenient_or_default")] + pub has_secret: bool, } /// A change made here to what a Microsoft account's server has that comparing with what the diff --git a/crates/model/src/mailbox_tests.rs b/crates/model/src/mailbox_tests.rs index 20141ade5b..a55280e2d3 100644 --- a/crates/model/src/mailbox_tests.rs +++ b/crates/model/src/mailbox_tests.rs @@ -892,8 +892,13 @@ fn a_file_from_before_the_jmap_setting_reads_and_writes_as_it_was() { assert_eq!(serde_json::to_string(&read).unwrap(), written); } - let oauth = - OAuth { provider: OAuthProvider::Microsoft, client_id: "app-id".into(), tenant: "organizations".into(), directory: Directory::Organisation }; + let oauth = OAuth { + provider: OAuthProvider::Microsoft, + client_id: "app-id".into(), + tenant: "organizations".into(), + directory: Directory::Organisation, + ..Default::default() + }; let microsoft = Account { id: 2, name: "Noor".into(), diff --git a/crates/model/src/oauth.rs b/crates/model/src/oauth.rs new file mode 100644 index 0000000000..75ef6f862e --- /dev/null +++ b/crates/model/src/oauth.rs @@ -0,0 +1,336 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The settings of an OAuth 2.0 sign-in beyond who signs the owner in ([`OAuth`]): the values +//! built in for Microsoft and Google, and the owner's own for an identity provider of their own +//! ([`OAuthProvider::Custom`]), with what makes them usable. +//! +//! Nothing here goes anywhere: these are settings, checked as text. The host that holds the +//! sockets uses them (`mailcraft-net`); the tokens and any client secret are never here. +//! +//! **Built in or the owner's.** Microsoft's and Google's addresses, scopes and mechanism are +//! the program's own ([`OAuthProvider::defaults`]) and can't be changed on such an account: only +//! its client id, tenant and redirect port can. An account whose addresses are anybody else's is +//! a [`OAuthProvider::Custom`] one, so that what may be sent to Microsoft's and Google's hosts +//! is never loosened by a setting ([`OAuth::check`]). + +use serde::{Deserialize, Serialize}; + +use crate::{ModelError, OAuth, OAuthProvider}; + +/// Where Microsoft signs people in. +pub const MICROSOFT_LOGIN: &str = "https://login.microsoftonline.com"; +/// What a Microsoft account's mail sign-in asks for: IMAP, SMTP, a refresh token and who signs in. +pub const MICROSOFT_MAIL_SCOPE: &str = + "https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access openid profile email"; +/// The mail servers a Microsoft account's token is for (as shown; the host decides by domain). +pub const MICROSOFT_HOSTS: [&str; 3] = ["outlook.office365.com", "smtp.office365.com", "smtp-mail.outlook.com"]; +/// Google's identity provider. +pub const GOOGLE_ISSUER: &str = "https://accounts.google.com"; +/// Google's sign-in page. +pub const GOOGLE_AUTHORIZE: &str = "https://accounts.google.com/o/oauth2/v2/auth"; +/// Google's token endpoint. +pub const GOOGLE_TOKEN: &str = "https://oauth2.googleapis.com/token"; +/// Where Google takes a refresh token back. +pub const GOOGLE_REVOKE: &str = "https://oauth2.googleapis.com/revoke"; +/// What a Google account's sign-in asks for: Gmail's IMAP and SMTP, and who signs in. +pub const GOOGLE_SCOPE: &str = "https://mail.google.com/ openid email"; +/// The mail servers a Google account's token is for. +pub const GOOGLE_HOSTS: [&str; 2] = ["imap.gmail.com", "smtp.gmail.com"]; +/// What an own identity provider is always asked for: who signs in, their address, and a refresh +/// token so that the owner isn't asked again each time a token runs out. +pub const CUSTOM_SCOPE: &str = "openid email offline_access"; + +/// Longest address of an identity provider, its pages or its endpoints. +pub const MAX_ENDPOINT: usize = 2048; +/// Longest list of extra scopes, in bytes. +pub const MAX_SCOPES: usize = 1024; +/// Most extra scopes. +pub const MAX_SCOPE_COUNT: usize = 32; +/// Longest client id. +pub const MAX_CLIENT_ID: usize = 200; + +/// How the mail servers are given an access token (SASL). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum SaslChoice { + /// OAUTHBEARER (RFC 7628) when the server offers it, else XOAUTH2. + #[default] + #[serde(rename = "auto")] + Auto, + /// OAUTHBEARER only. + #[serde(rename = "oauthbearer")] + OAuthBearer, + /// XOAUTH2 only. + #[serde(rename = "xoauth2")] + XOAuth2, +} + +impl SaslChoice { + pub fn is_auto(&self) -> bool { + *self == SaslChoice::Auto + } + + pub fn parse(text: &str) -> Option { + match text.trim().to_ascii_lowercase().as_str() { + "" | "auto" | "automatic" => Some(SaslChoice::Auto), + "oauthbearer" => Some(SaslChoice::OAuthBearer), + "xoauth2" => Some(SaslChoice::XOAuth2), + _ => None, + } + } + + pub fn code(self) -> &'static str { + match self { + SaslChoice::Auto => "auto", + SaslChoice::OAuthBearer => "oauthbearer", + SaslChoice::XOAuth2 => "xoauth2", + } + } +} + +/// Everything a sign-in uses, as it is used: built in for Microsoft and Google, the account's +/// own for an own identity provider ([`OAuth::effective`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OAuthDefaults { + pub provider: OAuthProvider, + /// The identity provider's own address; empty when there is none to show. + pub issuer: String, + pub authorize: String, + pub token: String, + /// Empty for none. + pub revoke: String, + /// Everything the tokens are asked for, separated by spaces. + pub scopes: String, + pub mechanism: SaslChoice, + /// The client id: the account's own, or empty for the build's own (Microsoft and Google only). + pub client_id: String, + /// Whether the client id used is the build's own. + pub built_in_client: bool, + /// The mail servers the token is for, when they are the provider's own; empty for an own + /// identity provider, whose token goes to the account's own IMAP and SMTP servers only. + pub hosts: Vec, + pub redirect_port: Option, +} + +impl OAuthProvider { + /// The values built in for this provider. `tenant` is Microsoft's directory (empty, or one + /// that can't be part of an address, reads as `common`); the others have none. An own + /// identity provider has no addresses built in: only what it is always asked for. + pub fn defaults(self, tenant: &str) -> OAuthDefaults { + match self { + OAuthProvider::Microsoft => { + let tenant = usable_tenant(tenant).unwrap_or("common"); + OAuthDefaults { + provider: self, + issuer: format!("{MICROSOFT_LOGIN}/{tenant}/v2.0"), + authorize: format!("{MICROSOFT_LOGIN}/{tenant}/oauth2/v2.0/authorize"), + token: format!("{MICROSOFT_LOGIN}/{tenant}/oauth2/v2.0/token"), + revoke: String::new(), + scopes: MICROSOFT_MAIL_SCOPE.into(), + mechanism: SaslChoice::XOAuth2, + client_id: String::new(), + built_in_client: true, + hosts: MICROSOFT_HOSTS.iter().map(|h| h.to_string()).collect(), + redirect_port: None, + } + } + OAuthProvider::Google => OAuthDefaults { + provider: self, + issuer: GOOGLE_ISSUER.into(), + authorize: GOOGLE_AUTHORIZE.into(), + token: GOOGLE_TOKEN.into(), + revoke: GOOGLE_REVOKE.into(), + scopes: GOOGLE_SCOPE.into(), + mechanism: SaslChoice::XOAuth2, + client_id: String::new(), + built_in_client: true, + hosts: GOOGLE_HOSTS.iter().map(|h| h.to_string()).collect(), + redirect_port: None, + }, + OAuthProvider::Custom => { + OAuthDefaults { provider: self, scopes: CUSTOM_SCOPE.into(), mechanism: SaslChoice::Auto, ..OAuthDefaults::default() } + } + } + } +} + +impl OAuth { + /// Settings for an own identity provider with nothing filled in yet. + pub fn custom() -> OAuth { + OAuth { provider: OAuthProvider::Custom, ..OAuth::default() } + } + + /// What a sign-in with these settings uses: the provider's built-in values with the + /// account's client id, tenant and redirect port over them; for an own identity provider, + /// the account's own values, with [`CUSTOM_SCOPE`] before its extra scopes. + pub fn effective(&self) -> OAuthDefaults { + let mut used = self.provider.defaults(&self.tenant); + let client = self.client_id.trim(); + if !client.is_empty() { + used.client_id = client.to_string(); + used.built_in_client = false; + } + used.redirect_port = self.redirect_port; + if self.provider == OAuthProvider::Custom { + used.built_in_client = false; + used.issuer = self.issuer.trim().to_string(); + used.authorize = self.authorize.trim().to_string(); + used.token = self.token.trim().to_string(); + used.revoke = self.revoke.trim().to_string(); + used.mechanism = self.mechanism; + used.scopes = scope_list(CUSTOM_SCOPE, &self.scopes); + } + used + } + + /// Whether these settings can be saved: every value that is there is one that can be used + /// (addresses `https://` ones, or `http://` ones on this computer; no user name or fragment + /// in them; scopes of the characters RFC 6749 §3.3 allows; a client id, tenant and port that + /// can be sent). An own identity provider needs a client id. Microsoft's and Google's + /// accounts have no addresses, scopes or mechanism of their own: those are built in. + /// + /// It doesn't say whether a sign-in can start: [`OAuth::ready`] does. + pub fn check(&self) -> Result<(), ModelError> { + let invalid = |text: String| Err(ModelError::Invalid(text)); + let client = self.client_id.trim(); + if client.len() > MAX_CLIENT_ID || !client.bytes().all(|b| b.is_ascii_graphic()) { + return invalid("the client id can only be letters, digits and punctuation, at most 200 of them".into()); + } + if self.redirect_port == Some(0) { + return invalid("the redirect port must be between 1 and 65535, or automatic".into()); + } + if self.provider == OAuthProvider::Microsoft && !self.tenant.trim().is_empty() && usable_tenant(&self.tenant).is_none() { + return invalid("use common, consumers, organizations, or a directory's id or domain as the tenant".into()); + } + let own = [&self.issuer, &self.authorize, &self.token, &self.revoke, &self.scopes].iter().any(|value| !value.trim().is_empty()) + || !self.mechanism.is_auto() + || self.has_secret; + if self.provider != OAuthProvider::Custom { + if own { + return invalid(format!( + "{}'s addresses, scopes and mechanism are built in: an account with its own is set up for your own identity provider", + self.provider.label() + )); + } + return Ok(()); + } + if client.is_empty() { + return invalid("enter the client id registered for MailCraft at your identity provider".into()); + } + for (what, value) in + [("identity provider (issuer)", &self.issuer), ("sign-in", &self.authorize), ("token", &self.token), ("revocation", &self.revoke)] + { + if let Err(why) = endpoint(value) { + return invalid(format!("the {what} address {why}")); + } + } + if !self.issuer.trim().is_empty() && self.issuer.contains(['?', '#']) { + return invalid("the identity provider (issuer) address can't have a query or a fragment".into()); + } + scopes(&self.scopes).map_err(ModelError::Invalid) + } + + /// Whether a sign-in can start with these settings ([`OAuth::check`], and for an own + /// identity provider both its sign-in and token addresses, found or typed). + pub fn ready(&self) -> Result<(), ModelError> { + self.check()?; + if self.provider == OAuthProvider::Custom && (self.authorize.trim().is_empty() || self.token.trim().is_empty()) { + return Err(ModelError::Invalid("find your identity provider's sign-in addresses (Discover), or enter them".into())); + } + Ok(()) + } + + /// The values a remembered sign-in belongs to: changing any of them needs a fresh sign-in on + /// the provider's page, so that a changed setting never sends a remembered token anywhere new. + pub fn binding(&self) -> String { + let used = self.effective(); + format!("{}|{}|{}|{}", self.provider.code(), used.issuer, used.token, used.client_id) + } +} + +/// `base` and the owner's `extra` scopes, each once, in that order. +pub fn scope_list(base: &str, extra: &str) -> String { + let mut all: Vec<&str> = Vec::new(); + for scope in base.split_ascii_whitespace().chain(extra.split_ascii_whitespace()) { + if !all.contains(&scope) { + all.push(scope); + } + } + all.join(" ") +} + +/// Whether `text` is a list of scopes that can be sent: at most [`MAX_SCOPE_COUNT`] of them in +/// [`MAX_SCOPES`] bytes, each of the characters RFC 6749 §3.3 allows. +pub fn scopes(text: &str) -> Result<(), String> { + if text.len() > MAX_SCOPES { + return Err("the extra scopes are too long".into()); + } + let mut count = 0usize; + for scope in text.split([' ', '\t']).filter(|s| !s.is_empty()) { + count = count.saturating_add(1); + if !scope.bytes().all(|b| b == 0x21 || (0x23..=0x5B).contains(&b) || (0x5D..=0x7E).contains(&b)) { + return Err("a scope can only be letters, digits and punctuation other than \" and \\".into()); + } + } + if count > MAX_SCOPE_COUNT { + return Err(format!("at most {MAX_SCOPE_COUNT} extra scopes")); + } + Ok(()) +} + +/// Whether `text` is an address an identity provider can be reached at: empty, or an absolute +/// `https://` one (an `http://` one only on this computer) with no user name or password and no +/// fragment, at most [`MAX_ENDPOINT`] bytes. The reason when not, to follow "the … address". +pub fn endpoint(text: &str) -> Result<(), String> { + let text = text.trim(); + if text.is_empty() { + return Ok(()); + } + if text.len() > MAX_ENDPOINT { + return Err("is too long".into()); + } + if text.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err("can't have spaces in it".into()); + } + let Some(link) = mailcraft_link::WebLink::parse(text) else { return Err("isn't a web address".into()) }; + if !link.is_https() && !is_loopback(link.host()) { + return Err("must start with https://".into()); + } + let after_scheme = text.split_once("://").map_or("", |(_, rest)| rest); + let authority = after_scheme.split(['/', '?', '#']).next().unwrap_or(""); + if authority.contains('@') { + return Err("can't have a user name or password in it".into()); + } + if text.contains('#') { + return Err("can't have a fragment (#) in it".into()); + } + Ok(()) +} + +/// Whether `host` (as [`mailcraft_link::WebLink::host`] writes it) is this computer. +pub fn is_loopback(host: &str) -> bool { + matches!(host, "127.0.0.1" | "[::1]" | "localhost") +} + +/// Microsoft's directory when it can be part of an address: letters, digits, dots and hyphens. +fn usable_tenant(tenant: &str) -> Option<&str> { + let tenant = tenant.trim(); + let plain = !tenant.is_empty() && tenant.len() <= 253 && tenant.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-')); + let edges = |b: Option| b.is_some_and(|b| b.is_ascii_alphanumeric()); + (plain && edges(tenant.bytes().next()) && edges(tenant.bytes().next_back()) && !tenant.contains("..")).then_some(tenant) +} + +/// [`OAuth::provider`] as a file has it: one this version doesn't know is an own identity +/// provider with nothing set up, never Microsoft. +pub(crate) fn provider_read<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + Ok(value.as_str().and_then(OAuthProvider::parse).unwrap_or(OAuthProvider::Custom)) +} + +/// The kind an IMAP account that signs in with an own identity provider is written with, so that +/// an earlier MailCraft, which can't read such a sign-in, keeps the account whole as one of a kind +/// it doesn't know ([`crate::AccountKind::Unknown`]) instead of failing to open the mailbox. +pub(crate) const OWN_SIGN_IN_KIND: &str = "imapOwnSignIn"; + +#[cfg(test)] +#[path = "oauth_custom_tests.rs"] +mod oauth_custom_tests; diff --git a/crates/model/src/oauth_custom_tests.rs b/crates/model/src/oauth_custom_tests.rs new file mode 100644 index 0000000000..fe1ba2e7b9 --- /dev/null +++ b/crates/model/src/oauth_custom_tests.rs @@ -0,0 +1,208 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Signing in with an own identity provider: the settings, how they are written and read, and +//! what is refused. + +use proptest::prelude::*; + +use crate::oauth::{CUSTOM_SCOPE, GOOGLE_TOKEN, MICROSOFT_MAIL_SCOPE, endpoint, scopes}; +use crate::{Account, AccountKind, Mailbox, OAuth, OAuthProvider, SaslChoice}; + +fn own() -> OAuth { + OAuth { + provider: OAuthProvider::Custom, + client_id: "mailcraft".into(), + issuer: "https://id.example.org/realms/mail".into(), + authorize: "https://id.example.org/realms/mail/protocol/openid-connect/auth".into(), + token: "https://id.example.org/realms/mail/protocol/openid-connect/token".into(), + revoke: "https://id.example.org/realms/mail/protocol/openid-connect/revoke".into(), + scopes: "mail".into(), + mechanism: SaslChoice::OAuthBearer, + redirect_port: Some(53_682), + has_secret: true, + ..OAuth::default() + } +} + +fn imap_account(oauth: OAuth) -> Account { + Account { id: 7, email: "alice@example.org".into(), kind: AccountKind::Imap, oauth: Some(oauth), ..Default::default() } +} + +#[test] +fn the_settings_go_round_and_come_back() { + let oauth = own(); + let text = serde_json::to_string(&oauth).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), oauth); + assert!( + text.contains("\"provider\":\"custom\"") && text.contains("\"mechanism\":\"oauthbearer\"") && text.contains("\"hasSecret\":true"), + "{text}" + ); + // A secret is never part of the settings: only that there is one. + assert!(!text.to_ascii_lowercase().contains("secret\":\""), "{text}"); +} + +#[test] +fn a_file_from_before_reads_as_it_did() { + let old: OAuth = serde_json::from_str(r#"{"provider":"google","clientId":"abc"}"#).unwrap(); + assert_eq!((old.provider, old.client_id.as_str(), old.issuer.as_str(), old.mechanism), (OAuthProvider::Google, "abc", "", SaslChoice::Auto)); + // Nothing new is written for an account that has none of it. + assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"provider":"google","clientId":"abc"}"#); + // Nothing said is Microsoft, as ever. + assert_eq!(serde_json::from_str::("{}").unwrap().provider, OAuthProvider::Microsoft); +} + +#[test] +fn a_provider_this_version_doesnt_know_is_never_microsoft() { + for provider in [r#""carrierPigeon""#, "7", "null", r#"{"x":1}"#, r#""Microsoft365x""#] { + let oauth: OAuth = serde_json::from_str(&format!(r#"{{"provider":{provider}}}"#)).unwrap(); + assert_eq!(oauth.provider, OAuthProvider::Custom, "{provider}"); + // With no addresses, it can't sign in anywhere. + assert!(oauth.ready().is_err()); + } + for (word, provider) in [("microsoft", OAuthProvider::Microsoft), ("google", OAuthProvider::Google), ("custom", OAuthProvider::Custom)] { + assert_eq!(serde_json::from_str::(&format!(r#"{{"provider":"{word}"}}"#)).unwrap().provider, provider); + } + // A new value that can't be read doesn't stop the rest being read. + let odd: OAuth = serde_json::from_str(r#"{"provider":"custom","clientId":"c","mechanism":"carrier","redirectPort":-4,"issuer":7}"#).unwrap(); + assert_eq!((odd.client_id.as_str(), odd.mechanism, odd.redirect_port, odd.issuer.as_str()), ("c", SaslChoice::Auto, None, "")); +} + +#[test] +fn an_earlier_version_keeps_such_an_account_whole_instead_of_failing_to_open_the_mailbox() { + let mut mb = Mailbox::default(); + mb.accounts.push(imap_account(own())); + let file = serde_json::to_value(&mb).unwrap(); + let written = &file["accounts"][0]; + // Written with a kind earlier versions don't know: they keep such an account as its file has it. + assert_eq!(written["kind"], "imapOwnSignIn"); + // And read back here as the IMAP account it is. + let back: Mailbox = serde_json::from_value(file.clone()).unwrap(); + assert_eq!(back.accounts[0].kind, AccountKind::Imap); + assert_eq!(back.accounts[0].oauth, Some(own())); + // A Microsoft or Google one is written as ever. + let mut plain = Mailbox::default(); + plain.accounts.push(imap_account(OAuth { provider: OAuthProvider::Google, ..OAuth::default() })); + assert_eq!(serde_json::to_value(&plain).unwrap()["accounts"][0]["kind"], "imap"); +} + +#[test] +fn what_is_used_is_built_in_for_microsoft_and_google_and_the_accounts_own_otherwise() { + let microsoft = OAuth { tenant: "contoso.example".into(), ..OAuth::default() }.effective(); + assert_eq!(microsoft.token, "https://login.microsoftonline.com/contoso.example/oauth2/v2.0/token"); + assert_eq!((microsoft.scopes.as_str(), microsoft.mechanism, microsoft.built_in_client), (MICROSOFT_MAIL_SCOPE, SaslChoice::XOAuth2, true)); + // A tenant that can't be part of an address is `common`, as in the sign-in itself. + assert!(OAuth { tenant: "a/../b".into(), ..OAuth::default() }.effective().token.contains("/common/")); + let google = OAuth { provider: OAuthProvider::Google, client_id: "mine".into(), ..OAuth::default() }.effective(); + assert_eq!((google.token.as_str(), google.client_id.as_str(), google.built_in_client), (GOOGLE_TOKEN, "mine", false)); + let custom = own().effective(); + assert_eq!(custom.scopes, format!("{CUSTOM_SCOPE} mail")); + assert_eq!((custom.mechanism, custom.redirect_port, custom.hosts.is_empty()), (SaslChoice::OAuthBearer, Some(53_682), true)); + // A scope said twice is asked for once. + assert_eq!(OAuth { scopes: "email mail mail".into(), ..own() }.effective().scopes, format!("{CUSTOM_SCOPE} mail")); +} + +#[test] +fn microsofts_and_googles_built_in_values_cant_be_changed_on_their_accounts() { + for provider in [OAuthProvider::Microsoft, OAuthProvider::Google] { + let base = OAuth { provider, ..OAuth::default() }; + assert!(base.check().is_ok()); + for changed in [ + OAuth { token: "https://id.example.org/token".into(), ..base.clone() }, + OAuth { issuer: "https://id.example.org".into(), ..base.clone() }, + OAuth { scopes: "more".into(), ..base.clone() }, + OAuth { mechanism: SaslChoice::OAuthBearer, ..base.clone() }, + ] { + assert!(changed.check().is_err(), "{changed:?}"); + } + // Their client id and redirect port can. + assert!(OAuth { client_id: "mine".into(), redirect_port: Some(8_400), ..base.clone() }.check().is_ok()); + } +} + +#[test] +fn an_own_provider_needs_a_client_id_and_its_two_addresses_to_sign_in() { + assert!(own().ready().is_ok()); + assert!(OAuth { client_id: String::new(), ..own() }.check().is_err()); + // The addresses may be found later (Discover): saved without them, not signed in with. + let found_later = OAuth { authorize: String::new(), token: String::new(), ..own() }; + assert!(found_later.check().is_ok() && found_later.ready().is_err()); + // Typed by hand, no issuer is needed. + assert!(OAuth { issuer: String::new(), ..own() }.ready().is_ok()); + assert!(OAuth::custom().ready().is_err()); +} + +#[test] +fn addresses_that_cant_be_used_are_refused() { + for bad in [ + "http://id.example.org/token", + "https://user:pw@id.example.org/token", + "https://id.example.org/token#x", + "javascript:alert(1)", + "ftp://id.example.org/", + "https://id.example.org/a b", + "https://id.example.org/\r\nHost: x", + "https://id.example.org/\0", + "id.example.org/token", + "https:///token", + ] { + assert!(endpoint(bad).is_err(), "{bad:?}"); + assert!(OAuth { token: bad.into(), ..own() }.check().is_err(), "{bad:?}"); + } + assert!(endpoint(&format!("https://id.example.org/{}", "a".repeat(5_000))).is_err()); + for good in + ["https://id.example.org/token", "https://xn--bcher-kva.example/t", "http://127.0.0.1:8080/token", "http://[::1]/t", "http://localhost/t", ""] + { + assert!(endpoint(good).is_ok(), "{good:?}"); + } + assert!(OAuth { issuer: "https://id.example.org/realms/mail?x=1".into(), ..own() }.check().is_err()); +} + +#[test] +fn scopes_ports_and_client_ids_that_cant_be_sent_are_refused() { + for bad in ["a\"b", "a\\b", "é", "a\nb", &"s ".repeat(40), &"x".repeat(2_000)] { + assert!(scopes(bad).is_err(), "{bad:?}"); + } + assert!(scopes("openid mail urn:ietf:params:oauth:scope:mail").is_ok()); + assert!(OAuth { redirect_port: Some(0), ..own() }.check().is_err()); + for bad in ["has space", "a\u{7f}", &"c".repeat(201), "ünïcode"] { + assert!(OAuth { client_id: bad.into(), ..own() }.check().is_err(), "{bad:?}"); + } + assert!(OAuth { tenant: "../evil".into(), ..OAuth::default() }.check().is_err()); +} + +#[test] +fn the_binding_changes_with_every_value_a_remembered_sign_in_belongs_to() { + let base = own().binding(); + for changed in [ + OAuth { issuer: "https://id2.example.org".into(), ..own() }, + OAuth { token: "https://id.example.org/other".into(), ..own() }, + OAuth { client_id: "other".into(), ..own() }, + OAuth { provider: OAuthProvider::Microsoft, ..OAuth::default() }, + ] { + assert_ne!(changed.binding(), base, "{changed:?}"); + } + // Not with the ones it doesn't. + assert_eq!(OAuth { scopes: String::new(), mechanism: SaslChoice::XOAuth2, redirect_port: None, ..own() }.binding(), base); +} + +proptest! { + #[test] + fn checking_never_panics(issuer in ".{0,300}", token in ".{0,300}", scope in ".{0,300}", client in ".{0,300}", tenant in ".{0,80}", port in proptest::option::of(any::())) { + for provider in [OAuthProvider::Microsoft, OAuthProvider::Google, OAuthProvider::Custom] { + let oauth = OAuth { provider, issuer: issuer.clone(), token: token.clone(), authorize: token.clone(), revoke: issuer.clone(), scopes: scope.clone(), client_id: client.clone(), tenant: tenant.clone(), redirect_port: port, ..OAuth::default() }; + let _ = oauth.check(); + let _ = oauth.ready(); + let _ = oauth.effective(); + let _ = oauth.binding(); + } + } + + #[test] + fn reading_any_provider_value_never_panics_and_is_never_microsoft_unless_it_says_so(value in ".{0,40}") { + let json = serde_json::json!({ "provider": value }); + let oauth: OAuth = serde_json::from_value(json).unwrap(); + if oauth.provider == OAuthProvider::Microsoft { + prop_assert_eq!(OAuthProvider::parse(&value), Some(OAuthProvider::Microsoft)); + } + } +} diff --git a/crates/net/src/oauth.rs b/crates/net/src/oauth.rs index 09fc7e670d..4574f28c2f 100644 --- a/crates/net/src/oauth.rs +++ b/crates/net/src/oauth.rs @@ -104,17 +104,17 @@ const MAX_LIFETIME: i64 = 7 * 24 * 3_600; /// Longest name or address taken from an identity token. const MAX_IDENTITY: usize = 254; -const MICROSOFT_LOGIN: &str = "https://login.microsoftonline.com"; -const GOOGLE_AUTHORIZE: &str = "https://accounts.google.com/o/oauth2/v2/auth"; -const GOOGLE_TOKEN: &str = "https://oauth2.googleapis.com/token"; -const GOOGLE_SCOPE: &str = "https://mail.google.com/ openid email"; +// (The built-in values are the model's, so that what the settings show is what is used.) +const MICROSOFT_LOGIN: &str = mailcraft_model::oauth::MICROSOFT_LOGIN; +const GOOGLE_AUTHORIZE: &str = mailcraft_model::oauth::GOOGLE_AUTHORIZE; +const GOOGLE_TOKEN: &str = mailcraft_model::oauth::GOOGLE_TOKEN; +const GOOGLE_SCOPE: &str = mailcraft_model::oauth::GOOGLE_SCOPE; const GOOGLE_DESKTOP_SECRET: &str = match option_env!("MAILCRAFT_GOOGLE_CLIENT_SECRET") { Some(secret) => secret, None => "", }; /// IMAP and SMTP, a refresh token to go with the access token, and who it is that signed in. -const MICROSOFT_SCOPE: &str = - "https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access openid profile email"; +const MICROSOFT_SCOPE: &str = mailcraft_model::oauth::MICROSOFT_MAIL_SCOPE; /// Microsoft Graph: sending mail, reading the calendar and writing to it (events made, moved, /// changed and deleted here go back to the server), and reading the contacts. A sign-in from /// before the calendar was written to agreed to reading it only: its refresh token gets no @@ -345,6 +345,12 @@ impl Endpoints { fewer: String::new(), lesser: String::new(), }, + // The owner's own identity provider: its addresses are the account's own settings, + // and it is asked for mail and nothing else (it has no Microsoft Graph). + OAuthProvider::Custom => { + let used = oauth.effective(); + Endpoints { authorize: used.authorize, token: used.token, scope: used.scopes, ..Endpoints::default() } + } } } } diff --git a/crates/net/src/sync.rs b/crates/net/src/sync.rs index e15474b4ca..2feaa2f658 100644 --- a/crates/net/src/sync.rs +++ b/crates/net/src/sync.rs @@ -436,9 +436,28 @@ pub fn token_may_go_to(account: &Account, server: &Server, google_host: &str) -> } Err(NetError::Config(said!("a Microsoft sign-in is only used with Microsoft's own mail servers: this account names another server"))) } + Some(OAuthProvider::Custom) => own_provider_destination(account, &server.host), } } +/// Where a token from the owner's own identity provider may go: the account's own IMAP and SMTP +/// servers, and never Microsoft's or Google's (they have providers of their own), nor this +/// computer outside a test. +fn own_provider_destination(account: &Account, host: &str) -> Result<(), NetError> { + let host = host.trim().trim_end_matches('.').to_ascii_lowercase(); + let named = |server: Option<&Server>| server.is_some_and(|s| s.host.trim().trim_end_matches('.').eq_ignore_ascii_case(&host)); + if host.is_empty() || !(named(account.incoming.as_ref()) || named(account.outgoing.as_ref())) { + return Err(NetError::Config(said!("a sign-in with your identity provider is only used with this account's own mail servers"))); + } + if is_microsoft_host(&host) || mailcraft_model::is_gmail_host(&host) || mailcraft_model::is_google_host(&host) { + return Err(NetError::Config(said!("a sign-in with your identity provider is never sent to Microsoft's or Google's mail servers"))); + } + if crate::transport::is_loopback(&host) && !microsoft_loopback_allowed() { + return Err(NetError::Config(said!("a sign-in with your identity provider is only sent to a mail server on this computer in a test"))); + } + Ok(()) +} + /// Whether a fake server on this computer may stand in for Microsoft's mail servers: in this /// crate's own tests, and in the tests of the crates on it that ask for it on their thread /// (`graph::standin::allow_loopback_tokens`, built with the `stand-in` feature alone). diff --git a/crates/net/src/tests.rs b/crates/net/src/tests.rs index fc26e6a461..cc20ef4562 100644 --- a/crates/net/src/tests.rs +++ b/crates/net/src/tests.rs @@ -429,6 +429,7 @@ fn oauth_destinations_cannot_cross_providers_or_protocols() { let expected = match provider { OAuthProvider::Google => "Google OAuth access tokens may only be sent", OAuthProvider::Microsoft => "a Microsoft sign-in is only used", + OAuthProvider::Custom => "a sign-in with your identity provider", }; for error in [test_account(&account, TOKEN).unwrap_err(), send(&account, TOKEN, &hello()).unwrap_err()] { assert!(matches!(&error, NetError::Config(why) if why.to_string().starts_with(expected)), "{provider:?}: {error:?}"); diff --git a/crates/net/tests/token_hosts.rs b/crates/net/tests/token_hosts.rs index 8fceddf28e..1a5c195ab6 100644 --- a/crates/net/tests/token_hosts.rs +++ b/crates/net/tests/token_hosts.rs @@ -11,15 +11,16 @@ use mailcraft_model::sync::SyncRequest; use mailcraft_model::{Account, AccountKind, OAuth, OAuthProvider, Security, Server}; use mailcraft_net::token_may_go_to; -/// Every provider. (A new one fails to build here until it has its row.) +/// Every provider with mail servers of its own. (A new one fails to build here until it has its +/// row; an own identity provider has its own test below.) fn providers() -> Vec { - let all = [OAuthProvider::Microsoft, OAuthProvider::Google]; - for provider in all { - match provider { - OAuthProvider::Microsoft | OAuthProvider::Google => {} - } - } - all.to_vec() + let all = [OAuthProvider::Microsoft, OAuthProvider::Google, OAuthProvider::Custom]; + all.into_iter() + .filter(|provider| match provider { + OAuthProvider::Microsoft | OAuthProvider::Google => true, + OAuthProvider::Custom => false, + }) + .collect() } /// The provider's own IMAP and SMTP servers. @@ -27,6 +28,7 @@ fn own_hosts(provider: OAuthProvider) -> [&'static str; 2] { match provider { OAuthProvider::Microsoft => ["outlook.office365.com", "smtp.office365.com"], OAuthProvider::Google => ["imap.gmail.com", "smtp.gmail.com"], + OAuthProvider::Custom => ["mail.example.org", "mail.example.org"], } } @@ -129,3 +131,24 @@ fn a_microsoft_account_at_a_loopback_server_is_refused_before_anything_connects( assert_eq!(listener.accept().map(|_| ()).map_err(|e| e.kind()), Err(std::io::ErrorKind::WouldBlock), "{host}"); } } + +#[test] +fn a_token_from_an_own_identity_provider_goes_to_the_accounts_own_servers_and_nowhere_else() { + // The account's own servers, wherever they are. + for host in ["mail.example.org", "imap.attacker.example", "192.0.2.10"] { + assert_eq!(allowed(OAuthProvider::Custom, host), [true, true], "{host}"); + } + // Never Microsoft's or Google's, whose tokens come from their own providers, nor this computer. + for host in own_hosts(OAuthProvider::Microsoft).into_iter().chain(own_hosts(OAuthProvider::Google)).chain([ + "gmail.googleapis.com", + "127.0.0.1", + "localhost", + "[::1]", + ]) { + assert_eq!(allowed(OAuthProvider::Custom, host), [false, false], "{host}"); + } + // And never a server the account doesn't name. + let a = account(OAuthProvider::Custom, "mail.example.org"); + let elsewhere = Server { host: "imap.attacker.example".into(), port: 993, security: Security::Tls }; + assert!(token_may_go_to(&a, &elsewhere, "imap.gmail.com").is_err()); +} From 462b487d0862c8e920f8e55c18839897bcce59b7 Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 08:50:15 +0100 Subject: [PATCH 02/25] GO2: proto: SASL OAUTHBEARER for IMAP and SMTP IMAP AUTHENTICATE and SMTP AUTH can now give a server an OAuth access token the standard way (RFC 7628), beside XOAUTH2: the GS2 header with the user name, the server's host and port, and the bearer token. The token goes with the command only to a server that offers the mechanism (and SASL-IR for IMAP); a server's reasons for refusing (JSON in base64) are answered with 0x01 as the RFC asks, read as hostile (three fields, capped and checked) and kept for the caller. XOAUTH2 now shares the same exchange. A fuzz target reads arbitrary refusal reasons. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- .github/workflows/fuzz.yml | 2 +- Cargo.lock | 1 + crates/i18n/po/cs.po | 11 +- crates/i18n/po/de.po | 11 +- crates/i18n/po/es.po | 11 +- crates/i18n/po/fr.po | 11 +- crates/i18n/po/hu.po | 11 +- crates/i18n/po/it.po | 11 +- crates/i18n/po/ka.po | 11 +- crates/i18n/po/messages.pot | 11 +- crates/i18n/po/nl.po | 11 +- crates/i18n/po/pl.po | 11 +- crates/i18n/po/ro.po | 11 +- crates/i18n/po/zh_CN.po | 11 +- crates/proto/Cargo.toml | 2 + crates/proto/src/imap/mod.rs | 68 +++++++-- crates/proto/src/lib.rs | 3 + crates/proto/src/oauthbearer.rs | 122 +++++++++++++++++ crates/proto/src/oauthbearer_tests.rs | 189 ++++++++++++++++++++++++++ crates/proto/src/smtp.rs | 59 ++++++-- crates/proto/src/smtp/tests.rs | 25 +++- fuzz/Cargo.toml | 7 + fuzz/fuzz_targets/sasl_failure.rs | 16 +++ 23 files changed, 562 insertions(+), 64 deletions(-) create mode 100644 crates/proto/src/oauthbearer.rs create mode 100644 crates/proto/src/oauthbearer_tests.rs create mode 100644 fuzz/fuzz_targets/sasl_failure.rs diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 95e9cde305..ed330fc3c9 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -50,7 +50,7 @@ jobs: ical) echo crates/ical/ ;; vcard) echo crates/vcard/ ;; link) echo crates/link/ ;; - imap|smtp) echo crates/proto/ ;; + imap|smtp|sasl_failure) echo crates/proto/ ;; po) echo crates/i18n/src/ ;; jmap_*) echo crates/jmap/ ;; pst|rtf) echo crates/pst/ ;; diff --git a/Cargo.lock b/Cargo.lock index 041bf4a3e3..b262ccce7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3460,6 +3460,7 @@ dependencies = [ "mailcraft-charset", "mailcraft-i18n", "proptest", + "serde_json", ] [[package]] diff --git a/crates/i18n/po/cs.po b/crates/i18n/po/cs.po index d1e125b748..7f4ba0c69a 100644 --- a/crates/i18n/po/cs.po +++ b/crates/i18n/po/cs.po @@ -24131,6 +24131,11 @@ msgstr "poslední Odeslat/přijmout mělo potíže" msgid "the last calendar can't be deleted" msgstr "poslední kalendář nelze odstranit" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24761,13 +24766,13 @@ msgid "the top level" msgstr "nejvyšší úroveň" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "uživatelské jméno nebo přístupový token obsahuje znak, který nelze odeslat" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "uživatelské jméno nebo přístupový token je příliš dlouhý na odeslání" @@ -24845,7 +24850,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "podpis s názvem „{to}“ už existuje" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "není žádný přístupový token, kterým se přihlásit" diff --git a/crates/i18n/po/de.po b/crates/i18n/po/de.po index 0ac7003972..9627cacd1c 100644 --- a/crates/i18n/po/de.po +++ b/crates/i18n/po/de.po @@ -22678,6 +22678,11 @@ msgstr "das letzte Senden/Empfangen hatte Probleme" msgid "the last calendar can't be deleted" msgstr "der letzte Kalender kann nicht gelöscht werden" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -23289,13 +23294,13 @@ msgid "the top level" msgstr "der obersten Ebene" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "Der Benutzername oder das Zugriffstoken enthält ein Zeichen, das nicht gesendet werden kann" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "Der Benutzername oder das Zugriffstoken ist zu lang, um gesendet zu werden" @@ -23372,7 +23377,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "es gibt bereits eine Signatur namens „{to}“" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "Es gibt kein Zugriffstoken für die Anmeldung" diff --git a/crates/i18n/po/es.po b/crates/i18n/po/es.po index 4fe5c32b24..5ec23d8a05 100644 --- a/crates/i18n/po/es.po +++ b/crates/i18n/po/es.po @@ -24078,6 +24078,11 @@ msgstr "el último Enviar/Recibir tuvo problemas" msgid "the last calendar can't be deleted" msgstr "no se puede eliminar el último calendario" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24708,13 +24713,13 @@ msgid "the top level" msgstr "el nivel superior" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "el nombre de usuario o el token de acceso tiene un carácter que no se puede enviar" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "el nombre de usuario o el token de acceso es demasiado largo para enviarse" @@ -24792,7 +24797,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "ya hay una firma llamada «{to}»" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "no hay ningún token de acceso para iniciar sesión" diff --git a/crates/i18n/po/fr.po b/crates/i18n/po/fr.po index 1a3bf28770..b958c99b3a 100644 --- a/crates/i18n/po/fr.po +++ b/crates/i18n/po/fr.po @@ -23981,6 +23981,11 @@ msgstr "le dernier Envoi/Réception a rencontré des problèmes" msgid "the last calendar can't be deleted" msgstr "le dernier calendrier ne peut pas être supprimé" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24611,13 +24616,13 @@ msgid "the top level" msgstr "le niveau supérieur" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "le nom d'utilisateur ou le jeton d'accès contient un caractère qui ne peut pas être envoyé" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "le nom d'utilisateur ou le jeton d'accès est trop long pour être envoyé" @@ -24695,7 +24700,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "il existe déjà une signature nommée « {to} »" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "il n'y a pas de jeton d'accès pour se connecter" diff --git a/crates/i18n/po/hu.po b/crates/i18n/po/hu.po index 4e16501a37..bd56ae9c36 100644 --- a/crates/i18n/po/hu.po +++ b/crates/i18n/po/hu.po @@ -24073,6 +24073,11 @@ msgstr "az utolsó Küldés/Fogadás során problémák voltak" msgid "the last calendar can't be deleted" msgstr "az utolsó naptár nem törölhető" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24703,13 +24708,13 @@ msgid "the top level" msgstr "felső szint" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "a felhasználó neve vagy a token-hez való hozzáférés olyan karakterrel rendelkezik, amelyet nem lehet elküldeni" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "a felhasználó neve vagy hozzáférése túl hosszú ahhoz, hogy elküldjék" @@ -24787,7 +24792,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "Van már egy \"{to}\" nevű aláírás." #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "nincs hozzáférése a bejelentkezéshez" diff --git a/crates/i18n/po/it.po b/crates/i18n/po/it.po index 1efcb8edb3..4e5a5db014 100644 --- a/crates/i18n/po/it.po +++ b/crates/i18n/po/it.po @@ -24053,6 +24053,11 @@ msgstr "l'ultimo Invia/Ricevi ha avuto problemi" msgid "the last calendar can't be deleted" msgstr "l'ultimo calendario non può essere eliminato" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24683,13 +24688,13 @@ msgid "the top level" msgstr "livello superiore" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "il nome utente o il token di accesso contiene un carattere che non può essere inviato" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "il nome utente o il token di accesso è troppo lungo per essere inviato" @@ -24767,7 +24772,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "esiste già una firma denominata «{to}»" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "non c'è alcun token di accesso con cui accedere" diff --git a/crates/i18n/po/ka.po b/crates/i18n/po/ka.po index e3a92a57c9..4f28edb3df 100644 --- a/crates/i18n/po/ka.po +++ b/crates/i18n/po/ka.po @@ -23995,6 +23995,11 @@ msgstr "ბოლო „გაგზავნა/მიღებისას“ msgid "the last calendar can't be deleted" msgstr "ბოლო კალენდრის წაშლა შეუძლებელია" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24625,13 +24630,13 @@ msgid "the top level" msgstr "ზედა დონე" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "მომხმარებლის სახელში ან წვდომის ტოკენში ისეთი სიმბოლოა, რომლის გაგზავნაც შეუძლებელია" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "მომხმარებლის სახელი ან წვდომის ტოკენი გასაგზავნად ზედმეტად გრძელია" @@ -24709,7 +24714,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "ხელმოწერა სახელით „{to}“ უკვე არსებობს" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "შესასვლელად წვდომის ტოკენი არ არის" diff --git a/crates/i18n/po/messages.pot b/crates/i18n/po/messages.pot index ff1405bf50..70f17b8fa3 100644 --- a/crates/i18n/po/messages.pot +++ b/crates/i18n/po/messages.pot @@ -19995,6 +19995,11 @@ msgstr "" msgid "the last calendar can't be deleted" msgstr "" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs msgid "the list shows every account's folder: open one account's folder, or name the folder" @@ -20521,12 +20526,12 @@ msgid "the top level" msgstr "" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs msgid "the user name or access token has a character that can't be sent" msgstr "" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs msgid "the user name or access token is too long to be sent" msgstr "" @@ -20591,7 +20596,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs msgid "there is no access token to sign in with" msgstr "" diff --git a/crates/i18n/po/nl.po b/crates/i18n/po/nl.po index 8606b7ad04..160f2d4548 100644 --- a/crates/i18n/po/nl.po +++ b/crates/i18n/po/nl.po @@ -23457,6 +23457,11 @@ msgstr "de laatste Verzenden/Ontvangen had problemen" msgid "the last calendar can't be deleted" msgstr "de laatste agenda kan niet worden verwijderd" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24083,13 +24088,13 @@ msgid "the top level" msgstr "het bovenste niveau" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "de gebruikersnaam of het toegangstoken bevat een teken dat niet kan worden verzonden" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "de gebruikersnaam of het toegangstoken is te lang om te worden verzonden" @@ -24167,7 +24172,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "er is al een handtekening met de naam „{to}”" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "er is geen toegangstoken om mee aan te melden" diff --git a/crates/i18n/po/pl.po b/crates/i18n/po/pl.po index 641ce07104..ba24e1ad34 100644 --- a/crates/i18n/po/pl.po +++ b/crates/i18n/po/pl.po @@ -24163,6 +24163,11 @@ msgstr "ostatnie Wyślij/Odbierz miało problemy" msgid "the last calendar can't be deleted" msgstr "nie można usunąć ostatniego kalendarza" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24793,13 +24798,13 @@ msgid "the top level" msgstr "najwyższy poziom" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "nazwa użytkownika lub token dostępu zawiera znak, którego nie można wysłać" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "nazwa użytkownika lub token dostępu są zbyt długie, by je wysłać" @@ -24877,7 +24882,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "podpis o nazwie „{to}” już istnieje" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "brak tokenu dostępu do logowania" diff --git a/crates/i18n/po/ro.po b/crates/i18n/po/ro.po index afcdf855e0..999f2b7589 100644 --- a/crates/i18n/po/ro.po +++ b/crates/i18n/po/ro.po @@ -24156,6 +24156,11 @@ msgstr "ultima Trimitere/Primire a avut probleme" msgid "the last calendar can't be deleted" msgstr "ultimul calendar nu poate fi șters" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24786,13 +24791,13 @@ msgid "the top level" msgstr "nivelul superior" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "numele de utilizator sau tokenul de acces conține un caracter care nu poate fi trimis" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "numele de utilizator sau tokenul de acces este prea lung pentru a fi trimis" @@ -24870,7 +24875,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "există deja o semnătură numită „{to}”" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "nu există un token de acces cu care să vă conectați" diff --git a/crates/i18n/po/zh_CN.po b/crates/i18n/po/zh_CN.po index b546fc3ffc..7ecd607222 100644 --- a/crates/i18n/po/zh_CN.po +++ b/crates/i18n/po/zh_CN.po @@ -24054,6 +24054,11 @@ msgstr "上一次发送/接收出现了问题" msgid "the last calendar can't be deleted" msgstr "最后一个日历无法删除" +#. why a mail server couldn't be used +#: crates/proto/src/oauthbearer.rs +msgid "the mail server's name can't be sent with a sign-in" +msgstr "" + #. what a command says #: crates/engine/src/cmd/folder.rs #, fuzzy @@ -24684,13 +24689,13 @@ msgid "the top level" msgstr "顶层" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token has a character that can't be sent" msgstr "用户名或访问令牌包含无法发送的字符" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "the user name or access token is too long to be sent" msgstr "用户名或访问令牌太长而无法发送" @@ -24768,7 +24773,7 @@ msgid "there is already a signature named \"{to}\"" msgstr "已经有一个名为“{to}”的签名" #. why a mail server couldn't be used -#: crates/proto/src/lib.rs +#: crates/proto/src/lib.rs crates/proto/src/oauthbearer.rs #, fuzzy msgid "there is no access token to sign in with" msgstr "没有可供登录的访问令牌" diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml index 9cbb9fdfed..293ea8279b 100644 --- a/crates/proto/Cargo.toml +++ b/crates/proto/Cargo.toml @@ -12,6 +12,8 @@ workspace = true mailcraft-charset = { workspace = true } mailcraft-i18n = { workspace = true } log = { workspace = true } +# The reasons a server gives for refusing an OAUTHBEARER sign-in come as JSON (RFC 7628 §3.2.2). +serde_json = { workspace = true } [dev-dependencies] proptest = { workspace = true } \ No newline at end of file diff --git a/crates/proto/src/imap/mod.rs b/crates/proto/src/imap/mod.rs index b6a3d2d1e2..e2d62cc00b 100644 --- a/crates/proto/src/imap/mod.rs +++ b/crates/proto/src/imap/mod.rs @@ -4,7 +4,8 @@ //! mailboxes, and changing flags, moving, copying, removing and filing messages (UID MOVE of //! RFC 6851; UID EXPUNGE and the `COPYUID` answer of RFC 4315). Special-use mailbox flags //! (RFC 6154) come through in [`Mailbox::flags`] as the server wrote them. Password sign-in prefers -//! advertised SASL PLAIN, with LOGIN as a fallback when PLAIN is not offered; OAuth uses XOAUTH2. +//! advertised SASL PLAIN, with LOGIN as a fallback when PLAIN is not offered; OAuth uses +//! OAUTHBEARER (RFC 7628) or XOAUTH2. //! //! There is no plain EXPUNGE and no CLOSE here, on purpose: both remove every message marked //! `\Deleted` in the mailbox, also those another program marked. @@ -31,7 +32,7 @@ use parse::{Piece, Status, StatusLine, Value}; pub use utf7::{decode_utf7, encode_utf7}; use crate::line::Wire; -use crate::{MAX_LINE, MAX_LITERAL, ProtoError, Secrets, for_trace, tidy, xoauth2}; +use crate::{FAILURE_ANSWER, MAX_LINE, MAX_LITERAL, ProtoError, Secrets, for_trace, oauthbearer, tidy, xoauth2}; use mailcraft_i18n::{Arg, Text, said}; /// Most responses the server may send to one command. @@ -132,6 +133,11 @@ pub struct Imap { skipped: bool, /// The tag of the IDLE command the server is waiting in, if it is ([`Imap::idle_begin`]). idle_tag: Option, + /// What followed the `+` of the last go-ahead the server sent, capped: the reasons a token + /// sign-in is refused for come there. + go_ahead: Vec, + /// Why the last token sign-in was refused, when the server said ([`Imap::sasl_failure`]). + sasl_failure: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -689,6 +695,8 @@ impl Imap { skip_long: false, skipped: false, idle_tag: None, + go_ahead: Vec::new(), + sasl_failure: None, } } @@ -795,23 +803,52 @@ impl Imap { /// go-ahead, so one that doesn't know the mechanism refuses without having seen it. pub fn authenticate_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { let payload = xoauth2(user, token)?; + self.authenticate_token("XOAUTH2", token, &payload, "") + } + + /// AUTHENTICATE OAUTHBEARER (RFC 7628): an OAuth access token in place of a password, the + /// standard way. `host` and `port` are the server's, as connected to. NO → `ProtoError::Auth`, + /// with the server's reasons, when it gave them, in [`Imap::sasl_failure`]. + /// + /// As for [`Imap::authenticate_xoauth2`], the token goes with the command only to a server + /// that listed `SASL-IR` and `AUTH=OAUTHBEARER`; any other is asked first. + pub fn authenticate_oauthbearer(&mut self, user: &str, host: &str, port: u16, token: &str) -> Result<(), ProtoError> { + let payload = oauthbearer(user, host, port, token)?; + self.authenticate_token("OAUTHBEARER", token, &payload, FAILURE_ANSWER) + } + + /// Whether the server offers the SASL mechanism `name` (`OAUTHBEARER`, `XOAUTH2`), as far as + /// it has said what it can do. + pub fn offers_mechanism(&self, name: &str) -> bool { + self.offers(&format!("AUTH={}", name.to_ascii_uppercase())) + } + + /// Why the server refused the last token sign-in, when it said in the way RFC 7628 has it. + pub fn sasl_failure(&self) -> Option<&crate::SaslFailure> { + self.sasl_failure.as_ref() + } + + /// A token sign-in with SASL `mechanism`: `payload` (base64) as the client's message, and + /// `failure_answer` for the server's reasons when it refuses. + fn authenticate_token(&mut self, mechanism: &str, token: &str, payload: &str, failure_answer: &str) -> Result<(), ProtoError> { self.secrets.add(token); - self.secrets.add(&payload); - let inline = self.offers("SASL-IR") && self.offers("AUTH=XOAUTH2"); + self.secrets.add(payload); + self.sasl_failure = None; + let inline = self.offers("SASL-IR") && self.offers(&format!("AUTH={mechanism}")); let tag = self.tag(); - log::trace!("C: {tag} AUTHENTICATE XOAUTH2{}", if inline { " ***" } else { "" }); - let mut out = format!("{tag} AUTHENTICATE XOAUTH2"); + log::trace!("C: {tag} AUTHENTICATE {mechanism}{}", if inline { " ***" } else { "" }); + let mut out = format!("{tag} AUTHENTICATE {mechanism}"); if inline { out.push(' '); - out.push_str(&payload); + out.push_str(payload); } out.push_str("\r\n"); self.wire.write(out.as_bytes())?; self.wire.flush()?; // What each `+` from the server is answered with: the token (unless it went with the - // command), an empty line for the reasons a refusal starts with (JSON in base64), and - // for a question after that, the end of the exchange. - let answers = [(payload.as_str(), "***"), ("", ""), ("*", "*")]; + // command), the mechanism's answer to the reasons a refusal starts with (JSON in base64), + // and for a question after that, the end of the exchange. + let answers = [(payload, "***"), (failure_answer, failure_answer), ("*", "*")]; let mut asked = usize::from(inline); let line = loop { if let Some(line) = self.read_until(&tag, true, &mut ignore)? { @@ -820,6 +857,10 @@ impl Imap { let Some((answer, shown)) = answers.get(asked) else { return Err(ProtoError::Protocol(said!("the server asked for more than a sign-in has"))); }; + // (The go-ahead after the token is the server's reasons for saying no.) + if asked == 1 { + self.sasl_failure = crate::SaslFailure::read(&self.go_ahead); + } asked += 1; log::trace!("C: {shown}"); self.wire.write(format!("{answer}\r\n").as_bytes())?; @@ -830,7 +871,10 @@ impl Imap { _ if asked == answers.len() => Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))), // Nobody is signed in by a token that was never sent. Status::Ok if asked == 0 => Err(ProtoError::Protocol(said!("the server ended the command early"))), - Status::Ok => self.signed_in(&line), + Status::Ok => { + self.sasl_failure = None; + self.signed_in(&line) + } Status::No => Err(ProtoError::Auth(self.refusal(&line))), _ => Err(ProtoError::Rejected(self.refusal(&line))), } @@ -1341,6 +1385,8 @@ impl Imap { log::trace!("S: {}", for_trace(&self.secrets.hide(&String::from_utf8_lossy(&line)))); } if line.first() == Some(&b'+') { + let text = line.get(1..).unwrap_or_default(); + self.go_ahead = text.get(..text.len().min(crate::oauthbearer::MAX_FAILURE.saturating_mul(2))).unwrap_or_default().to_vec(); return Ok(Response::GoAhead); } let Some(rest) = line.strip_prefix(b"* ") else { diff --git a/crates/proto/src/lib.rs b/crates/proto/src/lib.rs index b197845004..16efb758dc 100644 --- a/crates/proto/src/lib.rs +++ b/crates/proto/src/lib.rs @@ -17,7 +17,10 @@ use mailcraft_i18n::{Arg, Text, said}; pub mod imap; mod line; +mod oauthbearer; pub use line::DamagedStream; +pub use oauthbearer::SaslFailure; +pub(crate) use oauthbearer::{FAILURE_ANSWER, oauthbearer}; pub mod smtp; #[cfg(test)] diff --git a/crates/proto/src/oauthbearer.rs b/crates/proto/src/oauthbearer.rs new file mode 100644 index 0000000000..c3b3d1eff3 --- /dev/null +++ b/crates/proto/src/oauthbearer.rs @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! SASL OAUTHBEARER (RFC 7628): an OAuth 2.0 bearer token in place of a password, the standard +//! way, for IMAP (RFC 3501 AUTHENTICATE) and SMTP (RFC 4954 AUTH). +//! +//! What is sent is the GS2 header (RFC 5801) naming the user, then the server's host and port and +//! the token, each after the byte 0x01: `n,a=,^Ahost=^Aport=^Aauth=Bearer +//! ^A^A`. A server that refuses sends its reasons first, as JSON in base64 (§3.2.2); the +//! client answers them with the single byte 0x01 (§3.2.3), and the refusal follows. +//! +//! The reasons are written by the server and read as hostile: capped, three fields only, each +//! short, with no control characters, and none of them ever shown as it came. + +use crate::ProtoError; +use mailcraft_charset::base64::STANDARD; +use mailcraft_i18n::said; + +/// Longest user name and token together. +const MAX_PAYLOAD: usize = 32 * 1024; +/// Longest host name sent. +const MAX_HOST: usize = 255; +/// Longest reasons read, before and after base64. +pub(crate) const MAX_FAILURE: usize = 4 * 1024; +/// Longest value of one of the reasons kept. +const MAX_FIELD: usize = 512; + +/// What a client answers a server's reasons with: the byte 0x01, in base64 (RFC 7628 §3.2.3). +pub(crate) const FAILURE_ANSWER: &str = "AQ=="; + +/// What SASL OAUTHBEARER sends, in base64. `host` and `port` are the server's, as connected to. +/// A name, host or token that would break out of the message or the line it goes on is refused. +pub(crate) fn oauthbearer(user: &str, host: &str, port: u16, token: &str) -> Result { + if token.is_empty() { + return Err(ProtoError::Auth(said!("there is no access token to sign in with"))); + } + let unsendable = |text: &str| text.bytes().any(|b| matches!(b, 0 | 1 | b'\r' | b'\n')); + if unsendable(user) || unsendable(token) || unsendable(host) { + return Err(ProtoError::Auth(said!("the user name or access token has a character that can't be sent"))); + } + // RFC 6750's token characters: what a bearer token is made of, and nothing that ends the field. + if !token.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'+' | b'/' | b'=')) { + return Err(ProtoError::Auth(said!("the user name or access token has a character that can't be sent"))); + } + if host.len() > MAX_HOST || host.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) { + return Err(ProtoError::Auth(said!("the mail server's name can't be sent with a sign-in"))); + } + if user.len().saturating_add(token.len()) > MAX_PAYLOAD { + return Err(ProtoError::Auth(said!("the user name or access token is too long to be sent"))); + } + let user = saslname(user); + let host_field = if host.is_empty() { String::new() } else { format!("host={host}\x01") }; + let port_field = if port == 0 { String::new() } else { format!("port={port}\x01") }; + Ok(STANDARD.encode(format!("n,a={user},\x01{host_field}{port_field}auth=Bearer {token}\x01\x01"))) +} + +/// A name as RFC 5801 writes it in the GS2 header: `,` as `=2C` and `=` as `=3D`. +fn saslname(user: &str) -> String { + let mut out = String::with_capacity(user.len()); + for c in user.chars() { + match c { + ',' => out.push_str("=2C"), + '=' => out.push_str("=3D"), + c => out.push(c), + } + } + out +} + +/// Why a server refused an OAUTHBEARER (or XOAUTH2) sign-in, as far as it can be read: the three +/// fields of RFC 7628 §3.2.2, each checked and short. Nothing else of what it sent is kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SaslFailure { + /// `invalid_token`, `insufficient_scope` or another error code of RFC 6750 §3.1: letters, + /// digits and `_` only, else empty. + pub status: String, + /// The scopes the server says are needed: the characters RFC 6749 §3.3 allows, else empty. + pub scope: String, + /// Where the server says its identity provider describes itself: an `https://` address, + /// else empty. Written by the server: never used without the owner's yes. + pub openid_configuration: String, +} + +impl SaslFailure { + /// The reasons in a server's challenge, given as it came (base64 text, with or without the + /// `+ ` or `334 ` before it taken off). `None` when it isn't base64 of a JSON object, or is + /// longer than reasons are. + pub fn read(challenge: &[u8]) -> Option { + if challenge.len() > MAX_FAILURE.saturating_mul(2) { + return None; + } + let text = std::str::from_utf8(challenge).ok()?.trim(); + let bytes = STANDARD.decode(text).ok()?; + if bytes.len() > MAX_FAILURE { + return None; + } + let json: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + let object = json.as_object()?; + let field = |name: &str| object.get(name).and_then(serde_json::Value::as_str).filter(|v| v.len() <= MAX_FIELD).unwrap_or(""); + let status = field("status"); + let status = if !status.is_empty() && status.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { status } else { "" }; + let scope = field("scope"); + let scope_char = |b: u8| b == b' ' || b == 0x21 || (0x23..=0x5B).contains(&b) || (0x5D..=0x7E).contains(&b); + let scope = if scope.bytes().all(scope_char) { scope.trim() } else { "" }; + let config = field("openid-configuration"); + let config = if config.starts_with("https://") && config.bytes().all(|b| b.is_ascii_graphic()) { config } else { "" }; + Some(SaslFailure { status: status.into(), scope: scope.into(), openid_configuration: config.into() }) + } + + /// Whether the server says the token is no good (expired, or revoked): a fresh one may do. + pub fn token_rejected(&self) -> bool { + self.status == "invalid_token" + } + + /// Whether the server says the token doesn't cover mail: a fresh one won't do, a fresh sign-in may. + pub fn scope_missing(&self) -> bool { + self.status == "insufficient_scope" + } +} + +#[cfg(test)] +#[path = "oauthbearer_tests.rs"] +mod oauthbearer_tests; diff --git a/crates/proto/src/oauthbearer_tests.rs b/crates/proto/src/oauthbearer_tests.rs new file mode 100644 index 0000000000..c7a9148fdd --- /dev/null +++ b/crates/proto/src/oauthbearer_tests.rs @@ -0,0 +1,189 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! SASL OAUTHBEARER (RFC 7628) over IMAP and SMTP, against scripted servers. + +use proptest::prelude::*; + +use super::*; +use crate::imap::Imap; +use crate::script::Script; +use crate::smtp::Smtp; + +const TOKEN: &str = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhbGljZSJ9.c2ln"; + +fn decoded(payload: &str) -> String { + String::from_utf8(STANDARD.decode(payload).unwrap()).unwrap() +} + +/// What goes out for alice at mail.example.org:993. +fn message() -> String { + oauthbearer("alice@example.org", "mail.example.org", 993, TOKEN).unwrap() +} + +/// The reasons a server gives, in base64. +fn reasons(json: &str) -> String { + STANDARD.encode(json) +} + +#[test] +fn the_message_is_the_gs2_header_then_host_port_and_token() { + assert_eq!(decoded(&message()), format!("n,a=alice@example.org,\x01host=mail.example.org\x01port=993\x01auth=Bearer {TOKEN}\x01\x01")); + // A name with a comma or an equals sign is written as RFC 5801 has it. + let odd = oauthbearer("a,b=c", "mail.example.org", 587, TOKEN).unwrap(); + assert!(decoded(&odd).starts_with("n,a=a=2Cb=3Dc,\x01"), "{}", decoded(&odd)); +} + +#[test] +fn what_would_break_out_of_the_message_is_refused() { + for (user, host, token) in [ + ("alice\x01", "mail.example.org", TOKEN), + ("alice", "mail.example.org", "tok\x01en"), + ("alice\r\n", "mail.example.org", TOKEN), + ("alice", "mail.example.org\r\nA2 LOGOUT", TOKEN), + ("alice", "mail example.org", TOKEN), + ("alice", "mail.example.org", "tok en"), + ("alice", "mail.example.org", "tok,en"), + ("alice", "mail.example.org", ""), + ] { + assert!(matches!(oauthbearer(user, host, 993, token), Err(ProtoError::Auth(_))), "{user:?} {host:?} {token:?}"); + } + assert!(oauthbearer("alice", &"h".repeat(300), 993, TOKEN).is_err()); + assert!(oauthbearer("alice", "mail.example.org", 993, &"t".repeat(40_000)).is_err()); +} + +#[test] +fn imap_sends_the_token_with_the_command_when_the_server_takes_it_that_way() { + let mut s = + Script::new("* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=OAUTHBEARER AUTH=XOAUTH2] ready\r\nA0001 OK [CAPABILITY IMAP4rev1 IDLE] welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + assert!(imap.offers_mechanism("oauthbearer") && imap.offers_mechanism("XOAUTH2") && !imap.offers_mechanism("PLAIN")); + imap.authenticate_oauthbearer("alice@example.org", "mail.example.org", 993, TOKEN).unwrap(); + assert!(imap.is_authenticated()); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE OAUTHBEARER {}\r\n", message())); + assert!(s.finished()); +} + +#[test] +fn imap_waits_for_the_go_ahead_otherwise() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 AUTH=OAUTHBEARER] ready\r\n+ \r\nA0001 OK welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + imap.authenticate_oauthbearer("alice@example.org", "mail.example.org", 993, TOKEN).unwrap(); + // (Then what the server can do once signed in is asked for, as after any sign-in.) + assert!(s.sent().starts_with(&format!("A0001 AUTHENTICATE OAUTHBEARER\r\n{}\r\n", message())), "{}", s.sent()); +} + +#[test] +fn imap_answers_the_reasons_with_0x01_and_keeps_them() { + let why = reasons( + r#"{"status":"invalid_token","scope":"openid mail","openid-configuration":"https://id.example.org/.well-known/openid-configuration"}"#, + ); + let mut s = Script::new(format!( + "* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=OAUTHBEARER] ready\r\n+ {why}\r\nA0001 NO [AUTHENTICATIONFAILED] {TOKEN} expired\r\n" + )); + let mut imap = Imap::connect(&mut s).unwrap(); + let err = imap.authenticate_oauthbearer("alice@example.org", "mail.example.org", 993, TOKEN).unwrap_err(); + assert!(matches!(&err, ProtoError::Auth(_))); + assert!(!format!("{err} {err:?} {imap:?}").contains(TOKEN)); + let failure = imap.sasl_failure().unwrap().clone(); + drop(imap); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE OAUTHBEARER {}\r\nAQ==\r\n", message())); + assert!(failure.token_rejected() && !failure.scope_missing()); + assert_eq!( + (failure.scope.as_str(), failure.openid_configuration.as_str()), + ("openid mail", "https://id.example.org/.well-known/openid-configuration") + ); +} + +#[test] +fn imap_refused_without_reasons_or_with_a_server_that_keeps_asking() { + let mut s = Script::new("+ \r\nA0001 NO AUTHENTICATE failed.\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.authenticate_oauthbearer("alice", "mail.example.org", 993, TOKEN), Err(ProtoError::Auth("AUTHENTICATE failed.".into()))); + assert!(imap.sasl_failure().is_none()); + // Reasons that can't be read are no reasons; a third question ends the exchange. + let mut s = Script::new("+ \r\n+ !!!not base64\r\n+ again\r\nA0001 NO cancelled\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.authenticate_oauthbearer("alice", "mail.example.org", 993, TOKEN), Err(ProtoError::Auth(_)))); + assert!(imap.sasl_failure().is_none()); + assert!(s.sent().ends_with("AQ==\r\n*\r\n"), "{}", s.sent()); + // A fourth is more than a sign-in has. + let mut s = Script::new("+ \r\n+ x\r\n+ y\r\n+ z\r\n"); + assert!(matches!(Imap::resume(&mut s).authenticate_oauthbearer("alice", "mail.example.org", 993, TOKEN), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn smtp_sees_the_offer_and_signs_in() { + let mut s = Script::new("250-mail.example.org\r\n250 AUTH PLAIN OAUTHBEARER\r\n334 \r\n235 2.7.0 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + let ext = smtp.hello("localhost").unwrap(); + assert!(ext.auth_oauthbearer && !ext.auth_xoauth2); + smtp.auth_oauthbearer("alice@example.org", "mail.example.org", 587, TOKEN).unwrap(); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + let payload = + lines.iter().find_map(|l| l.strip_prefix("AUTH OAUTHBEARER ")).map(str::to_string).or_else(|| lines.get(2).map(|l| l.to_string())).unwrap(); + assert!(decoded(&payload).contains("host=mail.example.org\x01port=587\x01auth=Bearer ")); +} + +#[test] +fn smtp_answers_the_reasons_with_0x01_then_takes_the_refusal() { + let why = reasons(r#"{"status":"insufficient_scope","scope":"mail"}"#); + let mut s = Script::new(format!("250-x\r\n250 AUTH OAUTHBEARER\r\n334 {why}\r\n535 5.7.8 no {TOKEN}\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth_oauthbearer("alice@example.org", "mail.example.org", 587, TOKEN).unwrap_err(); + assert!(matches!(&err, ProtoError::Auth(_))); + assert!(!format!("{err} {err:?}").contains(TOKEN)); + let failure = smtp.sasl_failure().unwrap().clone(); + drop(smtp); + assert!(s.sent().ends_with("AQ==\r\n"), "{}", s.sent()); + assert!(failure.scope_missing()); + assert_eq!(failure.scope, "mail"); +} + +#[test] +fn smtp_never_shows_the_token_to_a_server_that_doesnt_offer_it() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN XOAUTH2\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth_oauthbearer("alice", "mail.example.org", 587, TOKEN), Err(ProtoError::Auth(_)))); + assert!(!s.sent().contains("AUTH")); +} + +#[test] +fn reasons_are_read_as_hostile() { + let read = |json: &str| SaslFailure::read(reasons(json).as_bytes()); + // Only what each field may be is kept. + let odd = read(r#"{"status":"invalid token\r\n","scope":"a\"b","openid-configuration":"http://id.example.org/","extra":"x"}"#).unwrap(); + assert_eq!(odd, SaslFailure::default()); + let odd = read(r#"{"status":7,"scope":["mail"],"openid-configuration":"https://id.example.org/a b"}"#).unwrap(); + assert_eq!(odd, SaslFailure::default()); + // Not JSON, not an object, not base64, too long: nothing. + assert!(read("[1,2]").is_none() && read("not json").is_none()); + assert!(SaslFailure::read(b"%%%").is_none()); + assert!(SaslFailure::read(reasons(&format!(r#"{{"status":"{}"}}"#, "a".repeat(5_000))).as_bytes()).is_none()); + // A field longer than any is dropped, the others kept. + let long = read(&format!(r#"{{"status":"invalid_token","scope":"{}"}}"#, "s".repeat(600))).unwrap(); + assert_eq!((long.status.as_str(), long.scope.as_str()), ("invalid_token", "")); +} + +proptest! { + #[test] + fn the_message_never_breaks_a_line_and_carries_what_it_was_given(user in "[ -~]{0,40}", host in "[a-z0-9.-]{0,40}", port in any::(), token in "[A-Za-z0-9._~+/-]{1,80}") { + if let Ok(payload) = oauthbearer(&user, &host, port, &token) { + prop_assert!(!payload.contains(['\r', '\n', '\0'])); + let text = decoded(&payload); + let header = text.split('\x01').next().unwrap(); + let name = header.strip_prefix("n,a=").and_then(|rest| rest.strip_suffix(',')).unwrap(); + prop_assert_eq!(name.replace("=2C", ",").replace("=3D", "="), user); + let auth = format!("auth=Bearer {token}"); + prop_assert!(text.split('\x01').any(|field| field == auth)); + } + } + + #[test] + fn reading_reasons_never_panics(bytes in proptest::collection::vec(any::(), 0..2_000)) { + let _ = SaslFailure::read(&bytes); + let _ = SaslFailure::read(STANDARD.encode(&bytes).as_bytes()); + } +} diff --git a/crates/proto/src/smtp.rs b/crates/proto/src/smtp.rs index 0f33a63f12..cacc3e2ef4 100644 --- a/crates/proto/src/smtp.rs +++ b/crates/proto/src/smtp.rs @@ -1,13 +1,14 @@ // SPDX-FileCopyrightText: MailCraft contributors // SPDX-License-Identifier: MIT OR Apache-2.0 -//! An SMTP client (RFC 5321) with STARTTLS (RFC 3207) and AUTH PLAIN / LOGIN / XOAUTH2 (RFC 4954). +//! An SMTP client (RFC 5321) with STARTTLS (RFC 3207) and AUTH PLAIN / LOGIN / XOAUTH2 / +//! OAUTHBEARER (RFC 4954, RFC 7628). use std::io::{Read, Write}; use mailcraft_charset::base64::STANDARD; use crate::line::Wire; -use crate::{ProtoError, Secrets, for_trace, tidy, xoauth2}; +use crate::{FAILURE_ANSWER, ProtoError, SaslFailure, Secrets, for_trace, oauthbearer, tidy, xoauth2}; use mailcraft_i18n::{Arg, Text, said}; /// Most lines one reply may have. @@ -24,6 +25,8 @@ pub struct Smtp { wire: Wire, ext: Extensions, secrets: Secrets, + /// Why the last token sign-in was refused, when the server said ([`Smtp::sasl_failure`]). + sasl_failure: Option, } /// What the server offered in its answer to EHLO. @@ -34,6 +37,8 @@ pub struct Extensions { pub auth_login: bool, /// The server takes an OAuth access token instead of a password (SASL XOAUTH2). pub auth_xoauth2: bool, + /// The server takes an OAuth access token the standard way (SASL OAUTHBEARER, RFC 7628). + pub auth_oauthbearer: bool, /// The largest message the server takes; `Some(0)` when it names no limit. pub size: Option, pub eight_bit_mime: bool, @@ -73,7 +78,7 @@ impl Smtp { /// Continue on a stream that already greeted (after the caller wrapped it in TLS). pub fn resume(stream: S) -> Self { - Smtp { wire: Wire::new(stream), ext: Extensions::default(), secrets: Secrets::default() } + Smtp { wire: Wire::new(stream), ext: Extensions::default(), secrets: Secrets::default(), sasl_failure: None } } /// What the last [`hello`](Self::hello) learned. @@ -164,30 +169,57 @@ impl Smtp { /// it isn't shown the token. 535 and friends → `ProtoError::Auth`. pub fn auth_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { let payload = xoauth2(user, token)?; - if !self.ext.auth_xoauth2 { + let offered = self.ext.auth_xoauth2; + self.auth_token("XOAUTH2", offered, token, &payload, "") + } + + /// AUTH OAUTHBEARER (RFC 7628): an OAuth access token in place of a password, the standard + /// way. `host` and `port` are the server's, as connected to. A server that doesn't offer it + /// isn't shown the token. 535 and friends → `ProtoError::Auth`, with the server's reasons, + /// when it gave them, in [`Smtp::sasl_failure`]. + pub fn auth_oauthbearer(&mut self, user: &str, host: &str, port: u16, token: &str) -> Result<(), ProtoError> { + let payload = oauthbearer(user, host, port, token)?; + let offered = self.ext.auth_oauthbearer; + self.auth_token("OAUTHBEARER", offered, token, &payload, FAILURE_ANSWER) + } + + /// Why the server refused the last token sign-in, when it said in the way RFC 7628 has it. + pub fn sasl_failure(&self) -> Option<&SaslFailure> { + self.sasl_failure.as_ref() + } + + /// A token sign-in with SASL `mechanism`: `payload` (base64) as the client's message, and + /// `failure_answer` for the server's reasons when it refuses. + fn auth_token(&mut self, mechanism: &str, offered: bool, token: &str, payload: &str, failure_answer: &str) -> Result<(), ProtoError> { + self.sasl_failure = None; + if !offered { return Err(ProtoError::Auth(said!("the server offers no way to sign in with an access token"))); } self.secrets.add(token); - self.secrets.add(&payload); - let line = format!("AUTH XOAUTH2 {payload}"); + self.secrets.add(payload); + let line = format!("AUTH {mechanism} {payload}"); let reply = if line.len() <= MAX_COMMAND { - self.secret_command(&line, "AUTH XOAUTH2 ***")? + self.secret_command(&line, &format!("AUTH {mechanism} ***"))? } else { // Too long for one line, as tokens mostly are: wait for the server to ask (RFC 4954 §4). - let ask = self.command("AUTH XOAUTH2")?; + let ask = self.command(&format!("AUTH {mechanism}"))?; if ask.code != 334 { return Err(self.sign_in_failed(&ask)); } - self.secret_command(&payload, "***")? + self.secret_command(payload, "***")? }; match reply.code { 235 => Ok(()), 334 => { - // A refusal comes in two parts: the reasons (JSON in base64), and, once an empty - // line has acknowledged them, the verdict. - let verdict = self.command("")?; + // A refusal comes in two parts: the reasons (JSON in base64), and, once they + // have been answered as the mechanism has it, the verdict. + self.sasl_failure = reply.lines.first().and_then(|reasons| SaslFailure::read(reasons.as_bytes())); + let verdict = self.command(failure_answer)?; match verdict.code { - 235 => Ok(()), + 235 => { + self.sasl_failure = None; + Ok(()) + } 334 => { let _ = self.command("*"); Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))) @@ -353,6 +385,7 @@ fn extensions(lines: &[String]) -> Extensions { "PLAIN" => ext.auth_plain = true, "LOGIN" => ext.auth_login = true, "XOAUTH2" => ext.auth_xoauth2 = true, + "OAUTHBEARER" => ext.auth_oauthbearer = true, _ => {} } } diff --git a/crates/proto/src/smtp/tests.rs b/crates/proto/src/smtp/tests.rs index 9d5d361fd6..7bf79f7768 100644 --- a/crates/proto/src/smtp/tests.rs +++ b/crates/proto/src/smtp/tests.rs @@ -26,7 +26,15 @@ fn a_whole_session() { let ext = smtp.hello("[127.0.0.1]").unwrap(); assert_eq!( ext, - Extensions { starttls: true, auth_plain: true, auth_login: true, auth_xoauth2: true, size: Some(35_882_577), eight_bit_mime: true } + Extensions { + starttls: true, + auth_plain: true, + auth_login: true, + auth_xoauth2: true, + auth_oauthbearer: false, + size: Some(35_882_577), + eight_bit_mime: true + } ); assert_eq!(smtp.extensions(), &ext); smtp.auth("ada@example.org", "hunter2").unwrap(); @@ -263,10 +271,21 @@ fn a_client_name_that_could_break_the_line_is_replaced() { fn extensions_are_read_whatever_their_case() { let mut s = Script::new("250-x\r\n250-starttls\r\n250-Size\r\n250-auth plain\r\n250 8bitmime\r\n"); let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); - assert_eq!(ext, Extensions { starttls: true, auth_plain: true, auth_login: false, auth_xoauth2: false, size: Some(0), eight_bit_mime: true }); + assert_eq!( + ext, + Extensions { + starttls: true, + auth_plain: true, + auth_login: false, + auth_xoauth2: false, + auth_oauthbearer: false, + size: Some(0), + eight_bit_mime: true + } + ); let mut s = Script::new("250-x\r\n250 auth=login xoauth2 OAUTHBEARER\r\n"); let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); - assert_eq!(ext, Extensions { auth_login: true, auth_xoauth2: true, ..Default::default() }); + assert_eq!(ext, Extensions { auth_login: true, auth_xoauth2: true, auth_oauthbearer: true, ..Default::default() }); } #[test] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a101a0411e..e7a95ad6fb 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -247,3 +247,10 @@ path = "fuzz_targets/header_block.rs" test = false doc = false bench = false + +[[bin]] +name = "sasl_failure" +path = "fuzz_targets/sasl_failure.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/sasl_failure.rs b/fuzz/fuzz_targets/sasl_failure.rs new file mode 100644 index 0000000000..960f346daf --- /dev/null +++ b/fuzz/fuzz_targets/sasl_failure.rs @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The reasons a hostile mail server gives for refusing a token sign-in (RFC 7628 §3.2.2) are +//! bounded and never panic, as given and in base64. +#![no_main] + +use mailcraft_charset::base64::STANDARD; +use mailcraft_proto::SaslFailure; + +libfuzzer_sys::fuzz_target!(|data: &[u8]| { + let _ = SaslFailure::read(data); + if let Some(failure) = SaslFailure::read(STANDARD.encode(data).as_bytes()) { + assert!(failure.status.len() <= 512 && failure.scope.len() <= 512 && failure.openid_configuration.len() <= 512); + assert!(!failure.scope.contains(['\r', '\n', '"', '\\'])); + } +}); From ad719c0ee99410e782ae06f6531faa986ba72963 Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 08:59:48 +0100 Subject: [PATCH 03/25] GO3-GO5, GO7: own identity provider: discovery, sign-in, mechanism, secrets Discovery (GO3): an identity provider's sign-in, token and revocation addresses are found from its issuer (OpenID Connect Discovery, then RFC 8414) over HTTPS, following at most three checked redirects. Only the issuer address goes out. The description must name the issuer asked for, byte for byte; its addresses must be usable https ones; a provider that lists PKCE methods without S256 is refused; hosts outside the issuer's own domain are reported for the owner to be asked about. Sign-in (GO4): authorization code with PKCE S256 on the provider's page, redirect to http://127.0.0.1 on any free port or a fixed one, an optional client secret sent to the token and revocation addresses only, refresh keeping the newest refresh token, and RFC 7009 revocation. A provider's refusal is told apart by its code alone, in fixed words. Mechanism (GO5): IMAP and SMTP give the token with OAUTHBEARER when the server offers it, else XOAUTH2, or as the settings force; a server that offers neither is never shown it. The fake servers learn OAUTHBEARER. Secrets (GO7): the refresh token and the client secret of such an account are kept under names bound to the provider, its token address, the client id and both servers, so a changed setting finds nothing remembered and needs a fresh sign-in. The desktop app hands the client secret to sign-in and refresh, reads it back from the credential store, and forgets it with the account. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- apps/mailcraft/src/approval_flow.rs | 2 +- apps/mailcraft/src/main.rs | 8 +- crates/engine/src/sync_driver/credentials.rs | 6 + crates/host/src/secrets.rs | 14 +- crates/host/src/secrets_tests.rs | 38 +++ crates/i18n/po/cs.po | 15 ++ crates/i18n/po/de.po | 15 ++ crates/i18n/po/es.po | 15 ++ crates/i18n/po/fr.po | 15 ++ crates/i18n/po/hu.po | 15 ++ crates/i18n/po/it.po | 15 ++ crates/i18n/po/ka.po | 15 ++ crates/i18n/po/messages.pot | 15 ++ crates/i18n/po/nl.po | 15 ++ crates/i18n/po/pl.po | 15 ++ crates/i18n/po/ro.po | 15 ++ crates/i18n/po/zh_CN.po | 15 ++ crates/net/src/custom_oauth_sync_tests.rs | 161 ++++++++++++ crates/net/src/fake.rs | 102 +++++++- crates/net/src/lib.rs | 3 + crates/net/src/oauth.rs | 61 ++++- crates/net/src/oauth/custom.rs | 190 ++++++++++++++ crates/net/src/oauth/custom_tests.rs | 235 ++++++++++++++++++ crates/net/src/oauth/discovery.rs | 203 +++++++++++++++ crates/net/src/oauth/discovery_tests.rs | 210 ++++++++++++++++ crates/net/src/send.rs | 8 +- crates/net/src/sync.rs | 40 ++- .../tests/google_oauth_first_tests.rs | 2 +- .../src/google_credential_security_tests.rs | 4 +- crates/ui-egui/src/lib.rs | 72 +++++- crates/ui-egui/src/secret_read.rs | 8 + crates/ui-egui/src/secrets_binding_tests.rs | 4 +- 32 files changed, 1510 insertions(+), 41 deletions(-) create mode 100644 crates/net/src/custom_oauth_sync_tests.rs create mode 100644 crates/net/src/oauth/custom.rs create mode 100644 crates/net/src/oauth/custom_tests.rs create mode 100644 crates/net/src/oauth/discovery.rs create mode 100644 crates/net/src/oauth/discovery_tests.rs diff --git a/apps/mailcraft/src/approval_flow.rs b/apps/mailcraft/src/approval_flow.rs index 54c2deb022..ac17a0b546 100644 --- a/apps/mailcraft/src/approval_flow.rs +++ b/apps/mailcraft/src/approval_flow.rs @@ -90,7 +90,7 @@ fn sign_in_request(cancel: &Arc) -> SignInRequest { oauth: settings(), email: "avery@lumen.example".into(), refresh: String::new(), - google_client_secret: String::new(), + client_secret: String::new(), cancel: cancel.clone(), quiet: false, graph: false, diff --git a/apps/mailcraft/src/main.rs b/apps/mailcraft/src/main.rs index 9bf166ff2c..141e902959 100644 --- a/apps/mailcraft/src/main.rs +++ b/apps/mailcraft/src/main.rs @@ -753,11 +753,13 @@ fn sign_in_with(request: SignInRequest, open_page: &dyn Fn(&str) -> bool) -> Res mailcraft_net::oauth::sign_in_google_explained_at( endpoints, &request.oauth, - &request.google_client_secret, + &request.client_secret, &request.email, &open, &request.cancel, ) + } else if request.oauth.provider == mailcraft_model::OAuthProvider::Custom { + mailcraft_net::oauth::sign_in_custom_explained(&request.oauth, &request.client_secret, &request.email, &open, &request.cancel) } else { mailcraft_net::oauth::sign_in_explained(endpoints, &request.oauth, &request.email, &open, &request.cancel) }; @@ -790,7 +792,9 @@ fn sign_in_with(request: SignInRequest, open_page: &dyn Fn(&str) -> bool) -> Res } if !request.refresh.is_empty() { let refreshed = if request.oauth.provider == mailcraft_model::OAuthProvider::Google { - mailcraft_net::oauth::refresh_google_at(&Endpoints::of(&request.oauth), &request.oauth, &request.google_client_secret, &request.refresh) + mailcraft_net::oauth::refresh_google_at(&Endpoints::of(&request.oauth), &request.oauth, &request.client_secret, &request.refresh) + } else if request.oauth.provider == mailcraft_model::OAuthProvider::Custom { + mailcraft_net::oauth::refresh_custom(&request.oauth, &request.client_secret, &request.refresh) } else { mailcraft_net::oauth::refresh(&request.oauth, &request.refresh) }; diff --git a/crates/engine/src/sync_driver/credentials.rs b/crates/engine/src/sync_driver/credentials.rs index 0197308840..ecf4ede033 100644 --- a/crates/engine/src/sync_driver/credentials.rs +++ b/crates/engine/src/sync_driver/credentials.rs @@ -36,6 +36,12 @@ pub fn effective_oauth(mut oauth: OAuth, ids: &ClientIds) -> OAuth { /// is not the account. A Google identity must match the account's address, not an alternate IMAP /// user name (that name is plain editable mailbox data and cannot authorise another owner). pub fn signed_in_as_other(account: &Account, tokens: &Tokens) -> bool { + // An own identity provider's names needn't be the account's: the mail server's user name is + // often neither the address nor what the provider calls the owner. What signs in to the mail + // servers is the token, which they judge themselves. + if account.signs_in_with_own_provider() { + return false; + } if account.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Google) && !tokens.email.trim().is_empty() { !tokens.email.trim().eq_ignore_ascii_case(account.email.trim()) } else { diff --git a/crates/host/src/secrets.rs b/crates/host/src/secrets.rs index 084d0b3616..cbc77684b0 100644 --- a/crates/host/src/secrets.rs +++ b/crates/host/src/secrets.rs @@ -112,6 +112,11 @@ pub fn dav_secret_keys(a: &mailcraft_model::Account) -> Vec { a.dav.as_ref().into_iter().flat_map(|dav| dav.origins()).filter_map(|origin| dav_secret_key(a, &origin)).collect() } +/// What the client secret of an account that signs in with an own identity provider is kept +/// under in the credential store (`kind`). Only such an account has one; it is never written +/// anywhere else ([`mailcraft_model::OAuth::has_secret`] says whether there is one). +pub const OAUTH_CLIENT: &str = "oauth-client"; + /// The name secrets were kept under before they were bound to servers. pub fn legacy_secret_key(kind: &str, address: &str) -> String { format!("{kind}:{}", address.trim().to_ascii_lowercase()) @@ -145,6 +150,13 @@ pub fn secret_key(kind: &str, a: &mailcraft_model::Account) -> String { None => format!("{kind}:{address}|ews={url}|user={user}"), } } else { - format!("{kind}:{address}|imap={}|smtp={}", server(&a.incoming), server(&a.outgoing)) + let base = format!("{kind}:{address}|imap={}|smtp={}", server(&a.incoming), server(&a.outgoing)); + // (An own identity provider's sign-in is also bound to the provider, its token address + // and the client: a changed setting, whoever made it, finds nothing remembered and needs + // a fresh sign-in on the provider's page, so that no remembered token goes anywhere new.) + match a.oauth.as_ref().filter(|o| o.provider == mailcraft_model::OAuthProvider::Custom) { + Some(oauth) => format!("{base}|oauth={}", oauth.binding()), + None => base, + } } } diff --git a/crates/host/src/secrets_tests.rs b/crates/host/src/secrets_tests.rs index 8f686f81f1..6279626c8c 100644 --- a/crates/host/src/secrets_tests.rs +++ b/crates/host/src/secrets_tests.rs @@ -92,3 +92,41 @@ fn a_dav_user_name_keeps_its_case_in_the_key_and_the_host_and_origin_do_not() { assert_eq!(dav_secret_key(&g, "https://outlook.office365.com/"), None); assert!(crate::dav_secret_keys(&g).iter().all(|k| !k.contains("googleapis"))); } + +#[test] +fn an_own_identity_providers_sign_in_is_bound_to_the_provider_and_the_client() { + use mailcraft_model::{OAuth, OAuthProvider}; + let server = |host: &str| Some(Server { host: host.to_string(), port: 993, ..Default::default() }); + let oauth = OAuth { + provider: OAuthProvider::Custom, + client_id: "mailcraft".into(), + issuer: "https://id.example.org/realms/mail".into(), + authorize: "https://id.example.org/auth".into(), + token: "https://id.example.org/token".into(), + ..OAuth::default() + }; + let account = Account { + kind: AccountKind::Imap, + email: "alice@example.org".into(), + incoming: server("mail.example.org"), + outgoing: server("mail.example.org"), + oauth: Some(oauth.clone()), + ..Default::default() + }; + let key = secret_key("refresh", &account); + assert!(key.contains("imap=mail.example.org:993") && key.contains("oauth=custom|https://id.example.org/realms/mail|"), "{key}"); + // A change of anything the sign-in belongs to is another name: nothing remembered is found. + for changed in [ + OAuth { issuer: "https://id.attacker.example".into(), ..oauth.clone() }, + OAuth { token: "https://id.attacker.example/token".into(), ..oauth.clone() }, + OAuth { client_id: "other".into(), ..oauth.clone() }, + ] { + assert_ne!(secret_key("refresh", &Account { oauth: Some(changed), ..account.clone() }), key); + } + assert_ne!(secret_key("refresh", &Account { incoming: server("imap.attacker.example"), ..account.clone() }), key); + // Nor are the refresh token and the client secret ever one name. + assert_ne!(secret_key(crate::secrets::OAUTH_CLIENT, &account), key); + // A Google account is named as ever. + let google = Account { oauth: Some(OAuth { provider: OAuthProvider::Google, ..OAuth::default() }), ..account.clone() }; + assert!(!secret_key("refresh", &google).contains("oauth=")); +} diff --git a/crates/i18n/po/cs.po b/crates/i18n/po/cs.po index 7f4ba0c69a..17d6858e57 100644 --- a/crates/i18n/po/cs.po +++ b/crates/i18n/po/cs.po @@ -24520,6 +24520,16 @@ msgstr "server nenabízí STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "server na tomto připojení nepřijímá heslo" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24568,6 +24578,11 @@ msgstr "server nenabízí žádný způsob přihlášení heslem" msgid "the server offers no way to sign in with an access token" msgstr "server nenabízí žádný způsob přihlášení přístupovým tokenem" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/de.po b/crates/i18n/po/de.po index 9627cacd1c..71a5a4c3c7 100644 --- a/crates/i18n/po/de.po +++ b/crates/i18n/po/de.po @@ -23055,6 +23055,16 @@ msgstr "Der Server bietet STARTTLS nicht an" msgid "the server doesn't take a password on this connection" msgstr "Der Server nimmt über diese Verbindung kein Passwort an" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -23101,6 +23111,11 @@ msgstr "Der Server bietet keine Möglichkeit, sich mit einem Passwort anzumelden msgid "the server offers no way to sign in with an access token" msgstr "Der Server bietet keine Möglichkeit, sich mit einem Zugriffstoken anzumelden" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs msgid "the server offers only older encryption (CBC suites) that MailCraft doesn't use; its administrator can turn on the AES-GCM suites" diff --git a/crates/i18n/po/es.po b/crates/i18n/po/es.po index 5ec23d8a05..9f48e35224 100644 --- a/crates/i18n/po/es.po +++ b/crates/i18n/po/es.po @@ -24467,6 +24467,16 @@ msgstr "el servidor no ofrece STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "el servidor no acepta una contraseña en esta conexión" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24515,6 +24525,11 @@ msgstr "el servidor no ofrece ninguna forma de iniciar sesión con contraseña" msgid "the server offers no way to sign in with an access token" msgstr "el servidor no ofrece ninguna forma de iniciar sesión con un token de acceso" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/fr.po b/crates/i18n/po/fr.po index b958c99b3a..10f9050da2 100644 --- a/crates/i18n/po/fr.po +++ b/crates/i18n/po/fr.po @@ -24370,6 +24370,16 @@ msgstr "le serveur ne propose pas STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "le serveur n'accepte pas de mot de passe sur cette connexion" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24418,6 +24428,11 @@ msgstr "le serveur ne propose aucun moyen de se connecter avec un mot de passe" msgid "the server offers no way to sign in with an access token" msgstr "le serveur ne propose aucun moyen de se connecter avec un jeton d'accès" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/hu.po b/crates/i18n/po/hu.po index bd56ae9c36..b0e4c249ca 100644 --- a/crates/i18n/po/hu.po +++ b/crates/i18n/po/hu.po @@ -24462,6 +24462,16 @@ msgstr "A kiszolgáló nem kínál StartTLS-t" msgid "the server doesn't take a password on this connection" msgstr "a kiszolgáló nem vesz jelszót ezen a kapcsolaton" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24510,6 +24520,11 @@ msgstr "a kiszolgáló nem tud jelszóval beiratkozni" msgid "the server offers no way to sign in with an access token" msgstr "a szerver nem tud bejelentkezni egy token-hozzáféréssel" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/it.po b/crates/i18n/po/it.po index 4e5a5db014..48be102f4a 100644 --- a/crates/i18n/po/it.po +++ b/crates/i18n/po/it.po @@ -24442,6 +24442,16 @@ msgstr "il server non offre STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "il server non accetta una password su questa connessione" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24490,6 +24500,11 @@ msgstr "il server non offre alcun modo di accedere con una password" msgid "the server offers no way to sign in with an access token" msgstr "il server non offre alcun modo di accedere con un token di accesso" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/ka.po b/crates/i18n/po/ka.po index 4f28edb3df..5fdf1ea4a2 100644 --- a/crates/i18n/po/ka.po +++ b/crates/i18n/po/ka.po @@ -24384,6 +24384,16 @@ msgstr "სერვერი STARTTLS-ს არ გვთავაზობს msgid "the server doesn't take a password on this connection" msgstr "სერვერი ამ კავშირზე პაროლს არ იღებს" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24432,6 +24442,11 @@ msgstr "სერვერი პაროლით შესვლის სა msgid "the server offers no way to sign in with an access token" msgstr "სერვერი წვდომის ტოკენით შესვლის საშუალებას არ გვთავაზობს" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/messages.pot b/crates/i18n/po/messages.pot index 70f17b8fa3..8b2eb08c94 100644 --- a/crates/i18n/po/messages.pot +++ b/crates/i18n/po/messages.pot @@ -20320,6 +20320,16 @@ msgstr "" msgid "the server doesn't take a password on this connection" msgstr "" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs msgid "the server ended the command early" @@ -20360,6 +20370,11 @@ msgstr "" msgid "the server offers no way to sign in with an access token" msgstr "" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs msgid "the server offers only older encryption (CBC suites) that MailCraft doesn't use; its administrator can turn on the AES-GCM suites" diff --git a/crates/i18n/po/nl.po b/crates/i18n/po/nl.po index 160f2d4548..233e11f64b 100644 --- a/crates/i18n/po/nl.po +++ b/crates/i18n/po/nl.po @@ -23842,6 +23842,16 @@ msgstr "de server biedt geen STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "de server accepteert geen wachtwoord via deze verbinding" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -23889,6 +23899,11 @@ msgstr "de server biedt geen manier om met een wachtwoord aan te melden" msgid "the server offers no way to sign in with an access token" msgstr "de server biedt geen manier om met een toegangstoken aan te melden" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/pl.po b/crates/i18n/po/pl.po index ba24e1ad34..6a379a7e78 100644 --- a/crates/i18n/po/pl.po +++ b/crates/i18n/po/pl.po @@ -24552,6 +24552,16 @@ msgstr "serwer nie oferuje STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "serwer nie przyjmuje hasła w tym połączeniu" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24600,6 +24610,11 @@ msgstr "serwer nie oferuje logowania hasłem" msgid "the server offers no way to sign in with an access token" msgstr "serwer nie oferuje logowania tokenem dostępu" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/ro.po b/crates/i18n/po/ro.po index 999f2b7589..087993974f 100644 --- a/crates/i18n/po/ro.po +++ b/crates/i18n/po/ro.po @@ -24545,6 +24545,16 @@ msgstr "serverul nu oferă STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "serverul nu acceptă o parolă pe această conexiune" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24593,6 +24603,11 @@ msgstr "serverul nu oferă nicio metodă de conectare cu parolă" msgid "the server offers no way to sign in with an access token" msgstr "serverul nu oferă nicio metodă de conectare cu token de acces" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/i18n/po/zh_CN.po b/crates/i18n/po/zh_CN.po index 7ecd607222..ba9975a33e 100644 --- a/crates/i18n/po/zh_CN.po +++ b/crates/i18n/po/zh_CN.po @@ -24443,6 +24443,16 @@ msgstr "服务器不提供 STARTTLS" msgid "the server doesn't take a password on this connection" msgstr "服务器不接受在此连接中使用密码" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" +msgstr "" + +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for" +msgstr "" + #. why a mail server couldn't be used #: crates/proto/src/imap/mod.rs #, fuzzy @@ -24491,6 +24501,11 @@ msgstr "服务器不支持使用密码登录" msgid "the server offers no way to sign in with an access token" msgstr "服务器不支持使用访问令牌登录" +#. why a mail server couldn't be used +#: crates/net/src/sync.rs +msgid "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" +msgstr "" + #. why a mail server couldn't be used #: crates/net/src/transport.rs #, fuzzy diff --git a/crates/net/src/custom_oauth_sync_tests.rs b/crates/net/src/custom_oauth_sync_tests.rs new file mode 100644 index 0000000000..c7e5eb0078 --- /dev/null +++ b/crates/net/src/custom_oauth_sync_tests.rs @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An account that signs in with an own identity provider, end to end against the fake IMAP and +//! SMTP servers on loopback: which way its token is given, and where it may go. + +use mailcraft_model::sync::{FolderState, SyncRequest}; +use mailcraft_model::{Account, AccountKind, Address, FolderKind, Message, OAuth, OAuthProvider, SaslChoice, Security, Server}; + +use crate::fake::{Fake, FakeImap, FakeMailbox, FakeSmtp, ImapWorld, SmtpWorld, oauthbearer_parts}; +use crate::{NetError, send, sync, test_account}; + +const TOKEN: &str = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhbGljZSJ9.c2ln"; +const USER: &str = "alice"; + +fn servers(oauthbearer: bool, xoauth2: bool) -> (FakeImap, FakeSmtp) { + let inbox = + FakeMailbox { raw: "INBOX".into(), flags: "\\HasNoChildren".into(), uid_validity: 1, messages: Vec::new(), refuse_open: false, next_uid: 0 }; + let imap = Fake::imap(ImapWorld { + user: USER.into(), + token: TOKEN.into(), + oauthbearer, + no_xoauth2: !xoauth2, + mailboxes: vec![inbox], + ..Default::default() + }); + let smtp = Fake::smtp(SmtpWorld { user: USER.into(), token: TOKEN.into(), oauthbearer, no_xoauth2: !xoauth2, ..Default::default() }); + (imap, smtp) +} + +fn account(imap: &FakeImap, smtp: &FakeSmtp, mechanism: SaslChoice) -> Account { + let server = |port: u16| Some(Server { host: "127.0.0.1".into(), port, security: Security::None }); + Account { + id: 3, + email: "alice@example.org".into(), + username: USER.into(), + kind: AccountKind::Imap, + incoming: server(imap.port), + outgoing: server(smtp.port), + oauth: Some(OAuth { + provider: OAuthProvider::Custom, + client_id: "mailcraft".into(), + authorize: "https://id.example.org/auth".into(), + token: "https://id.example.org/token".into(), + mechanism, + ..OAuth::default() + }), + ..Default::default() + } +} + +fn hello() -> Message { + Message { + id: 9, + from: Address::new("Alice", "alice@example.org"), + to: vec![Address::new("Bob", "bob@example.org")], + subject: "Hello".into(), + ..Default::default() + } +} + +fn used(log: &[String]) -> Vec<&str> { + log.iter().filter_map(|l| l.split_whitespace().find(|w| *w == "OAUTHBEARER" || *w == "XOAUTH2")).collect() +} + +#[test] +fn oauthbearer_is_preferred_when_offered_and_carries_the_servers_host_and_port() { + let (imap, smtp) = servers(true, true); + let a = account(&imap, &smtp, SaslChoice::Auto); + assert_eq!(test_account(&a, TOKEN), Ok(())); + assert_eq!(send(&a, TOKEN, &hello()), Ok(())); + let imap_log = imap.world().log.clone(); + assert_eq!(used(&imap_log).first(), Some(&"OAUTHBEARER"), "{imap_log:?}"); + assert!(used(&smtp.world().log).iter().all(|m| *m == "OAUTHBEARER")); + // What went out names the server it went to. + let payload = imap_log.iter().find(|l| !l.contains(' ') && l.len() > 40).cloned().unwrap_or_default(); + let (user, host, port, token) = oauthbearer_parts(&payload); + assert_eq!((user.as_str(), host.as_str(), port, token.as_str()), (USER, "127.0.0.1", imap.port.to_string(), TOKEN)); + assert_eq!(smtp.world().delivered.len(), 1); +} + +#[test] +fn xoauth2_is_used_when_it_is_all_the_server_takes_or_what_the_settings_say() { + let (imap, smtp) = servers(false, true); + let a = account(&imap, &smtp, SaslChoice::Auto); + assert_eq!(test_account(&a, TOKEN), Ok(())); + assert!(used(&imap.world().log).iter().all(|m| *m == "XOAUTH2")); + let (imap, smtp) = servers(true, true); + let a = account(&imap, &smtp, SaslChoice::XOAuth2); + assert_eq!(test_account(&a, TOKEN), Ok(())); + assert_eq!(send(&a, TOKEN, &hello()), Ok(())); + assert!(used(&imap.world().log).iter().all(|m| *m == "XOAUTH2")); + assert!(used(&smtp.world().log).iter().all(|m| *m == "XOAUTH2")); +} + +#[test] +fn a_mechanism_the_server_doesnt_offer_is_an_error_and_the_token_never_goes() { + for (bearer, xoauth2, choice) in [(false, true, SaslChoice::OAuthBearer), (true, false, SaslChoice::XOAuth2), (false, false, SaslChoice::Auto)] { + let (imap, smtp) = servers(bearer, xoauth2); + // (A server that takes no token at all: one that says so.) + if !bearer && !xoauth2 { + imap.world().token = String::new(); + smtp.world().token = String::new(); + } + let a = account(&imap, &smtp, choice); + let error = test_account(&a, TOKEN).unwrap_err(); + assert!(matches!(error, NetError::Proto(mailcraft_proto::ProtoError::Auth(_))), "{choice:?}: {error:?}"); + assert!(!imap.world().log.iter().any(|l| l.contains("AUTHENTICATE")), "{choice:?}: {:?}", imap.world().log); + let error = send(&a, TOKEN, &hello()).unwrap_err(); + assert!(!format!("{error:?}").contains(TOKEN)); + assert!(!smtp.world().log.iter().any(|l| l.starts_with("AUTH")), "{choice:?}: {:?}", smtp.world().log); + } +} + +#[test] +fn a_refused_token_says_why_without_showing_it() { + let (imap, smtp) = servers(true, false); + let a = account(&imap, &smtp, SaslChoice::Auto); + let error = test_account(&a, "eyJ.stale.token").unwrap_err(); + assert!(error.is_refused_sign_in(), "{error:?}"); + assert!(!format!("{error} {error:?}").contains("eyJ.stale.token")); + // The server's reasons were answered as RFC 7628 has it. + assert!(imap.world().log.iter().any(|l| l == "AQ=="), "{:?}", imap.world().log); + let error = send(&a, "eyJ.stale.token", &hello()).unwrap_err(); + assert!(!format!("{error} {error:?}").contains("eyJ.stale.token")); + assert!(smtp.world().log.iter().any(|l| l == "AQ==")); +} + +#[test] +fn mail_comes_down_and_goes_out_on_the_token() { + let (imap, smtp) = servers(true, true); + let a = account(&imap, &smtp, SaslChoice::Auto); + let folders: Vec = + FolderKind::STANDARD.iter().zip(100..).map(|(kind, id)| FolderState { id, kind: *kind, ..Default::default() }).collect(); + let request = SyncRequest { account: a, access_token: TOKEN.into(), folders, outbox: vec![hello()], ..Default::default() }; + let result = sync(&request); + assert_eq!(result.errors, Vec::::new()); + assert_eq!(result.sent, [9]); +} + +#[test] +fn the_token_never_goes_to_a_server_the_account_doesnt_name() { + let (imap, smtp) = servers(true, true); + let mut a = account(&imap, &smtp, SaslChoice::Auto); + // Edited to point at Google's server after signing in: refused before anything connects. + a.incoming = Some(Server { host: "imap.gmail.com".into(), port: 993, security: Security::Tls }); + let error = test_account(&a, TOKEN).unwrap_err(); + assert!(matches!(error, NetError::Config(_)), "{error:?}"); + assert_eq!(imap.world().connections, 0); +} + +#[test] +fn starttls_missing_is_refused_before_any_token_is_sent() { + let (imap, smtp) = servers(true, true); + let mut a = account(&imap, &smtp, SaslChoice::Auto); + a.incoming.as_mut().unwrap().security = Security::StartTls; + a.outgoing.as_mut().unwrap().security = Security::StartTls; + assert!(matches!(test_account(&a, TOKEN), Err(NetError::Tls { .. }))); + assert!(!imap.world().log.iter().any(|l| l.contains("AUTHENTICATE"))); + assert!(matches!(send(&a, TOKEN, &hello()), Err(NetError::Tls { .. }))); + assert!(!smtp.world().log.iter().any(|l| l.starts_with("AUTH"))); +} diff --git a/crates/net/src/fake.rs b/crates/net/src/fake.rs index c0af22676e..6c919a511e 100644 --- a/crates/net/src/fake.rs +++ b/crates/net/src/fake.rs @@ -295,6 +295,10 @@ pub(crate) struct ImapWorld { pub(crate) password: String, /// The access token that signs `user` in (XOAUTH2); empty for a server that takes none. pub(crate) token: String, + /// With `token`: take it with OAUTHBEARER (RFC 7628) too. + pub(crate) oauthbearer: bool, + /// With `token`: don't take it with XOAUTH2. + pub(crate) no_xoauth2: bool, /// Say the token may come with the command (SASL-IR). pub(crate) sasl_ir: bool, /// Offer the password-based PLAIN mechanism. @@ -377,7 +381,12 @@ pub(crate) struct ImapWorld { impl ImapWorld { /// What the server says it can do. fn capabilities(&self, secured: bool) -> String { - let xoauth2 = if self.token.is_empty() { "" } else { " AUTH=XOAUTH2" }; + let xoauth2 = match (self.token.is_empty(), self.oauthbearer, self.no_xoauth2) { + (true, ..) => "", + (false, true, true) => " AUTH=OAUTHBEARER", + (false, true, false) => " AUTH=OAUTHBEARER AUTH=XOAUTH2", + (false, false, _) => " AUTH=XOAUTH2", + }; let sasl_ir = if self.sasl_ir { " SASL-IR" } else { "" }; let plain = if self.plain && (!self.offer_starttls || secured) { " AUTH=PLAIN" } else { "" }; let starttls = if self.offer_starttls { " STARTTLS" } else { "" }; @@ -418,6 +427,10 @@ pub(crate) struct SmtpWorld { pub(crate) auth_optional: bool, /// The access token that signs `user` in (XOAUTH2, insisted on likewise); empty for a server that takes none. pub(crate) token: String, + /// With `token`: take it with OAUTHBEARER (RFC 7628) too. + pub(crate) oauthbearer: bool, + /// With `token`: don't take it with XOAUTH2. + pub(crate) no_xoauth2: bool, /// Say STARTTLS is on offer (it isn't: what follows the go-ahead is no handshake). pub(crate) offer_starttls: bool, /// Recipients to answer 550 for. @@ -504,6 +517,30 @@ fn pretend_tls(out: &mut TcpStream, reader: &mut BufReader, go_ahead: /// What a server writes in place of its reasons for refusing a token: `{"status":"401"}`. const REASONS: &str = "eyJzdGF0dXMiOiI0MDEifQ=="; +/// What a server writes in place of its reasons for refusing an OAUTHBEARER token: +/// `{"status":"invalid_token","openid-configuration":"https://id.example.org/.well-known/openid-configuration"}`. +const BEARER_REASONS: &str = "eyJzdGF0dXMiOiJpbnZhbGlkX3Rva2VuIiwib3BlbmlkLWNvbmZpZ3VyYXRpb24iOiJodHRwczovL2lkLmV4YW1wbGUub3JnLy53ZWxsLWtub3duL29wZW5pZC1jb25maWd1cmF0aW9uIn0="; + +/// The user, host, port and token of an OAUTHBEARER message (`n,a=…,^Ahost=…^Aport=…^Aauth=Bearer …^A^A` +/// in base64); empty when it isn't one. +pub(crate) fn oauthbearer_parts(payload: &str) -> (String, String, String, String) { + let decoded = mailcraft_charset::base64::STANDARD.decode(payload).unwrap_or_default(); + let decoded = String::from_utf8_lossy(&decoded).into_owned(); + let mut fields = decoded.split('\u{1}'); + let Some(user) = fields.next().and_then(|h| h.strip_prefix("n,a=")).and_then(|h| h.strip_suffix(',')) else { return Default::default() }; + let (mut host, mut port, mut token) = (String::new(), String::new(), String::new()); + for field in fields { + if let Some(v) = field.strip_prefix("host=") { + host = v.into(); + } else if let Some(v) = field.strip_prefix("port=") { + port = v.into(); + } else if let Some(v) = field.strip_prefix("auth=Bearer ") { + token = v.into(); + } + } + (user.replace("=2C", ",").replace("=3D", "="), host, port, token) +} + /// The user and the token of an XOAUTH2 response (`user=…^Aauth=Bearer …^A^A` in base64); empty when it isn't one. fn bearer(payload: &str) -> (String, String) { let decoded = mailcraft_charset::base64::STANDARD.decode(payload).unwrap_or_default(); @@ -673,7 +710,9 @@ fn serve_imap(stream: TcpStream, shared: Arc>) { let _ = reader.get_mut().write_all(format!("{tag} {verdict}\r\n").as_bytes()); continue; } - if world.token.is_empty() || !mechanism.eq_ignore_ascii_case("XOAUTH2") { + let bearer = mechanism.eq_ignore_ascii_case("OAUTHBEARER"); + let takes = if bearer { world.oauthbearer } else { mechanism.eq_ignore_ascii_case("XOAUTH2") && !world.no_xoauth2 }; + if world.token.is_empty() || !takes { reply.extend(format!("{tag} NO [CANNOT] no such way to sign in\r\n").bytes()); } else { let (user, token) = (world.user.clone(), world.token.clone()); @@ -688,14 +727,20 @@ fn serve_imap(stream: TcpStream, shared: Arc>) { } else { with_command.to_string() }; - let (given_user, given_token) = bearer(&payload); + let (given_user, given_token) = if bearer { + let (u, _, _, t) = oauthbearer_parts(&payload); + (u, t) + } else { + self::bearer(&payload) + }; if (given_user, &given_token) == (user, &token) { signed_in = true; let _ = reader.get_mut().write_all(format!("{tag} OK [CAPABILITY {caps}] welcome\r\n").as_bytes()); } else { - // The reasons, and after the client's empty line the verdict. A careless + // The reasons, and after the client's answer the verdict. A careless // server: it repeats the token it was sent. - let _ = reader.get_mut().write_all(format!("+ {REASONS}\r\n").as_bytes()); + let reasons = if bearer { BEARER_REASONS } else { REASONS }; + let _ = reader.get_mut().write_all(format!("+ {reasons}\r\n").as_bytes()); let Some(line) = read_line(&mut reader) else { return }; shared.lock().unwrap().log.push(line); let _ = reader @@ -1095,12 +1140,17 @@ fn serve_smtp(stream: TcpStream, shared: Arc>) { let mut world = shared.lock().unwrap(); world.log.push(line.clone()); let reply = if upper.starts_with("EHLO") { - let auth = match (world.auth, !world.token.is_empty()) { - (true, true) => "250-AUTH PLAIN LOGIN XOAUTH2\r\n", - (true, false) => "250-AUTH PLAIN LOGIN\r\n", - (false, true) => "250-AUTH XOAUTH2\r\n", - (false, false) => "", - }; + let mut mechanisms: Vec<&str> = Vec::new(); + if world.auth { + mechanisms.extend(["PLAIN", "LOGIN"]); + } + if !world.token.is_empty() && !world.no_xoauth2 { + mechanisms.push("XOAUTH2"); + } + if !world.token.is_empty() && world.oauthbearer { + mechanisms.push("OAUTHBEARER"); + } + let auth = if mechanisms.is_empty() { String::new() } else { format!("250-AUTH {}\r\n", mechanisms.join(" ")) }; let starttls = if world.offer_starttls { "250-STARTTLS\r\n" } else { "" }; format!("250-fake.example.org\r\n250-8BITMIME\r\n250-SIZE 10485760\r\n{auth}{starttls}250 HELP") } else if upper == "STARTTLS" && world.offer_starttls { @@ -1119,8 +1169,36 @@ fn serve_smtp(stream: TcpStream, shared: Arc>) { // A careless server: it repeats the password it was sent. format!("535 5.7.8 no user with the password {}", parts.get(2).copied().unwrap_or("")) } + } else if upper == "AUTH OAUTHBEARER" || upper.starts_with("AUTH OAUTHBEARER ") { + if world.token.is_empty() || !world.oauthbearer { + "504 5.5.4 no such way to sign in".to_string() + } else { + let (user, token) = (world.user.clone(), world.token.clone()); + drop(world); + let with_command = line.get("AUTH OAUTHBEARER ".len()..).unwrap_or(""); + let payload = if with_command.is_empty() { + let _ = out.write_all(b"334 \r\n"); + let Some(line) = read_line(&mut reader) else { return }; + shared.lock().unwrap().log.push(line.clone()); + line + } else { + with_command.to_string() + }; + let (given_user, _, _, given_token) = oauthbearer_parts(&payload); + if (given_user, &given_token) == (user, &token) { + signed_in = true; + shared.lock().unwrap().sign_ins += 1; + let _ = out.write_all(b"235 2.7.0 welcome\r\n"); + } else { + let _ = out.write_all(format!("334 {BEARER_REASONS}\r\n").as_bytes()); + let Some(line) = read_line(&mut reader) else { return }; + shared.lock().unwrap().log.push(line); + let _ = out.write_all(b"535 5.7.8 refused\r\n"); + } + continue; + } } else if upper == "AUTH XOAUTH2" || upper.starts_with("AUTH XOAUTH2 ") { - if world.token.is_empty() { + if world.token.is_empty() || world.no_xoauth2 { "504 5.5.4 no such way to sign in".to_string() } else { let (user, token) = (world.user.clone(), world.token.clone()); diff --git a/crates/net/src/lib.rs b/crates/net/src/lib.rs index 771f9bfd70..dba126d856 100644 --- a/crates/net/src/lib.rs +++ b/crates/net/src/lib.rs @@ -86,6 +86,9 @@ mod xml_text; // (`cfg(test)` on its own line: that is how clippy knows test code, which may unwrap.) #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] +mod custom_oauth_sync_tests; +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod fake; #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/net/src/oauth.rs b/crates/net/src/oauth.rs index 4574f28c2f..34ac0e7bf7 100644 --- a/crates/net/src/oauth.rs +++ b/crates/net/src/oauth.rs @@ -395,6 +395,9 @@ pub fn sign_in_for(oauth: &OAuth, login_hint: &str, open: &dyn Fn(&str), cancel: if oauth.provider == OAuthProvider::Google && resource != Resource::Mail { return Err(NetError::Config("Google sign-in supports mail only, not Microsoft Graph".into())); } + if oauth.provider == OAuthProvider::Custom && resource != Resource::Mail { + return Err(NetError::Config("a sign-in with your own identity provider is for mail only, not Microsoft Graph".into())); + } let mut endpoints = Endpoints::for_resource(oauth, resource); // (An Outlook.com address is a personal account whatever the settings know yet.) if resource != Resource::Mail && oauth.is_personal(login_hint) { @@ -415,6 +418,11 @@ pub fn sign_in_at(endpoints: &Endpoints, oauth: &OAuth, login_hint: &str, open: if oauth.provider == OAuthProvider::Google { return sign_in_google_at(endpoints, oauth, GOOGLE_DESKTOP_SECRET, login_hint, open, cancel); } + // (Its addresses are its settings': a public client, with no secret. One with a secret signs + // in with [`sign_in_custom`], which the host hands it to.) + if oauth.provider == OAuthProvider::Custom { + return sign_in_custom(&at_endpoints(oauth, endpoints), "", login_hint, open, cancel); + } sign_in_within(endpoints, oauth, login_hint, open, cancel, SIGN_IN_TIMEOUT) } @@ -431,6 +439,10 @@ pub fn sign_in_explained( return google::sign_in_google_refused(endpoints, oauth, GOOGLE_DESKTOP_SECRET, login_hint, open, cancel, SIGN_IN_TIMEOUT) .map_err(SignInEnd::from); } + if oauth.provider == OAuthProvider::Custom { + return custom::sign_in_custom_refused(&at_endpoints(oauth, endpoints), "", login_hint, open, cancel, SIGN_IN_TIMEOUT) + .map_err(SignInEnd::from); + } sign_in_refused(endpoints, oauth, login_hint, open, cancel, SIGN_IN_TIMEOUT).map_err(SignInEnd::from) } @@ -1221,6 +1233,12 @@ pub fn refresh_at(endpoints: &Endpoints, oauth: &OAuth, refresh_token: &str) -> /// [`refresh_for`] at endpoints other than the provider's usual ones: the tokens are asked for /// [`Endpoints::scope`], and a refusal is read as one of a token for `resource`. pub fn refresh_for_at(endpoints: &Endpoints, oauth: &OAuth, refresh_token: &str, resource: Resource) -> Result { + if oauth.provider == OAuthProvider::Custom { + if resource != Resource::Mail { + return Err(NetError::Config("a sign-in with your own identity provider is for mail only, not Microsoft Graph".into())); + } + return refresh_custom(&at_endpoints(oauth, endpoints), "", refresh_token); + } if oauth.provider == OAuthProvider::Google { if resource != Resource::Mail { return Err(NetError::Config("Google sign-in supports mail only, not Microsoft Graph".into())); @@ -1932,6 +1950,19 @@ impl Redirect { Redirect::listen_avoiding(blocked_port) } + /// Listen on `port` of 127.0.0.1 alone: for a provider whose registration names the port, with + /// a redirect to the IP literal (no browser takes `127.0.0.1` to be IPv6). A port somebody + /// else has is refused rather than another taken: the provider wouldn't send the owner there. + fn listen_at(port: u16) -> Result { + if port == 0 || blocked_port(port) { + return Err(NetError::Config("that redirect port can't be used: choose another, or automatic".into())); + } + let v4 = TcpListener::bind((Ipv4Addr::LOCALHOST, port)) + .map_err(|_| NetError::Config(format!("port {port} on this computer is in use: choose another redirect port, or automatic").into()))?; + v4.set_nonblocking(true).map_err(|_| NetError::Config("couldn't open a port on this computer for the sign-in to come back to".into()))?; + Ok(Redirect { listeners: vec![v4], port }) + } + /// [`listen`](Self::listen) with the test for a port a browser refuses given, so a test can drive it. fn listen_avoiding(blocked: impl Fn(u16) -> bool) -> Result { let failed = || NetError::Config("couldn't open a port on this computer for the sign-in to come back to".into()); @@ -2056,8 +2087,8 @@ pub fn sign_in_via( if matches!(via, RedirectStrategy::Loopback) { return sign_in_at(endpoints, oauth, login_hint, open, cancel); } - if oauth.provider == OAuthProvider::Google { - return Err(NetError::Config("Google sign-in comes back through a loopback port only".into())); + if oauth.provider != OAuthProvider::Microsoft { + return Err(NetError::Config(format!("a sign-in with {} comes back through a loopback port only", oauth.provider.label()).into())); } sign_in_refused_via(endpoints, oauth, login_hint, open, cancel, SIGN_IN_TIMEOUT, via).map_err(|refused| refused.error) } @@ -2074,15 +2105,37 @@ pub fn sign_in_explained_via( if matches!(via, RedirectStrategy::Loopback) { return sign_in_explained(endpoints, oauth, login_hint, open, cancel); } - if oauth.provider == OAuthProvider::Google { - return Err(SignInEnd::Other(NetError::Config("Google sign-in comes back through a loopback port only".into()))); + if oauth.provider != OAuthProvider::Microsoft { + return Err(SignInEnd::Other(NetError::Config( + format!("a sign-in with {} comes back through a loopback port only", oauth.provider.label()).into(), + ))); } sign_in_refused_via(endpoints, oauth, login_hint, open, cancel, SIGN_IN_TIMEOUT, via).map_err(SignInEnd::from) } mod google; pub use google::{refresh_google_at, sign_in_google_at}; +mod custom; +pub use custom::{refresh_custom, revoke_custom, sign_in_custom, sign_in_custom_explained}; + +/// An own identity provider's settings with the addresses `endpoints` gives in place of its own +/// (what the `…_at` functions are for). +fn at_endpoints(oauth: &OAuth, endpoints: &Endpoints) -> OAuth { + let mut oauth = oauth.clone(); + if !endpoints.authorize.trim().is_empty() { + oauth.authorize = endpoints.authorize.clone(); + } + if !endpoints.token.trim().is_empty() { + oauth.token = endpoints.token.clone(); + } + oauth +} +pub mod discovery; +#[cfg(test)] +mod custom_tests; +#[cfg(test)] +mod discovery_tests; #[cfg(test)] mod google_tests; #[cfg(test)] diff --git a/crates/net/src/oauth/custom.rs b/crates/net/src/oauth/custom.rs new file mode 100644 index 0000000000..ac5e75941b --- /dev/null +++ b/crates/net/src/oauth/custom.rs @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Signing in with the owner's own identity provider ([`OAuthProvider::Custom`]): an OpenID +//! Connect or OAuth 2.0 server in front of their own IMAP and SMTP servers. +//! +//! The same protected sign-in as Microsoft's and Google's (authorization code with PKCE `S256`, +//! a random `state`, the system browser, a loopback redirect: RFC 6749, 7636, 8252), at the +//! addresses the account's settings name ([`OAuth::effective`]). The client is the one the +//! owner (or their administrator) registered there for MailCraft: a public client, or one with a +//! client secret, which the host hands in from the system's credential store and which goes to +//! the token and revocation addresses alone (RFC 8252 §8.5 says what such a secret is worth). +//! +//! The redirect is `http://127.0.0.1:{port}/`, the IP literal RFC 8252 §7.3 asks for, on any free +//! port or the one the settings name for a provider that can't register "any port". +//! +//! What the provider answers is hostile. Its refusals are told apart by their code alone, in +//! fixed words; the text it adds for people is never shown (it could say anything, or repeat a +//! secret). + +use super::*; + +/// The fixed words for a provider's refusal, by its code (RFC 6749 §5.2, §4.1.2.1). +fn refused(code: &str) -> NetError { + let (text, auth) = match code { + "invalid_grant" => ("your identity provider no longer takes this sign-in: sign in again", true), + "invalid_client" | "unauthorized_client" => { + ("your identity provider doesn't know this client id, or its client secret: check the OAuth settings", true) + } + "invalid_scope" => ("your identity provider won't give what was asked for: check the extra scopes in the OAuth settings", true), + "access_denied" => ("access was refused on the sign-in page", true), + "server_error" | "temporarily_unavailable" => ("your identity provider can't sign anybody in just now: try again later", false), + _ => ("your identity provider refused the sign-in", true), + }; + NetError::Proto(if auth { ProtoError::Auth(text.into()) } else { ProtoError::Rejected(text.into()) }) +} + +/// The client id and the addresses a sign-in uses, when the settings are ready for one. +fn registration(oauth: &OAuth, client_secret: &str) -> Result { + if oauth.provider != OAuthProvider::Custom { + return Err(NetError::Config("this account doesn't sign in with your own identity provider".into())); + } + oauth.ready().map_err(|why| NetError::Config(why.to_string().into()))?; + if client_secret.len() > 1024 || !client_secret.bytes().all(|b| b.is_ascii_graphic()) { + return Err(NetError::Config("the client secret can only be letters, digits and punctuation".into())); + } + Ok(oauth.effective()) +} + +/// Sign the owner in on their identity provider's page and bring back tokens for the mail +/// servers. `client_secret` is empty for a public client. As for [`sign_in`]: `open` is given the +/// page's address, the wait is five minutes at most, and `cancel` ends it. +pub fn sign_in_custom(oauth: &OAuth, client_secret: &str, login_hint: &str, open: &dyn Fn(&str), cancel: &AtomicBool) -> Result { + sign_in_custom_refused(oauth, client_secret, login_hint, open, cancel, SIGN_IN_TIMEOUT).map_err(|refused| refused.error) +} + +/// [`sign_in_custom`], saying how a sign-in that brought no tokens ended ([`SignInEnd`]). +pub fn sign_in_custom_explained( + oauth: &OAuth, + client_secret: &str, + login_hint: &str, + open: &dyn Fn(&str), + cancel: &AtomicBool, +) -> Result { + sign_in_custom_refused(oauth, client_secret, login_hint, open, cancel, SIGN_IN_TIMEOUT).map_err(SignInEnd::from) +} + +/// [`sign_in_custom`], with what a no was about and whose it was. +pub(super) fn sign_in_custom_refused( + oauth: &OAuth, + client_secret: &str, + login_hint: &str, + open: &dyn Fn(&str), + cancel: &AtomicBool, + patience: Duration, +) -> Result { + let used = registration(oauth, client_secret)?; + Url::parse(&used.authorize)?; + let token_endpoint = Url::parse(&used.token)?; + if cancel.load(Ordering::Relaxed) { + return Err(NetError::SignInCancelled.into()); + } + let redirect = match used.redirect_port { + Some(port) => Redirect::listen_at(port)?, + None => Redirect::listen()?, + }; + let redirect_uri = format!("http://127.0.0.1:{}/", redirect.port); + let verifier = random(32)?; + let state = random(24)?; + open(&page(&used, &redirect_uri, &state, &challenge(&verifier), login_hint)); + let code = redirect.wait(&state, cancel, patience)?; + drop(redirect); + let mut fields = vec![ + ("grant_type", "authorization_code"), + ("client_id", used.client_id.as_str()), + ("code", code.as_str()), + ("redirect_uri", redirect_uri.as_str()), + ("code_verifier", verifier.as_str()), + ]; + if !client_secret.is_empty() { + fields.push(("client_secret", client_secret)); + } + trade_custom(&token_endpoint, &fields, "", &[code.as_str(), verifier.as_str(), client_secret]).map_err(Refused::from) +} + +/// The address of the identity provider's sign-in page, with everything it needs to send the +/// owner back here. Nothing of the owner's but the address they sign in as (`login_hint`). +fn page(used: &mailcraft_model::OAuthDefaults, redirect_uri: &str, state: &str, challenge: &str, login_hint: &str) -> String { + let mut fields = vec![ + ("client_id", used.client_id.as_str()), + ("response_type", "code"), + ("redirect_uri", redirect_uri), + ("scope", used.scopes.as_str()), + ("state", state), + ("code_challenge", challenge), + ("code_challenge_method", "S256"), + ]; + let hint = login_hint.trim(); + if !hint.is_empty() && hint.len() <= 320 && !hint.chars().any(char::is_control) { + fields.push(("login_hint", hint)); + } + let address = used.authorize.trim(); + format!("{address}{}{}", if address.contains('?') { '&' } else { '?' }, http::form(&fields)) +} + +/// Trade a refresh token for new tokens for the mail servers, without asking the owner anything. +/// The tokens carry the refresh token to use next time (a new one when the provider sent one). +/// `ProtoError::Auth`: the provider no longer takes it, and the owner has to sign in again; +/// `ProtoError::Rejected` or a connection error: it couldn't say, and the refresh token is as good +/// as it was. +pub fn refresh_custom(oauth: &OAuth, client_secret: &str, refresh_token: &str) -> Result { + let used = registration(oauth, client_secret)?; + let token_endpoint = Url::parse(&used.token)?; + if refresh_token.is_empty() || !usable(refresh_token) { + return Err(NetError::Proto(ProtoError::Auth("there is no earlier sign-in to renew".into()))); + } + // (No scope: the new tokens are for what the sign-in was given, RFC 6749 §6.) + let mut fields = vec![("grant_type", "refresh_token"), ("client_id", used.client_id.as_str()), ("refresh_token", refresh_token)]; + if !client_secret.is_empty() { + fields.push(("client_secret", client_secret)); + } + trade_custom(&token_endpoint, &fields, refresh_token, &[refresh_token, client_secret]) +} + +/// Give a refresh token back to the identity provider (RFC 7009), when it names where: what is +/// done when the account is removed. Nothing to do when it names nowhere. A refusal or a provider +/// that can't be reached is an error, which the caller may let be: the token is forgotten here +/// either way. +pub fn revoke_custom(oauth: &OAuth, client_secret: &str, refresh_token: &str) -> Result<(), NetError> { + let used = registration(oauth, client_secret).or_else(|error| { + // (Settings that can't sign in may still say where to give a token back.) + if oauth.provider == OAuthProvider::Custom && !oauth.revoke.trim().is_empty() { Ok(oauth.effective()) } else { Err(error) } + })?; + if used.revoke.is_empty() || refresh_token.is_empty() || !usable(refresh_token) { + return Ok(()); + } + mailcraft_model::oauth::endpoint(&used.revoke).map_err(|why| NetError::Config(format!("the revocation address {why}").into()))?; + let endpoint = Url::parse(&used.revoke)?; + let mut fields = vec![("token", refresh_token), ("token_type_hint", "refresh_token"), ("client_id", used.client_id.as_str())]; + if !client_secret.is_empty() { + fields.push(("client_secret", client_secret)); + } + let answer = http::post_form(&endpoint, &fields, TOKEN_TIMEOUT).map_err(|e| e.without(refresh_token).without(client_secret))?; + // RFC 7009 §2.2: 200 whether or not the token was still good. + if answer.status == 200 { + return Ok(()); + } + let json = serde_json::from_slice::(&answer.body).ok(); + let code = json.as_ref().and_then(|j| j.get("error")).and_then(Value::as_str).unwrap_or(""); + Err(if code.is_empty() { + NetError::Proto(ProtoError::Rejected(format!("your identity provider answered with status {}", answer.status).into())) + } else { + refused(code) + }) +} + +/// POST the form to the token endpoint and read the tokens out of the answer, the refusal by its +/// code alone. `secrets` are the parts of the form that must not come back in an error. +fn trade_custom(endpoint: &Url, fields: &[(&str, &str)], earlier_refresh: &str, secrets: &[&str]) -> Result { + let answer = http::post_form(endpoint, fields, TOKEN_TIMEOUT) + .map_err(|e| secrets.iter().filter(|s| !s.is_empty()).fold(e, |e, secret| e.without(secret)))?; + let json = serde_json::from_slice::(&answer.body).ok().filter(Value::is_object); + if let Some(code) = json.as_ref().and_then(|j| j.get("error")).and_then(Value::as_str) { + let code: String = code.chars().take(64).collect(); + return Err(refused(&code)); + } + if answer.status >= 500 { + return Err(NetError::Proto(ProtoError::Rejected(format!("your identity provider answered with status {}", answer.status).into()))); + } + tokens_from(&answer, earlier_refresh, mailcraft_time::now(), secrets).map_err(|refused| refused.error) +} diff --git a/crates/net/src/oauth/custom_tests.rs b/crates/net/src/oauth/custom_tests.rs new file mode 100644 index 0000000000..97f26794eb --- /dev/null +++ b/crates/net/src/oauth/custom_tests.rs @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Signing in with an own identity provider, against a fake token service and an in-process +//! loopback browser. Invented example.org identities; no real provider is contacted. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use super::*; +use crate::fake::{FakeHttp, json_answer}; + +const PATIENCE: Duration = Duration::from_secs(10); +const SECRET: &str = "not-a-real-client-secret"; + +fn own(server: &FakeHttp) -> OAuth { + OAuth { + provider: OAuthProvider::Custom, + client_id: "mailcraft-desktop".into(), + issuer: server.url("/realms/mail"), + authorize: server.url("/auth"), + token: server.url("/token"), + revoke: server.url("/revoke"), + scopes: "mail".into(), + ..OAuth::default() + } +} + +fn jwt(address: &str) -> String { + let claims = serde_json::json!({ "email": address, "name": "Alice Example" }); + format!("header.{}.signature", URL_SAFE_NO_PAD.encode(claims.to_string().as_bytes())) +} + +fn good(refresh: &str) -> Vec { + let mut body = serde_json::json!({ + "token_type": "Bearer", + "expires_in": 300, + "access_token": "fake-access", + "id_token": jwt("alice@example.org"), + }); + if !refresh.is_empty() { + body["refresh_token"] = serde_json::json!(refresh); + } + json_answer("200 OK", &body.to_string()) +} + +fn form(server: &FakeHttp, n: usize) -> HashMap { + http::pairs(server.request(n).split_once("\r\n\r\n").unwrap().1).into_iter().collect() +} + +type Seen = Arc>; + +/// A browser on another thread that comes back to the loopback port with a code, and the state +/// the page was given (or another). +fn browser(right_state: bool) -> (impl Fn(&str) + use<>, Seen) { + let seen = Seen::default(); + let kept = seen.clone(); + let opener = move |url: &str| { + *kept.lock().unwrap() = url.into(); + let args: HashMap = http::pairs(url.split_once('?').unwrap().1).into_iter().collect(); + let port: u16 = args["redirect_uri"].strip_prefix("http://127.0.0.1:").unwrap().trim_end_matches('/').parse().unwrap(); + let state = if right_state { args["state"].clone() } else { "somebody-elses".into() }; + std::thread::spawn(move || { + let mut socket = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + socket.set_read_timeout(Some(PATIENCE)).unwrap(); + let request = format!("GET /?code=synthetic-code&state={state} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n"); + socket.write_all(request.as_bytes()).unwrap(); + let mut answer = Vec::new(); + let _ = socket.read_to_end(&mut answer); + }); + }; + (opener, seen) +} + +fn page_args(seen: &Seen) -> HashMap { + let page = seen.lock().unwrap().clone(); + http::pairs(page.split_once('?').unwrap().1).into_iter().collect() +} + +#[test] +fn a_whole_sign_in_against_the_providers_own_addresses() { + let server = FakeHttp::answering(good("fake-refresh")); + let (open, seen) = browser(true); + let cancel = AtomicBool::new(false); + let tokens = sign_in_custom(&own(&server), "", "alice@example.org", &open, &cancel).unwrap(); + assert_eq!((tokens.access.as_str(), tokens.refresh.as_str(), tokens.email.as_str()), ("fake-access", "fake-refresh", "alice@example.org")); + // The page: the client, PKCE S256, the IP-literal redirect, what it is asked for. + let args = page_args(&seen); + assert!(seen.lock().unwrap().starts_with(&server.url("/auth?"))); + assert_eq!((args["client_id"].as_str(), args["code_challenge_method"].as_str()), ("mailcraft-desktop", "S256")); + assert_eq!(args["scope"], "openid email offline_access mail"); + assert!(args["redirect_uri"].starts_with("http://127.0.0.1:") && args["redirect_uri"].ends_with('/')); + assert_eq!(args["login_hint"], "alice@example.org"); + // The trade: the code, the verifier whose hash the page got, the same redirect, no secret. + let trade = form(&server, 0); + assert!(server.request(0).starts_with("POST /token ")); + assert_eq!((trade["grant_type"].as_str(), trade["code"].as_str()), ("authorization_code", "synthetic-code")); + assert_eq!(challenge(&trade["code_verifier"]), args["code_challenge"]); + assert_eq!(trade["redirect_uri"], args["redirect_uri"]); + assert!(!trade.contains_key("client_secret")); +} + +#[test] +fn a_client_secret_goes_to_the_token_address_alone_and_never_into_an_error() { + let server = + FakeHttp::answering(json_answer("401 Unauthorized", &format!(r#"{{"error":"invalid_client","error_description":"bad secret {SECRET}"}}"#))); + let (open, seen) = browser(true); + let cancel = AtomicBool::new(false); + let error = sign_in_custom(&own(&server), SECRET, "alice@example.org", &open, &cancel).unwrap_err(); + assert_eq!(form(&server, 0)["client_secret"], SECRET); + assert!(!seen.lock().unwrap().contains(SECRET), "the secret went through the browser"); + // In fixed words: the provider's own text is never shown. + let shown = format!("{error} {error:?}"); + assert!(!shown.contains(SECRET) && !shown.contains("bad secret"), "{shown}"); + assert!(shown.contains("client id"), "{shown}"); +} + +#[test] +fn a_code_with_the_wrong_state_is_never_traded() { + let server = FakeHttp::answering(good("r")); + let (open, _) = browser(false); + let cancel = AtomicBool::new(false); + let outcome = custom::sign_in_custom_refused(&own(&server), "", "", &open, &cancel, Duration::from_millis(1_500)); + assert!(matches!(outcome.map_err(|r| r.error), Err(NetError::SignInTimedOut))); + assert_eq!(server.asked(), 0); +} + +#[test] +fn a_fixed_redirect_port_is_the_one_used() { + let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let server = FakeHttp::answering(good("r")); + let (open, seen) = browser(true); + let cancel = AtomicBool::new(false); + sign_in_custom(&OAuth { redirect_port: Some(port), ..own(&server) }, "", "", &open, &cancel).unwrap(); + assert_eq!(page_args(&seen)["redirect_uri"], format!("http://127.0.0.1:{port}/")); + // One somebody else has is refused, not swapped for another the provider wouldn't send to. + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let busy = taken.local_addr().unwrap().port(); + let error = sign_in_custom(&OAuth { redirect_port: Some(busy), ..own(&server) }, "", "", &open, &cancel).unwrap_err(); + assert!(matches!(error, NetError::Config(_)), "{error:?}"); +} + +#[test] +fn settings_that_cant_sign_in_are_refused_before_the_page_opens() { + let server = FakeHttp::answering(good("r")); + let opened = Arc::new(Mutex::new(false)); + let flag = opened.clone(); + let open = move |_: &str| *flag.lock().unwrap() = true; + let cancel = AtomicBool::new(false); + for broken in [ + OAuth { client_id: String::new(), ..own(&server) }, + OAuth { token: String::new(), ..own(&server) }, + OAuth { authorize: "http://id.example.org/auth".into(), ..own(&server) }, + OAuth { provider: OAuthProvider::Google, ..own(&server) }, + ] { + assert!(matches!(sign_in_custom(&broken, "", "", &open, &cancel), Err(NetError::Config(_))), "{broken:?}"); + } + assert!(matches!(sign_in_custom(&own(&server), "a secret with spaces", "", &open, &cancel), Err(NetError::Config(_)))); + assert!(!*opened.lock().unwrap()); + assert_eq!(server.asked(), 0); + // Nor is it ever a Microsoft Graph sign-in. + assert!(matches!(sign_in_for(&own(&server), "", &open, &cancel, Resource::Graph), Err(NetError::Config(_)))); + assert!(matches!(refresh_for(&own(&server), "r", Resource::Graph), Err(NetError::Config(_)))); +} + +#[test] +fn refreshing_keeps_the_newest_refresh_token() { + let server = FakeHttp::start(|n, _| if n == 0 { good("rotated") } else { good("") }); + let first = refresh_custom(&own(&server), SECRET, "original").unwrap(); + assert_eq!(first.refresh, "rotated"); + let trade = form(&server, 0); + assert_eq!( + (trade["grant_type"].as_str(), trade["refresh_token"].as_str(), trade["client_secret"].as_str()), + ("refresh_token", "original", SECRET) + ); + assert!(!trade.contains_key("scope")); + // An answer without a new one keeps the one given. + assert_eq!(refresh_custom(&own(&server), "", "rotated").unwrap().refresh, "rotated"); + // The generic path takes it too, as a public client. + assert!(refresh(&own(&server), "rotated").is_ok()); +} + +#[test] +fn a_refused_refresh_says_sign_in_again_and_a_provider_that_cant_say_doesnt() { + let refused = FakeHttp::answering(json_answer("400 Bad Request", r#"{"error":"invalid_grant","error_description":""}"#)); + let error = refresh_custom(&own(&refused), "", "old").unwrap_err(); + assert!(error.is_refused_sign_in(), "{error:?}"); + assert!(!format!("{error}").contains("script")); + let down = FakeHttp::answering(json_answer("503 Service Unavailable", "down")); + let error = refresh_custom(&own(&down), "", "old").unwrap_err(); + assert!(!error.is_refused_sign_in(), "{error:?}"); + let busy = FakeHttp::answering(json_answer("400 Bad Request", r#"{"error":"temporarily_unavailable"}"#)); + assert!(!refresh_custom(&own(&busy), "", "old").unwrap_err().is_refused_sign_in()); + // A provider that can't be reached isn't a refusal either. + let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let gone = OAuth { token: format!("http://127.0.0.1:{port}/token"), ..own(&down) }; + assert!(matches!(refresh_custom(&gone, "", "old"), Err(NetError::Connect { .. }))); + // No refresh token: nothing to renew, and nothing asked. + let quiet = FakeHttp::answering(good("r")); + assert!(refresh_custom(&own(&quiet), "", "").unwrap_err().is_refused_sign_in()); + assert_eq!(quiet.asked(), 0); +} + +#[test] +fn an_answer_without_a_usable_token_is_refused() { + for body in [r#"{"token_type":"mac","access_token":"a"}"#, r#"{"token_type":"Bearer"}"#, "not json", r#"{"access_token":"a b\r\nc"}"#] { + let server = FakeHttp::answering(json_answer("200 OK", body)); + assert!(refresh_custom(&own(&server), "", "old").is_err(), "{body}"); + } +} + +#[test] +fn revoking_gives_the_refresh_token_back_where_the_provider_says() { + let server = FakeHttp::answering(json_answer("200 OK", "")); + revoke_custom(&own(&server), SECRET, "the-refresh").unwrap(); + let sent = form(&server, 0); + assert!(server.request(0).starts_with("POST /revoke ")); + assert_eq!((sent["token"].as_str(), sent["token_type_hint"].as_str(), sent["client_secret"].as_str()), ("the-refresh", "refresh_token", SECRET)); + // Nowhere to give it back: nothing is sent. + let quiet = FakeHttp::answering(json_answer("200 OK", "")); + revoke_custom(&OAuth { revoke: String::new(), ..own(&quiet) }, "", "the-refresh").unwrap(); + assert_eq!(quiet.asked(), 0); + // A refusal is an error that names no token. + let refused = FakeHttp::answering(json_answer("400 Bad Request", r#"{"error":"invalid_client","error_description":"the-refresh"}"#)); + let error = revoke_custom(&own(&refused), "", "the-refresh").unwrap_err(); + assert!(!format!("{error} {error:?}").contains("the-refresh")); +} + +#[test] +fn the_endpoints_of_an_own_provider_are_its_settings() { + let server = FakeHttp::answering(good("r")); + let ends = Endpoints::of(&own(&server)); + assert_eq!((ends.authorize, ends.token), (server.url("/auth"), server.url("/token"))); + assert_eq!(ends.scope, "openid email offline_access mail"); + assert!(ends.consent.is_empty() && ends.fewer.is_empty() && ends.lesser.is_empty()); +} diff --git a/crates/net/src/oauth/discovery.rs b/crates/net/src/oauth/discovery.rs new file mode 100644 index 0000000000..638e0f5318 --- /dev/null +++ b/crates/net/src/oauth/discovery.rs @@ -0,0 +1,203 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Finding an identity provider's sign-in and token addresses from its own address (its issuer): +//! OpenID Connect Discovery 1.0 (`{issuer}/.well-known/openid-configuration`), then RFC 8414 +//! (`https://host/.well-known/oauth-authorization-server{path}`). +//! +//! Only the issuer's address goes out: no mail address, no client id, no cookie. Fetched over +//! HTTPS alone (an `http://` address only on this computer, for tests), following at most +//! [`MAX_REDIRECTS`] redirects, each to an address that is checked as the first was; the answer +//! is capped by the HTTP layer. +//! +//! The document is hostile. It must name the issuer that was asked for, byte for byte (RFC 8414 +//! §3.3, OpenID Connect Discovery §4.3): a document that names another is refused, so that one +//! provider can't speak for another. Only the fields a sign-in needs are read, each capped; +//! every address in it must be one an identity provider can be reached at +//! ([`mailcraft_model::oauth::endpoint`]). A provider that says which PKCE methods it takes and +//! doesn't list `S256` is refused: `plain` is never sent. + +use std::time::Duration; + +use serde_json::Value; + +use crate::NetError; +use crate::http::{self, Url}; + +/// How long fetching one document may take. +const PATIENCE: Duration = Duration::from_secs(10); +/// Most redirects followed from one address. +pub(crate) const MAX_REDIRECTS: usize = 3; +/// Most entries of a list kept, and the longest one. +const MAX_LIST: usize = 64; +const MAX_ENTRY: usize = 256; + +/// What an identity provider says of itself, as far as a sign-in needs it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Discovered { + /// The issuer, as asked for and as the document names it. + pub issuer: String, + /// The page the owner signs in on. + pub authorize: String, + /// Where codes and refresh tokens are traded for tokens. + pub token: String, + /// Where a refresh token is given back; empty when it names none. + pub revoke: String, + /// The scopes it says it supports; empty when it doesn't say. + pub scopes_supported: Vec, + /// The hosts of its addresses that lie outside the issuer's own domain (its registrable + /// part), for the owner to be asked about once before anything is sent there. + pub outside: Vec, + /// It takes a client secret only in the `Authorization` header (`client_secret_basic`), + /// not in the form. + pub secret_in_header: bool, +} + +impl Discovered { + /// Whether it says it can't hand out refresh tokens: it lists its scopes and + /// `offline_access` isn't among them. (Saying nothing is no such word.) + pub fn lacks_offline_access(&self) -> bool { + !self.scopes_supported.is_empty() && !self.scopes_supported.iter().any(|s| s == "offline_access") + } +} + +/// Fetch and read what the identity provider at `issuer` says of itself: its OpenID Connect +/// document, else its RFC 8414 one. The error says what was wrong with the last one tried. +pub fn discover(issuer: &str) -> Result { + let issuer = checked_issuer(issuer)?; + let mut last = NetError::Config("the identity provider doesn't describe itself at the usual addresses: enter its sign-in addresses".into()); + for address in addresses(&issuer) { + match fetch(&address) { + Ok(Some(body)) => match read(&issuer, &body) { + Ok(found) => return Ok(found), + // A document that is there but wrong says so, whatever the other address has. + Err(error) => last = error, + }, + Ok(None) => {} + Err(error) => last = error, + } + } + Err(last) +} + +/// The issuer as typed, if it is one: an `https://` address with no query or fragment. +fn checked_issuer(issuer: &str) -> Result { + let issuer = issuer.trim(); + if issuer.is_empty() { + return Err(NetError::Config("enter your identity provider's address (its issuer)".into())); + } + mailcraft_model::oauth::endpoint(issuer).map_err(|why| NetError::Config(format!("the identity provider's address {why}").into()))?; + if issuer.contains(['?', '#']) { + return Err(NetError::Config("the identity provider's address can't have a query or a fragment".into())); + } + Ok(issuer.to_string()) +} + +/// Where the issuer's documents are, in the order they are tried. +pub(crate) fn addresses(issuer: &str) -> Vec { + let base = issuer.trim_end_matches('/'); + let mut out = vec![format!("{base}/.well-known/openid-configuration")]; + // RFC 8414 §3.1: the well-known part goes between the host and the issuer's path. + if let Some((scheme, rest)) = base.split_once("://") { + let (host, path) = rest.find('/').map_or((rest, ""), |at| rest.split_at(at)); + out.push(format!("{scheme}://{host}/.well-known/oauth-authorization-server{path}")); + } + out +} + +/// The body at `address`, following redirects to addresses that are checked as it was. +/// `Ok(None)` when there is nothing there (a status other than 200 and a redirect). +fn fetch(address: &str) -> Result>, NetError> { + let mut url = Url::parse(address)?; + for _ in 0..=MAX_REDIRECTS { + let request = + http::Request { method: "GET", headers: &[("Accept", "application/json")], body: None, patience: PATIENCE, max_body: http::MAX_BODY }; + let answer = http::request(&url, &request)?; + match answer.status { + 200 => return Ok(Some(answer.body)), + 301 | 302 | 303 | 307 | 308 => { + let Some(next) = answer.location.as_deref().map(|to| absolute(&url, to)) else { return Ok(None) }; + // (`Url::parse` refuses `http://` anywhere but on this computer.) + url = Url::parse(&next)?; + } + _ => return Ok(None), + } + } + Err(NetError::Config("the identity provider sent its description on through too many redirects".into())) +} + +/// A `Location` as an absolute address: as written when it is one, else on `from`'s host. +fn absolute(from: &Url, location: &str) -> String { + let location = location.trim(); + if location.contains("://") { + return location.to_string(); + } + let scheme = if from.secure { "https" } else { "http" }; + let host = if from.host.contains(':') { format!("[{}]", from.host) } else { from.host.clone() }; + let port = if from.port == 0 { String::new() } else { format!(":{}", from.port) }; + let path = if location.starts_with('/') { location.to_string() } else { format!("/{location}") }; + format!("{scheme}://{host}{port}{path}") +} + +/// Read an identity provider's description of itself, fetched for `issuer` (as typed). +pub fn read(issuer: &str, body: &[u8]) -> Result { + let bad = |why: &str| NetError::Config(format!("the identity provider's description {why}").into()); + if body.len() > http::MAX_BODY { + return Err(bad("is too long")); + } + let json: Value = serde_json::from_slice(body).map_err(|_| bad("isn't the JSON it should be"))?; + let object = json.as_object().ok_or_else(|| bad("isn't the JSON it should be"))?; + let text = |name: &str| object.get(name).and_then(Value::as_str).map(str::trim).unwrap_or(""); + let list = |name: &str| -> Vec { + let entries = object.get(name).and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + entries + .iter() + .take(MAX_LIST) + .filter_map(Value::as_str) + .filter(|entry| entry.len() <= MAX_ENTRY && entry.bytes().all(|b| b.is_ascii_graphic())) + .map(str::to_string) + .collect() + }; + let issuer = issuer.trim(); + if text("issuer") != issuer { + return Err(NetError::Config( + "the identity provider's description names another issuer than the address entered: check the address, character for character".into(), + )); + } + let address = |name: &str, what: &str, needed: bool| -> Result { + let value = text(name); + if value.is_empty() { + return if needed { Err(bad(&format!("has no {what} address"))) } else { Ok(String::new()) }; + } + mailcraft_model::oauth::endpoint(value) + .map_err(|why| bad(&format!("gives a {what} address that {}", why.trim_start_matches("is ").trim_start_matches("must "))))?; + Ok(value.to_string()) + }; + let authorize = address("authorization_endpoint", "sign-in", true)?; + let token = address("token_endpoint", "token", true)?; + let revoke = address("revocation_endpoint", "revocation", false)?; + let methods = list("code_challenge_methods_supported"); + if object.contains_key("code_challenge_methods_supported") && !methods.iter().any(|m| m == "S256") { + return Err(bad("says it doesn't take the protected sign-in (PKCE with S256) MailCraft uses")); + } + let grants = list("grant_types_supported"); + if !grants.is_empty() && !grants.iter().any(|g| g == "authorization_code") { + return Err(bad("says it doesn't sign people in on its page (authorization code)")); + } + let auth_methods = list("token_endpoint_auth_methods_supported"); + let secret_in_header = auth_methods.iter().any(|m| m == "client_secret_basic") && !auth_methods.iter().any(|m| m == "client_secret_post"); + let home = host_of(issuer); + let home = mailcraft_model::sender_warnings::registrable(&home).to_string(); + let mut outside: Vec = Vec::new(); + for found in [&authorize, &token, &revoke].into_iter().filter(|a| !a.is_empty()) { + let host = host_of(found); + if !mailcraft_model::is_within(&host, &home) && !outside.contains(&host) { + outside.push(host); + } + } + Ok(Discovered { issuer: issuer.to_string(), authorize, token, revoke, scopes_supported: list("scopes_supported"), outside, secret_in_header }) +} + +/// The host of an address, lower-cased. +fn host_of(address: &str) -> String { + Url::parse(address).map(|url| url.host.to_ascii_lowercase()).unwrap_or_default() +} diff --git a/crates/net/src/oauth/discovery_tests.rs b/crates/net/src/oauth/discovery_tests.rs new file mode 100644 index 0000000000..c963c767b1 --- /dev/null +++ b/crates/net/src/oauth/discovery_tests.rs @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Finding an identity provider's addresses from its issuer, against synthetic documents. + +use proptest::prelude::*; + +use super::discovery::{addresses, discover, read}; +use crate::NetError; +use crate::fake::{FakeHttp, json_answer}; + +const ISSUER: &str = "https://id.example.org/realms/mail"; + +/// What a Keycloak-shaped provider says of itself. +fn keycloak(issuer: &str) -> String { + serde_json::json!({ + "issuer": issuer, + "authorization_endpoint": format!("{issuer}/protocol/openid-connect/auth"), + "token_endpoint": format!("{issuer}/protocol/openid-connect/token"), + "revocation_endpoint": format!("{issuer}/protocol/openid-connect/revoke"), + "userinfo_endpoint": format!("{issuer}/protocol/openid-connect/userinfo"), + "jwks_uri": format!("{issuer}/protocol/openid-connect/certs"), + "grant_types_supported": ["authorization_code", "refresh_token", "password"], + "code_challenge_methods_supported": ["plain", "S256"], + "scopes_supported": ["openid", "email", "profile", "offline_access"], + "token_endpoint_auth_methods_supported": ["private_key_jwt", "client_secret_basic", "client_secret_post"], + }) + .to_string() +} + +fn error(result: Result) -> String { + match result { + Err(NetError::Config(why)) => why.to_string(), + other => panic!("expected the description to be refused, got {other:?}"), + } +} + +#[test] +fn a_keycloak_shaped_description_gives_the_addresses() { + let found = read(ISSUER, keycloak(ISSUER).as_bytes()).unwrap(); + assert_eq!(found.authorize, format!("{ISSUER}/protocol/openid-connect/auth")); + assert_eq!(found.token, format!("{ISSUER}/protocol/openid-connect/token")); + assert_eq!(found.revoke, format!("{ISSUER}/protocol/openid-connect/revoke")); + assert!(found.outside.is_empty() && !found.lacks_offline_access() && !found.secret_in_header); +} + +#[test] +fn an_authentik_shaped_one_with_its_token_on_another_host_says_so() { + let issuer = "https://auth.example.org/application/o/mail/"; + let doc = serde_json::json!({ + "issuer": issuer, + "authorization_endpoint": "https://auth.example.org/application/o/authorize/", + "token_endpoint": "https://tokens.example.net/application/o/token/", + "scopes_supported": ["openid", "email"], + "token_endpoint_auth_methods_supported": ["client_secret_basic"], + }); + let found = read(issuer, doc.to_string().as_bytes()).unwrap(); + assert_eq!(found.outside, ["tokens.example.net"]); + // It lists its scopes, and offline_access isn't one: no refresh tokens. + assert!(found.lacks_offline_access()); + assert!(found.secret_in_header); + assert!(found.revoke.is_empty()); +} + +#[test] +fn a_description_naming_another_issuer_is_refused() { + for typed in [ + "https://id.example.org/realms/other", + "https://id.example.org/realms/mail/", + "https://ID.example.org/realms/mail", + " https://evil.example/realms/mail", + ] { + let why = error(read(typed, keycloak(ISSUER).as_bytes())); + assert!(why.contains("another issuer"), "{typed}: {why}"); + } +} + +#[test] +fn addresses_that_cant_be_used_are_refused() { + for (field, value) in [ + ("token_endpoint", "http://id.example.org/token"), + ("authorization_endpoint", "javascript:alert(1)"), + ("token_endpoint", "https://user:pw@id.example.org/token"), + ("token_endpoint", "https://id.example.org/token#frag"), + ("authorization_endpoint", ""), + ("revocation_endpoint", "ftp://id.example.org/revoke"), + ] { + let mut doc: serde_json::Value = serde_json::from_str(&keycloak(ISSUER)).unwrap(); + doc[field] = serde_json::json!(value); + assert!(read(ISSUER, doc.to_string().as_bytes()).is_err(), "{field}={value}"); + } + // A token address that isn't text at all is no address. + let mut doc: serde_json::Value = serde_json::from_str(&keycloak(ISSUER)).unwrap(); + doc["token_endpoint"] = serde_json::json!({"deep": [1, 2]}); + assert!(read(ISSUER, doc.to_string().as_bytes()).is_err()); +} + +#[test] +fn a_provider_without_s256_or_the_code_grant_is_refused_and_one_that_doesnt_say_is_not() { + let mut doc: serde_json::Value = serde_json::from_str(&keycloak(ISSUER)).unwrap(); + doc["code_challenge_methods_supported"] = serde_json::json!(["plain"]); + assert!(error(read(ISSUER, doc.to_string().as_bytes())).contains("PKCE")); + doc["code_challenge_methods_supported"] = serde_json::json!("S256"); + assert!(read(ISSUER, doc.to_string().as_bytes()).is_err()); + doc.as_object_mut().unwrap().remove("code_challenge_methods_supported"); + assert!(read(ISSUER, doc.to_string().as_bytes()).is_ok()); + doc["grant_types_supported"] = serde_json::json!(["client_credentials"]); + assert!(read(ISSUER, doc.to_string().as_bytes()).is_err()); +} + +#[test] +fn what_isnt_a_description_is_refused_without_panicking() { + for body in [&b""[..], b"null", b"[1,2]", b"{\"issuer\":", b"\xff\xfe{}", b"\"text\""] { + assert!(read(ISSUER, body).is_err(), "{body:?}"); + } + // Deep nesting and huge lists are capped, not followed. + let deep = format!("{}1{}", "[".repeat(5_000), "]".repeat(5_000)); + assert!(read(ISSUER, deep.as_bytes()).is_err()); + let mut doc: serde_json::Value = serde_json::from_str(&keycloak(ISSUER)).unwrap(); + doc["scopes_supported"] = serde_json::json!((0..1_000).map(|n| format!("s{n}")).collect::>()); + let found = read(ISSUER, doc.to_string().as_bytes()).unwrap(); + assert!(found.scopes_supported.len() <= 64); + assert!(read(ISSUER, &vec![b' '; 200_000]).is_err()); +} + +#[test] +fn the_documents_are_looked_for_where_the_two_standards_say() { + assert_eq!( + addresses(ISSUER), + [ + "https://id.example.org/realms/mail/.well-known/openid-configuration".to_string(), + "https://id.example.org/.well-known/oauth-authorization-server/realms/mail".to_string() + ] + ); + assert_eq!( + addresses("https://id.example.org/"), + [ + "https://id.example.org/.well-known/openid-configuration".to_string(), + "https://id.example.org/.well-known/oauth-authorization-server".to_string() + ] + ); +} + +#[test] +fn discovery_fetches_only_the_issuers_document_and_follows_redirects_it_may() { + let issuer_of = |port: u16| format!("http://127.0.0.1:{port}/realms/mail"); + let server = FakeHttp::start(move |n, request| { + let port = request.lines().find_map(|l| l.strip_prefix("Host: 127.0.0.1:")).and_then(|p| p.trim().parse().ok()).unwrap_or(0); + match n { + 0 => b"HTTP/1.1 302 Found\r\nLocation: /moved\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(), + _ => json_answer("200 OK", &keycloak(&issuer_of(port))), + } + }); + let found = discover(&issuer_of(server.port)).unwrap(); + assert_eq!(found.token, format!("{}/protocol/openid-connect/token", issuer_of(server.port))); + let first = server.request(0); + assert!(first.starts_with("GET /realms/mail/.well-known/openid-configuration HTTP/1.1"), "{first}"); + assert!(server.request(1).starts_with("GET /moved HTTP/1.1")); + // Nothing of the owner goes along: no address, no client id, no cookie. + for request in [first, server.request(1)] { + assert!(!request.to_ascii_lowercase().contains("cookie") && !request.contains('@') && !request.contains("client"), "{request}"); + } +} + +#[test] +fn the_second_standards_address_is_tried_when_the_first_has_nothing() { + let server = FakeHttp::start(move |n, request| match n { + 0 => json_answer("404 Not Found", "{}"), + _ => { + let port = request.lines().find_map(|l| l.strip_prefix("Host: 127.0.0.1:")).unwrap_or("0").trim().to_string(); + json_answer("200 OK", &keycloak(&format!("http://127.0.0.1:{port}/realms/mail"))) + } + }); + assert!(discover(&server.url("/realms/mail")).is_ok()); + assert!(server.request(1).starts_with("GET /.well-known/oauth-authorization-server/realms/mail HTTP/1.1")); +} + +#[test] +fn a_redirect_to_plain_http_elsewhere_or_round_and_round_is_not_followed() { + let away = + FakeHttp::answering(b"HTTP/1.1 301 Moved\r\nLocation: http://id.example.org/x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec()); + assert!(discover(&away.url("/realms/mail")).is_err()); + let round = FakeHttp::answering(b"HTTP/1.1 302 Found\r\nLocation: /again\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec()); + assert!(discover(&round.url("/realms/mail")).is_err()); + // Four for the first address and four for the second, no more. + assert!(round.asked() <= 8, "{}", round.asked()); +} + +#[test] +fn an_issuer_that_isnt_one_is_refused_before_anything_is_fetched() { + for issuer in ["", "http://id.example.org", "https://id.example.org/?x=1", "https://id.example.org/#f", "id.example.org"] { + assert!(matches!(discover(issuer), Err(NetError::Config(_))), "{issuer:?}"); + } +} + +proptest! { + #[test] + fn reading_any_bytes_never_panics(bytes in proptest::collection::vec(any::(), 0..4_000)) { + let _ = read(ISSUER, &bytes); + } + + #[test] + fn reading_any_json_never_panics(keys in proptest::collection::vec(("[a-z_]{1,30}", ".{0,60}"), 0..20)) { + let mut doc = serde_json::Map::new(); + doc.insert("issuer".into(), serde_json::json!(ISSUER)); + for (key, value) in keys { + doc.insert(key, serde_json::json!(value)); + } + let _ = read(ISSUER, serde_json::Value::Object(doc).to_string().as_bytes()); + } +} diff --git a/crates/net/src/send.rs b/crates/net/src/send.rs index 6ff92e4d50..7d0bfcdcfe 100644 --- a/crates/net/src/send.rs +++ b/crates/net/src/send.rs @@ -111,7 +111,13 @@ pub(crate) fn open_smtp_with<'a>( smtp = Smtp::resume(transport::upgrade(plain, &host)?); offered = smtp.hello(CLIENT_NAME)?; } - if account.oauth.is_some() { + if let Some(oauth) = account.oauth.as_ref().filter(|o| o.provider == mailcraft_model::OAuthProvider::Custom) { + // An own identity provider's token, the way the server and the settings say. + match crate::sync::token_mechanism(oauth.mechanism, offered.auth_oauthbearer, offered.auth_xoauth2)? { + mailcraft_model::SaslChoice::XOAuth2 => smtp.auth_xoauth2(user, secret)?, + _ => smtp.auth_oauthbearer(user, server.host.trim(), server.port, secret)?, + } + } else if account.oauth.is_some() { // A server that doesn't take tokens is an error, not a reason to go on unsigned. smtp.auth_xoauth2(user, secret)?; } else if !account.outgoing_without_sign_in && !user.is_empty() && !secret.is_empty() && (offered.auth_plain || offered.auth_login) { diff --git a/crates/net/src/sync.rs b/crates/net/src/sync.rs index 2feaa2f658..4286f12c16 100644 --- a/crates/net/src/sync.rs +++ b/crates/net/src/sync.rs @@ -22,7 +22,7 @@ use mailcraft_model::sync::{ FolderDelta, FolderState, GmailLabels, GmailSorted, MAX_GMAIL_MOVES, MAX_TRIES, RemoteFlags, RemoteOp, SyncPhase, SyncRequest, SyncResult, SyncStage, SyncStep, }; -use mailcraft_model::{Account, Body, FlagStatus, FolderKind, GmailCategory, Id, Message, OAuthProvider, Security, Server}; +use mailcraft_model::{Account, Body, FlagStatus, FolderKind, GmailCategory, Id, Message, OAuthProvider, SaslChoice, Security, Server}; use mailcraft_proto::ProtoError; use mailcraft_proto::imap::{Fetched, FolderStatus, Imap, Mailbox, uid_sets}; use mailcraft_time::{Date, DateTime, Timestamp}; @@ -542,14 +542,44 @@ pub(crate) fn open_imap_with<'a>( if imap.is_authenticated() { return Ok(imap); } - if account.oauth.is_some() { - imap.authenticate_xoauth2(user, secret)?; - } else { - imap.authenticate_password(user, secret)?; + match account.oauth.as_ref() { + Some(oauth) if oauth.provider == OAuthProvider::Custom => { + // What the server takes is known once it has said what it can do. + if !imap.offers_mechanism("OAUTHBEARER") && !imap.offers_mechanism("XOAUTH2") { + imap.capabilities()?; + } + let (bearer, xoauth2) = (imap.offers_mechanism("OAUTHBEARER"), imap.offers_mechanism("XOAUTH2")); + match token_mechanism(oauth.mechanism, bearer, xoauth2)? { + SaslChoice::XOAuth2 => imap.authenticate_xoauth2(user, secret)?, + _ => imap.authenticate_oauthbearer(user, server.host.trim(), server.port, secret)?, + } + } + Some(_) => imap.authenticate_xoauth2(user, secret)?, + None => imap.authenticate_password(user, secret)?, } Ok(imap) } +/// How a token from an own identity provider is given to a server that offers OAUTHBEARER +/// (`bearer`) and XOAUTH2 (`xoauth2`) as it does: the account's choice, when the server offers +/// it; by itself, OAUTHBEARER first. A server that offers neither (or not the one chosen) is +/// never shown the token. +pub(crate) fn token_mechanism(choice: SaslChoice, bearer: bool, xoauth2: bool) -> Result { + match (choice, bearer, xoauth2) { + (SaslChoice::OAuthBearer | SaslChoice::Auto, true, _) => Ok(SaslChoice::OAuthBearer), + (SaslChoice::XOAuth2 | SaslChoice::Auto, _, true) => Ok(SaslChoice::XOAuth2), + (SaslChoice::OAuthBearer, false, _) => Err(NetError::Proto(ProtoError::Auth(said!( + "the server doesn't take a token with OAUTHBEARER, which this account's OAuth settings ask for" + )))), + (SaslChoice::XOAuth2, _, false) => { + Err(NetError::Proto(ProtoError::Auth(said!("the server doesn't take a token with XOAUTH2, which this account's OAuth settings ask for")))) + } + (SaslChoice::Auto, false, false) => Err(NetError::Proto(ProtoError::Auth(said!( + "the server offers no way to sign in with an access token (neither OAUTHBEARER nor XOAUTH2)" + )))), + } +} + /// What Exchange calls, in English, the folders of a mailbox that are no folders of mail to /// keep: where it has appointments, people, tasks, notes and the journal, mail on its way out, /// and its reports on synchronising with Outlook. diff --git a/crates/ui-egui/src/account_setup/tests/google_oauth_first_tests.rs b/crates/ui-egui/src/account_setup/tests/google_oauth_first_tests.rs index beee6d77e3..52d7fdadca 100644 --- a/crates/ui-egui/src/account_setup/tests/google_oauth_first_tests.rs +++ b/crates/ui-egui/src/account_setup/tests/google_oauth_first_tests.rs @@ -235,7 +235,7 @@ fn google_desktop_requires_registration_and_keeps_password_as_default() { let seen: Log<(String, OAuthProvider, String, String, bool)> = Default::default(); let written = seen.clone(); app.services.sign_in = Some(Box::new(move |request: SignInRequest| { - written.lock().unwrap().push((request.email, request.oauth.provider, request.oauth.client_id, request.google_client_secret, request.graph)); + written.lock().unwrap().push((request.email, request.oauth.provider, request.oauth.client_id, request.client_secret, request.graph)); mpsc::channel().1 })); let mut wizard = AccountSetup::open(&app, &json!({"email": "one@gmail.com"})).unwrap(); diff --git a/crates/ui-egui/src/google_credential_security_tests.rs b/crates/ui-egui/src/google_credential_security_tests.rs index 88e1322000..5631ae247e 100644 --- a/crates/ui-egui/src/google_credential_security_tests.rs +++ b/crates/ui-egui/src/google_credential_security_tests.rs @@ -601,7 +601,7 @@ fn google_security_microsoft_command_skips_google_by_default() { assert_eq!(requests[0].account, microsoft); assert_eq!(requests[0].oauth.provider, mailcraft_model::OAuthProvider::Microsoft); assert!(requests[0].graph); - assert!(requests[0].google_client_secret.is_empty()); + assert!(requests[0].client_secret.is_empty()); } /// Reject Google's explicit id without asking the host or store, even while Google is signing in. @@ -682,7 +682,7 @@ fn google_security_microsoft_command_accepts_explicit_microsoft_accounts() { assert_eq!(requests[0].mail_write, graph_mail); assert!(!requests[0].quiet); assert!(requests[0].refresh.is_empty()); - assert!(requests[0].google_client_secret.is_empty()); + assert!(requests[0].client_secret.is_empty()); assert!(a.signing_in.as_ref().unwrap().browser); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c749f0ac..98f6b5718b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -815,9 +815,11 @@ pub struct SignInRequest { pub email: String, /// A refresh token from earlier in this session to try first; empty when there is none. pub refresh: String, - /// Google Desktop registration's installed-app secret for this one sign-in. Never stored - /// in a mailbox or passed to an IMAP/SMTP server; not an owner credential. - pub google_client_secret: String, + /// The client secret for this one sign-in: Google Desktop registration's installed-app + /// secret, or the one registered at an own identity provider (from the system's credential + /// store, or typed this session); empty for none. Sent to the provider's token address alone; + /// never stored in a mailbox or passed to an IMAP/SMTP server. + pub client_secret: String, /// Set when the owner gives up waiting, for the host to stop too. pub cancel: std::sync::Arc, /// Nobody asked for this (a Send/Receive that started by itself): renew with the refresh @@ -1705,6 +1707,9 @@ pub struct MailApp { /// What the credential store gave back for each key this session, read in the background /// ([`secret_read`]); only what was found. The window asks this, never the store. secret_cache: std::collections::HashMap, + /// The client secrets typed this session for accounts that sign in with an own identity + /// provider (0: the account being set up). Never saved; redacted from `Debug`. + pub(crate) client_secrets: std::collections::HashMap, /// The background read of the store under way, with the opening it was started for. secret_read: Option<(u64, std::sync::mpsc::Receiver)>, /// The opening, and whether remembering was on, when the store was last read by itself. @@ -2058,6 +2063,7 @@ impl MailApp { ews_certificate: Default::default(), secrets_opening: 0, secret_cache: Default::default(), + client_secrets: Default::default(), secret_read: None, secrets_asked: None, sync_after_secrets: Vec::new(), @@ -3250,8 +3256,8 @@ impl MailApp { && Self::secret_key("refresh", before) == Self::secret_key("refresh", after) && before.incoming.as_ref().map(|s| s.security) == after.incoming.as_ref().map(|s| s.security) && before.outgoing.as_ref().map(|s| s.security) == after.outgoing.as_ref().map(|s| s.security) - && before.oauth.as_ref().map(|o| (o.provider, o.client_id.as_str(), o.tenant.as_str())) - == after.oauth.as_ref().map(|o| (o.provider, o.client_id.as_str(), o.tenant.as_str())) + && before.oauth.as_ref().map(|o| (o.provider, o.client_id.as_str(), o.tenant.as_str(), o.binding())) + == after.oauth.as_ref().map(|o| (o.provider, o.client_id.as_str(), o.tenant.as_str(), o.binding())) } /// Stop only this account's pending sign-in and remove its waiting text. @@ -3454,7 +3460,7 @@ impl MailApp { /// account `account` of this mailbox, with the servers it has now: that account's own, never /// one found by its address (another may have it too, with other servers, AU3-03). fn remembered(&self, kind: &str, account: Id) -> Option { - if !matches!(kind, "password" | "refresh") || !self.ui.remember_sign_in || self.unconfirmed { + if !matches!(kind, "password" | "refresh" | mailcraft_host::secrets::OAUTH_CLIENT) || !self.ui.remember_sign_in || self.unconfirmed { return None; } let a = self.session.mailbox.account(account)?; @@ -3501,7 +3507,7 @@ impl MailApp { pub(crate) fn forget_every_secret(&mut self) -> Vec { let mut keys: Vec = std::mem::take(&mut self.ui.remembered_keys); for a in &self.session.mailbox.accounts { - for kind in ["password", "refresh"] { + for kind in ["password", "refresh", mailcraft_host::secrets::OAUTH_CLIENT] { keys.extend(Self::secret_keys_of(kind, a)); } keys.extend(Self::dav_secret_keys(a)); @@ -3558,7 +3564,8 @@ impl MailApp { let Some(store) = &self.services.secrets else { return }; let mut gone = Vec::new(); let dav = if with_dav { Self::dav_secret_keys(a) } else { Vec::new() }; - let named = ["password", "refresh"].into_iter().flat_map(|kind| Self::secret_keys_of(kind, a)).chain(dav); + let named = + ["password", "refresh", mailcraft_host::secrets::OAUTH_CLIENT].into_iter().flat_map(|kind| Self::secret_keys_of(kind, a)).chain(dav); for key in named { store.delete(&key); if store.get(&key).is_none() { @@ -3609,6 +3616,42 @@ impl MailApp { ) } + /// The client secret of `account` (0 for the one being set up), an account that signs in with + /// an own identity provider: typed this session, else what the credential store gave back; + /// empty for none. + pub(crate) fn client_secret_of(&self, account: Id) -> String { + if let Some(typed) = self.client_secrets.get(&account) { + return typed.clone(); + } + let Some(a) = self.session.mailbox.account(account).filter(|a| a.oauth.as_ref().is_some_and(|o| o.has_secret)) else { return String::new() }; + self.secret_cache.get(&Self::secret_key(mailcraft_host::secrets::OAUTH_CLIENT, a)).cloned().unwrap_or_default() + } + + /// Keep the client secret the owner typed for `account` (0 for the one being set up): in + /// memory for the session, and in the credential store when sign-ins are remembered. An empty + /// one forgets it. + pub(crate) fn set_client_secret(&mut self, account: Id, secret: &str) { + if secret.is_empty() { + self.client_secrets.remove(&account); + if let Some(a) = self.session.mailbox.account(account).cloned() { + let keys = Self::secret_keys_of(mailcraft_host::secrets::OAUTH_CLIENT, &a); + for key in &keys { + self.secret_cache.remove(key); + } + if let Some(store) = &self.services.secrets { + for key in keys { + store.delete(&key); + } + } + } + return; + } + self.client_secrets.insert(account, secret.to_string()); + if account != 0 { + self.remember(mailcraft_host::secrets::OAUTH_CLIENT, account, secret); + } + } + /// The host's Desktop registration value. UI preferences never supply or retain it. pub(crate) fn google_client_secret(&self) -> &str { &self.services.google_client_secret @@ -3652,14 +3695,17 @@ impl MailApp { let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let browser = refresh.is_empty(); let waiting = if browser { tl!("Sign in on the page that opened in your browser…") } else { tl!("Renewing the sign-in…") }; - let google_client_secret = - if oauth.provider == mailcraft_model::OAuthProvider::Google { self.google_client_secret().to_string() } else { String::new() }; + let client_secret = match oauth.provider { + mailcraft_model::OAuthProvider::Google => self.google_client_secret().to_string(), + mailcraft_model::OAuthProvider::Custom => self.client_secret_of(account), + mailcraft_model::OAuthProvider::Microsoft => String::new(), + }; let request = SignInRequest { account, oauth: self.effective_oauth(oauth), email: email.to_string(), refresh, - google_client_secret, + client_secret, cancel: cancel.clone(), quiet, graph, @@ -3706,6 +3752,10 @@ impl MailApp { if self.signed_in_as_other(account, &tokens) { return; } + // The client secret typed while it was set up is the account's now. + if let Some(secret) = self.client_secrets.remove(&0) { + self.set_client_secret(account, &secret); + } self.remember("refresh", account, &tokens.refresh); self.note_directory(account, &tokens.tenant); self.tokens.insert(account, tokens); diff --git a/crates/ui-egui/src/secret_read.rs b/crates/ui-egui/src/secret_read.rs index 2ba5555a6b..d47b41d1d7 100644 --- a/crates/ui-egui/src/secret_read.rs +++ b/crates/ui-egui/src/secret_read.rs @@ -94,6 +94,14 @@ impl MailApp { }) }) .collect(); + // The client secret of an account that signs in with an own identity provider and has one. + let clients = self + .session + .mailbox + .accounts + .iter() + .filter(|a| a.oauth.as_ref().is_some_and(|o| o.has_secret && o.provider == mailcraft_model::OAuthProvider::Custom)); + asks.extend(clients.map(|a| Ask { key: Self::secret_key(mailcraft_host::secrets::OAUTH_CLIENT, a), old: None })); // The addresses of the calendars subscribed to, which may hold a secret (#209): kept like a password. let subscribed = self .session diff --git a/crates/ui-egui/src/secrets_binding_tests.rs b/crates/ui-egui/src/secrets_binding_tests.rs index f48fba9e39..60d20be213 100644 --- a/crates/ui-egui/src/secrets_binding_tests.rs +++ b/crates/ui-egui/src/secrets_binding_tests.rs @@ -353,7 +353,9 @@ fn the_secret_cache_and_the_old_names_are_used_only_where_they_are_listed() { let allowed: &[(&str, &str, usize)] = &[ ("lib.rs", "legacy_secret_key(", 2), ("secret_read.rs", "legacy_secret_key(", 1), - ("lib.rs", "secret_cache.get(", 2), + // (And the client secret of an account with its own identity provider, read where a + // sign-in is handed to the host: `client_secret_of`.) + ("lib.rs", "secret_cache.get(", 3), ("secret_read.rs", "secret_cache.contains_key(", 2), // A subscribed calendar's address is kept like a password (#209): found again by the name // that holds its host (`subscribed_address`), and moved into memory for the session when From f247826ecce9ed019a4fbb7174ca097790d6ff83 Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 09:23:16 +0100 Subject: [PATCH 04/25] GO6, GO8, GO9: own identity provider: commands, OAuth settings, autoconfig hint Commands (GO8): account.add and account.edit take an own identity provider's settings (issuer, sign-in, token and revocation addresses, extra scopes, mechanism, redirect port, whether a client secret is kept), checked with OAuth::check; an IMAP account only. Microsoft's and Google's built-in addresses, scopes and mechanism are changed only by setting the account up for an own provider (`asCustom`), starting from the values it had. A client secret or a token is never a parameter. account.oauthDefaults answers a provider's built-in values; account.oauthRestoreDefaults puts an account's back. The agent gate names where an edited account signs in when that changes. OAuth settings (GO9): Add Account offers signing in with an own identity provider for a domain nobody here knows the sign-in of, and Account Settings shows every value a sign-in uses: Microsoft's and Google's built in, with the client id and tenant editable and the choice, after a question, to use an own provider instead; an own provider's values typed or found with Discover (only the issuer goes out), addresses outside its domain agreed to first, its client secret masked, kept in the credential store and replaceable or forgettable, and the servers the sign-in is sent to shown. Autoconfig (GO6): an incoming server a domain's autoconfig document says signs in with OAuth2, and the issuer it names, are offered to the owner (account.preset `oauthIssuer`); nothing signs in by itself. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- apps/mailcraft/src/main.rs | 14 + crates/engine/src/account_oauth_tests.rs | 159 ++++++++ crates/engine/src/agent.rs | 22 +- crates/engine/src/agent/bind.rs | 1 + crates/engine/src/cmd/account.rs | 213 +++++++++- crates/engine/src/lib.rs | 2 + crates/i18n/po/cs.po | 253 +++++++++++- crates/i18n/po/de.po | 253 +++++++++++- crates/i18n/po/es.po | 253 +++++++++++- crates/i18n/po/fr.po | 253 +++++++++++- crates/i18n/po/hu.po | 253 +++++++++++- crates/i18n/po/it.po | 253 +++++++++++- crates/i18n/po/ka.po | 253 +++++++++++- crates/i18n/po/messages.pot | 253 +++++++++++- crates/i18n/po/nl.po | 253 +++++++++++- crates/i18n/po/pl.po | 253 +++++++++++- crates/i18n/po/ro.po | 253 +++++++++++- crates/i18n/po/zh_CN.po | 253 +++++++++++- crates/model/src/provider.rs | 3 + crates/net/src/autoconfig.rs | 51 ++- crates/net/src/autoconfig_tests.rs | 44 +++ crates/net/src/discover.rs | 1 + crates/ui-egui/src/account_setup.rs | 99 ++++- .../src/account_setup/oauth_settings.rs | 368 ++++++++++++++++++ .../src/account_setup/tests/autodiscover.rs | 1 + .../src/account_setup/tests/found_servers.rs | 6 + .../src/account_setup/tests/own_provider.rs | 223 +++++++++++ .../ui-egui/src/agent_gate_binding_tests.rs | 1 + crates/ui-egui/src/lib.rs | 17 + 29 files changed, 4194 insertions(+), 67 deletions(-) create mode 100644 crates/engine/src/account_oauth_tests.rs create mode 100644 crates/ui-egui/src/account_setup/oauth_settings.rs create mode 100644 crates/ui-egui/src/account_setup/tests/own_provider.rs diff --git a/apps/mailcraft/src/main.rs b/apps/mailcraft/src/main.rs index 141e902959..0739178efb 100644 --- a/apps/mailcraft/src/main.rs +++ b/apps/mailcraft/src/main.rs @@ -1123,6 +1123,7 @@ fn services( let pst_ctx = ctx.clone(); let alert_ctx = ctx.clone(); let autodiscover_ctx = ctx.clone(); + let oauth_discover_ctx = ctx.clone(); let (keys_ctx, keys_store) = (ctx.clone(), secrets::store()); let attachment_preview = attachment_render::service(&ctx); let (sync_ctx, sign_in_ctx, graph_ctx, mx_ctx, test_ctx) = (ctx.clone(), ctx.clone(), ctx.clone(), ctx.clone(), ctx); @@ -1246,6 +1247,19 @@ fn services( discover: Some(Box::new(move |domain| { background(&mx_ctx, "server discovery", move || mailcraft_net::discover(&domain).map_err(|e| e.to_string())) })), + oauth_discover: Some(Box::new(move |issuer: String| { + background(&oauth_discover_ctx, "identity provider discovery", move || { + mailcraft_net::oauth::discovery::discover(&issuer) + .map(|found| mailcraft_ui_egui::OAuthFound { + no_refresh: found.lacks_offline_access(), + authorize: found.authorize, + token: found.token, + revoke: found.revoke, + outside: found.outside, + }) + .map_err(|e| e.to_string()) + }) + })), lookup_autodiscover: Some(Box::new(move |domain| { background(&autodiscover_ctx, "autodiscover records", move || mailcraft_net::autodiscover_hosts(&domain).map_err(|e| e.to_string())) })), diff --git a/crates/engine/src/account_oauth_tests.rs b/crates/engine/src/account_oauth_tests.rs new file mode 100644 index 0000000000..7e958202a8 --- /dev/null +++ b/crates/engine/src/account_oauth_tests.rs @@ -0,0 +1,159 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An account that signs in with an own identity provider, through the account commands: what is +//! taken, what is refused, and that Microsoft's and Google's built-in values stay theirs. + +use mailcraft_model::{OAuthProvider, SaslChoice}; +use serde_json::{Value, json}; + +use crate::Session; + +const ISSUER: &str = "https://id.example.org/realms/mail"; + +fn own(extra: Value) -> Value { + let mut v = json!({ + "email": "alice@example.org", + "username": "alice", + "incoming": {"host": "mail.example.org", "port": 993}, + "outgoing": {"host": "mail.example.org", "port": 465}, + "auth": "oauth2", + "provider": "custom", + "clientId": "mailcraft", + "issuer": ISSUER, + "authorizeUrl": format!("{ISSUER}/protocol/openid-connect/auth"), + "tokenUrl": format!("{ISSUER}/protocol/openid-connect/token"), + }); + if let (Some(v), Value::Object(extra)) = (v.as_object_mut(), extra) { + v.extend(extra); + } + v +} + +fn add(s: &mut Session, v: &Value) -> u64 { + s.run("account.add", v).unwrap()["id"].as_u64().unwrap() +} + +#[test] +fn an_imap_account_is_set_up_with_its_own_identity_provider() { + let mut s = Session::empty(); + let id = add(&mut s, &own(json!({"scopes": "mail", "mechanism": "oauthbearer", "redirectPort": 53682}))); + let a = s.mailbox.account(id).unwrap(); + let oauth = a.oauth.as_ref().unwrap(); + assert_eq!((oauth.provider, oauth.client_id.as_str(), oauth.issuer.as_str()), (OAuthProvider::Custom, "mailcraft", ISSUER)); + assert_eq!((oauth.mechanism, oauth.redirect_port, oauth.scopes.as_str()), (SaslChoice::OAuthBearer, Some(53_682), "mail")); + assert!(oauth.ready().is_ok()); + // account.list says how it signs in, and nothing secret. + let listed = s.run("account.list", &json!({})).unwrap(); + let shown = listed.to_string(); + assert!(shown.contains("\"provider\":\"custom\"") && shown.contains(ISSUER), "{shown}"); + assert!(!shown.to_ascii_lowercase().contains("secret\":\""), "{shown}"); +} + +#[test] +fn what_cant_be_used_is_refused() { + let mut s = Session::empty(); + for extra in [ + json!({"clientId": ""}), + json!({"tokenUrl": "http://id.example.org/token"}), + json!({"authorizeUrl": "https://user:pw@id.example.org/auth"}), + json!({"issuer": "https://id.example.org/?x"}), + json!({"scopes": "a\"b"}), + json!({"mechanism": "plain"}), + json!({"mechanism": 3}), + json!({"redirectPort": 0}), + json!({"redirectPort": 70000}), + json!({"tokenUrl": 5}), + json!({"clientSecret": "s3cret"}), + ] { + let error = s.run("account.add", &own(extra.clone())).unwrap_err().to_string(); + assert!(!error.contains("s3cret"), "{error}"); + assert!(s.mailbox.accounts.iter().all(|a| !a.signs_in_with_own_provider()), "{extra}"); + } + // Only an account with IMAP and SMTP servers. + let no_servers = own(json!({"incoming": null, "outgoing": null})); + assert!(s.run("account.add", &no_servers).is_err()); + // (A JMAP account has no such sign-in: the settings go with the servers.) + let jmap = own(json!({"kind": "jmap", "jmap": {"session": "https://jmap.example.org/session"}})); + let id = add(&mut s, &jmap); + assert!(s.mailbox.account(id).unwrap().oauth.is_none()); +} + +#[test] +fn microsofts_and_googles_built_in_values_are_changed_only_by_becoming_an_own_provider() { + let mut s = Session::empty(); + let google = json!({"email": "ada@gmail.example", "incoming": {"host": "imap.gmail.com"}, "outgoing": {"host": "smtp.gmail.com"}, "auth": "oauth2", "provider": "google"}); + let id = add(&mut s, &google); + // An address of its own is refused as it is… + let error = s.run("account.edit", &json!({"id": id, "tokenUrl": "https://id.example.org/token"})).unwrap_err().to_string(); + assert!(error.contains("asCustom"), "{error}"); + assert_eq!(s.mailbox.account(id).unwrap().oauth.as_ref().unwrap().provider, OAuthProvider::Google); + // …and taken when it is to be an own provider, from the values it had. + s.run("account.edit", &json!({"id": id, "asCustom": true, "clientId": "mine", "tokenUrl": "https://id.example.org/token"})).unwrap(); + let oauth = s.mailbox.account(id).unwrap().oauth.clone().unwrap(); + assert_eq!(oauth.provider, OAuthProvider::Custom); + assert_eq!((oauth.token.as_str(), oauth.authorize.as_str()), ("https://id.example.org/token", "https://accounts.google.com/o/oauth2/v2/auth")); + assert!(oauth.effective().scopes.contains("https://mail.google.com/")); + // Its client id and redirect port can change as they are. + let id2 = + add(&mut s, &json!({"email": "noor@example.org", "incoming": {"host": "outlook.office365.com"}, "auth": "oauth2", "provider": "microsoft"})); + s.run("account.edit", &json!({"id": id2, "clientId": "my-app", "redirectPort": 8400})).unwrap(); + let ms = s.mailbox.account(id2).unwrap().oauth.clone().unwrap(); + assert_eq!((ms.provider, ms.client_id.as_str(), ms.redirect_port), (OAuthProvider::Microsoft, "my-app", Some(8_400))); +} + +#[test] +fn going_back_to_microsoft_or_google_takes_the_own_providers_addresses_away() { + let mut s = Session::empty(); + let id = add(&mut s, &own(json!({"scopes": "mail"}))); + s.run("account.edit", &json!({"id": id, "provider": "google"})).unwrap(); + let oauth = s.mailbox.account(id).unwrap().oauth.clone().unwrap(); + assert_eq!((oauth.provider, oauth.issuer.as_str(), oauth.token.as_str(), oauth.scopes.as_str()), (OAuthProvider::Google, "", "", "")); +} + +#[test] +fn the_built_in_values_of_each_provider_are_shown_and_restored() { + let mut s = Session::empty(); + let ms = s.run("account.oauthDefaults", &json!({"provider": "microsoft", "tenant": "organizations"})).unwrap(); + assert_eq!(ms["tokenUrl"], "https://login.microsoftonline.com/organizations/oauth2/v2.0/token"); + assert_eq!((ms["mechanism"].as_str(), ms["builtInClient"].as_bool()), (Some("xoauth2"), Some(true))); + assert!(ms["hosts"].as_array().unwrap().iter().any(|h| h == "outlook.office365.com")); + let google = s.run("account.oauthDefaults", &json!({"provider": "google"})).unwrap(); + assert_eq!(google["revokeUrl"], "https://oauth2.googleapis.com/revoke"); + let custom = s.run("account.oauthDefaults", &json!({"provider": "custom"})).unwrap(); + assert_eq!( + (custom["scopes"].as_str(), custom["tokenUrl"].as_str(), custom["mechanism"].as_str()), + (Some("openid email offline_access"), Some(""), Some("auto")) + ); + assert!(s.run("account.oauthDefaults", &json!({"provider": "carrier"})).is_err()); + + let id = add(&mut s, &own(json!({"scopes": "mail", "mechanism": "xoauth2", "redirectPort": 9000}))); + let back = s.run("account.oauthRestoreDefaults", &json!({"id": id})).unwrap(); + assert_eq!(back["oauth"]["provider"], "custom"); + let oauth = s.mailbox.account(id).unwrap().oauth.clone().unwrap(); + assert_eq!((oauth.scopes.as_str(), oauth.mechanism, oauth.redirect_port, oauth.client_id.as_str()), ("", SaslChoice::Auto, None, "mailcraft")); + let local = add(&mut s, &json!({"email": "local@example.org"})); + assert!(s.run("account.oauthRestoreDefaults", &json!({"id": local})).is_err()); +} + +#[test] +fn preset_can_be_asked_for_an_own_provider() { + let mut s = Session::empty(); + let preset = s.run("account.preset", &json!({"email": "alice@example.org", "provider": "custom"})).unwrap(); + assert_eq!((preset["auth"].as_str(), preset["provider"].as_str()), (Some("oauth2"), Some("custom"))); +} + +#[test] +fn an_identity_provider_a_domains_document_names_is_offered_never_taken_by_itself() { + let mut s = Session::empty(); + let found = |issuer: &str| json!({"email": "alice@unknown-domain.example", "found": {"incoming": {"host": "mail.unknown-domain.example", "security": "tls", "via": "autoconfig"}, "oauthIssuer": issuer}}); + let preset = s.run("account.preset", &found("https://id.unknown-domain.example/realms/mail")).unwrap(); + assert_eq!(preset["oauthIssuer"], "https://id.unknown-domain.example/realms/mail"); + // Offered, not set up: the sign-in stays a password until the owner says otherwise. + assert_eq!(preset["auth"], "password"); + for bad in ["http://id.example.org", "javascript:x", "https://id.example.org/?q", "https://u:p@id.example.org"] { + assert_eq!(s.run("account.preset", &found(bad)).unwrap()["oauthIssuer"], Value::Null, "{bad}"); + } + // A provider this program knows has its own sign-in: nothing is offered for it. + let gmail = json!({"email": "ada@gmail.com", "found": {"oauthIssuer": "https://id.example.org"}}); + assert_eq!(s.run("account.preset", &gmail).unwrap()["oauthIssuer"], Value::Null); +} diff --git a/crates/engine/src/agent.rs b/crates/engine/src/agent.rs index b298b88030..55c5315a39 100644 --- a/crates/engine/src/agent.rs +++ b/crates/engine/src/agent.rs @@ -413,6 +413,8 @@ const SAFE: &[&str] = &[ "account.senderAddresses", "account.offlineSize", "account.preset", + // The values built in for a provider's sign-in: read only, never a secret. + "account.oauthDefaults", // What Send/Receive is doing, or did: read only. "sync.progress", // Calls off the run under way; nothing is sent or lost by it. @@ -519,6 +521,8 @@ const ACCOUNTS: &[&str] = &[ "account.remove", // An Exchange server account stops trusting the certificate its owner chose to trust (#252). "account.forgetEwsCertificate", + // An account's sign-in settings back to what is built in: where it signs in is the owner's. + "account.oauthRestoreDefaults", // Who the owner's mail can say it is from (#797). "account.setSenderAddresses", // Calendar and contacts servers (#209): choosing where an account's calendars and contacts @@ -3536,13 +3540,29 @@ fn what_it_does(s: &Session, id: &str, params: &Value) -> String { }; // The tick of a relay that takes mail without a sign-in (#836) is named: it decides // whether the password is shown to the outgoing server. - match new.map(|new| new.outgoing_without_sign_in) { + match new.as_ref().map(|new| new.outgoing_without_sign_in) { Some(true) if !account.outgoing_without_sign_in => { text.push_str("; the outgoing server needs no sign-in (the password is never sent to it)"); } Some(false) if account.outgoing_without_sign_in => text.push_str("; MailCraft signs in to the outgoing server again"), _ => {} } + // Where it signs in is named when that changes: that is where the owner's sign-in goes. + let signs_in_at = |a: &mailcraft_model::Account| { + a.oauth.as_ref().map(|o| { + let used = o.effective(); + (o.provider, clip(&used.authorize, 120), clip(&used.token, 120), clip(&used.client_id, 80)) + }) + }; + if let Some(now) = new.as_ref().map(signs_in_at).filter(|now| *now != signs_in_at(account)) { + match now { + Some((mailcraft_model::OAuthProvider::Custom, page, token, _)) => { + text.push_str(&format!("; it signs in with its own identity provider, on the page {page}, with tokens from {token}")); + } + Some((provider, ..)) => text.push_str(&format!("; it signs in with {}", provider.label())), + None => text.push_str("; it signs in with a password"), + } + } text.push_str(&rules); text.push_str(&reads); return text; diff --git a/crates/engine/src/agent/bind.rs b/crates/engine/src/agent/bind.rs index 60f483ce11..88368181d2 100644 --- a/crates/engine/src/agent/bind.rs +++ b/crates/engine/src/agent/bind.rs @@ -116,6 +116,7 @@ pub fn object(id: &str) -> Option { | "account.edit" | "account.remove" | "account.forgetEwsCertificate" + | "account.oauthRestoreDefaults" | "account.davSet" | "account.davOff" | "account.graphSwitch" diff --git a/crates/engine/src/cmd/account.rs b/crates/engine/src/cmd/account.rs index eac696d155..e4664f58aa 100644 --- a/crates/engine/src/cmd/account.rs +++ b/crates/engine/src/cmd/account.rs @@ -16,7 +16,7 @@ use mailcraft_model::sync::{ }; use mailcraft_model::{ Account, AccountKind, Directory, EwsServer, FlagStatus, Folder, FolderKind, Id, JmapServer, MailIdentity, Mailbox, Message, OAuth, OAuthProvider, - Pending, Queued, Rgb, Security, Server, clean_name, + Pending, Queued, Rgb, SaslChoice, Security, Server, clean_name, }; use serde_json::{Value, json}; @@ -33,9 +33,14 @@ pub fn specs() -> Vec { CommandSpec::new("account.remove", "Remove Account", "File › Info", remove).params(r#"{"id": number} — removes the account, its mail and what is kept for it on this computer (bodies and attachments leave the content folder once a state without it is saved; no Undo step is kept), and what came from its server: its events, contacts, to-dos and calendars (what was made here and not sent yet stays, as this computer's own), Outlook's list of categories, its rules (those its server keeps stay there; those for every account stay here), and, where the window's settings are kept (the window, not mailcraft-cli), its mailbox's working hours; nothing on the server is touched. Mail moved into it from elsewhere that its server wasn't given yet goes back to where it came from, and so does mail moved into it whose original another server keeps until the copy is safe; once the copy is safe on its server, that original goes as it would have (mail moved onto this computer goes back to its original, as its copy goes with the account). The only account leaves an empty mailbox, as at a first start. Answers {"deleted": id, "leftToSweep": n (content files the sweep removes later)}"#), CommandSpec::new("account.move", "Move Account", "Folder Pane", move_account).params(r#"{"id": number, "before"?: number | null} — puts the account in another place in the folder pane, as dragging its name there does (#702): right before the account `before` names, or last without one. The shared mailboxes opened through it move with it; a shared mailbox can't be moved by itself, nor named as `before`. The order is kept in the mailbox and followed by the folder pane, File › Info, the From list of a new message, the list of calendars, Junk E-mail Options, Signatures, Rules and Alerts, the accounts of Tasks, account.list, folder.list, file.account and file.info (Send/Receive keeps the order the accounts were added in); the default account, which new mail is written from, stays the one it was. Answers {"moved": bool, "order": [id] (the accounts as the folder pane lists them, shared mailboxes included)}"#), CommandSpec::new("account.list", "List Accounts", "File › Info", list).pure(), + CommandSpec::new("account.oauthDefaults", "OAuth Built-in Settings", "File › Info", oauth_defaults) + .pure() + .params(r#"{"provider": "microsoft"|"google"|"custom", "tenant"?: string} — the values a sign-in with that provider uses when an account says nothing else: its identity provider (issuer), sign-in, token and revocation addresses, scopes, SASL mechanism, whether the client id is the build's own, and the mail servers its token is for (none for custom: an own provider's token goes to the account's own servers). For the OAuth Settings dialog and agents. Never a secret. Changes nothing. Answers {"provider", "issuer", "authorizeUrl", "tokenUrl", "revokeUrl", "scopes", "mechanism", "builtInClient", "hosts"}"#), + CommandSpec::new("account.oauthRestoreDefaults", "Restore Default OAuth Settings", "File › Info", oauth_restore_defaults) + .params(r#"{"id": number} — an account that signs in on its provider's page goes back to the values built in: a Microsoft or Google account to the build's client id and any free redirect port (its tenant stays); an account with its own identity provider to no extra scopes, the mechanism chosen by what the server offers and any free redirect port (its addresses and client id stay). Answers {"id": id, "oauth": the settings}"#), CommandSpec::new("account.preset", "Suggest Account Settings", "File › Info", preset) .pure() - .params(r#"{"email": string, "provider"?: "microsoft"|"google", "service"?: "microsoft365"|"outlook.com"|"google"|"yahoo"|"icloud"|"fastmail"|"aol"|"zoho", "mx"?: [string] (the domain's mail exchangers, when the host looked them up), "found"?: {"incoming"?: {"host": string, "port"?: number, "security": "tls"|"starttls", "via": "srv"|"autoconfig"|"ispdb"}, "outgoing"?: same, "username"?: string (the found incoming server's, as its source wrote it: %EMAILADDRESS%, %EMAILLOCALPART% or %EMAILDOMAIN% stand for the address or its parts; taken only with an incoming server found by autoconfig or ispdb)} (what the host found for the domain: its SRV records (RFC 6186, #1063), the autoconfig document it publishes, or Mozilla's ISP database (#1112); taken only when the domain and its exchangers name no provider this program knows, and a server without encryption is never taken)} — answers the servers and sign-in an address usually takes, with `via` saying where they came from (domain, mx, asked, srv, autoconfig, ispdb, or guess), `known` whether they are a provider's own, and `outside` on a server that was found and isn't in the address's own domain (the owner is asked before a password goes there, #1063, #1112); what is found or guessed is for the owner to confirm; changes nothing"#), + .params(r#"{"email": string, "provider"?: "microsoft"|"google", "service"?: "microsoft365"|"outlook.com"|"google"|"yahoo"|"icloud"|"fastmail"|"aol"|"zoho", "mx"?: [string] (the domain's mail exchangers, when the host looked them up), "found"?: {"incoming"?: {"host": string, "port"?: number, "security": "tls"|"starttls", "via": "srv"|"autoconfig"|"ispdb"}, "outgoing"?: same, "username"?: string (the found incoming server's, as its source wrote it: %EMAILADDRESS%, %EMAILLOCALPART% or %EMAILDOMAIN% stand for the address or its parts; taken only with an incoming server found by autoconfig or ispdb), "oauthIssuer"?: string (the identity provider the found incoming server's document names for an OAuth 2.0 sign-in: answered back as `oauthIssuer` for the owner to confirm, never signed in with by itself)} (what the host found for the domain: its SRV records (RFC 6186, #1063), the autoconfig document it publishes, or Mozilla's ISP database (#1112); taken only when the domain and its exchangers name no provider this program knows, and a server without encryption is never taken)} — answers the servers and sign-in an address usually takes, with `via` saying where they came from (domain, mx, asked, srv, autoconfig, ispdb, or guess), `known` whether they are a provider's own, and `outside` on a server that was found and isn't in the address's own domain (the owner is asked before a password goes there, #1063, #1112); what is found or guessed is for the owner to confirm; changes nothing"#), CommandSpec::new("sync.request", "Send/Receive All Folders", "Send / Receive", request) .pure() .key("F9") @@ -48,7 +53,7 @@ pub fn specs() -> Vec { ] } -const ACCOUNT: &str = r##"{"email": string, "displayName"?: string, "name"?: string (what the folder pane calls the account; empty: its address), "username"?: string, "incoming"?: {"host": string, "port"?: number, "security"?: "tls"|"starttls"|"none"} | null, "outgoing"?: same | null, "outgoingWithoutSignIn"?: bool (the outgoing server takes mail without a sign-in, a relay: it is never shown the password; not for an account that signs in on the provider's page), "auth"?: "password"|"oauth2" (oauth2: sign in on the provider's page), "provider"?: "microsoft"|"google", "clientId"?: string, "tenant"?: string, "directory"?: "organisation"|"personal" (which kind of Microsoft account signs in, when the sign-in said), "kind"?: "imap"|"local"|"microsoft"|"jmap"|"exchange" (microsoft: kept in step through Microsoft Graph, no mail servers; jmap: kept in step over JMAP, no mail servers; exchange: an Exchange server account, kept in step through Exchange Web Services, no mail servers), "ews"?: {"url": string (the https:// address of the server's Exchange Web Services, `…/EWS/Exchange.asmx`), "username"?: string (DOMAIN\user or a UPN; default the e-mail address), "trusted"?: string (the SHA-256 fingerprint of the one certificate trusted for this account besides the system's)} (an Exchange server account's server; the password is never a setting), "jmap"?: {"session": string (the https:// address of the server's JMAP session resource), "bearer"?: bool (the secret is a bearer token, not the account's password)} (a JMAP account's server; the secret is never a setting), "color"?: "#RRGGBB" | null (the account's colour: a dot by its name in the folder pane and a stripe on its mail in a list of more than one account's; a new account is given one of the palette's that no other has unless this says, null for none)}"##; +const ACCOUNT: &str = r##"{"email": string, "displayName"?: string, "name"?: string (what the folder pane calls the account; empty: its address), "username"?: string, "incoming"?: {"host": string, "port"?: number, "security"?: "tls"|"starttls"|"none"} | null, "outgoing"?: same | null, "outgoingWithoutSignIn"?: bool (the outgoing server takes mail without a sign-in, a relay: it is never shown the password; not for an account that signs in on the provider's page), "auth"?: "password"|"oauth2" (oauth2: sign in on the provider's page), "provider"?: "microsoft"|"google"|"custom" (custom: the owner's own identity provider, an OpenID Connect or OAuth 2.0 server in front of their own IMAP and SMTP servers; an IMAP account only), "clientId"?: string (required for custom: the client registered there for MailCraft), "tenant"?: string, "issuer"?: string|null (custom: the identity provider's https:// address, from which its sign-in addresses are found), "authorizeUrl"?: string|null, "tokenUrl"?: string|null, "revokeUrl"?: string|null (custom: its sign-in, token and revocation addresses, https:// ones, as found from the issuer or typed), "scopes"?: string|null (custom: what the tokens are asked for besides openid email offline_access, separated by spaces), "mechanism"?: "auto"|"oauthbearer"|"xoauth2" (custom: how the mail servers are given the token; auto: OAUTHBEARER when the server offers it, else XOAUTH2), "redirectPort"?: number|null (the port on this computer the provider's page sends the owner back to; null: any free one), "hasSecret"?: bool (custom: whether a client secret for it is kept in the system's credential store; the window sets it with the secret), "asCustom"?: bool (with an address, scopes or a mechanism for a Microsoft or Google account: set it up for an own identity provider instead, starting from the values it had; without it such a change is refused), — a client secret is never a parameter, nor is any token: they are kept in the system's credential store, "directory"?: "organisation"|"personal" (which kind of Microsoft account signs in, when the sign-in said), "kind"?: "imap"|"local"|"microsoft"|"jmap"|"exchange" (microsoft: kept in step through Microsoft Graph, no mail servers; jmap: kept in step over JMAP, no mail servers; exchange: an Exchange server account, kept in step through Exchange Web Services, no mail servers), "ews"?: {"url": string (the https:// address of the server's Exchange Web Services, `…/EWS/Exchange.asmx`), "username"?: string (DOMAIN\user or a UPN; default the e-mail address), "trusted"?: string (the SHA-256 fingerprint of the one certificate trusted for this account besides the system's)} (an Exchange server account's server; the password is never a setting), "jmap"?: {"session": string (the https:// address of the server's JMAP session resource), "bearer"?: bool (the secret is a bearer token, not the account's password)} (a JMAP account's server; the secret is never a setting), "color"?: "#RRGGBB" | null (the account's colour: a dot by its name in the folder pane and a stripe on its mail in a list of more than one account's; a new account is given one of the palette's that no other has unless this says, null for none)}"##; fn has_server(s: &Session) -> Option<&'static str> { if s.mailbox.accounts.iter().any(|a| a.kind.has_server()) { @@ -103,18 +108,38 @@ fn sign_in(a: &mut Account, v: &Value) -> Result<(), CmdError> { } Some(_) => return Err(bad("`auth` is password or oauth2")), } + // A secret is never a setting: it is kept in the system's credential store, set in the window. + if v.get("clientSecret").is_some() { + return Err(bad( + "the client secret is never a parameter: it is entered in the window's OAuth Settings and kept in the system's credential store", + )); + } let provider = match p::str(v, "provider") { - // (An own identity provider is set up with its own fields, which this doesn't take yet.) - Some(name) => { - Some(OAuthProvider::parse(name).filter(|p| *p != OAuthProvider::Custom).ok_or_else(|| bad("`provider` is microsoft or google"))?) - } + Some(name) => Some(OAuthProvider::parse(name).ok_or_else(|| bad("`provider` is microsoft, google or custom"))?), None => None, }; let (client_id, tenant) = (word("clientId", 200)?, word("tenant", 64)?); let directory = directory_of(v)?; + let own = own_provider_fields(v)?; + let as_custom = match v.get("asCustom") { + None => false, + Some(Value::Bool(yes)) => *yes, + Some(_) => return Err(bad("`asCustom` is true or false")), + }; if let Some(o) = a.oauth.as_mut() { if let Some(provider) = provider { o.provider = provider; + // (An own identity provider's addresses are none of Microsoft's or Google's.) + if provider != OAuthProvider::Custom { + *o = OAuth { + provider, + client_id: std::mem::take(&mut o.client_id), + tenant: std::mem::take(&mut o.tenant), + directory: o.directory, + redirect_port: o.redirect_port, + ..OAuth::default() + }; + } } if let Some(client_id) = client_id { o.client_id = client_id; @@ -125,10 +150,171 @@ fn sign_in(a: &mut Account, v: &Value) -> Result<(), CmdError> { if let Some(directory) = directory { o.directory = directory; } + if let Some(port) = own.redirect_port { + o.redirect_port = port; + } + if own.changes_built_in() && o.provider != OAuthProvider::Custom { + // Microsoft's and Google's addresses, scopes and mechanism are built in: an account + // with its own is set up for an own identity provider, and only when asked to be + // (the window asks the owner first), with the values it had as a start. + if !as_custom { + return Err(bad(format!( + "{}'s addresses, scopes and mechanism are built in: to use others, set up the account for your own identity provider (`asCustom`: true)", + o.provider.label() + ))); + } + let used = o.effective(); + let extra = used + .scopes + .split_ascii_whitespace() + .filter(|s| !mailcraft_model::oauth::CUSTOM_SCOPE.split(' ').any(|c| c == *s)) + .collect::>() + .join(" "); + *o = OAuth { + provider: OAuthProvider::Custom, + client_id: used.client_id, + issuer: used.issuer, + authorize: used.authorize, + token: used.token, + revoke: used.revoke, + scopes: extra, + mechanism: used.mechanism, + redirect_port: o.redirect_port, + ..OAuth::default() + }; + } + own.apply(o); + o.check().map_err(|why| bad(why.to_string()))?; + } else if own.changes_built_in() || provider.is_some() && provider != Some(OAuthProvider::Microsoft) { + return Err(bad("these settings are for an account that signs in on its provider's page (`auth`: \"oauth2\")")); } Ok(()) } +/// What a command says of an own identity provider's settings: each `None` when it doesn't say. +#[derive(Default)] +struct OwnProvider { + issuer: Option, + authorize: Option, + token: Option, + revoke: Option, + scopes: Option, + mechanism: Option, + redirect_port: Option>, + has_secret: Option, +} + +impl OwnProvider { + /// Whether it says anything that Microsoft's and Google's accounts have built in. + fn changes_built_in(&self) -> bool { + self.issuer.is_some() + || self.authorize.is_some() + || self.token.is_some() + || self.revoke.is_some() + || self.scopes.is_some() + || self.mechanism.is_some() + } + + fn apply(self, o: &mut OAuth) { + for (given, field) in [ + (self.issuer, &mut o.issuer), + (self.authorize, &mut o.authorize), + (self.token, &mut o.token), + (self.revoke, &mut o.revoke), + (self.scopes, &mut o.scopes), + ] { + if let Some(given) = given { + *field = given; + } + } + if let Some(mechanism) = self.mechanism { + o.mechanism = mechanism; + } + if let Some(has_secret) = self.has_secret { + o.has_secret = has_secret; + } + } +} + +/// An own identity provider's settings from a command's params, each checked as text (what can +/// be used is for [`OAuth::check`] to say once they are all in). +fn own_provider_fields(v: &Value) -> Result { + let text = |key: &str, max: usize| -> Result, CmdError> { + match v.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(String::new())), + Some(Value::String(text)) if text.len() <= max => Ok(Some(text.trim().to_string())), + Some(_) => Err(bad(format!("`{key}` is a string of at most {max} bytes, or null for none"))), + } + }; + let mechanism = match p::str(v, "mechanism") { + Some(name) => Some(SaslChoice::parse(name).ok_or_else(|| bad("`mechanism` is auto, oauthbearer or xoauth2"))?), + None if v.get("mechanism").is_some_and(|m| !m.is_null()) => return Err(bad("`mechanism` is auto, oauthbearer or xoauth2")), + None => None, + }; + let redirect_port = match v.get("redirectPort") { + None => None, + Some(Value::Null) => Some(None), + Some(port) => match port.as_u64() { + Some(port @ 1..=65_535) => Some(Some(port as u16)), + _ => return Err(bad("`redirectPort` is a port from 1 to 65535, or null for any free one")), + }, + }; + let max = mailcraft_model::oauth::MAX_ENDPOINT; + Ok(OwnProvider { + issuer: text("issuer", max)?, + authorize: text("authorizeUrl", max)?, + token: text("tokenUrl", max)?, + revoke: text("revokeUrl", max)?, + scopes: text("scopes", mailcraft_model::oauth::MAX_SCOPES)?, + mechanism, + redirect_port, + has_secret: match v.get("hasSecret") { + None => None, + Some(Value::Bool(has)) => Some(*has), + Some(_) => return Err(bad("`hasSecret` is true or false")), + }, + }) +} + +/// `account.oauthDefaults`: what a provider's sign-in uses when the account says nothing else. +fn oauth_defaults(_: &mut Session, v: &Value) -> CmdResult { + let provider = OAuthProvider::parse(p::req_str(v, "provider")?).ok_or_else(|| bad("`provider` is microsoft, google or custom"))?; + let tenant: String = p::str(v, "tenant").unwrap_or_default().chars().take(64).collect(); + let used = provider.defaults(&tenant); + Ok(json!({ + "provider": provider.code(), + "issuer": used.issuer, + "authorizeUrl": used.authorize, + "tokenUrl": used.token, + "revokeUrl": used.revoke, + "scopes": used.scopes, + "mechanism": used.mechanism.code(), + "builtInClient": used.built_in_client, + "hosts": used.hosts, + })) +} + +/// `account.oauthRestoreDefaults`: an account's sign-in back to the values built in. +fn oauth_restore_defaults(s: &mut Session, v: &Value) -> CmdResult { + let id = p::req_id(v, "id")?; + let a = s.mailbox.account_mut(id)?; + let o = a.oauth.as_mut().ok_or_else(|| bad("the account signs in with a password: it has no OAuth settings"))?; + match o.provider { + OAuthProvider::Microsoft | OAuthProvider::Google => { + o.client_id.clear(); + o.redirect_port = None; + } + OAuthProvider::Custom => { + o.scopes.clear(); + o.mechanism = SaslChoice::Auto; + o.redirect_port = None; + } + } + let oauth = o.clone(); + Ok(json!({"id": id, "oauth": oauth})) +} + /// Which kind of Microsoft account a command says it is (`directory`), when it says. fn directory_of(v: &Value) -> Result, CmdError> { match v.get("directory") { @@ -190,6 +376,14 @@ fn preset(_: &mut Session, v: &Value) -> CmdResult { username = found_username(p::str(records, "username").unwrap_or_default(), &email, &domain); } } + // The identity provider a domain's document names for its incoming server, offered for the + // owner to confirm (an own provider's sign-in starts only when they ask for it). + let oauth_issuer = v + .get("found") + .and_then(|records| p::str(records, "oauthIssuer")) + .map(str::trim) + .filter(|issuer| !known && issuer.starts_with("https://") && !issuer.contains(['?', '#']) && mailcraft_model::oauth::endpoint(issuer).is_ok()) + .map(|issuer| issuer.chars().take(mailcraft_model::oauth::MAX_ENDPOINT).collect::()); let preset = found.unwrap_or_else(|| provider::guess(&domain)); let via_of = |server: &Option<(Server, Via)>| server.as_ref().map(|(_, via)| via.code()).unwrap_or("guess"); let (incoming_via, outgoing_via) = (via_of(&incoming), via_of(&outgoing)); @@ -214,6 +408,7 @@ fn preset(_: &mut Session, v: &Value) -> CmdResult { "incoming": server(incoming.as_ref().map(|(s, _)| s).unwrap_or(&preset.incoming), if known { via } else { incoming_via }), "outgoing": server(outgoing.as_ref().map(|(s, _)| s).unwrap_or(&preset.outgoing), if known { via } else { outgoing_via }), "note": preset.note, + "oauthIssuer": oauth_issuer, })) } @@ -386,6 +581,10 @@ fn apply_fields(a: &mut Account, v: &Value) -> Result<(), CmdError> { } } } + // An own identity provider is for an IMAP account's servers alone. + if a.signs_in_with_own_provider() && a.kind != AccountKind::Imap { + return Err(bad("only an account with IMAP and SMTP servers signs in with your own identity provider")); + } // Only an account with an outgoing server that signs in with a password has the choice. if a.oauth.is_some() || a.outgoing.is_none() { a.outgoing_without_sign_in = false; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e249eb3709..1cad05b0b5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -422,6 +422,8 @@ pub mod p { } } +#[cfg(test)] +mod account_oauth_tests; #[cfg(test)] mod agent_gate_tests; #[cfg(test)] diff --git a/crates/i18n/po/cs.po b/crates/i18n/po/cs.po index 17d6858e57..288625d76c 100644 --- a/crates/i18n/po/cs.po +++ b/crates/i18n/po/cs.po @@ -1786,7 +1786,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Vše, co ještě čeká na odeslání na server, jde první: pošta ve složce Pošta k odeslání a příznaky a přesuny provedené offline. Pokud se MailCraft k serveru nedostane, přepnutí počká, dokud to nepůjde." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "ID aplikace (klienta)" @@ -2373,7 +2373,7 @@ msgid "AutoArchive" msgstr "Automatická archivace" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automaticky" @@ -16757,7 +16757,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Řekněte tvůrcům MailCraftu, co nefungovalo, na GitHubu nebo e-mailem. Hlášení zkontrolujete a odešlete sami." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Tenant" @@ -17970,7 +17970,7 @@ msgid "The notes are too long to edit here." msgstr "Poznámky jsou příliš dlouhé na úpravu zde." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Ten v Soubor › Možnosti" @@ -27731,3 +27731,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/de.po b/crates/i18n/po/de.po index 71a5a4c3c7..5de8995c15 100644 --- a/crates/i18n/po/de.po +++ b/crates/i18n/po/de.po @@ -1705,7 +1705,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Alles, was noch an den Server gehen soll, geht zuerst: E-Mails im Postausgang sowie Kennzeichnungen und Verschiebungen, die Sie offline vorgenommen haben. Erreicht MailCraft den Server nicht, wartet der Wechsel, bis es so weit ist." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "Anwendungs-ID (Client-ID)" @@ -2268,7 +2268,7 @@ msgid "AutoArchive" msgstr "AutoArchivierung" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatisch" @@ -15746,7 +15746,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Teilen Sie den Entwicklern von MailCraft auf GitHub oder per E-Mail mit, was schiefgelaufen ist. Sie können den Bericht überprüfen und selbst versenden." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Mandant" @@ -16875,7 +16875,7 @@ msgid "The notes are too long to edit here." msgstr "Die Notizen sind zu lang, um sie hier zu bearbeiten." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Die unter Datei › Optionen" @@ -26198,3 +26198,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/es.po b/crates/i18n/po/es.po index 9f48e35224..7358d91df0 100644 --- a/crates/i18n/po/es.po +++ b/crates/i18n/po/es.po @@ -1793,7 +1793,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Primero se envía todo lo que aún espera para ir al servidor: el correo de la Bandeja de salida y las marcas y movimientos hechos mientras estaba sin conexión. Si MailCraft no puede conectar con el servidor, el cambio espera hasta que pueda." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "Id. de aplicación (cliente)" @@ -2379,7 +2379,7 @@ msgid "AutoArchive" msgstr "Archivado automático" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automático" @@ -16734,7 +16734,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Cuente a los creadores de MailCraft qué salió mal, en GitHub o por correo electrónico. Usted revisa el informe y lo envía." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Inquilino" @@ -17946,7 +17946,7 @@ msgid "The notes are too long to edit here." msgstr "Las notas son demasiado largas para editarlas aquí." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "El de Archivo › Opciones" @@ -27755,3 +27755,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/fr.po b/crates/i18n/po/fr.po index 10f9050da2..7fbce5484c 100644 --- a/crates/i18n/po/fr.po +++ b/crates/i18n/po/fr.po @@ -1790,7 +1790,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Tout ce qui attend encore d'être envoyé au serveur part d'abord : le courrier de la Boîte d'envoi, ainsi que les indicateurs et déplacements effectués hors connexion. Si MailCraft ne peut pas joindre le serveur, le basculement attend que ce soit possible." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "ID d'application (client)" @@ -2373,7 +2373,7 @@ msgid "AutoArchive" msgstr "AutoArchivage" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatique" @@ -16655,7 +16655,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Indiquez aux concepteurs de MailCraft ce qui n'a pas fonctionné, sur GitHub ou par e-mail. Vous vérifiez le rapport et l'envoyez vous-même." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Locataire" @@ -17863,7 +17863,7 @@ msgid "The notes are too long to edit here." msgstr "Les notes sont trop longues pour être modifiées ici." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Celui de Fichier › Options" @@ -27656,3 +27656,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/hu.po b/crates/i18n/po/hu.po index b0e4c249ca..0fc23212f9 100644 --- a/crates/i18n/po/hu.po +++ b/crates/i18n/po/hu.po @@ -1795,7 +1795,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Bármi, ami még vár a szerverre, az az első: a postafiókban, a zászlók és a mozdulatok, amíg offline. Ha MailCraft nem éri el a szervert, a kapcsoló vár, amíg nem." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "Alkalmazás (ügyfél) azonosító" @@ -2379,7 +2379,7 @@ msgid "AutoArchive" msgstr "Automatikus archívum" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatikus" @@ -16727,7 +16727,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Mondd el MailCraft készítőinek, mi történt rosszul, GitHub-on vagy e-mailben." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Bérlő" @@ -17939,7 +17939,7 @@ msgid "The notes are too long to edit here." msgstr "A jegyzetek túl hosszúak ahhoz, hogy itt szerkessze őket." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "A fájlban lévő › beállítások" @@ -27601,3 +27601,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/it.po b/crates/i18n/po/it.po index 48be102f4a..49fda63f48 100644 --- a/crates/i18n/po/it.po +++ b/crates/i18n/po/it.po @@ -1791,7 +1791,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Tutto ciò che è ancora in attesa di andare al server parte per primo: la posta in Posta in uscita e i contrassegni e gli spostamenti fatti offline. Se MailCraft non riesce a raggiungere il server, il passaggio attende finché non ci riesce." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "ID applicazione (client)" @@ -2377,7 +2377,7 @@ msgid "AutoArchive" msgstr "AutoArchiviazione" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatico" @@ -16716,7 +16716,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Racconta agli autori di MailCraft cosa è andato storto, su GitHub o via e-mail. Controlli tu la segnalazione e la invii tu stesso." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Tenant" @@ -17925,7 +17925,7 @@ msgid "The notes are too long to edit here." msgstr "Le note sono troppo lunghe per modificarle qui." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Quello in File › Opzioni" @@ -27737,3 +27737,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/ka.po b/crates/i18n/po/ka.po index 5fdf1ea4a2..ca09501732 100644 --- a/crates/i18n/po/ka.po +++ b/crates/i18n/po/ka.po @@ -1790,7 +1790,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "ჯერ იგზავნება ყველაფერი, რაც სერვერზე გასაგზავნად ელოდება: გასაგზავნებში არსებული ფოსტა და ოფლაინ რეჟიმში დასმული დროშები და გადატანები. თუ MailCraft სერვერს ვერ უკავშირდება, გადასვლა დაელოდება, სანამ შეძლებს." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "აპლიკაციის (კლიენტის) ID" @@ -2372,7 +2372,7 @@ msgid "AutoArchive" msgstr "ავტოდაარქივება" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "ავტომატური" @@ -16665,7 +16665,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "აცნობეთ MailCraft-ის შემქმნელებს, რა მოხდა არასწორად, GitHub-ზე ან ელფოსტით. მოხსენებას თავად ამოწმებთ და აგზავნით." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "ტენანტი" @@ -17877,7 +17877,7 @@ msgid "The notes are too long to edit here." msgstr "შენიშვნები ზედმეტად გრძელია აქ რედაქტირებისთვის." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "ის, რაც ფაილი › პარამეტრებშია" @@ -27521,3 +27521,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/messages.pot b/crates/i18n/po/messages.pot index 8b2eb08c94..30ea3b91f4 100644 --- a/crates/i18n/po/messages.pot +++ b/crates/i18n/po/messages.pot @@ -1491,7 +1491,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs msgid "Application (client) ID" msgstr "" @@ -1977,7 +1977,7 @@ msgid "AutoArchive" msgstr "" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs msgid "Automatic" msgstr "" @@ -13878,7 +13878,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs msgid "Tenant" msgstr "" @@ -14885,7 +14885,7 @@ msgid "The notes are too long to edit here." msgstr "" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs msgid "The one in File › Options" msgstr "" @@ -22747,3 +22747,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/nl.po b/crates/i18n/po/nl.po index 233e11f64b..5f1d9e5528 100644 --- a/crates/i18n/po/nl.po +++ b/crates/i18n/po/nl.po @@ -1752,7 +1752,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Alles wat nog naar de server moet, gaat eerst: e-mail in Postvak UIT, en markeringen en verplaatsingen die u hebt gemaakt terwijl u offline was. Als MailCraft de server niet kan bereiken, wacht de overstap tot dat wel kan." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "Toepassings-id (client)" @@ -2301,7 +2301,7 @@ msgid "AutoArchive" msgstr "AutoArchive" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatisch" @@ -16171,7 +16171,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Vertel de makers van MailCraft wat er misging, op GitHub of per e-mail. U controleert het rapport en verzendt het zelf." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Tenant" @@ -17376,7 +17376,7 @@ msgid "The notes are too long to edit here." msgstr "De notities zijn te lang om hier te bewerken." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Die in Bestand › Opties" @@ -27149,3 +27149,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/pl.po b/crates/i18n/po/pl.po index 6a379a7e78..b899fb937e 100644 --- a/crates/i18n/po/pl.po +++ b/crates/i18n/po/pl.po @@ -1795,7 +1795,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Najpierw wysyłane jest wszystko, co nadal czeka na serwer: poczta w Skrzynce nadawczej oraz flagi i przeniesienia wykonane w trybie offline. Jeśli MailCraft nie może połączyć się z serwerem, przełączenie czeka, aż będzie to możliwe." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "Identyfikator aplikacji (klienta)" @@ -2382,7 +2382,7 @@ msgid "AutoArchive" msgstr "Archiwizacja automatyczna" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automatycznie" @@ -16783,7 +16783,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Powiedz twórcom MailCraft, co poszło nie tak, na GitHubie lub e-mailem. Raport sprawdzasz i wysyłasz samodzielnie." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Dzierżawa" @@ -17998,7 +17998,7 @@ msgid "The notes are too long to edit here." msgstr "Notatki są zbyt długie, aby edytować je tutaj." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Ten z Plik › Opcje" @@ -27786,3 +27786,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/ro.po b/crates/i18n/po/ro.po index 087993974f..b29dc0f714 100644 --- a/crates/i18n/po/ro.po +++ b/crates/i18n/po/ro.po @@ -1793,7 +1793,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "Tot ce încă așteaptă să ajungă pe server pleacă primul: e-mailurile din Mesaje de trimis și marcajele și mutările făcute cât ați fost offline. Dacă MailCraft nu poate contacta serverul, schimbarea așteaptă până poate." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "ID aplicație (client)" @@ -2380,7 +2380,7 @@ msgid "AutoArchive" msgstr "Arhivare automată" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "Automat" @@ -16779,7 +16779,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "Spuneți-le autorilor MailCraft ce nu a mers, pe GitHub sau prin e-mail. Verificați raportul și îl trimiteți chiar dvs." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "Tenant" @@ -17994,7 +17994,7 @@ msgid "The notes are too long to edit here." msgstr "Notele sunt prea lungi pentru a fi editate aici." #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "Cel din Fișier › Opțiuni" @@ -27814,3 +27814,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/i18n/po/zh_CN.po b/crates/i18n/po/zh_CN.po index ba9975a33e..f1e154d329 100644 --- a/crates/i18n/po/zh_CN.po +++ b/crates/i18n/po/zh_CN.po @@ -1791,7 +1791,7 @@ msgid "Anything still waiting to go to the server goes first: mail in the Outbox msgstr "等待发送到服务器的内容将先被处理:发件箱中的邮件,以及您离线时的标记和移动。如果 MailCraft 无法连接服务器,切换将等待连接恢复。" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup.rs crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Application (client) ID" msgstr "应用程序(客户端)ID" @@ -2376,7 +2376,7 @@ msgid "AutoArchive" msgstr "自动归档" #. interface -#: crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs crates/ui-egui/src/backstage.rs crates/ui-egui/src/calendar_view.rs crates/ui-egui/src/ribbon.rs crates/ui-egui/src/spelling.rs #, fuzzy msgid "Automatic" msgstr "自动" @@ -16726,7 +16726,7 @@ msgid "Tell MailCraft's makers what went wrong, on GitHub or by email. You check msgstr "通过 GitHub 或电子邮件向 MailCraft 开发者反馈问题。由您检查并亲自发送报告。" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "Tenant" msgstr "租户" @@ -17935,7 +17935,7 @@ msgid "The notes are too long to edit here." msgstr "备注太长,无法在此编辑。" #. interface -#: crates/ui-egui/src/account_setup.rs +#: crates/ui-egui/src/account_setup/oauth_settings.rs #, fuzzy msgid "The one in File › Options" msgstr "“文件 › 选项”中的设置" @@ -27450,3 +27450,248 @@ msgstr "" #: crates/model/src/mailbox.rs msgid "your identity provider" msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Agree to the addresses outside your identity provider's domain, or enter others" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Asked for besides openid email offline_access" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Automatic (OAUTHBEARER, else XOAUTH2)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client ID" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Client secret (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Discover" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Extra scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find the sign-in and token addresses from the identity provider's address. Only that address is sent." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Find your identity provider's addresses with Discover, or enter them" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Finding the addresses stopped unexpectedly" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Forget the client secret" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Found: sign-in at {signIn}, tokens from {token}." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Google (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "I trust these addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Identity provider (issuer)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Keep the built-in settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Kept: type a new one to replace it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Mechanism" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Microsoft 365 or Outlook.com (built in)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "No addresses found: {reason}" +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "OAuth Built-in Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "OAuth settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Only if your provider gave one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Redirect port" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Register http://127.0.0.1 with any port (or the one above) as the redirect address." +msgstr "" + +#. command label +#: crates/engine/src/cmd/account.rs +msgid "Restore Default OAuth Settings" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Revocation address (optional)" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Scopes" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Sign in with your identity provider (OAuth 2.0) instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Sign-in address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The client secret can only be letters, digits and punctuation" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The one registered for MailCraft" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The redirect port is a number from 1 to 65535, or empty for any free one" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "The sign-in is only sent to: {servers}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These addresses are outside your identity provider's domain: {hosts}" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Token address" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "Use a password instead" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use it" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use my own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Use your own identity provider instead…" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Wait for your identity provider's addresses" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your domain names {issuer} for signing in." +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "Your own identity provider" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup/oauth_settings.rs +msgid "the incoming and outgoing servers above" +msgstr "" + +#. interface +#: crates/ui-egui/src/account_setup.rs +msgid "{domain} says its mail signs in with an identity provider (OAuth 2.0)." +msgstr "" diff --git a/crates/model/src/provider.rs b/crates/model/src/provider.rs index 4ed978df35..f762f9c5ac 100644 --- a/crates/model/src/provider.rs +++ b/crates/model/src/provider.rs @@ -450,6 +450,9 @@ pub struct Discovered { /// How the owner signs in, as the servers' source wrote it: the address or one of its /// parts, `%EMAILADDRESS%`, `%EMAILLOCALPART%` or `%EMAILDOMAIN%`; empty for the address. pub username: String, + /// The identity provider the incoming server's document names for an OAuth 2.0 sign-in, as + /// an `https://` address; empty when it names none. Offered to the owner, never followed by itself. + pub oauth_issuer: String, } /// The hosts are the organisation's own: not for a log. diff --git a/crates/net/src/autoconfig.rs b/crates/net/src/autoconfig.rs index da0a4aec3d..2518c25734 100644 --- a/crates/net/src/autoconfig.rs +++ b/crates/net/src/autoconfig.rs @@ -45,6 +45,10 @@ pub(crate) struct ClientConfig { /// empty when it says none, or names no incoming server that is taken. (An account has one /// user name, the one it reads its mail with: the outgoing server's is not read for it.) pub(crate) username: String, + /// The identity provider the document names (`oAuth2`'s `issuer`, as an `https://` address) + /// when the incoming server taken signs in with OAuth 2.0 (`authentication` `OAuth2`); empty + /// otherwise. Only ever offered to the owner: nothing signs in by itself because of it. + pub(crate) oauth_issuer: String, } /// The document isn't one this reads. @@ -74,6 +78,11 @@ enum Tag { Port, SocketType, Username, + /// `authentication` of a server: how it signs in (`password-cleartext`, `OAuth2`). + Authentication, + /// `clientConfig/oAuth2`, and its `issuer`. + OAuth2, + OAuthIssuer, Other, } @@ -84,6 +93,8 @@ struct Listed { port: String, socket_type: String, username: String, + /// It lists `OAuth2` among the ways it signs in. + oauth2: bool, } impl Listed { @@ -119,6 +130,8 @@ struct Walk { server: Option<(Listed, bool)>, incoming: Vec, outgoing: Vec, + /// The text of `oAuth2`'s `issuer`. + issuer: String, } impl Walk { @@ -136,13 +149,17 @@ impl Walk { ([.., Tag::Server(_)], "port") => Tag::Port, ([.., Tag::Server(_)], "socketType") => Tag::SocketType, ([.., Tag::Server(_)], "username") => Tag::Username, + ([.., Tag::Server(_)], "authentication") => Tag::Authentication, + ([Tag::ClientConfig], "oAuth2") => Tag::OAuth2, + ([Tag::ClientConfig, Tag::OAuth2], "issuer") => Tag::OAuthIssuer, _ => Tag::Other, }; if let Tag::Server(incoming) = tag { self.server = Some((Listed::default(), incoming)); } self.stack.push(tag); - if matches!(tag, Tag::Hostname | Tag::Port | Tag::SocketType | Tag::Username) && self.field.is_none() { + if matches!(tag, Tag::Hostname | Tag::Port | Tag::SocketType | Tag::Username | Tag::Authentication | Tag::OAuthIssuer) && self.field.is_none() + { self.field = Some((String::new(), self.stack.len())); self.spoiled = false; } @@ -155,6 +172,14 @@ impl Walk { if self.field.as_ref().is_some_and(|(_, at)| *at == depth) { let text = self.field.take().map(|(text, _)| text).unwrap_or_default(); let text = if self.spoiled { String::new() } else { text.trim().to_string() }; + if tag == Tag::OAuthIssuer && self.issuer.is_empty() { + self.issuer = text.clone(); + } + if tag == Tag::Authentication + && let Some((server, _)) = &mut self.server + { + server.oauth2 |= text.eq_ignore_ascii_case("OAuth2"); + } // (The first of a field is the one taken.) if let Some((server, _)) = &mut self.server { let field = match tag { @@ -213,7 +238,8 @@ pub(crate) fn read(xml: &[u8]) -> Result, Malformed> { let mut reader = Reader::from_str(&xml); let config = reader.config_mut(); (config.check_end_names, config.allow_unmatched_ends, config.expand_empty_elements) = (true, false, false); - let mut walk = Walk { stack: Vec::new(), field: None, spoiled: false, server: None, incoming: Vec::new(), outgoing: Vec::new() }; + let mut walk = + Walk { stack: Vec::new(), field: None, spoiled: false, server: None, incoming: Vec::new(), outgoing: Vec::new(), issuer: String::new() }; // Every event takes at least a byte of the document, which bounds the loop. for _ in 0..=xml.len() { match reader.read_event().map_err(|_| Malformed)? { @@ -242,7 +268,26 @@ pub(crate) fn read(xml: &[u8]) -> Result, Malformed> { } // The user name is the incoming server's, and goes with it alone. let username = incoming.as_ref().map(|(_, listed)| listed.username.clone()).unwrap_or_default(); - Ok(Some(ClientConfig { incoming: incoming.map(|(server, _)| server), outgoing: outgoing.map(|(server, _)| server), username })) + // The identity provider, for an incoming server that signs in with it, as an address. + let oauth2 = incoming.as_ref().is_some_and(|(_, listed)| listed.oauth2); + let oauth_issuer = if oauth2 { issuer_address(&walk.issuer) } else { String::new() }; + Ok(Some(ClientConfig { incoming: incoming.map(|(server, _)| server), outgoing: outgoing.map(|(server, _)| server), username, oauth_issuer })) +} + +/// `issuer` as an identity provider's address: as written when it is an `https://` one, a bare +/// host name made one; empty when it is neither, or isn't one that can be used. +fn issuer_address(issuer: &str) -> String { + let issuer = issuer.trim(); + let address = if issuer.contains("://") { + issuer.to_string() + } else { + match domain_name(issuer) { + Some(host) => format!("https://{host}"), + None => return String::new(), + } + }; + let usable = address.starts_with("https://") && !address.contains(['?', '#']) && mailcraft_model::oauth::endpoint(&address).is_ok(); + if usable { address } else { String::new() } } #[cfg(test)] diff --git a/crates/net/src/autoconfig_tests.rs b/crates/net/src/autoconfig_tests.rs index f41d31cb08..11424a9445 100644 --- a/crates/net/src/autoconfig_tests.rs +++ b/crates/net/src/autoconfig_tests.rs @@ -225,3 +225,47 @@ proptest! { } } } + +/// [`DOCUMENT`] with an `oAuth2` block naming `issuer`. +fn with_issuer(issuer: &str) -> String { + DOCUMENT.replace( + r#" \n {issuer}\n openid email\n \n OAuth2\n", ""); + assert_eq!(read(password_only.as_bytes()).unwrap().unwrap().oauth_issuer, ""); +} + +#[test] +fn an_issuer_that_cant_be_used_is_left_out() { + for issuer in [ + "http://id.example.org", + "https://user:pw@id.example.org", + "https://id.example.org/?x=1", + "javascript:alert(1)", + "not a host", + "https://id.example.org/ x", + "&custom;", + ] { + let config = read(with_issuer(issuer).as_bytes()).ok().flatten(); + assert_eq!(config.map(|c| c.oauth_issuer).unwrap_or_default(), "", "{issuer:?}"); + } + let long = format!("https://id.example.org/{}", "a".repeat(5_000)); + assert_eq!(read(with_issuer(&long).as_bytes()).unwrap().unwrap().oauth_issuer, ""); +} diff --git a/crates/net/src/discover.rs b/crates/net/src/discover.rs index 39850cf899..014af97fd9 100644 --- a/crates/net/src/discover.rs +++ b/crates/net/src/discover.rs @@ -121,6 +121,7 @@ fn take(found: &mut Discovered, config: autoconfig::ClientConfig, via: Via) { { found.incoming = Some(FoundServer { server, via }); found.username = config.username; + found.oauth_issuer = config.oauth_issuer; } if found.outgoing.is_none() && let Some(server) = config.outgoing diff --git a/crates/ui-egui/src/account_setup.rs b/crates/ui-egui/src/account_setup.rs index e15d7b35a4..1b4d1205a0 100644 --- a/crates/ui-egui/src/account_setup.rs +++ b/crates/ui-egui/src/account_setup.rs @@ -21,6 +21,7 @@ mod exchange; mod help; +mod oauth_settings; mod senders; use std::sync::mpsc::{Receiver, TryRecvError}; @@ -217,6 +218,10 @@ pub enum Action { Imap, /// Ask the domain's DNS again where its Autodiscover is (Search again). LookAgain, + /// Sign in with an own identity provider (OAuth 2.0) instead of a password. + OwnProvider, + /// Sign in with a password after all. + PasswordInstead, } /// How setting the account up ended, for the last page to say. @@ -381,6 +386,8 @@ pub struct Preset { guessed: (bool, bool), /// Where each of the two servers came from, the incoming first; `None` for a guess. sources: (Option, Option), + /// The identity provider the domain's document names for an OAuth 2.0 sign-in; empty for none. + oauth_issuer: String, } impl Preset { @@ -404,6 +411,7 @@ impl Preset { found, guessed: if found.is_some() { (sources.0.is_none(), sources.1.is_none()) } else { (false, false) }, sources, + oauth_issuer: text("oauthIssuer", 2048), } } @@ -488,6 +496,9 @@ pub struct AccountSetup { client_id: String, /// The Microsoft directory an existing account signs in to. tenant: String, + /// The OAuth settings' fields beside [`AccountSetup::oauth`] (an own identity provider's + /// redirect port, client secret, Discover). + own: oauth_settings::OwnFields, /// What went wrong, shown on the page in view. error: String, /// The page's first field takes the keyboard. @@ -638,6 +649,7 @@ impl AccountSetup { password: Secret::default(), client_id: String::new(), tenant: String::new(), + own: Default::default(), error: String::new(), focus: true, lookup: None, @@ -734,6 +746,7 @@ impl AccountSetup { w.tenant = line(&oauth.tenant, 64); } w.oauth = a.oauth.clone(); + w.own = oauth_settings::OwnFields::of(a.oauth.as_ref()); w.edit = Some(Editing { id: a.id, baseline: w.fields() }); if a.kind.has_offline_window() && !a.is_shared() { w.keep_offline = Some((a.keep_offline, a.keep_offline)); @@ -792,6 +805,9 @@ impl AccountSetup { } if !records.is_empty() { records.insert("username".into(), json!(line(&found.username, LINE))); + if !found.oauth_issuer.is_empty() { + records.insert("oauthIssuer".into(), json!(line(&found.oauth_issuer, LINE))); + } m.insert("found".into(), Value::Object(records)); } } @@ -820,6 +836,9 @@ impl AccountSetup { Some(oauth) => { m.insert("auth".into(), json!("oauth2")); m.insert("provider".into(), json!(oauth.provider.code())); + if oauth.provider == OAuthProvider::Custom { + self.oauth_params(&mut m); + } // Which kind of Microsoft account it is, once a sign-in has said. if let Some(kind) = self.directory.code() { m.insert("directory".into(), json!(kind)); @@ -912,6 +931,7 @@ impl AccountSetup { if self.oauth.is_some() { m.insert("clientId".into(), json!(self.client_id.trim())); m.insert("tenant".into(), json!(self.tenant.trim())); + self.oauth_params(&mut m); } else if self.outgoing.value().is_some() { m.insert("outgoingWithoutSignIn".into(), json!(self.outgoing_without_sign_in)); } @@ -953,6 +973,9 @@ impl AccountSetup { _ => {} } } + if self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom) { + return self.oauth_problem(); + } None } @@ -983,6 +1006,7 @@ impl AccountSetup { self.service = preset.service; self.note = preset.note; self.oauth = preset.oauth.map(|provider| OAuth { provider, ..Default::default() }); + self.own = oauth_settings::OwnFields::offering(preset.oauth_issuer); self.username = preset.username; self.incoming = preset.incoming; self.outgoing = preset.outgoing; @@ -1168,6 +1192,28 @@ impl AccountSetup { self.proceed(app); } } + (Page::Password, Action::OwnProvider) => { + let offered = self.own.offered.clone(); + self.choose_own_provider(&offered); + } + (Page::Password, Action::PasswordInstead) => { + self.oauth = None; + self.own.wipe(); + self.error.clear(); + } + (Page::Password, Action::Go) if self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom) => { + if let Some(problem) = self.settings_problem(true).or_else(|| self.own_sign_in_problem()) { + self.error = problem; + } else if !self.hosts_to_ask().is_empty() { + self.go(Page::ServerConsent); + } else { + self.start_own_sign_in(app); + } + } + (Page::ServerConsent, Action::Go) if self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom) => { + self.agreed_hosts.extend(self.hosts_to_ask()); + self.start_own_sign_in(app); + } (Page::Password, Action::Go) => { // Do not let an Enter key or a command bypass the OAuth-first choice and // add a Google account without the owner selecting app-password setup. @@ -1393,6 +1439,14 @@ impl AccountSetup { } } + /// A new account with its own identity provider: its client secret where the sign-in finds + /// it, then the provider's page. + fn start_own_sign_in(&mut self, app: &mut MailApp) { + self.oauth = self.oauth_now(); + self.keep_client_secret(app, 0); + self.start_sign_in(app); + } + /// Send the owner to the provider's page. fn start_sign_in(&mut self, app: &mut MailApp) { let Some(oauth) = self.oauth.clone() else { return }; @@ -1530,7 +1584,9 @@ impl AccountSetup { /// signed in as somebody other than the address typed is not added: the owner is asked /// whether to sign in again, set up that account, or confirm a personal custom-domain alias. fn add_signed_in(&mut self, app: &mut MailApp, tokens: mailcraft_model::sync::Tokens) { - if tokens.someone_else(self.email.trim(), "") { + // (An own identity provider's names needn't be the address: its mail servers judge the token.) + let own = self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom); + if !own && tokens.someone_else(self.email.trim(), "") { self.someone_else = Some(tokens); self.go(Page::SomeoneElse); return; @@ -1666,6 +1722,7 @@ impl AccountSetup { self.error = e; return false; } + self.keep_client_secret(app, id); if let Some((_, ask)) = self.ask_conversation.filter(|(was, ask)| was != ask) { if let Err(e) = app.execute("account.edit", json!({"id": id, "askBeforeDeletingConversation": ask})) { self.error = e; @@ -1730,6 +1787,7 @@ impl AccountSetup { Page::Checking => self.poll_check(app), Page::ExchangeChecking | Page::ExchangeConsent => self.poll_exchange(app), Page::Exchange => self.poll_look_again(), + Page::Password | Page::Settings => self.poll_discover(), _ => {} } } @@ -1845,6 +1903,8 @@ impl AccountSetup { } else if self.oauth.as_ref().is_some_and(|oauth| oauth.provider == OAuthProvider::Google) { self.oauth = None; self.go(Page::Password); + } else if self.oauth.as_ref().is_some_and(|oauth| oauth.provider == OAuthProvider::Custom) { + self.go(Page::Password); } else { self.go(Page::Address); } @@ -2146,6 +2206,10 @@ impl AccountSetup { }; let mut offered = None; let mut change_method = None; + // An own identity provider instead of a password: for a new account on servers nobody + // here knows the sign-in of (a provider this program knows has its own). + let own = self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom); + let can_own = self.edit.is_none() && !oauth_first && !google && (own || (self.oauth.is_none() && self.service.is_empty())); page(ui, &t, |ui| { heading(ui, &title, &t); note(ui, &shown(self.email.trim(), 120), t.text_dim); @@ -2234,12 +2298,29 @@ impl AccountSetup { } note(ui, tl!("Use a Google app password, not your everyday Google account password."), t.text_dim); } - if asks { + if own { + self.oauth_section(app, ui, pass); + if button(ui, tl!("Use a password instead"), false, true).clicked() { + change_method = Some(Action::PasswordInstead); + } + } else if asks { self.password_field(ui, pass, app.secret_watch(), ""); note(ui, kept_where(app), t.text_dim); } else { note(ui, tl!("This build can't connect to mail servers. The account can still be added."), t.text_dim); } + if can_own && !own && app.services.sign_in.is_some() { + if !self.own.offered.is_empty() { + note( + ui, + &fmt(tl!("{domain} says its mail signs in with an identity provider (OAuth 2.0)."), &[("domain", &domain)]), + t.text_dim, + ); + } + if button(ui, tl!("Sign in with your identity provider (OAuth 2.0) instead"), false, true).clicked() { + change_method = Some(Action::OwnProvider); + } + } } ui.add_space(2.0); disclosure(ui, tl!("Change account settings"), &mut self.settings_open, &t); @@ -2253,7 +2334,7 @@ impl AccountSetup { ui.hyperlink(GOOGLE_APP_PASSWORDS); }); } - let ready = !asks || !self.password.0.is_empty(); + let ready = own || !asks || !self.password.0.is_empty(); let (mut go, mut back, mut google_sign_in) = (false, false, false); strip(ui, self.page, |ui| { if oauth_first { @@ -2472,11 +2553,8 @@ impl AccountSetup { } else if !self.graph { self.settings(ui, pass); } - if let Some(oauth) = &self.oauth { - field(ui, pass, "clientId", tl!("Application (client) ID"), &mut self.client_id, tl!("The one in File › Options"), 200); - if oauth.provider == OAuthProvider::Microsoft { - field(ui, pass, "tenant", tl!("Tenant"), &mut self.tenant, "common", 64); - } + if self.oauth.is_some() { + self.oauth_section(app, ui, pass); } if let Some((_, keep)) = self.keep_offline.as_mut() { caption(ui, tl!("Mail to keep offline"), &t); @@ -2916,6 +2994,9 @@ mod tests { mod help; /// Explicit confirmation of personal Outlook.com custom-domain aliases. mod legacy_alias; + /// An account with its own identity provider: the OAuth settings, Discover, the client + /// secret, and a Microsoft or Google account set up for an own provider. + mod own_provider; /// An outgoing server that needs no sign-in (#836). mod relay_without_sign_in; /// The password's eye (#438). @@ -3187,6 +3268,7 @@ mod tests { }), outgoing: None, username: "%EMAILLOCALPART%".into(), + oauth_issuer: String::new(), }; let (_, params) = w.preset_command(Some(&found), None).unwrap(); assert_eq!( @@ -3337,6 +3419,7 @@ mod tests { incoming: Some(provider::FoundServer { server: Server { host: long.clone(), port: 993, security: Security::Tls }, via: Via::Srv }), outgoing: None, username: long.clone(), + oauth_issuer: long.clone(), }; let (_, params) = w.preset_command(Some(&hostile), None).unwrap(); let passed = params["mx"].as_array().unwrap(); diff --git a/crates/ui-egui/src/account_setup/oauth_settings.rs b/crates/ui-egui/src/account_setup/oauth_settings.rs new file mode 100644 index 0000000000..bec2f91b18 --- /dev/null +++ b/crates/ui-egui/src/account_setup/oauth_settings.rs @@ -0,0 +1,368 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The OAuth settings of an account that signs in on its provider's page: every value its sign-in +//! uses, shown, and those that are the account's own, entered, saved and edited. +//! +//! Microsoft's and Google's values are built in ([`OAuthProvider::defaults`]): they are shown as +//! they are used and only the client id, Microsoft's tenant and the redirect port can change. To +//! use other addresses, scopes or a mechanism the account becomes one with its own identity +//! provider, after a question, starting from the values it had: so that what may be sent to +//! Microsoft's and Google's servers is never loosened from here. +//! +//! An own identity provider (Keycloak, Authentik and the like, in front of the owner's own IMAP +//! and SMTP servers) has every value typed, or its addresses found from its issuer (Discover: +//! only the issuer's address goes out, and only when the owner presses it). Its client secret, +//! when it has one, is typed here and kept in the system's credential store alone; the mailbox +//! says only that there is one. Saving goes through `account.add` and `account.edit`. + +use mailcraft_model::{OAuthProvider, SaslChoice}; + +use super::*; + +/// What the OAuth settings keep beside the account's [`OAuth`] while the dialog is open. +#[derive(Default)] +pub(super) struct OwnFields { + /// The redirect port as typed; empty for any free one. + pub(super) port: String, + /// A client secret typed here, to keep in place of the one there is; empty for no change. + secret: Secret, + /// Its eye was clicked: it is shown. + reveal: bool, + /// The owner asked to forget the client secret there is. + forget_secret: bool, + /// The identity provider's description, while it is fetched. + discovering: Option>>, + /// What Discover found, said in a line; or why it found nothing. + found: String, + /// The hosts of the found addresses outside the issuer's own domain, and whether the owner + /// agreed to them. + outside: Vec, + agreed: bool, + /// The question whether a Microsoft or Google account is to use its own identity provider. + asking: bool, + /// The owner said yes: saving sets it up for its own identity provider (`asCustom`). + pub(super) as_custom: bool, + /// The identity provider the domain's own document names, when it does: offered. + pub(super) offered: String, +} + +impl OwnFields { + pub(super) fn of(oauth: Option<&OAuth>) -> OwnFields { + OwnFields { port: oauth.and_then(|o| o.redirect_port).map(|p| p.to_string()).unwrap_or_default(), ..OwnFields::default() } + } + + /// Nothing typed yet, with the identity provider the domain's document named offered. + pub(super) fn offering(issuer: String) -> OwnFields { + OwnFields { offered: issuer, ..OwnFields::default() } + } + + /// The client secret typed, if any. + pub(super) fn typed_secret(&self) -> &str { + &self.secret.0 + } + + /// Blank what was typed of the secret. + pub(super) fn wipe(&mut self) { + self.secret.wipe(); + } +} + +/// The redirect port as typed: `Ok(None)` for any free one. +fn port(text: &str) -> Result, ()> { + match text.trim() { + "" => Ok(None), + digits => digits.parse::().ok().filter(|p| *p != 0).map(Some).ok_or(()), + } +} + +impl AccountSetup { + /// Set the account up to sign in with an own identity provider, from nothing (or the issuer + /// the domain's document offered, when the owner takes it). + pub(super) fn choose_own_provider(&mut self, issuer: &str) { + self.forget_password(); + self.oauth = Some(OAuth { issuer: issuer.to_string(), ..OAuth::custom() }); + self.client_id.clear(); + let offered = std::mem::take(&mut self.own.offered); + self.own = OwnFields { offered, ..OwnFields::default() }; + self.error.clear(); + } + + /// The account's sign-in settings as the fields have them now. + pub(super) fn oauth_now(&self) -> Option { + let mut oauth = self.oauth.clone()?; + oauth.client_id = self.client_id.trim().to_string(); + if oauth.provider == OAuthProvider::Microsoft { + oauth.tenant = self.tenant.trim().to_string(); + } + oauth.redirect_port = port(&self.own.port).unwrap_or(oauth.redirect_port); + if oauth.provider == OAuthProvider::Custom { + oauth.has_secret = !self.own.typed_secret().is_empty() || (oauth.has_secret && !self.own.forget_secret); + } + Some(oauth) + } + + /// What keeps the OAuth settings from being saved, in the interface's language. + pub(super) fn oauth_problem(&self) -> Option { + let oauth = self.oauth_now()?; + if port(&self.own.port).is_err() { + return Some(tl!("The redirect port is a number from 1 to 65535, or empty for any free one").to_string()); + } + if self.own.discovering.is_some() { + return Some(tl!("Wait for your identity provider's addresses").to_string()); + } + if !self.own.outside.is_empty() && !self.own.agreed { + return Some(tl!("Agree to the addresses outside your identity provider's domain, or enter others").to_string()); + } + let secret = self.own.typed_secret(); + if secret.len() > 1024 || !secret.bytes().all(|b| b.is_ascii_graphic()) { + return Some(tl!("The client secret can only be letters, digits and punctuation").to_string()); + } + oauth.check().err().map(|why| why.to_string()) + } + + /// What signing in needs that the settings don't have yet, before a new account's sign-in. + pub(super) fn own_sign_in_problem(&self) -> Option { + if let Some(problem) = self.oauth_problem() { + return Some(problem); + } + let oauth = self.oauth_now()?; + oauth.ready().err().map(|_| tl!("Find your identity provider's addresses with Discover, or enter them").to_string()) + } + + /// The OAuth settings, as `account.add` and `account.edit` take them. + pub(super) fn oauth_params(&self, m: &mut Map) { + let Some(oauth) = self.oauth_now() else { return }; + m.insert("redirectPort".into(), json!(oauth.redirect_port)); + if oauth.provider != OAuthProvider::Custom { + return; + } + m.insert("clientId".into(), json!(oauth.client_id)); + if self.own.as_custom { + m.insert("asCustom".into(), json!(true)); + } + for (key, value) in [ + ("issuer", &oauth.issuer), + ("authorizeUrl", &oauth.authorize), + ("tokenUrl", &oauth.token), + ("revokeUrl", &oauth.revoke), + ("scopes", &oauth.scopes), + ] { + m.insert(key.into(), json!(value.trim())); + } + m.insert("mechanism".into(), json!(oauth.mechanism.code())); + m.insert("hasSecret".into(), json!(oauth.has_secret)); + } + + /// Keep the client secret typed (or forget the one there is) for `account`, once the + /// settings that name it are saved (0: the account being set up, until it exists). + pub(super) fn keep_client_secret(&mut self, app: &mut MailApp, account: Id) { + if !self.oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom) { + return; + } + if !self.own.typed_secret().is_empty() { + let secret = self.own.typed_secret().to_string(); + app.set_client_secret(account, &secret); + self.own.wipe(); + } else if self.own.forget_secret { + app.set_client_secret(account, ""); + self.own.forget_secret = false; + } + } + + /// Take in what Discover found, once it has. + pub(super) fn poll_discover(&mut self) { + let answer = match self.own.discovering.as_ref().map(Receiver::try_recv) { + Some(Err(TryRecvError::Empty)) | None => return, + Some(Ok(answer)) => answer, + Some(Err(TryRecvError::Disconnected)) => Err(tl!("Finding the addresses stopped unexpectedly").to_string()), + }; + self.own.discovering = None; + let Some(oauth) = self.oauth.as_mut().filter(|o| o.provider == OAuthProvider::Custom) else { return }; + match answer { + Ok(found) => { + (oauth.authorize, oauth.token, oauth.revoke) = (line(&found.authorize, 2048), line(&found.token, 2048), line(&found.revoke, 2048)); + let host = |address: &str| address.split("://").nth(1).and_then(|rest| rest.split(['/', '?', ':']).next()).unwrap_or("").to_string(); + let mut said = fmt( + tl!("Found: sign-in at {signIn}, tokens from {token}."), + &[("signIn", &shown(&host(&oauth.authorize), 80)), ("token", &shown(&host(&oauth.token), 80))], + ); + if found.no_refresh { + said.push(' '); + said.push_str(tl!("It hands out no refresh tokens: you'll be asked to sign in again each time a sign-in runs out.")); + } + self.own.found = said; + self.own.outside = found.outside.iter().take(8).map(|h| line(h, 253)).collect(); + self.own.agreed = false; + } + Err(why) => self.own.found = fmt(tl!("No addresses found: {reason}"), &[("reason", &shown(&why, 200))]), + } + } + + /// The OAuth settings section of a page, for an account that signs in on its provider's page. + pub(super) fn oauth_section(&mut self, app: &MailApp, ui: &mut Ui, pass: &mut Pass) { + let t = pass.t; + let Some(provider) = self.oauth.as_ref().map(|o| o.provider) else { return }; + caption(ui, tl!("OAuth settings"), &t); + match provider { + OAuthProvider::Custom => self.own_provider_fields(app, ui, pass), + built_in => self.built_in_fields(ui, pass, built_in), + } + // The servers the token is for: never chosen here, they follow the server settings. + let servers: Vec = match provider { + OAuthProvider::Custom => { + let mut hosts: Vec = + [self.incoming.host.trim(), self.outgoing.host.trim()].into_iter().filter(|h| !h.is_empty()).map(|h| shown(h, 80)).collect(); + hosts.dedup(); + hosts + } + other => other.defaults("").hosts, + }; + let servers = if servers.is_empty() { tl!("the incoming and outgoing servers above").to_string() } else { servers.join(", ") }; + note(ui, &fmt(tl!("The sign-in is only sent to: {servers}"), &[("servers", &servers)]), t.text_dim); + } + + /// Microsoft's or Google's built-in values, shown; the client id, tenant and port, edited. + fn built_in_fields(&mut self, ui: &mut Ui, pass: &mut Pass, provider: OAuthProvider) { + let t = pass.t; + let profile = if provider == OAuthProvider::Google { tl!("Google (built in)") } else { tl!("Microsoft 365 or Outlook.com (built in)") }; + note(ui, profile, t.text); + let used = provider.defaults(&self.tenant); + for (label, value) in [ + (tl!("Identity provider"), used.issuer.as_str()), + (tl!("Sign-in address"), used.authorize.as_str()), + (tl!("Token address"), used.token.as_str()), + (tl!("Scopes"), used.scopes.as_str()), + (tl!("Mechanism"), used.mechanism.code()), + ] { + note(ui, &format!("{label}: {}", shown(value, 200)), t.text_dim); + } + field(ui, pass, "clientId", tl!("Application (client) ID"), &mut self.client_id, tl!("The one in File › Options"), 200); + if provider == OAuthProvider::Microsoft { + field(ui, pass, "tenant", tl!("Tenant"), &mut self.tenant, "common", 64); + } + if !self.own.asking { + if button(ui, tl!("Use your own identity provider instead…"), false, true).clicked() { + self.own.asking = true; + } + return; + } + let question = fmt( + tl!( + "These settings will no longer be {provider}'s: MailCraft will treat this account as one with your own identity provider, starting from the values above, and you'll sign in again." + ), + &[("provider", provider.label())], + ); + note(ui, &question, t.orange); + let (mut yes, mut no) = (false, false); + ui.horizontal(|ui| { + yes = button(ui, tl!("Use my own identity provider"), true, true).clicked(); + no = button(ui, tl!("Keep the built-in settings"), false, true).clicked(); + }); + if yes { + let mut oauth = self.oauth_now().unwrap_or_default(); + let used = oauth.effective(); + let extra = used + .scopes + .split_ascii_whitespace() + .filter(|s| !mailcraft_model::oauth::CUSTOM_SCOPE.split(' ').any(|c| c == *s)) + .collect::>() + .join(" "); + oauth = OAuth { + provider: OAuthProvider::Custom, + client_id: used.client_id.clone(), + issuer: used.issuer, + authorize: used.authorize, + token: used.token, + revoke: used.revoke, + scopes: extra, + mechanism: used.mechanism, + redirect_port: oauth.redirect_port, + ..OAuth::default() + }; + self.client_id = used.client_id; + self.oauth = Some(oauth); + (self.own.as_custom, self.own.asking) = (true, false); + } else if no { + self.own.asking = false; + } + } + + /// An own identity provider's values, every one entered here. + fn own_provider_fields(&mut self, app: &MailApp, ui: &mut Ui, pass: &mut Pass) { + let t = pass.t; + note(ui, tl!("Your own identity provider"), t.text); + if !self.own.offered.is_empty() && self.oauth.as_ref().is_some_and(|o| o.issuer.trim().is_empty()) { + note(ui, &fmt(tl!("Your domain names {issuer} for signing in."), &[("issuer", &shown(&self.own.offered, 120))]), t.text_dim); + if button(ui, tl!("Use it"), false, true).clicked() + && let Some(oauth) = self.oauth.as_mut() + { + oauth.issuer = self.own.offered.clone(); + } + } + let has_secret = self.oauth.as_ref().is_some_and(|o| o.has_secret); + let Some(oauth) = self.oauth.as_mut() else { return }; + field(ui, pass, "issuer", tl!("Identity provider (issuer)"), &mut oauth.issuer, "https://id.example.org/realms/mail", 2048); + let can_discover = app.services.oauth_discover.is_some() && !oauth.issuer.trim().is_empty() && self.own.discovering.is_none(); + let mut discover = false; + ui.horizontal(|ui| { + discover = button(ui, tl!("Discover"), false, can_discover) + .on_hover_text(tl!("Find the sign-in and token addresses from the identity provider's address. Only that address is sent.")) + .clicked(); + if self.own.discovering.is_some() { + ui.spinner(); + } + }); + if discover && let Some(start) = app.services.oauth_discover.as_ref() { + self.own.discovering = Some(start(oauth.issuer.trim().to_string())); + self.own.found.clear(); + } + if !self.own.found.is_empty() { + note(ui, &self.own.found, t.text_dim); + } + if !self.own.outside.is_empty() { + let hosts = self.own.outside.join(", "); + note(ui, &fmt(tl!("These addresses are outside your identity provider's domain: {hosts}"), &[("hosts", &hosts)]), t.orange); + ui.checkbox(&mut self.own.agreed, tl!("I trust these addresses")); + } + let Some(oauth) = self.oauth.as_mut() else { return }; + let before = (oauth.authorize.clone(), oauth.token.clone()); + field(ui, pass, "authorizeUrl", tl!("Sign-in address"), &mut oauth.authorize, "https://…/auth", 2048); + field(ui, pass, "tokenUrl", tl!("Token address"), &mut oauth.token, "https://…/token", 2048); + // (Addresses typed by hand are the owner's own: nothing to agree to.) + if before != (oauth.authorize.clone(), oauth.token.clone()) { + self.own.outside.clear(); + } + field(ui, pass, "revokeUrl", tl!("Revocation address (optional)"), &mut oauth.revoke, "https://…/revoke", 2048); + field(ui, pass, "clientId", tl!("Client ID"), &mut self.client_id, tl!("The one registered for MailCraft"), 200); + caption(ui, tl!("Client secret (optional)"), &t); + let hint = + if has_secret && !self.own.forget_secret { tl!("Kept: type a new one to replace it") } else { tl!("Only if your provider gave one") }; + let resp = secret_field::field(ui, &mut self.own.secret.0, &mut self.own.reveal, app.secret_watch(), FIELD_MARGIN, |edit| { + edit.id(field_id(("account", "clientSecret"))).char_limit(1024).hint_text(hint.to_owned()) + }); + pass.field(&resp); + if has_secret { + ui.checkbox(&mut self.own.forget_secret, tl!("Forget the client secret")); + } + note( + ui, + tl!("Kept in your system's credential store, never in the mailbox. A desktop program can't really keep it secret from you."), + t.text_dim, + ); + let Some(oauth) = self.oauth.as_mut() else { return }; + field(ui, pass, "scopes", tl!("Extra scopes"), &mut oauth.scopes, tl!("Asked for besides openid email offline_access"), 1024); + field(ui, pass, "redirectPort", tl!("Redirect port"), &mut self.own.port, tl!("Automatic"), 5); + note(ui, tl!("Register http://127.0.0.1 with any port (or the one above) as the redirect address."), t.text_dim); + caption(ui, tl!("Mechanism"), &t); + let label = |choice: SaslChoice| match choice { + SaslChoice::Auto => tl!("Automatic (OAUTHBEARER, else XOAUTH2)"), + SaslChoice::OAuthBearer => "OAUTHBEARER", + SaslChoice::XOAuth2 => "XOAUTH2", + }; + egui::ComboBox::from_id_salt(field_id(("account", "mechanism"))).selected_text(label(oauth.mechanism)).show_ui(ui, |ui| { + for choice in [SaslChoice::Auto, SaslChoice::OAuthBearer, SaslChoice::XOAuth2] { + ui.selectable_value(&mut oauth.mechanism, choice, label(choice)); + } + }); + } +} diff --git a/crates/ui-egui/src/account_setup/tests/autodiscover.rs b/crates/ui-egui/src/account_setup/tests/autodiscover.rs index 0acf3b3676..e7f8651dd1 100644 --- a/crates/ui-egui/src/account_setup/tests/autodiscover.rs +++ b/crates/ui-egui/src/account_setup/tests/autodiscover.rs @@ -325,6 +325,7 @@ fn imap_after_the_question_takes_the_servers_the_domain_s_own_records_name() { incoming: server("imap.lumen.example", 993, Security::Tls), outgoing: server("smtp.lumen.example", 465, Security::Tls), username: String::new(), + oauth_issuer: String::new(), }; discoveries(&mut a, Some(Ok(discovered))); autodiscovers(&mut a, Some(Ok(vec![HOSTED_AUTODISCOVER]))); diff --git a/crates/ui-egui/src/account_setup/tests/found_servers.rs b/crates/ui-egui/src/account_setup/tests/found_servers.rs index 020a042a0a..ab2ac4f558 100644 --- a/crates/ui-egui/src/account_setup/tests/found_servers.rs +++ b/crates/ui-egui/src/account_setup/tests/found_servers.rs @@ -33,6 +33,7 @@ fn servers_found_in_the_domains_records_are_shown_to_check_and_said_to_be_found( incoming: found("mail.lumen.example", 993, Security::Tls, Via::Srv), outgoing: found("mail.lumen.example", 587, Security::StartTls, Via::Srv), username: String::new(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); let w = wizard(&h).unwrap(); @@ -75,6 +76,7 @@ fn a_server_outside_the_domain_is_named_before_the_password_goes_there() { incoming: found(incoming, 993, Security::Tls, Via::Srv), outgoing: found(outgoing, 465, Security::Tls, Via::Srv), username: String::new(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); assert_eq!(wizard(&h).map(|w| w.found), Some(Some(Via::Srv))); @@ -113,6 +115,7 @@ fn a_host_the_owner_typed_is_their_own_and_what_is_not_found_is_said_to_be_a_gue incoming: found("imap.hosted.example", 993, Security::Tls, Via::Srv), outgoing: None, username: String::new(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); let w = wizard(&h).unwrap(); @@ -140,6 +143,7 @@ fn servers_from_a_published_document_or_the_isp_database_say_so_and_sign_in_as_i incoming: found("mail.lumen.example", 993, Security::Tls, via), outgoing: found("mail.lumen.example", 465, Security::Tls, via), username: "%EMAILLOCALPART%".into(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); let w = wizard(&h).unwrap(); @@ -164,6 +168,7 @@ fn a_server_outside_the_domain_is_named_whatever_named_it() { incoming: found("imap.hosted.example", 993, Security::Tls, via), outgoing: found("smtp.hosted.example", 465, Security::Tls, via), username: "%EMAILADDRESS%".into(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); assert_eq!(wizard(&h).map(|w| (w.found, w.username.clone())), Some((Some(via), "noor@lumen.example".to_string()))); @@ -192,6 +197,7 @@ fn each_server_is_said_to_come_from_the_source_that_named_it() { incoming: found("imap.lumen.example", 993, Security::Tls, Via::Autoconfig), outgoing: found("smtp.hosted.example", 465, Security::Tls, Via::Ispdb), username: String::new(), + oauth_issuer: String::new(), }; let mut h = with_found(a, discovered); assert_eq!(wizard(&h).map(|w| (w.found, w.guessed)), Some((Some(Via::Autoconfig), false))); diff --git a/crates/ui-egui/src/account_setup/tests/own_provider.rs b/crates/ui-egui/src/account_setup/tests/own_provider.rs new file mode 100644 index 0000000000..f21cfcda93 --- /dev/null +++ b/crates/ui-egui/src/account_setup/tests/own_provider.rs @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An account that signs in with an own identity provider (OAuth 2.0): set up from Add Account +//! with Discover and a client secret, and a built-in account turned into one after a question. +//! Invented example.org addresses; nothing leaves the test. + +use mailcraft_model::{OAuthProvider, SaslChoice}; + +use super::*; +use crate::OAuthFound; + +const ISSUER: &str = "https://id.example.org/realms/mail"; + +type Requests = Log<(OAuth, String)>; + +/// A host that signs owners in and says yes; the log is the settings and client secret each +/// sign-in was handed. +fn signing_in(app: &mut MailApp) -> Requests { + let asked: Requests = Default::default(); + let log = asked.clone(); + app.services.sign_in = Some(Box::new(move |req: SignInRequest| { + log.lock().unwrap().push((req.oauth.clone(), req.client_secret.clone())); + let (tx, rx) = mpsc::channel(); + tx.send(Ok(signed_in("Alice"))).unwrap(); + rx + })); + asked +} + +/// A host that finds the identity provider's addresses; the log is the issuers it was asked about. +fn discovering(app: &mut MailApp, outside: &[&str]) -> Log { + let asked: Log = Default::default(); + let log = asked.clone(); + let outside: Vec = outside.iter().map(|h| h.to_string()).collect(); + app.services.oauth_discover = Some(Box::new(move |issuer: String| { + log.lock().unwrap().push(issuer.clone()); + let (tx, rx) = mpsc::channel(); + tx.send(Ok(OAuthFound { + authorize: format!("{issuer}/protocol/openid-connect/auth"), + token: format!("{issuer}/protocol/openid-connect/token"), + revoke: String::new(), + outside: outside.clone(), + no_refresh: false, + })) + .unwrap(); + rx + })); + asked +} + +/// The window with the wizard open, tall enough for every OAuth setting to be on screen. +fn open_tall(mut app: MailApp, mut params: Value) -> Harness<'static, MailApp> { + params["name"] = json!("account"); + app.execute("ui.dialog", params).unwrap(); + window(app, (1280.0, 2400.0)) +} + +/// The wizard on the password page for an address at a domain nobody knows. +fn at_password(a: MailApp) -> Harness<'static, MailApp> { + let mut h = open_tall(a, json!({})); + connect(&mut h, "alice@unknown.example"); + assert_eq!(page(&h), Some(Page::Password)); + h +} + +#[test] +fn a_new_account_signs_in_with_its_own_identity_provider_found_from_its_issuer() { + let mut a = app(false); + let requests = signing_in(&mut a); + let asked = discovering(&mut a, &[]); + let mut h = at_password(a); + click(&mut h, "Sign in with your identity provider (OAuth 2.0) instead"); + assert!(wizard(&h).unwrap().oauth.as_ref().is_some_and(|o| o.provider == OAuthProvider::Custom)); + assert!(says(&h, "Your own identity provider")); + // The issuer, then Discover: only the issuer goes out. + wizard_mut(&mut h).oauth.as_mut().unwrap().issuer = ISSUER.into(); + h.run_steps(2); + click(&mut h, "Discover"); + h.run_steps(3); + assert_eq!(*asked.lock().unwrap(), [ISSUER]); + let oauth = wizard(&h).unwrap().oauth.clone().unwrap(); + assert_eq!(oauth.token, format!("{ISSUER}/protocol/openid-connect/token")); + assert!(says(&h, "Found: sign-in at id.example.org")); + // The client, and its secret typed in the masked field. + wizard_mut(&mut h).client_id = "mailcraft".into(); + type_password(&mut h); + click(&mut h, "Connect"); + // Signed in with the settings on screen and the secret typed. + let requests = requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 1, "{:?}", wizard(&h).map(|w| w.error.clone())); + let (sent, secret) = &requests[0]; + assert_eq!((sent.provider, sent.client_id.as_str(), secret.as_str()), (OAuthProvider::Custom, "mailcraft", TYPED)); + // The account is there, with its own provider and the word that a secret is kept. + let account = h.state().session.mailbox.accounts.iter().find(|x| x.email == "alice@unknown.example").cloned().expect("the account is added"); + let oauth = account.oauth.clone().unwrap(); + assert_eq!((oauth.provider, oauth.issuer.as_str(), oauth.has_secret), (OAuthProvider::Custom, ISSUER, true)); + // The secret is the account's for the session; never in the mailbox, a command's answer or Debug. + assert_eq!(h.state().client_secret_of(account.id), TYPED); + let mailbox = serde_json::to_string(&h.state().session.mailbox).unwrap(); + let listed = h.state_mut().execute("account.list", json!({})).unwrap().to_string(); + assert!(!mailbox.contains(TYPED) && !listed.contains(TYPED) && !format!("{account:?}").contains(TYPED)); +} + +#[test] +fn addresses_outside_the_providers_domain_are_agreed_to_first() { + let mut a = app(false); + let requests = signing_in(&mut a); + discovering(&mut a, &["tokens.example.net"]); + let mut h = at_password(a); + click(&mut h, "Sign in with your identity provider (OAuth 2.0) instead"); + wizard_mut(&mut h).oauth.as_mut().unwrap().issuer = ISSUER.into(); + wizard_mut(&mut h).client_id = "mailcraft".into(); + h.run_steps(2); + click(&mut h, "Discover"); + h.run_steps(3); + assert!(says(&h, "tokens.example.net")); + click(&mut h, "Connect"); + assert!(requests.lock().unwrap().is_empty()); + assert!(wizard(&h).unwrap().error.contains("outside"), "{}", wizard(&h).unwrap().error); + h.get_by_role_and_label(Role::CheckBox, "I trust these addresses").click(); + h.run_steps(3); + click(&mut h, "Connect"); + assert_eq!(requests.lock().unwrap().len(), 1); +} + +#[test] +fn settings_that_cant_be_used_are_said_and_nothing_is_signed_in() { + let mut a = app(false); + let requests = signing_in(&mut a); + let mut h = at_password(a); + click(&mut h, "Sign in with your identity provider (OAuth 2.0) instead"); + // No client id; no addresses; an address that isn't https; a port that isn't one. + click(&mut h, "Connect"); + assert!(!wizard(&h).unwrap().error.is_empty()); + wizard_mut(&mut h).client_id = "mailcraft".into(); + click(&mut h, "Connect"); + assert!(wizard(&h).unwrap().error.contains("Discover"), "{}", wizard(&h).unwrap().error); + { + let w = wizard_mut(&mut h); + let oauth = w.oauth.as_mut().unwrap(); + oauth.authorize = "https://id.example.org/auth".into(); + oauth.token = "http://id.example.org/token".into(); + } + click(&mut h, "Connect"); + assert!(wizard(&h).unwrap().error.contains("https"), "{}", wizard(&h).unwrap().error); + wizard_mut(&mut h).oauth.as_mut().unwrap().token = "https://id.example.org/token".into(); + wizard_mut(&mut h).own.port = "70000".into(); + click(&mut h, "Connect"); + assert!(wizard(&h).unwrap().error.contains("redirect port"), "{}", wizard(&h).unwrap().error); + assert!(requests.lock().unwrap().is_empty()); + // A password instead, after all. + click(&mut h, "Use a password instead"); + assert!(wizard(&h).unwrap().oauth.is_none()); +} + +#[test] +fn a_google_account_becomes_one_with_its_own_provider_only_after_the_question() { + let mut a = app(false); + let id = a + .execute( + "account.add", + json!({"email": "ada@gmail.example", "incoming": {"host": "imap.gmail.com"}, "outgoing": {"host": "smtp.gmail.com"}, "auth": "oauth2", "provider": "google"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let mut h = open_tall(a, json!({"id": id})); + assert_eq!(page(&h), Some(Page::Settings)); + // Its built-in values are shown. + assert!(says(&h, "Google (built in)") && says(&h, "https://oauth2.googleapis.com/token")); + click(&mut h, "Use your own identity provider instead…"); + assert!(says(&h, "will no longer be Google's")); + click(&mut h, "Keep the built-in settings"); + assert_eq!(wizard(&h).unwrap().oauth.as_ref().unwrap().provider, OAuthProvider::Google); + click(&mut h, "Use your own identity provider instead…"); + click(&mut h, "Use my own identity provider"); + // Google's client is the build's: an own provider needs its own before anything is saved. + assert!(wizard(&h).unwrap().edit_command().is_none()); + wizard_mut(&mut h).client_id = "my-own-client".into(); + let (_, params) = wizard(&h).unwrap().edit_command().expect("a change to save"); + assert_eq!((params["asCustom"].as_bool(), params["provider"].as_str()), (Some(true), None)); + assert_eq!(params["tokenUrl"], "https://oauth2.googleapis.com/token"); + click(&mut h, "Save"); + let oauth = h.state().session.mailbox.account(id).unwrap().oauth.clone().unwrap(); + assert_eq!((oauth.provider, oauth.client_id.as_str(), oauth.mechanism), (OAuthProvider::Custom, "my-own-client", SaslChoice::XOAuth2)); +} + +#[test] +fn an_own_providers_settings_are_edited_and_its_secret_replaced_or_forgotten() { + let mut a = app(false); + let id = a + .execute( + "account.add", + json!({"email": "alice@example.org", "incoming": {"host": "mail.example.org"}, "outgoing": {"host": "mail.example.org"}, "auth": "oauth2", "provider": "custom", "clientId": "mailcraft", "issuer": ISSUER, "authorizeUrl": format!("{ISSUER}/auth"), "tokenUrl": format!("{ISSUER}/token"), "hasSecret": true}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let mut h = open_tall(a, json!({"id": id})); + assert!(says(&h, "Your own identity provider") && says(&h, "The sign-in is only sent to: mail.example.org")); + // Nothing changed: nothing to save. + assert!(wizard(&h).unwrap().edit_command().is_none()); + wizard_mut(&mut h).oauth.as_mut().unwrap().mechanism = SaslChoice::OAuthBearer; + type_password(&mut h); + click(&mut h, "Save"); + let oauth = h.state().session.mailbox.account(id).unwrap().oauth.clone().unwrap(); + assert_eq!((oauth.mechanism, oauth.has_secret), (SaslChoice::OAuthBearer, true)); + assert_eq!(h.state().client_secret_of(id), TYPED); + // Forgotten. + let mut h = open_tall(app_with(h), json!({"id": id})); + h.get_by_role_and_label(Role::CheckBox, "Forget the client secret").click(); + h.run_steps(3); + click(&mut h, "Save"); + assert!(!h.state().session.mailbox.account(id).unwrap().oauth.as_ref().unwrap().has_secret); + assert_eq!(h.state().client_secret_of(id), ""); +} + +/// The app a harness holds, for another dialog. +fn app_with(h: Harness<'static, MailApp>) -> MailApp { + let mut a = h.into_state(); + a.dialog = None; + a +} diff --git a/crates/ui-egui/src/agent_gate_binding_tests.rs b/crates/ui-egui/src/agent_gate_binding_tests.rs index 1bce46ac7f..cf8d8d864e 100644 --- a/crates/ui-egui/src/agent_gate_binding_tests.rs +++ b/crates/ui-egui/src/agent_gate_binding_tests.rs @@ -166,6 +166,7 @@ const ROWS: &[(&str, &str, Setup)] = &[ ("account.edit", r#"{"id": $account, "name": "X"}"#, Setup::None), ("account.remove", r#"{"id": $account}"#, Setup::None), ("account.forgetEwsCertificate", r#"{"id": $account}"#, Setup::None), + ("account.oauthRestoreDefaults", r#"{"id": $account}"#, Setup::None), ("account.davSet", r#"{"id": $account, "calendarHomes": ["https://dav.example.org/cal/"]}"#, Setup::None), ("account.davOff", r#"{"id": $account}"#, Setup::None), ("account.graphSwitch", r#"{"account": $account}"#, Setup::None), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 98f6b5718b..d869107854 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -463,6 +463,10 @@ pub struct Services { /// records, RFC 6186, #1063; what it publishes for mail programs; Mozilla's ISP database, /// #1112), for the owner to confirm. Only the domain is given, never the mailbox name. pub discover: Option Receiver>>>, + /// Desktop: find an own identity provider's sign-in, token and revocation addresses from its + /// issuer, on a background thread (OpenID Connect Discovery, RFC 8414). Only the issuer's + /// address goes out; only when the owner presses Discover. + pub oauth_discover: Option Receiver>>>, /// Desktop: ask the DNS, on a background thread, for the hosts a domain names for /// Autodiscover (its `_autodiscover._tcp` SRV record and the alias of `autodiscover.`), /// so account setup can tell an address on an Exchange server from one on an IMAP server. @@ -801,6 +805,19 @@ pub trait PictureCache { fn clear(&self) -> Result<(), String>; } +/// What an own identity provider says of itself ([`Services::oauth_discover`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OAuthFound { + pub authorize: String, + pub token: String, + /// Empty when it names none. + pub revoke: String, + /// The hosts of those addresses outside the issuer's own domain, for the owner to agree to. + pub outside: Vec, + /// It says it hands out no refresh tokens: the owner signs in again each time a token runs out. + pub no_refresh: bool, +} + /// What the host needs to sign an account's owner in ([`Services::sign_in`]). A sign-in on the /// provider's page that ends without tokens in one of the ways the window has something of its /// own to say about is answered with exactly [`approval::NEEDS_APPROVAL`], From 8762acb6296f9cdb84c2b2705b1dd442edf56fab Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 09:34:07 +0100 Subject: [PATCH 05/25] GO7: give an own identity provider its refresh token back on Remove Account When an account that signs in with an own identity provider is removed and the provider names a revocation address, its refresh token is given back (RFC 7009) on a thread of the host's, with the client secret if one is kept; best effort, and the sign-in is forgotten here either way. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- apps/mailcraft/src/main.rs | 10 ++++++++ .../src/account_setup/tests/own_provider.rs | 25 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 23 +++++++++++++++++ crates/ui-egui/src/secrets_binding_tests.rs | 5 ++-- 4 files changed, 61 insertions(+), 2 deletions(-) diff --git a/apps/mailcraft/src/main.rs b/apps/mailcraft/src/main.rs index 0739178efb..cc9f9b0fd3 100644 --- a/apps/mailcraft/src/main.rs +++ b/apps/mailcraft/src/main.rs @@ -1260,6 +1260,16 @@ fn services( .map_err(|e| e.to_string()) }) })), + revoke_sign_in: Some(Box::new(|oauth: mailcraft_model::OAuth, secret: String, refresh: String| { + let started = std::thread::Builder::new().name("give back a sign-in".into()).spawn(move || { + if mailcraft_net::oauth::revoke_custom(&oauth, &secret, &refresh).is_err() { + log::info!("the identity provider couldn't be told to forget a removed account's sign-in"); + } + }); + if started.is_err() { + log::info!("couldn't start giving a removed account's sign-in back"); + } + })), lookup_autodiscover: Some(Box::new(move |domain| { background(&autodiscover_ctx, "autodiscover records", move || mailcraft_net::autodiscover_hosts(&domain).map_err(|e| e.to_string())) })), diff --git a/crates/ui-egui/src/account_setup/tests/own_provider.rs b/crates/ui-egui/src/account_setup/tests/own_provider.rs index f21cfcda93..c8733545f0 100644 --- a/crates/ui-egui/src/account_setup/tests/own_provider.rs +++ b/crates/ui-egui/src/account_setup/tests/own_provider.rs @@ -221,3 +221,28 @@ fn app_with(h: Harness<'static, MailApp>) -> MailApp { a.dialog = None; a } + +#[test] +fn removing_the_account_gives_the_refresh_token_back_where_the_provider_says() { + let mut a = app(false); + let given: Log<(String, String, String)> = Default::default(); + let log = given.clone(); + a.services.revoke_sign_in = Some(Box::new(move |oauth: OAuth, secret: String, refresh: String| { + log.lock().unwrap().push((oauth.revoke, secret, refresh)); + })); + let add = |a: &mut MailApp, revoke: &str| { + let v = json!({"email": "alice@example.org", "incoming": {"host": "mail.example.org"}, "outgoing": {"host": "mail.example.org"}, "auth": "oauth2", "provider": "custom", "clientId": "mailcraft", "issuer": ISSUER, "authorizeUrl": format!("{ISSUER}/auth"), "tokenUrl": format!("{ISSUER}/token"), "revokeUrl": revoke, "hasSecret": true}); + a.execute("account.add", v).unwrap()["id"].as_u64().unwrap() + }; + let id = add(&mut a, &format!("{ISSUER}/revoke")); + a.adopt_tokens(id, signed_in("Alice")); + a.set_client_secret(id, TYPED); + a.execute("account.remove", json!({"id": id})).unwrap(); + assert_eq!(*given.lock().unwrap(), [(format!("{ISSUER}/revoke"), TYPED.to_string(), "ref-1".to_string())]); + assert_eq!(a.client_secret_of(id), ""); + // A provider that names nowhere to give it back is told nothing. + let id = add(&mut a, ""); + a.adopt_tokens(id, signed_in("Alice")); + a.execute("account.remove", json!({"id": id})).unwrap(); + assert_eq!(given.lock().unwrap().len(), 1); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d869107854..4c72dcfc43 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -467,6 +467,10 @@ pub struct Services { /// issuer, on a background thread (OpenID Connect Discovery, RFC 8414). Only the issuer's /// address goes out; only when the owner presses Discover. pub oauth_discover: Option Receiver>>>, + /// Desktop: give an own identity provider a refresh token back (RFC 7009) on a thread of its + /// own, with the account's sign-in settings and its client secret (empty for none), when the + /// account is removed. Best effort: nothing waits for it, and nothing it says is shown. + pub revoke_sign_in: Option>, /// Desktop: ask the DNS, on a background thread, for the hosts a domain names for /// Autodiscover (its `_autodiscover._tcp` SRV record and the alias of `autodiscover.`), /// so account setup can tell an address on an Exchange server from one on an IMAP server. @@ -2715,6 +2719,9 @@ impl MailApp { self.graph_tokens.remove(&account); self.passwords.remove(&account); self.dav_passwords.retain(|(id, _), _| *id != account); + // An own identity provider is given its refresh token back, when it says where + // (RFC 7009): on a thread of the host's, best effort; it is forgotten here either way. + self.revoke_own_sign_in(&gone); self.tokens.remove(&account); self.jmap_refused.remove(&account); self.ews_unreadable.remove(&account); @@ -3669,6 +3676,22 @@ impl MailApp { } } + /// Hand an own identity provider's refresh token for `gone`, an account being removed, to the + /// host to give back (`Services::revoke_sign_in`), with its client secret. Nothing when it + /// names nowhere to give it back, or there is none. + fn revoke_own_sign_in(&mut self, gone: &mailcraft_model::Account) { + let Some(oauth) = gone.oauth.clone().filter(|o| o.provider == mailcraft_model::OAuthProvider::Custom && !o.revoke.trim().is_empty()) else { + return; + }; + let kept = self.tokens.get(&gone.id).map(|t| t.refresh.clone()).filter(|r| !r.is_empty()); + let refresh = kept.or_else(|| self.secret_cache.get(&Self::secret_key("refresh", gone)).cloned()).unwrap_or_default(); + let secret = self.client_secret_of(gone.id); + self.client_secrets.remove(&gone.id); + if let (false, Some(revoke)) = (refresh.is_empty(), self.services.revoke_sign_in.as_ref()) { + revoke(oauth, secret, refresh); + } + } + /// The host's Desktop registration value. UI preferences never supply or retain it. pub(crate) fn google_client_secret(&self) -> &str { &self.services.google_client_secret diff --git a/crates/ui-egui/src/secrets_binding_tests.rs b/crates/ui-egui/src/secrets_binding_tests.rs index 60d20be213..b76d7cd117 100644 --- a/crates/ui-egui/src/secrets_binding_tests.rs +++ b/crates/ui-egui/src/secrets_binding_tests.rs @@ -354,8 +354,9 @@ fn the_secret_cache_and_the_old_names_are_used_only_where_they_are_listed() { ("lib.rs", "legacy_secret_key(", 2), ("secret_read.rs", "legacy_secret_key(", 1), // (And the client secret of an account with its own identity provider, read where a - // sign-in is handed to the host: `client_secret_of`.) - ("lib.rs", "secret_cache.get(", 3), + // sign-in is handed to the host, `client_secret_of`; and its refresh token, given back + // to the provider when the account is removed, `revoke_own_sign_in`.) + ("lib.rs", "secret_cache.get(", 4), ("secret_read.rs", "secret_cache.contains_key(", 2), // A subscribed calendar's address is kept like a password (#209): found again by the name // that holds its host (`subscribed_address`), and moved into memory for the session when From 3b6170825d1644a0ab2dbabb05b979222ad27ccf Mon Sep 17 00:00:00 2001 From: Marcel Ritter Date: Sun, 22 Nov 2026 09:34:07 +0100 Subject: [PATCH 06/25] GO10: docs: signing in with your own identity provider A guide (docs/oauth-servers.md): what an own identity provider needs, setting the account up, Keycloak, Authentik, Dovecot and Postfix, and what the errors mean. The privacy rules and the privacy statement say what discovery sends and where the sign-in may go; the architecture page names OAUTHBEARER and discovery; gap 3 says what is and isn't done. Progress, revision and release-note fragments. Human-reviewed, AI-assisted, nobody's mailbox harmed. --- PRIVACY.md | 1 + docs/architecture.md | 4 +- docs/gaps.md | 2 +- docs/log.d/ROADMAP/progress/1831.md | 1 + .../log.d/docs/architecture/revisions/1831.md | 1 + docs/log.d/docs/gaps/revisions/1831.md | 1 + .../docs/mail-privacy-rules/revisions/1831.md | 1 + .../docs/oauth-servers/revisions/1831.md | 1 + docs/mail-privacy-rules.md | 1 + docs/oauth-servers.md | 129 ++++++++++++++++++ packaging/release-notes.d/new/1831.md | 1 + 11 files changed, 140 insertions(+), 3 deletions(-) create mode 100644 docs/log.d/ROADMAP/progress/1831.md create mode 100644 docs/log.d/docs/architecture/revisions/1831.md create mode 100644 docs/log.d/docs/gaps/revisions/1831.md create mode 100644 docs/log.d/docs/mail-privacy-rules/revisions/1831.md create mode 100644 docs/log.d/docs/oauth-servers/revisions/1831.md create mode 100644 docs/oauth-servers.md create mode 100644 packaging/release-notes.d/new/1831.md diff --git a/PRIVACY.md b/PRIVACY.md index 0864f60ac6..100eafe972 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -75,6 +75,7 @@ MailCraft connects only to these, over encrypted connections: | A JMAP server you add an account for (the session address you gave it, and the addresses at the same server that its session names) | Send/Receive, on the timer you set, a few seconds after you mark, move or delete a message of the account or send one from it, and when you open a message that isn't downloaded yet; only in a build that connects to JMAP servers (the browser build, from the version that adds it) | What a mail program sends: your password or access token, and what you change in your mail: the marks you set on a message (read, flagged, answered, forwarded), the messages you move between the server's folders and those you delete for good are told to that server, and to nobody else. Mail you send from the account goes to that server to be sent, and to nobody else: the message whole, and the addresses it goes to, those in Bcc among them (the message itself names no Bcc); the server keeps its copy, in the account's Sent folder where it has one. A password or token you type is kept in memory only, until the program closes, the server turns it down or the account's server changes; it is never remembered in the credential store, the mailbox file, the settings or the browser's storage. Where the page you use signed you in itself, the program asks it for the credential at each Send/Receive or download (once more if the server turns it down), and keeps none of it beyond that | | Microsoft's sign-in pages and Microsoft Graph, for an account that signs in with Microsoft | When you sign in; for calendar, contacts, tasks (Microsoft To Do), sending mail, working hours, categories (read, and made, recoloured and deleted there: their names and colours; after a rename, the mail and events that carry the old name are asked for by that name and given the new one), automatic replies, the rules kept on the server and Outlook's Favorites | Your sign-in happens on Microsoft's page in your browser; the program receives tokens, never your password | | Google's sign-in page (`accounts.google.com/o/oauth2/v2/auth`) and token endpoint (`oauth2.googleapis.com/token`), for an account that signs in with Google | When you sign in, switch an existing account to Google sign-in or reconnect; the token endpoint is also used when a saved sign-in is renewed | The browser's sign-in request carries the application's client ID, the permissions requested, your account address as a login hint, a random state value, a PKCE challenge and a return address on your own computer. The token endpoint receives the authorization code and PKCE verifier, or the refresh token, together with the application's client ID and Desktop client-secret registration value. Google returns tokens and identifies the signed-in address in the identity token; MailCraft makes no separate user-info request. You enter your Google password on Google's page: MailCraft never sees it. | +| Your own identity provider (an OpenID Connect or OAuth 2.0 server you name), for an IMAP account you set up to sign in with it | When you press Discover in its OAuth settings (its description, at its own address); when you sign in or a saved sign-in is renewed (its sign-in page in your browser, and its token address); when you remove the account, if it names where a refresh token is given back | For Discover, a request for the provider's own description and nothing of yours: not your address, not the client id. The browser's sign-in request carries the client ID you entered, the permissions requested, your address as a hint, a one-time check value and the address on your own computer the page sends you back to; the token address gets the one-time code or the saved sign-in, the client ID, and the client secret only if you entered one. The sign-in is used only with your account's own mail servers | | Gmail's API (`gmail.googleapis.com`), for an account that signs in with Google, to move mail between Gmail's inbox categories | Not in this version: moving mail between Gmail's categories is switched off until Google has reviewed MailCraft's use of the API. Once it is switched on, only at the Send/Receive after you move a message of the Inbox from one Gmail category to another; never for an account that signs in with an app password | Gmail's own id of each message you moved, the category it goes to (the labels to add and take off), and the account's sign-in token, which Gmail's API takes as it is; nothing else of the message or of you | | The Exchange server of an Exchange server account (your organisation's own Exchange Server, Grommunio or SmarterMail), for its address list | When you press Check Names (Ctrl+K) in a message written from that account and a name you typed matches none or more than one of your contacts; and when you search the account's address list in People (its Address Book, chosen at the top of the list), for what you type in the search box, from two characters on, once you pause. Never while you type a recipient, never while you work offline, and never for a script or an agent | The names as you typed them (ten a request, at most fifty for one Check Names), with your sign-in, over the account's own connection. Who it finds (a name, an address, the job title, department and company, and in the Address Book the work and mobile numbers and the office) is kept in the window while you choose or look, and in the recipients you choose, and nowhere else: not in the mailbox file, not on disk, not in a log. Add to Contacts makes a contact on this computer of the person shown, on your press | | A public DNS-over-HTTPS resolver (Cloudflare, then Google) | When you press Connect while adding an account at a domain the program does not know: once for the domain's mail exchangers and twice for where its Exchange automatic setup is (the `_autodiscover._tcp` record and `autodiscover.`), and, when the exchangers name no provider the program knows, up to four times more for the DNS records that say where the domain's mail servers are (its `_imaps`, `_imap`, `_submissions` and `_submission` SRV records); and while an Exchange server account is set up | The domain of your address (the part after the @), never the mailbox name | diff --git a/docs/architecture.md b/docs/architecture.md index 7615e7f4d2..334892f228 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,10 +36,10 @@ egui, eframe, winit or rfd. | L2 | `tnef` | Reader of TNEF streams (`winmail.dat`, `application/ms-tnef`) from [MS-OXTNEF]: the files of their attachments and the plain text of their message, with what isn't read (attached messages, OLE objects, attachments with no data, attributes with a wrong checksum) named; every length checked against what is left, nothing opened inside another stream, caps on attributes, files, properties and values, and never more out than went in; no I/O of its own, builds for wasm. `mime` adds the files before the stream, which it keeps | | L2 | `openpgp` | Checking OpenPGP Digital signatures (#30) on rPGP: a PGP/MIME message over its signed part's canonical bytes (RFC 3156) or a cleartext-signed text (RFC 9580 §7), with the four results (verified, valid but not verified, changed after signing, can't be checked; MD5, SHA-1, DSA and RSA under 2048 bits refused), and what of the message it covers: only a whole message is Verified; Public keys from attached `application/pgp-keys` parts and the `Autocrypt:` header, their self-signatures checked; whether a key is Verified is the caller's answer (no web of trust). MIME, armour and the cleartext framework read here with every size, count and depth capped; no I/O and no clock of its own, builds for wasm | | L2 | `smime` | S/MIME (RFC 8551) Digital signatures checked (#30), from RFC 5652 (CMS), RFC 5280 (X.509) and the algorithms' RFCs: the signer's digest against the message's, the signature (RSA of 2048 bits or more, ECDSA on P-256 or P-384, over SHA-2), and whether the certificate rests on a trust anchor the host hands in, is for signing mail and is for the From address; the same four results as OpenPGP; revocation isn't checked. No I/O, hostile input bounded | -| L3 | `proto` | IMAP4rev1 and SMTP clients over any `Read + Write` stream (no sockets, so they test against scripted transcripts and build for wasm) | +| L3 | `proto` | IMAP4rev1 and SMTP clients over any `Read + Write` stream (no sockets, so they test against scripted transcripts and build for wasm), signing in with a password, or a token through SASL XOAUTH2 or OAUTHBEARER (RFC 7628, with a server's refusal reasons read as hostile) | | L3 | `dav` | Bounded DAV XML and byte-preserving iCalendar/vCard edits over model snapshots; no sockets or browser APIs, builds for wasm | | L3 | `assuan` | The Assuan protocol and gpg-agent over any `Read + Write` stream, so that OpenPGP keys stay in GnuPG (smartcards included) and MailCraft never sees a PIN: lines of at most 1000 bytes, percent-escaping, `D`/`S`/`OK`/`ERR`/`INQUIRE`, every size and count capped; gpg-agent's `HAVEKEY`, `KEYINFO`, `READKEY`, signing a SHA-256/384/512 digest (`PKSIGN`) and decrypting a session key (`PKDECRYPT`, answering `INQUIRE CIPHERTEXT`), with the hints its own pinentry needs; a bounded canonical S-expression reader; Assuan's socket files (a redirect, Windows' loopback port and nonce). No sockets: the desktop program finds the agent with `gpgconf` and opens it (`apps/mailcraft/src/gpg_agent.rs`); builds for wasm, which never uses it (#30) | -| L3 | `net` | TCP + TLS (rustls), sending through SMTP, two-way IMAP synchronisation, OAuth sign-in, MX and Autodiscover SRV lookup, Microsoft Graph (`graph`), one HTTPS exchange with an Exchange server that can trust one certificate by its fingerprint, and a held connection that carries the legs of an NTLM sign-in on one socket and names its certificate's hash for channel binding (`https`); empty on wasm | +| L3 | `net` | TCP + TLS (rustls), sending through SMTP, two-way IMAP synchronisation, OAuth sign-in (Microsoft, Google, and the owner's own identity provider, whose addresses `oauth::discovery` finds from its issuer), MX and Autodiscover SRV lookup, Microsoft Graph (`graph`), one HTTPS exchange with an Exchange server that can trust one certificate by its fingerprint, and a held connection that carries the legs of an NTLM sign-in on one socket and names its certificate's hash for channel binding (`https`); empty on wasm | | L3 | `ews` | Exchange Web Services (Microsoft's public documentation only) without sockets or browser APIs: the SOAP request writer, a hostile XML reader, the response-code and `ErrorServerBusy` judgement and `GetFolder`, Autodiscover as a state machine the host drives (the order of places, redirects, the owner's say for another host, Exchange Online told apart), Basic credentials, NTLMv2 written from MS-NLMP (the three legs, MIC, channel binding; MD4, MD5 and HMAC from RustCrypto) and the choice of NTLM or Basic from what the server offers, and mail down: `SyncFolderHierarchy`, `SyncFolderItems` and `GetItem` with their answer readers, and `sync_mail`/`fetch_messages`, which run them over any `HttpExchange` and hand the run back in pieces (waiting for a busy server through a hook the host gives); the program does the exchange (`HttpExchange`); a strict in-process stand-in of Exchange Web Services and of Autodiscover for tests (`stand-in` feature) (#252); going up: changes of messages and folders, drafts kept in the server's Drafts and found again by a marker, sending, never repeated after a lost answer (`changes`, `compose`, `up`); NTLM or Basic chosen from the server's offer (`auth`) | | L3 | `jmap` | JMAP (RFC 8620, 8621) without sockets or browser APIs: builds each HTTP request and judges the answer, the program does the exchange (`HttpExchange`); an in-process server for tests (`stand-in` feature). The browser build runs it over `fetch` (M6, [jmap.md](jmap.md)) | | L4 | `engine` | `Session` (mailbox, selection, view, the message being written, undo), the **command registry** (`cmd/*.rs`), the message list (`list.rs`), the Outlook feature catalog (`catalog.rs`), the sample mailbox, file dispatch (`io.rs`) | diff --git a/docs/gaps.md b/docs/gaps.md index 39c57e83c7..3383a7e64a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -18,7 +18,7 @@ this code base. |---|---|---|---|---|---|---| | 1 | **Limited live interoperability.** MailCraft is in daily use on one Microsoft 365 mailbox. Windows acceptance now also covers Gmail/Workspace OAuth, real app-password authentication, restart/reconnect and explicit conversion with downloaded mail preserved; SMTP authentication was checked without sending. Other providers, self-hosted servers, real outbound delivery for this Google contribution and other desktop platforms still need broader acceptance. Automated tests remain synthetic; no CI job runs against a mail server in a container | B | `crates/net/src/fake.rs`; [Google acceptance scope](google-accounts.md#what-has-been-verified-and-what-has-not) | People on untested servers, platforms or organisation policies | 20–40 | [ROADMAP.md](../ROADMAP.md#the-beta-checklist) | | 2 | **Two-way sync has gaps.** Read marks, flags, moves, permanent deletes, folders created by a move and a copy of sent mail go to the server, and so does mail moved (by the owner or a rule) or copied in from another account or from this computer, its original removed from its own server once the copy is there (#451); a run arrives in pieces with progress and can be called off; folder renames, moves and deletes, drafts written here (by Save Draft, or every five minutes by themselves, #286: they stay in Drafts here), copies within an account, imported mail (mail imported into an account's folder is kept on this computer, in Imported, #1401), categories and importance are not sent over IMAP. A Microsoft account is kept in step through Microsoft Graph instead (R3; one added before switches when its owner says so, R3.7): its folders both ways, by server id, made, renamed, moved and deleted as Outlook does (R3.1); its mail down by delta and fetched whole (R3.2); and the changes made here to its messages up: read, flag with its dates, categories (merged with the server's) and importance, moves, copies, Delete into Deleted Items and Delete for good, twenty to a `$batch`, refusals put back and said, and a move into a local folder removing the server's copy only once the whole message is saved here (R3.3). Drafts and sending still go the old way (R3.4). New mail on an account whose server offers IDLE arrives within moments, through one extra connection kept open on the Inbox (#276; the others keep to the timer), messages over 25 MB are kept as a header with a note, and undoing a move or delete after it reached the server is not possible over IMAP (through Graph it is sent as the reverse change, R3.5) | B | `crates/net/src/push.rs`, `sync.rs`; `apply_sync_part` in `crates/engine/src/cmd/account.rs` | Anyone who organises folders or keeps drafts on two devices | 20–35 | [ROADMAP.md](../ROADMAP.md#the-beta-checklist) | -| 3 | **Microsoft sign-in needs administrator consent for some; Google public rollout needs the official registration and verification.** The Microsoft publisher remains unverified. Desktop Gmail/Workspace OAuth now has scoped live Windows acceptance with a development registration: OAuth-first setup, explicit app-password fallback, account-isolated refresh credentials and opt-in conversion. Existing accounts are unchanged unless their owner converts them. OAuth uses the primary Google account address; Workspace aliases are not accepted as account identities. The maintainer-owned Google Desktop registration and public restricted-scope verification remain outstanding; test-user access does not override Workspace policy. Other providers still take a password | B | `crates/net/src/oauth.rs`; [Google account guide](google-accounts.md); synthetic OAuth/IMAP/SMTP tests; publishing/verification status | People in organisations that restrict consent; Google users outside development access | 10–20 | [ROADMAP.md](../ROADMAP.md#the-beta-checklist) | +| 3 | **Microsoft sign-in needs administrator consent for some; Google public rollout needs the official registration and verification.** The Microsoft publisher remains unverified. Desktop Gmail/Workspace OAuth now has scoped live Windows acceptance with a development registration: OAuth-first setup, explicit app-password fallback, account-isolated refresh credentials and opt-in conversion. Existing accounts are unchanged unless their owner converts them. OAuth uses the primary Google account address; Workspace aliases are not accepted as account identities. The maintainer-owned Google Desktop registration and public restricted-scope verification remain outstanding; test-user access does not override Workspace policy. Other hosted providers still take a password; a self-hosted IMAP server behind the owner's own identity provider (Keycloak, Authentik…) can sign in with it ([own identity providers](oauth-servers.md)), tested against synthetic servers only so far, with no refresh-and-retry inside a run when a server turns a token down and no sign-in for the command line without a browser | B | `crates/net/src/oauth.rs`; [Google account guide](google-accounts.md); synthetic OAuth/IMAP/SMTP tests; publishing/verification status | People in organisations that restrict consent; Google users outside development access | 10–20 | [ROADMAP.md](../ROADMAP.md#the-beta-checklist) | | 4 | **Sign-ins remembered on Linux are not yet proven across a restart.** A password or refresh token goes to Windows Credential Manager, the macOS keychain, or on Linux and FreeBSD the desktop's Secret Service (GNOME Keyring, KWallet; R5, pure Rust over D-Bus) (File › Options to switch off). A round trip through GNOME Keyring is tested by hand; remembered across a restart on GNOME and on KDE is still to be seen. Where no Secret Service runs, or it stays locked, the program asks at each start and says why once a session. OpenBSD and NetBSD have no store | | `apps/mailcraft/src/secrets.rs` | Linux and BSD users | 1–2 | [ui-parity.md](ui-parity.md) | | 5 | **Microsoft Graph is used for a little; JMAP in the browser build only; no CalDAV or CardDAV, and Exchange servers for mail only.** For accounts that sign in with Microsoft, Graph sends mail, brings the contacts down (read-only) and keeps the account's calendars both ways: appointments, repeating series, meetings (invitations, updates and cancellations sent by the server after the owner's yes), answers to invitations and categories. What is still missing is in [calendar-parity.md](calendar-parity.md): Find a Time over several days, shared calendars, and none of it has met the real service beyond one mailbox. Other providers have no server calendar or contacts, but a calendar on the web can be subscribed to (an `.ics` address, https or webcal, read-only under Other Calendars and refreshed every hour: Internet Calendars, #209); shared mailboxes are read through Graph for any work or school Microsoft account (#70: read through Graph, searched, counted on their own and put among the Favorites; what is changed in them goes up to their own address, deleted mail to their own Deleted Items, and undo with it; mail moves and copies between a shared mailbox and its owner's mailbox or another of his shared mailboxes, made in the destination at its own address and the original removed only once the copy is there; mail written in them is from their address, kept in their own Drafts and sent through them, once the owner has allowed sending from shared mailboxes; each with signatures of its own; their calendars are read once ticked, with the owner's permission asked for by itself and free/busy-only ones drawn as blocks, but not changed from here yet), and the browser build connects only to JMAP servers: the mailboxes, the newest messages and their marks come down, the marks, moves between the server's folders and deletions made here go up, and mail is sent through the server (#1074: an alias with an identity of its own on the server isn't sent from, and who got a blind copy isn't kept after sending); what is changed in folders doesn't go up yet (it can't open the sockets IMAP and SMTP need; [jmap.md](jmap.md)); an Exchange server account (an organisation's own Exchange Server, Grommunio or SmarterMail, reached through Exchange Web Services, #252) (what has been seen on Grommunio, and what has not: [exchange-servers.md](exchange-servers.md)) is a kind of account anyone can add, for its mail only (its calendar and contacts are not kept in step yet), and reads its mail down, and takes up what is changed in it, drafts and sent mail (Send/Receive brings its folders and messages as headers and a preview, then whole messages within Mail to keep offline, from the sync states the server gave; Basic over TLS or NTLMv2 on one held connection, one certificate trusted by its fingerprint; added from Add Account's explicit Exchange server choice: the address and a password, and Server settings for the server's address and the user name; nothing is sent until Connect; the server is found by Autodiscover or taken as typed, the owner is asked (naming the host whole) before the sign-in goes to a host outside their mail domain, and inside it to any host but its Autodiscover host and the hosts its SRV record names (the domain's own name is often a web site, AU3-V1), a mailbox in Microsoft 365 is offered as a Microsoft account with no password sent, the account is tried with one request for its Inbox before it is added, a certificate the system doesn't trust is shown and trusted for that account by its fingerprint only on the owner's tick (asked again from File › Info when it changes, never for an expired or wrong-name one), the password is remembered with the system's credential store when the owner lets it be, and File › Info shows the server, the user name, how it signed in and the trusted certificate, with Forget): Kerberos and modern sign-in are not built, Autodiscover can't sign in with NTLM (a server that wants it is set up by typing its address), a message moved on the server comes as a new one, and one over about 12 MB is not downloaded whole. The DAV foundation has collection/resource snapshots, preserving iCalendar/vCard document edits and a bounded XML reader (`mailcraft-dav`, #376); it does not discover servers, upload changes or sync calendars and contacts. | B | `crates/net/src/graph.rs`, `crates/engine/src/cmd/remote.rs`, `crates/dav` | Anyone who runs meetings from here; everyone not on Microsoft; everyone on the web build | 50–100 | [ROADMAP.md](../ROADMAP.md#after-beta) | | 6 | **HTML mail is close, not exact.** Tables, colours, alignment, sizes, lists, quotes and pictures are shown, adjusted for the dark theme, with nothing run; pictures on the web come only when the owner asks for them, and are kept on this computer for 30 days (`apps/mailcraft/src/picture_cache.rs`); pictures written into the message (`data:`) are shown as attached ones are (#533), and a reply or forward carries them in the original, each as a part of its own as Outlook sends them (#602); a message's `