Skip to content

Commit 64bb6e6

Browse files
committed
fix(auth): imported GitHub and Google addresses are recorded, and verified only where the provider hosts them
1 parent f89437e commit 64bb6e6

37 files changed

Lines changed: 625 additions & 184 deletions

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,12 @@ address, receives at most 3. An address another active account verified cannot b
394394
verified again; adding it is allowed, so adding reveals nothing. The email names
395395
the account the address would join, and a browser signed in to another account
396396
cannot confirm it. An address that stops being primary, or is removed, is told.
397+
Signing up or linking with GitHub or Google imports the provider's address into an
398+
account without a verified one, recorded in its history as imported. It arrives
399+
verified only where the provider hosts the mailbox, Gmail and the account's
400+
Google Workspace domain; any other address arrives unverified with a link, since
401+
it may have changed owners. An address another account verified, or whose link
402+
can't be sent now, is skipped.
397403

398404
Auth sends email through the delivery queue, never from a request. Messages are
399405
transactional security notices: no tracking, no remote images, and links only to

‎apps/auth-service/src/account/tests.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -789,7 +789,7 @@ impl Confirming {
789789
service.remove_email(&subject, state.address).await
790790
}
791791
Self::LinkIdentity => service
792-
.link_identity(&owner, &state.pending)
792+
.link_identity(&owner, &state.email, &state.pending)
793793
.await
794794
.map(drop),
795795
Self::UnlinkIdentity => {

‎apps/auth-service/src/emails/mod.rs‎

Lines changed: 177 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,14 @@ use crate::{
1818
use axum::{Json, Router, extract::State, http::StatusCode, routing::post};
1919
use chrono::{Duration, Utc};
2020
use piquel_common::{
21-
EmailId, Personal, UserId,
21+
EmailId, ErrorChain, Personal, Provider, UserId,
2222
email::NormalizedEmail,
2323
events::{Actor, DomainEvent, EventContext},
2424
};
2525
use piquel_crypto::{CryptoError, Digest, Secret};
2626
use piquel_repository::{
27-
Database, DatabaseError, DatabaseTransaction, InsertUnverifiedEmail, StoredEmail,
27+
Database, DatabaseError, DatabaseTransaction, InsertUnverifiedEmail, InsertVerifiedEmail,
28+
PendingFederation, StoredEmail,
2829
};
2930
use serde::{Deserialize, Serialize};
3031
use 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,

‎apps/auth-service/src/federation/error.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Federation failures and their single mapping to browser responses.
22
33
use super::MAX_RETURN_TO_BYTES;
4+
use crate::emails::EmailError;
45
use crate::security::{ApiError, SessionError};
56
use axum::http::header::InvalidHeaderValue;
67
use piquel_common::{VocabularyError, config::ConfigurationError};
@@ -73,6 +74,9 @@ pub(crate) enum FederationError {
7374
/// A database operation failed.
7475
#[error(transparent)]
7576
Database(#[from] DatabaseError),
77+
/// The provider's address could not be imported.
78+
#[error(transparent)]
79+
Email(#[from] EmailError),
7680
/// Shared browser-session policy rejected the request.
7781
#[error(transparent)]
7882
Session(#[from] SessionError),
@@ -138,6 +142,7 @@ impl From<FederationError> for ApiError {
138142
Self::bad_request("This provider is not linked to your account.")
139143
}
140144
FederationError::Database(error) => error.into(),
145+
FederationError::Email(error) => error.into(),
141146
FederationError::Session(error) => error.into(),
142147
error @ (FederationError::Crypto(_)
143148
| FederationError::CookieHeader(_)

‎apps/auth-service/src/federation/identities.rs‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
33
use super::{FederationApplication, FederationError, Flow, FlowCookie, Provider, ProviderPicture};
44
use crate::account::{AccountError, AccountService, Owner, Subject, Viewer};
5+
use crate::config::EmailConfig;
6+
use crate::emails::EmailApplication;
57
use crate::security::BrowserCookie;
68
use axum::http::HeaderMap;
79
use piquel_common::{
@@ -10,6 +12,7 @@ use piquel_common::{
1012
protocol::api::Identity,
1113
};
1214
use piquel_repository::{Database, DatabaseTransaction, InsertExternalIdentity, PendingFederation};
15+
use std::net::IpAddr;
1316

1417
impl FederationApplication {
1518
/// Verifies that the signup ID shown by the social page belongs to this browser.
@@ -35,11 +38,14 @@ impl FederationApplication {
3538
}
3639

3740
/// Attaches verified signup evidence only inside account-and-first-passkey
38-
/// creation. Returns the profile picture the provider reported, which the
39-
/// caller imports once the account is committed.
41+
/// creation, from `client_ip`, importing its address as `email` allows.
42+
/// Returns the profile picture the provider reported, which the caller
43+
/// imports once the account is committed.
4044
pub(crate) async fn attach_signup(
4145
tx: &mut DatabaseTransaction<'_>,
4246
context: &EventContext,
47+
email: &EmailConfig,
48+
client_ip: IpAddr,
4349
pending_id: TokenId,
4450
headers: &HeaderMap,
4551
user_id: UserId,
@@ -63,11 +69,9 @@ impl FederationApplication {
6369
tx.federation()
6470
.insert_identity(&Self::identity(&pending, user_id))
6571
.await?;
66-
if let Some(email) = &pending.email {
67-
tx.federation().set_first_email(user_id, email).await?;
68-
}
6972
tx.record(context, Some(user_id), Self::linked(&pending))
7073
.await?;
74+
EmailApplication::import(tx, context, email, client_ip, user_id, &pending).await?;
7175
// Checked again, as stored evidence is read back.
7276
Ok(pending
7377
.picture_url
@@ -147,10 +151,12 @@ impl AccountService {
147151
/// once they confirmed with a passkey, and returns where the browser continues, with
148152
/// the deletion of the evidence's cookie. The evidence must name this account, and
149153
/// this session when settings started the link. The account must keep a passkey, and
150-
/// a repeated callback may confirm only the identity already linked here.
154+
/// a repeated callback may confirm only the identity already linked here. Its
155+
/// address is imported as `email` allows.
151156
pub(crate) async fn link_identity(
152157
&self,
153158
owner: &Owner,
159+
email: &EmailConfig,
154160
headers: &HeaderMap,
155161
) -> Result<(String, FlowCookie), AccountError> {
156162
let user = owner.user();
@@ -179,6 +185,7 @@ impl AccountService {
179185
if tx.passkeys().list_active(user).await?.is_empty() {
180186
return Err(FederationError::LinkRequiresPasskey.into());
181187
}
188+
let context = owner.context();
182189
match tx
183190
.federation()
184191
.find_active(&evidence.issuer, &evidence.subject)
@@ -191,16 +198,15 @@ impl AccountService {
191198
.insert_identity(&FederationApplication::identity(&evidence, user))
192199
.await?;
193200
tx.record(
194-
&owner.context(),
201+
&context,
195202
Some(user),
196203
FederationApplication::linked(&evidence),
197204
)
198205
.await?;
199206
}
200207
}
201-
if let Some(email) = &evidence.email {
202-
tx.federation().set_first_email(user, email).await?;
203-
}
208+
let client_ip = owner.request().client_ip;
209+
EmailApplication::import(&mut tx, &context, email, client_ip, user, &evidence).await?;
204210
tx.commit().await?;
205211
Ok((evidence.return_to, FlowCookie(Flow::Settled)))
206212
}

‎apps/auth-service/src/federation/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,7 @@ impl FederationApplication {
548548
issuer: self.endpoints[&provider].issuer.into(),
549549
subject: identity.subject,
550550
email: identity.email,
551+
email_authoritative: identity.email_authoritative,
551552
display_name: identity.display_name,
552553
picture_url: identity.picture.map(|picture| picture.as_str().to_owned()),
553554
return_to,

0 commit comments

Comments
 (0)