Skip to content

Commit e70bfe9

Browse files
authored
fix(auth): the consent page says who is asking and who is answering
An app any account registers got a consent page with only its name, so an app named "Piquel Settings" or "Google" looked first-party. The consent page now names the host the app sends the browser back to, labels an app an account registered as unverified with its owner's handle, and names the signed-in account with a way to switch. Accounts can no longer name an app after Piquel or another well-known brand, look-alikes included; operators still can. offline_access reads "Access your account while you're away". Closes #273
1 parent cccbbf9 commit e70bfe9

14 files changed

Lines changed: 304 additions & 67 deletions

File tree

‎README.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -524,8 +524,9 @@ Accounts can also register clients for their own applications in the developer
524524
console, at `auth.piquel.fr/developers`: see
525525
[Managing your own OIDC clients](docs/guides/client-management.md).
526526
Auth generates their IDs and limits their scopes to `openid`, `profile`, `email`
527-
and `offline_access`; they are never trusted, and an account can have 10 and
528-
register 20 a day. They never appear in other accounts' consoles, while
527+
and `offline_access`; they are never trusted, their names cannot contain Piquel's
528+
or another well-known brand (`RESERVED_BRANDS` in `piquel_common::clients`), and
529+
an account can have 10 and register 20 a day. They never appear in other accounts' consoles, while
529530
`client list` shows every client. Owners can disable and enable their clients;
530531
`client suspend` disables one so that its owner cannot enable it until
531532
`client unsuspend`, which leaves it disabled. Deleting a client, from either side, disables it, revokes its
@@ -591,7 +592,10 @@ intended for the configured client audience. Only requested claims are released;
591592
passkey-only accounts have no email claim. Browser clients should keep tokens in
592593
memory and use SSO again after reload. Refresh permission is off unless explicitly
593594
enabled and `offline_access` is allowed/requested. Consent is remembered per user,
594-
client and scope; explicitly trusted clients bypass consent. Users see the apps
595+
client and scope; explicitly trusted clients bypass consent. The consent page
596+
names the host the app sends the browser back to and the signed-in account, which
597+
can switch to another, and labels an app an account registered as unverified,
598+
with its owner's handle. Users see the apps
595599
they consented to, or whose refresh grants still work, under Connected apps in
596600
settings (`/settings/apps`), and remove an app's access there: its refresh grants
597601
end, it asks for consent again, and its outstanding codes stop working. Access

‎apps/auth-service/src/clients/owned.rs‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
//! under, and the [`AccountService`] operations that apply it, for the owner
33
//! only. The policy lives in the input types rather than in callers: an owner
44
//! never chooses a client's ID, which auth generates, or its trust, so its
5-
//! clients always show the consent screen, and scopes are limited to the standard
6-
//! [`Scope`]s. [`OperatorSettings`] validate the same settings for an operator,
7-
//! who also chooses any scope and a client's trust.
5+
//! clients always show the consent screen, scopes are limited to the standard
6+
//! [`Scope`]s, and names to those without a reserved brand. [`OperatorSettings`]
7+
//! validate the same settings for an operator, who also chooses any scope, any
8+
//! name and a client's trust.
89
910
use super::{ClientRegistry, ClientRegistryError, MAX_DAILY_REGISTRATIONS, MAX_OWNED_CLIENTS};
1011
use crate::{
@@ -157,7 +158,8 @@ pub(crate) struct InvalidSetting {
157158
impl ClientSettings {
158159
/// Validates every setting, naming the first one that is invalid, and builds
159160
/// the registration of an untrusted client `id` of `kind`. Each URI is a
160-
/// [`RedirectUri`], as the `client` command parses it.
161+
/// [`RedirectUri`], as the `client` command parses it, and the name must not
162+
/// contain a reserved brand, which only operators' clients use.
161163
fn registration(
162164
self,
163165
id: ClientId,
@@ -176,7 +178,12 @@ impl ClientSettings {
176178
})
177179
})
178180
.collect::<Result<Vec<_>, _>>()?;
179-
self.validated(id, kind, scopes, false)
181+
let registration = self.validated(id, kind, scopes, false)?;
182+
registration
183+
.display_name
184+
.ensure_unreserved()
185+
.map_err(InvalidSetting::with(ClientField::DisplayName))?;
186+
Ok(registration)
180187
}
181188

182189
/// Validates every setting but the scopes, already `scopes`, and builds the

‎apps/auth-service/src/clients/tests/owners.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,9 @@ async fn confirmations_never_reach_owners_found_before_them() {
155155
}
156156

157157
/// An invalid setting names its field apart from what is wrong with it, so a
158-
/// form can show the message beside it: owners grant only the standard scopes
159-
/// and send browsers only to URIs auth accepts. Settings are checked before
158+
/// form can show the message beside it: owners grant only the standard scopes,
159+
/// send browsers only to URIs auth accepts and name no client after a reserved
160+
/// brand. Settings are checked before
160161
/// anything else, so an unconfirmed owner's invalid registration is refused for
161162
/// its settings rather than for the confirmation.
162163
#[tokio::test]
@@ -211,6 +212,13 @@ async fn invalid_settings_name_their_field_first() {
211212
},
212213
ClientField::DisplayName,
213214
),
215+
(
216+
ClientPatch {
217+
display_name: Some("Piquel Settings".into()),
218+
..ClientPatch::default()
219+
},
220+
ClientField::DisplayName,
221+
),
214222
] {
215223
let changed = account.service.update_client(&client, patch).await;
216224
invalid(changed.map(drop), field);

‎apps/auth-service/src/oidc/authorize/consent.rs‎

Lines changed: 54 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ use crate::{
77
AUTHORIZATION_CODE_MINUTES, OAuthCode, OAuthError, OidcApplication, OpaqueToken, Reject,
88
TokenPrefix,
99
},
10-
security::{RequestContext, Session},
10+
security::{RequestContext, Session, SessionError},
1111
};
1212
use axum::http::HeaderMap;
1313
use chrono::{Duration, Utc};
14-
use piquel_common::events::DomainEvent;
14+
use piquel_common::{Handle, UserId, events::DomainEvent};
1515
use piquel_repository::{
1616
DatabaseTransaction, InsertAuthorizationCode, SessionAuthentication,
17-
StoredAuthorizationRequest, StoredSession,
17+
StoredAuthorizationRequest, StoredOidcClient, StoredSession,
1818
};
1919
use serde::Deserialize;
2020
use url::Url;
@@ -35,6 +35,18 @@ impl AuthorizationDecision {
3535
}
3636
}
3737

38+
/// A pending authorization as the consent page shows it: who asks, and who would
39+
/// answer.
40+
pub(crate) struct ConsentRequest {
41+
/// The request.
42+
pub(crate) request: StoredAuthorizationRequest,
43+
/// The handle of the account that registered the client, which nobody
44+
/// verified; `None` for a client operators registered.
45+
pub(crate) registered_by: Option<Handle>,
46+
/// The handle of the account the browser is signed in to, which would approve.
47+
pub(crate) account: Handle,
48+
}
49+
3850
/// Consent choice posted by the consent page.
3951
#[derive(Debug, Deserialize, PartialEq, Eq)]
4052
#[serde(rename_all = "snake_case")]
@@ -51,16 +63,51 @@ pub(super) enum ConsentDecision {
5163

5264
impl OidcApplication {
5365
/// The pending authorization the consent page shows, once the browser's session
54-
/// meets its requirements.
66+
/// meets its requirements, with who registered its client and who is signed in.
5567
pub(crate) async fn consent(
5668
&self,
5769
headers: &HeaderMap,
5870
transaction: &str,
59-
) -> Result<StoredAuthorizationRequest, OAuthError> {
71+
) -> Result<ConsentRequest, OAuthError> {
6072
let session = Session::required(&self.database, headers).await?;
6173
let request = self.find_authorization_request(transaction).await?;
6274
Self::require_authorization_session(&request, &session)?;
63-
Ok(request)
75+
let registered_by = match self.client(&request).await?.owner_id {
76+
Some(owner) => Some(self.handle(owner).await?.ok_or_else(Self::unregistered)?),
77+
None => None,
78+
};
79+
let account = self
80+
.handle(session.user_id)
81+
.await?
82+
.ok_or(SessionError::Missing)?;
83+
Ok(ConsentRequest {
84+
request,
85+
registered_by,
86+
account,
87+
})
88+
}
89+
90+
/// The current handle of account `user`, or `None` once it is purged.
91+
async fn handle(&self, user: UserId) -> Result<Option<Handle>, OAuthError> {
92+
let user = self.database.users().find_by_id(user).await?;
93+
Ok(user.map(|user| user.handle))
94+
}
95+
96+
/// The client `request` is for, as it is registered now.
97+
async fn client(
98+
&self,
99+
request: &StoredAuthorizationRequest,
100+
) -> Result<StoredOidcClient, OAuthError> {
101+
self.database
102+
.oidc()
103+
.find_client(request.client_id.as_str())
104+
.await?
105+
.ok_or_else(Self::unregistered)
106+
}
107+
108+
/// Refuses a request whose client, or its owner, is gone since it was found.
109+
fn unregistered() -> OAuthError {
110+
OAuthCode::InvalidRequest.reject("the client is no longer registered")
64111
}
65112

66113
/// Consumes the pending authorization and returns the client redirect: an error
@@ -176,15 +223,7 @@ impl OidcApplication {
176223
if request.interaction.forces_consent() {
177224
return Ok(false);
178225
}
179-
let client = self
180-
.database
181-
.oidc()
182-
.find_client(request.client_id.as_str())
183-
.await?
184-
.ok_or_else(|| {
185-
OAuthCode::InvalidRequest.reject("the client is no longer registered")
186-
})?;
187-
Ok(client.trusted
226+
Ok(self.client(request).await?.trusted
188227
|| self
189228
.database
190229
.oidc()

‎apps/auth-service/src/web/auth/oidc.rs‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::{
66
oidc::{AuthorizationDecision, LogoutQuery, OAuthError, TransactionQuery},
77
routes,
88
};
9+
use piquel_common::Handle;
910
use piquel_ui::{LoginQuery, Query, Title};
1011
use std::slice;
1112
use topcoat::{
@@ -17,22 +18,29 @@ use topcoat::{
1718
use url::Url;
1819

1920
impl WebApplication {
20-
/// `GET /authorize?transaction=…`: what the application asks to receive, and the
21+
/// `GET /authorize?transaction=…`: what the application asks to receive, where
22+
/// it sends the browser, who registered it and who is signed in, and the
2123
/// buttons deciding on it.
2224
pub(in crate::web) async fn consent(cx: &Cx) -> Result<Response, Failure> {
2325
let web = app_context::<Self>(cx);
2426
let TransactionQuery { transaction } = Self::query(cx)?;
25-
let request = web
27+
let consent = web
2628
.oidc
2729
.consent(headers(cx), &transaction)
2830
.await
2931
.map_err(|error| Failure::signing_in(error, &transaction))?;
30-
let redirect = Url::parse(&request.redirect_uri).map_err(OAuthError::from)?;
32+
let redirect = Url::parse(&consent.request.redirect_uri).map_err(OAuthError::from)?;
33+
let host = redirect.host_str().unwrap_or_default().to_owned();
34+
let sign_in = LoginQuery::continuing(&transaction).on(routes::page::LOGIN)?;
3135
let page = view! { cx =>
3236
piquel_ui::consent(
33-
client: &request.client_display_name,
34-
scopes: &request.scopes,
37+
client: &consent.request.client_display_name,
38+
host: &host,
39+
registered_by: consent.registered_by.as_ref().map(Handle::as_str),
40+
account: consent.account.as_str(),
41+
scopes: &consent.request.scopes,
3542
action: routes::page::CONSENT,
43+
sign_in: &sign_in,
3644
transaction: &transaction,
3745
)
3846
};
@@ -101,11 +109,7 @@ impl Failure {
101109
/// Explains `error` with a link to sign in again, which then continues the
102110
/// pending authorization `transaction`.
103111
fn signing_in(error: OAuthError, transaction: &str) -> Self {
104-
let query = LoginQuery {
105-
transaction: Some(transaction.to_owned()),
106-
..LoginQuery::default()
107-
};
108-
match query.on(routes::page::LOGIN) {
112+
match LoginQuery::continuing(transaction).on(routes::page::LOGIN) {
109113
Ok(sign_in) => Self::Explained {
110114
error,
111115
link: Some(("Sign in again", sign_in)),

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

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::{
1313
},
1414
security::BrowserCookie,
1515
tests::{
16-
Browser, OWN_PAGE, Replicas, WEB_ORIGIN, cookie, html, location, parameter, policy,
16+
Browser, OWN_PAGE, Replicas, WEB_ORIGIN, change, cookie, html, location, parameter, policy,
1717
redirect, register, registration,
1818
},
1919
};
@@ -24,7 +24,7 @@ use axum::{
2424
};
2525
use piquel_common::{
2626
ClientId,
27-
clients::{ClientKind, ClientRegistration},
27+
clients::{ClientKind, ClientOwner, ClientRegistration},
2828
};
2929
use piquel_ui::{DeviceChange, Section};
3030
use serde::Serialize;
@@ -210,7 +210,8 @@ fn account_pages(app: &ClientId) -> Vec<(String, Section)> {
210210
settings.into_iter().chain(console).chain(app).collect()
211211
}
212212

213-
/// The consent page shows what the application asks for. Its form decides once, and
213+
/// The consent page shows what the application asks for, and nothing about who
214+
/// registered one operators manage. Its form decides once, and
214215
/// only from auth's own pages and within the body limit; its policy lets the form
215216
/// redirect to the application.
216217
#[tokio::test]
@@ -237,6 +238,7 @@ async fn consent_page_decides_from_its_own_form() {
237238
),
238239
"{html}"
239240
);
241+
assert!(!html.contains("Unverified"), "{html}");
240242

241243
let transaction = parameter(&page, "transaction");
242244
let approve = [
@@ -281,6 +283,54 @@ async fn consent_page_decides_from_its_own_form() {
281283
assert_eq!(replayed.status(), StatusCode::BAD_REQUEST);
282284
}
283285

286+
/// An app an account registered says so on its consent page: where it sends the
287+
/// browser, who registered it and that nobody verified it, beside the account
288+
/// signed in, which can switch to another one and come back to the authorization.
289+
#[tokio::test]
290+
#[ignore = "requires TEST_DATABASE_URL"]
291+
async fn consent_page_says_who_asks_and_who_answers() {
292+
let database = Replicas::database().await;
293+
let owner = Browser::new_account(&database).await;
294+
let client = registration(ClientKind::Public, "https://notes.example");
295+
change(&database, async |registry| {
296+
registry
297+
.create(ClientOwner::Account(owner.user_id), &client, None)
298+
.await
299+
})
300+
.await
301+
.expect("client");
302+
let harness = Harness {
303+
browser: Browser::new_account(&database).await,
304+
replicas: Replicas::new().await,
305+
client,
306+
};
307+
let handle = async |browser: &Browser| {
308+
let user = database.users().find_by_id(browser.user_id).await;
309+
user.expect("lookup").expect("account").handle
310+
};
311+
let page = harness.consent_page().await;
312+
let html = html(harness.follow(&page).await).await;
313+
for shown in [
314+
"You’ll be sent to <strong>notes.example</strong>".to_owned(),
315+
format!("Unverified app, registered by @{}", handle(&owner).await),
316+
format!("Signed in as @{}.", handle(&harness.browser).await),
317+
] {
318+
assert!(html.contains(&shown), "{shown}: {html}");
319+
}
320+
321+
let query = value_after(&html, &format!(r#"action="{}?"#, routes::page::LOGIN));
322+
let sign_in = format!("{}?{query}", routes::page::LOGIN);
323+
assert_eq!(
324+
query,
325+
format!("transaction={}", parameter(&page, "transaction"))
326+
);
327+
let switched = harness
328+
.submit(&sign_in, &[("action", "switch_account")], OWN_PAGE)
329+
.await;
330+
assert_eq!(switched.status(), StatusCode::SEE_OTHER);
331+
assert_eq!(redirect(&switched), sign_in);
332+
}
333+
284334
/// No Content-Security-Policy can name a native application's loopback callback, or
285335
/// a host with characters host sources lack, so the consent form may post only to
286336
/// auth, then links on to the callback rather than redirecting, which the browser

0 commit comments

Comments
 (0)