Skip to content

Commit fefe129

Browse files
committed
Sign-in, review fixes: the site's signed-in hint (vci_signed_in, plain and readable by its script, on the site's domain) is set at sign-in, renewed or cleared by /auth/session and cleared at logout, as today's; /auth/providers and /login offer a forge only when its OAuth application has its ID and its secret
1 parent c388ce7 commit fefe129

3 files changed

Lines changed: 131 additions & 17 deletions

File tree

‎app/src/auth/sign_in.rs‎

Lines changed: 86 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,16 @@ fn safe_return(to: &str) -> Option<String> {
6666
/// `GET /login`: where a page that needs a signed-in person (an MCP client's consent page) sends someone who isn't,
6767
/// and where they come back from afterwards (sign-in returns to the page they were sent from). One line per forge.
6868
#[laravel::auth::page(login)]
69-
pub async fn login_page() -> laravel::http::Response {
70-
let page = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
69+
pub async fn login_page(apps: laravel::config::Section<ForgeApps>) -> laravel::http::Response {
70+
let forges = apps.forges();
71+
let gitlab =
72+
if forges.contains(&"gitlab") { "<p><a href=\"/auth/gitlab\">Sign in with GitLab</a></p>" } else { "" };
73+
let head = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
7174
content=\"width=device-width, initial-scale=1\"><title>Sign in · VisualCI</title><style>body{font:16px/1.5 \
7275
system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;color:#1a1a1a;\
7376
background:#fff}@media (prefers-color-scheme:dark){body{color:#eee;background:#111}a{color:#9cf}}\
74-
p{margin:0 0 8px}</style></head><body><main><p><a href=\"/auth/github\">Sign in with GitHub</a></p>\
75-
<p><a href=\"/auth/gitlab\">Sign in with GitLab</a></p></main></body></html>";
77+
p{margin:0 0 8px}</style></head><body><main><p><a href=\"/auth/github\">Sign in with GitHub</a></p>";
78+
let page = format!("{head}{gitlab}</main></body></html>");
7679
laravel::http::Response::new(laravel::view::Html::raw(page))
7780
}
7881

@@ -113,6 +116,7 @@ pub async fn callback(
113116
auth: Auth<User>,
114117
sign_ups: laravel::config::Section<SignUps>,
115118
gitlab: laravel::config::Section<forge::gitlab::GitlabConfig>,
119+
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
116120
session: Session,
117121
) -> laravel::Result<laravel::http::Response> {
118122
let provider = provider(&forge)?;
@@ -158,7 +162,7 @@ pub async fn callback(
158162
// needs a route for its fallback)
159163
None => Redirect::to(session.pull::<String>("url.intended").unwrap_or_else(|| "/".to_string())),
160164
};
161-
Ok(laravel::http::Response::new(back))
165+
Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true)))
162166
}
163167

164168
/// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of
@@ -170,7 +174,20 @@ pub async fn session(
170174
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
171175
headers: axum::http::HeaderMap,
172176
) -> laravel::Result<laravel::http::Response> {
173-
let body = match auth.user().await? {
177+
let user = auth.user().await?;
178+
// The site's hint follows the answer: renewed while signed in, cleared once the session has gone.
179+
let hinted = headers
180+
.get_all(axum::http::header::COOKIE)
181+
.iter()
182+
.filter_map(|v| v.to_str().ok())
183+
.flat_map(|v| v.split(';'))
184+
.any(|c| c.trim() == format!("{SIGNED_IN_HINT}=1"));
185+
let hint = match (&user, hinted) {
186+
(Some(_), _) => Some(signed_in_hint(&hosts, true)),
187+
(None, true) => Some(signed_in_hint(&hosts, false)),
188+
(None, false) => None,
189+
};
190+
let body = match user {
174191
Some(user) => {
175192
let user_id = user.id;
176193
let orgs = db::query!(
@@ -188,6 +205,9 @@ pub async fn session(
188205
let mut response = laravel::http::Response::new(Json(body))
189206
.with_header("cache-control", "no-store")
190207
.with_header("vary", "Origin, Cookie");
208+
if let Some(hint) = hint {
209+
response = response.with_cookie(hint);
210+
}
191211
let site = hosts.site.as_deref().map(|s| s.trim_end_matches('/').to_string());
192212
if let (Some(origin), Some(site)) = (headers.get(axum::http::header::ORIGIN).and_then(|o| o.to_str().ok()), site)
193213
&& origin == site
@@ -204,26 +224,75 @@ pub async fn session(
204224
pub struct ForgeApps {
205225
#[env("GITHUB_CLIENT_ID")]
206226
pub github: Option<String>,
227+
#[env("GITHUB_CLIENT_SECRET")]
228+
pub github_secret: Option<String>,
207229
#[env("GITLAB_CLIENT_ID")]
208230
pub gitlab: Option<String>,
231+
#[env("GITLAB_CLIENT_SECRET")]
232+
pub gitlab_secret: Option<String>,
233+
}
234+
235+
impl ForgeApps {
236+
/// The forges whose OAuth application has both its ID and its secret.
237+
#[must_use]
238+
pub fn forges(&self) -> Vec<&'static str> {
239+
let set = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.trim().is_empty());
240+
let mut forges = Vec::new();
241+
if set(&self.github) && set(&self.github_secret) {
242+
forges.push("github");
243+
}
244+
if set(&self.gitlab) && set(&self.gitlab_secret) {
245+
forges.push("gitlab");
246+
}
247+
forges
248+
}
209249
}
210250

211251
/// `GET /auth/providers`: the sign-in buttons the web app shows.
212252
pub async fn providers(apps: laravel::config::Section<ForgeApps>) -> Json<serde_json::Value> {
213-
let mut forges = Vec::new();
214-
if apps.github.as_deref().is_some_and(|s| !s.is_empty()) {
215-
forges.push("github");
216-
}
217-
if apps.gitlab.as_deref().is_some_and(|s| !s.is_empty()) {
218-
forges.push("gitlab");
219-
}
220-
Json(serde_json::json!({ "forges": forges, "dev_login": false }))
253+
Json(serde_json::json!({ "forges": apps.forges(), "dev_login": false }))
221254
}
222255

223-
/// `POST /auth/logout`.
224-
pub async fn logout(auth: Auth<User>) -> laravel::Result<Json<serde_json::Value>> {
256+
/// `POST /auth/logout`: the session ends, and so does the site's hint.
257+
pub async fn logout(
258+
auth: Auth<User>,
259+
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
260+
) -> laravel::Result<laravel::http::Response> {
225261
auth.logout().await?;
226-
Ok(Json(serde_json::json!({ "ok": true })))
262+
Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, false)))
263+
}
264+
265+
/// The cookie visualci.com's static pages read to show "Open app" instead of "Sign in": `1` while signed in. It says
266+
/// nothing else, so it's readable by the site's script (not `HttpOnly`) and not encrypted (`EncryptCookies` passes it
267+
/// through). On the site's domain when the app is one of its subdomains (`Domain=visualci.com`), host-only otherwise.
268+
pub const SIGNED_IN_HINT: &str = "vci_signed_in";
269+
/// How long the hint lasts: today's session's 30 days, renewed by every `/auth/session`.
270+
const HINT_DAYS: i64 = 30;
271+
272+
/// The hint, set (`on`) or cleared.
273+
pub fn signed_in_hint(hosts: &crate::http::hosts::HostUrls, on: bool) -> laravel::cookie::Cookie {
274+
use laravel::time::ToSpan;
275+
let host = |url: &Option<String>| {
276+
let url = url.as_deref()?.trim();
277+
let rest = url.split_once("://").map_or(url, |(_, r)| r);
278+
let host = rest.split(['/', ':']).next()?.to_ascii_lowercase();
279+
(!host.is_empty()).then_some(host)
280+
};
281+
let domain = match (host(&hosts.site), host(&hosts.app)) {
282+
(Some(site), Some(app)) if app.ends_with(&format!(".{site}")) => Some(site),
283+
_ => None,
284+
};
285+
let production = laravel::config().app.env.is_production();
286+
let mut cookie = laravel::cookie::Cookie::new(SIGNED_IN_HINT, if on { "1" } else { "" })
287+
.path("/")
288+
.http_only(false)
289+
.secure(production)
290+
.same_site(laravel::cookie::SameSite::Lax)
291+
.max_age(if on { HINT_DAYS.days() } else { 0.seconds() });
292+
if let Some(domain) = domain {
293+
cookie = cookie.domain(domain);
294+
}
295+
cookie
227296
}
228297

229298
/// The MCP client an authorization's return address names (`/oauth/authorize?client_id=…`).

‎app/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ pub fn configure() -> ApplicationBuilder {
3939
})
4040
.with_middleware(|middleware, _| {
4141
middleware.prepend(http::hosts::route_by_host);
42+
// The site's signed-in hint is read by its script: plain, not encrypted
43+
middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT]));
4244
})
4345
.with_routing(|routing, _| {
4446
routing.web(auth::routes).api(http::api::routes).health("/up");

‎app/tests/sign_in.rs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ async fn a_new_person_gets_an_account_and_returns_where_they_started(app: Applic
4545
start.assert_redirect();
4646
let done = app.get("/auth/github/callback").with_cookies_from(&start).await;
4747
done.assert_redirect_to("/acme/web/builds/3");
48+
// The site's hint: plain, so its script can read it
49+
done.assert_cookie("vci_signed_in", "1");
4850

4951
let user = User::first_where(User::email.eq("ada@example.com")).await?.expect("an account");
5052
assert_eq!(user.name, "Ada Lovelace");
@@ -242,3 +244,44 @@ fn with_github() -> Application {
242244
async fn providers_are_the_configured_forges(app: Application) {
243245
app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": ["github"], "dev_login": false }));
244246
}
247+
248+
fn with_site_and_app() -> Application {
249+
app::testing::configure()
250+
.with_envs([("VISUALCI_SITE_URL", "https://visualci.test"), ("VISUALCI_APP_URL", "https://app.visualci.test")])
251+
.create()
252+
}
253+
254+
#[laravel::test(app = with_site_and_app)]
255+
async fn the_sites_hint_follows_the_session(app: Application) -> laravel::Result<()> {
256+
// A hint left over from a session that has gone is cleared; no hint and no session sends none.
257+
app.get("/auth/session").cookie("vci_signed_in", "1").await.assert_ok().assert_cookie_expired("vci_signed_in");
258+
app.get("/auth/session").await.assert_ok().assert_cookie_missing("vci_signed_in");
259+
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
260+
let renewed = app.get("/auth/session").acting_as(&ada).await;
261+
renewed.assert_ok().assert_cookie("vci_signed_in", "1");
262+
assert!(
263+
renewed
264+
.headers()
265+
.get_all("set-cookie")
266+
.iter()
267+
.any(|v| v.to_str().unwrap_or("").contains("Domain=visualci.test")),
268+
"shared with the site's domain"
269+
);
270+
app.post("/auth/logout")
271+
.acting_as(&ada)
272+
.header("sec-fetch-site", "same-origin")
273+
.await
274+
.assert_ok()
275+
.assert_cookie_expired("vci_signed_in");
276+
Ok(())
277+
}
278+
279+
fn with_github_id_only() -> Application {
280+
app::testing::configure().with_envs([("GITHUB_CLIENT_ID", "id"), ("GITLAB_CLIENT_ID", "id")]).create()
281+
}
282+
283+
#[laravel::test(app = with_github_id_only)]
284+
async fn a_forge_without_its_secret_is_not_offered(app: Application) {
285+
app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": [], "dev_login": false }));
286+
app.get("/login").await.assert_ok().assert_dont_see("GitLab");
287+
}

0 commit comments

Comments
 (0)