@@ -18,13 +18,14 @@ use crate::{
1818use axum:: { Json , Router , extract:: State , http:: StatusCode , routing:: post} ;
1919use chrono:: { Duration , Utc } ;
2020use piquel_common:: {
21- EmailId , Personal , UserId ,
21+ EmailId , ErrorChain , Personal , Provider , UserId ,
2222 email:: NormalizedEmail ,
2323 events:: { Actor , DomainEvent , EventContext } ,
2424} ;
2525use piquel_crypto:: { CryptoError , Digest , Secret } ;
2626use piquel_repository:: {
27- Database , DatabaseError , DatabaseTransaction , InsertUnverifiedEmail , StoredEmail ,
27+ Database , DatabaseError , DatabaseTransaction , InsertUnverifiedEmail , InsertVerifiedEmail ,
28+ PendingFederation , StoredEmail ,
2829} ;
2930use serde:: { Deserialize , Serialize } ;
3031use std:: { net:: IpAddr , time:: Duration as StdDuration } ;
@@ -238,6 +239,171 @@ impl EmailApplication {
238239 }
239240 Ok ( ( ) )
240241 }
242+
243+ /// Refuses another address for an account that holds `count`.
244+ const fn room ( count : usize ) -> Result < ( ) , EmailError > {
245+ if count >= MAX_EMAILS {
246+ return Err ( EmailError :: TooMany { max : MAX_EMAILS } ) ;
247+ }
248+ Ok ( ( ) )
249+ }
250+
251+ /// Imports the address `pending`'s provider verified into `user_id`'s
252+ /// account, as `context`'s from `client_ip`, while linking that identity in
253+ /// `tx`. It joins verified and primary when the provider is authoritative for
254+ /// it; otherwise unverified, with its verification email, as when the owner
255+ /// adds it, since it may have changed owners since the provider verified it.
256+ /// Only an account with no verified address and without it takes one, and
257+ /// never one another account holds verified, even while that one is being
258+ /// deleted: a provider never replaces the owner's own address or takes
259+ /// someone else's. An address that would be one
260+ /// too many, or whose link cannot be sent now, is skipped, since signing in
261+ /// matters more: the owner can add it later. Another account verifying the
262+ /// same address in the same instant still fails the ownership trigger, and so
263+ /// the transaction; retrying skips the address.
264+ pub ( crate ) async fn import (
265+ tx : & mut DatabaseTransaction < ' _ > ,
266+ context : & EventContext ,
267+ config : & EmailConfig ,
268+ client_ip : IpAddr ,
269+ user_id : UserId ,
270+ pending : & PendingFederation ,
271+ ) -> Result < ( ) , EmailError > {
272+ let Some ( address) = & pending. email else {
273+ return Ok ( ( ) ) ;
274+ } ;
275+ let address = NormalizedEmail :: parse ( address) . map_err ( EmailError :: Invalid ) ?;
276+ let emails = tx. emails ( ) . list ( user_id) . await ?;
277+ if emails
278+ . iter ( )
279+ . any ( |email| email. verified_at . is_some ( ) || email. normalized_email == address. as_str ( ) )
280+ || tx
281+ . emails ( )
282+ . is_owned_elsewhere ( address. as_str ( ) , user_id)
283+ . await ?
284+ {
285+ return Ok ( ( ) ) ;
286+ }
287+ let added = Added {
288+ context,
289+ user_id,
290+ address : & address,
291+ provider : Some ( pending. provider ) ,
292+ } ;
293+ let imported = match Self :: room ( emails. len ( ) ) {
294+ Ok ( ( ) ) if pending. email_authoritative => added. verified ( tx) . await ,
295+ Ok ( ( ) ) => added. unverified ( tx, config, client_ip) . await . map ( drop) ,
296+ Err ( error) => Err ( error) ,
297+ } ;
298+ match imported {
299+ Err (
300+ error @ ( EmailError :: TooMany { .. }
301+ | EmailError :: Disabled
302+ | EmailError :: Unsendable ( _)
303+ | EmailError :: RateLimited { .. } ) ,
304+ ) => {
305+ tracing:: info!( error = %ErrorChain ( & error) , provider = pending. provider. as_str( ) , "provider address not imported" ) ;
306+ Ok ( ( ) )
307+ }
308+ imported => imported,
309+ }
310+ }
311+ }
312+
313+ /// An address joining an account, as `context`'s, and the provider it is
314+ /// imported from, if any. Every address joins through it, so each is recorded
315+ /// and counted the same way.
316+ struct Added < ' a > {
317+ /// Who adds it.
318+ context : & ' a EventContext ,
319+ /// The account it joins.
320+ user_id : UserId ,
321+ /// The address.
322+ address : & ' a NormalizedEmail ,
323+ /// The provider it is imported from.
324+ provider : Option < Provider > ,
325+ }
326+
327+ impl Added < ' _ > {
328+ /// Adds the address unverified, and records it with its verification email,
329+ /// counted against the hourly limits of the account, `client_ip` and the
330+ /// mailbox. Returns its ID.
331+ async fn unverified (
332+ self ,
333+ tx : & mut DatabaseTransaction < ' _ > ,
334+ config : & EmailConfig ,
335+ client_ip : IpAddr ,
336+ ) -> Result < EmailId , EmailError > {
337+ if config. smtp . is_none ( ) {
338+ return Err ( EmailError :: Disabled ) ;
339+ }
340+ // The sender must be able to send to it, or its link would never arrive.
341+ self . address
342+ . as_str ( )
343+ . parse :: < lettre:: Address > ( )
344+ . map_err ( EmailError :: Unsendable ) ?;
345+ EmailApplication :: limit ( tx, self . user_id , client_ip, self . address ) . await ?;
346+ let id = EmailId :: new ( ) ;
347+ let digest = config
348+ . verification_keys
349+ . token ( id)
350+ . map_err ( EmailError :: Crypto ) ?
351+ . digest ( ) ;
352+ tx. emails ( )
353+ . insert_unverified ( & InsertUnverifiedEmail {
354+ id,
355+ user_id : self . user_id ,
356+ normalized_email : self . address . as_str ( ) ,
357+ secret_digest : digest. as_bytes ( ) ,
358+ expires_at : Utc :: now ( ) + VERIFICATION_LIFETIME ,
359+ } )
360+ . await ?;
361+ self . record ( tx, id) . await ?;
362+ Ok ( id)
363+ }
364+
365+ /// Adds the address verified, as the primary one of an account that has
366+ /// none, which a provider authoritative for it vouches for.
367+ async fn verified ( self , tx : & mut DatabaseTransaction < ' _ > ) -> Result < ( ) , EmailError > {
368+ let id = EmailId :: new ( ) ;
369+ tx. emails ( )
370+ . insert_verified ( & InsertVerifiedEmail {
371+ id,
372+ user_id : self . user_id ,
373+ normalized_email : self . address . as_str ( ) . to_owned ( ) ,
374+ is_primary : true ,
375+ verified_at : Utc :: now ( ) ,
376+ } )
377+ . await ?;
378+ self . record ( tx, id) . await ?;
379+ let subject = Some ( self . user_id ) ;
380+ tx. record (
381+ self . context ,
382+ subject,
383+ DomainEvent :: EmailVerified { email_id : id } ,
384+ )
385+ . await ?;
386+ let primary = DomainEvent :: PrimaryEmailChanged {
387+ email_id : id,
388+ previous_email_id : None ,
389+ } ;
390+ tx. record ( self . context , subject, primary) . await ?;
391+ Ok ( ( ) )
392+ }
393+
394+ /// Records the address's addition as `id`.
395+ async fn record (
396+ & self ,
397+ tx : & mut DatabaseTransaction < ' _ > ,
398+ id : EmailId ,
399+ ) -> Result < ( ) , EmailError > {
400+ let added = DomainEvent :: EmailAdded {
401+ email_id : id,
402+ address : Personal :: Value ( self . address . clone ( ) ) ,
403+ provider : self . provider ,
404+ } ;
405+ Ok ( tx. record ( self . context , Some ( self . user_id ) , added) . await ?)
406+ }
241407}
242408
243409/// The account's addresses. Any administrator may also list them, choose the
@@ -265,15 +431,7 @@ impl AccountService {
265431 config : & EmailConfig ,
266432 address : & str ,
267433 ) -> Result < EmailView , AccountError > {
268- if config. smtp . is_none ( ) {
269- return Err ( EmailError :: Disabled . into ( ) ) ;
270- }
271434 let address = NormalizedEmail :: parse ( address) . map_err ( EmailError :: Invalid ) ?;
272- // The sender must be able to send to it, or its link would never arrive.
273- address
274- . as_str ( )
275- . parse :: < lettre:: Address > ( )
276- . map_err ( EmailError :: Unsendable ) ?;
277435 let user = owner. user ( ) ;
278436 let context = owner. context ( ) ;
279437 let mut tx = self . database . begin ( ) . await ?;
@@ -290,34 +448,16 @@ impl AccountService {
290448 EmailApplication :: delete ( & mut tx, & context, user, existing. id ) . await ?;
291449 count -= 1 ;
292450 }
293- if count >= MAX_EMAILS {
294- return Err ( EmailError :: TooMany { max : MAX_EMAILS } . into ( ) ) ;
295- }
296- EmailApplication :: limit ( & mut tx, user, owner. request ( ) . client_ip , & address) . await ?;
297- let id = EmailId :: new ( ) ;
298- let digest = config
299- . verification_keys
300- . token ( id)
301- . map_err ( EmailError :: Crypto ) ?
302- . digest ( ) ;
303- tx. emails ( )
304- . insert_unverified ( & InsertUnverifiedEmail {
305- id,
306- user_id : user,
307- normalized_email : address. as_str ( ) ,
308- secret_digest : digest. as_bytes ( ) ,
309- expires_at : Utc :: now ( ) + VERIFICATION_LIFETIME ,
310- } )
451+ EmailApplication :: room ( count) ?;
452+ let added = Added {
453+ context : & context,
454+ user_id : user,
455+ address : & address,
456+ provider : None ,
457+ } ;
458+ let id = added
459+ . unverified ( & mut tx, config, owner. request ( ) . client_ip )
311460 . await ?;
312- tx. record (
313- & context,
314- Some ( user) ,
315- DomainEvent :: EmailAdded {
316- email_id : id,
317- address : Personal :: Value ( address. clone ( ) ) ,
318- } ,
319- )
320- . await ?;
321461 tx. commit ( ) . await ?;
322462 Ok ( EmailView {
323463 id,
0 commit comments