Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ pub struct StartQuery {
fn provider(forge: &str) -> laravel::Result<Provider> {
match ForgeKind::parse(forge) {
Some(ForgeKind::Github) => Ok(Provider::GITHUB),
// GitLab sign-in comes with the GitLab provider (social login's custom providers)
_ => Err(laravel::abort(404)),
Some(ForgeKind::Gitlab) => Ok(Provider::from("gitlab")),
None => Err(laravel::abort(404)),
}
}

Expand Down Expand Up @@ -99,6 +99,7 @@ pub async fn callback(
Params(forge): Params<String>,
auth: Auth<User>,
sign_ups: laravel::config::Section<SignUps>,
gitlab: laravel::config::Section<forge::gitlab::GitlabConfig>,
session: Session,
) -> laravel::Result<laravel::http::Response> {
let provider = provider(&forge)?;
Expand All @@ -111,7 +112,10 @@ pub async fn callback(
}
Err(e) => return Err(e.into()),
};
let sign_in = forge::github::sign_in(&profile).await?;
let sign_in = match ForgeKind::parse(&forge) {
Some(ForgeKind::Gitlab) => forge::gitlab::sign_in(&gitlab.url, &profile).await?,
_ => forge::github::sign_in(&profile).await?,
};
let current = auth.user().await?;
let link_to = current.as_ref().filter(|_| linking);
let via = return_to.as_deref().and_then(mcp_client).map_or_else(|| "web".to_string(), |c| format!("mcp: {c}"));
Expand Down
158 changes: 158 additions & 0 deletions app/src/forge/gitlab.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
//! GitLab sign-in, ported from today's server: gitlab.com, or the one GitLab instance `VISUALCI_GITLAB_URL` names.
//! Laravel's social login runs the OAuth dance through [`Driver`]; [`sign_in`] then reads the projects the person can
//! reach and their access level on each. Self-managed instances that organizations register come later: their OAuth
//! applications are in the database, while social login's providers are fixed at boot.

use laravel::auth::social::{self, Email, Profile, Tokens};
use laravel::http::client;
use serde_json::Value;

use super::{ForgeKind, Identity, Permission, Repository, SignIn};

/// The GitLab VisualCI's own OAuth application is on (`VISUALCI_GITLAB_URL`, default gitlab.com). Its client ID and
/// secret are `GITLAB_CLIENT_ID` and `GITLAB_CLIENT_SECRET`, as social login reads them for the `gitlab` provider.
#[derive(Clone, Debug, laravel::config::Section)]
pub struct GitlabConfig {
#[env("VISUALCI_GITLAB_URL", default = "https://gitlab.com")]
pub url: String,
}

/// Social login's `gitlab` provider.
pub struct Driver {
pub url: String,
}

impl Driver {
fn base(&self) -> &str {
self.url.trim_end_matches('/')
}
}

impl social::Driver for Driver {
fn authorize_url(&self) -> String {
format!("{}/oauth/authorize", self.base())
}

fn token_url(&self) -> String {
format!("{}/oauth/token", self.base())
}

fn scopes(&self) -> &[&str] {
&["read_user", "read_api"]
}

async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
let user: Value = client::get(format!("{}/api/v4/user", self.base()))
.token(tokens.access_token())
.ensure_successful()
.await
.and_then(|response| response.json())
.map_err(|error| social::Error::Provider(error.to_string()))?;
// GitLab lists a person's addresses only once their account is confirmed, so the primary one counts then
let confirmed = !user["confirmed_at"].is_null();
Ok(Profile {
id: user["id"].as_i64().map(|i| i.to_string()).unwrap_or_default(),
name: user["name"].as_str().map(str::to_owned),
nickname: user["username"].as_str().map(str::to_owned),
email: user["email"].as_str().map(|address| Email { address: address.to_owned(), verified: confirmed }),
avatar: user["avatar_url"].as_str().map(str::to_owned),
raw: user,
})
}
}

/// Everything a GitLab sign-in learns, from the profile social login fetched and the person's token.
///
/// # Errors
/// When GitLab can't be reached or refuses.
pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result<SignIn> {
let base = base.trim_end_matches('/');
let raw = &profile.raw;
let confirmed = !raw["confirmed_at"].is_null();
let verified_emails = [raw["email"].as_str(), raw["commit_email"].as_str()]
.into_iter()
.flatten()
.filter(|_| confirmed)
.map(str::to_lowercase)
.fold(Vec::new(), |mut v, e| {
if !e.is_empty() && !v.contains(&e) {
v.push(e);
}
v
});
let mut repositories = Vec::new();
let token = profile.token.access.as_str();
for project in all_pages(base, token, "/projects?membership=true&min_access_level=20&simple=false").await? {
let repository = project["web_url"]
.as_str()
.and_then(Repository::parse_gitlab)
.filter(|r| r.site_url().eq_ignore_ascii_case(base));
if let (Some(repository), Some(permission)) = (repository, permission_from_level(level_of(&project))) {
repositories.push((repository.with_id(project["id"].as_i64().map(|i| i.to_string())), permission));
}
}
Ok(SignIn {
identity: Identity {
forge: ForgeKind::Gitlab,
id: profile.id.clone(),
login: raw["username"].as_str().unwrap_or_default().to_string(),
name: profile.name.clone(),
avatar_url: profile.avatar.clone(),
verified_emails,
site: site_of(base),
},
repositories,
})
}

/// An identity's `site`: empty for gitlab.com, whose confirmed addresses are trusted to match an account by email,
/// and the base URL for any other instance, whose addresses its own admins can set, so they never match an account
/// (`Identity::trusted_emails`).
#[must_use]
pub fn site_of(base: &str) -> String {
let base = base.trim().trim_end_matches('/').to_ascii_lowercase();
if base == "https://gitlab.com" { String::new() } else { base }
}

/// Every item of a paged API list, 100 a page, up to 50 pages.
async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result<Vec<Value>> {
let mut items = Vec::new();
for page in 1..=50 {
let sep = if path.contains('?') { '&' } else { '?' };
let response =
client::get(format!("{base}/api/v4{path}{sep}per_page=100&page={page}")).token(token).accept_json().await?;
if !response.successful() {
return Err(laravel::Error::msg(format!("GitLab {path}: HTTP {}", response.status())));
}
let batch: Vec<Value> = response.json()?;
let done = batch.len() < 100;
items.extend(batch);
if done {
break;
}
}
Ok(items)
}

/// GitLab's access level as a permission: Owner (50) → admin, Maintainer (40) → maintain, Developer (30) → write,
/// Reporter (20) → read. Guests, planners and minimal access get nothing.
#[must_use]
pub const fn permission_from_level(level: i64) -> Option<Permission> {
match level {
50.. => Some(Permission::Admin),
40..=49 => Some(Permission::Maintain),
30..=39 => Some(Permission::Write),
20..=29 => Some(Permission::Read),
_ => None,
}
}

/// The higher of a project's direct and group access levels.
fn level_of(project: &Value) -> i64 {
let p = &project["permissions"];
[&p["project_access"]["access_level"], &p["group_access"]["access_level"]]
.into_iter()
.filter_map(Value::as_i64)
.max()
.unwrap_or(0)
}
1 change: 1 addition & 0 deletions app/src/forge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! forge's API calls are in its own module.

pub mod github;
pub mod gitlab;

use crate::auth::Role;

Expand Down
5 changes: 5 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ pub fn configure() -> ApplicationBuilder {
.with_auth(|auth, _| {
auth.session::<models::Users>();
})
.with_services(|app| {
app.social().extend("gitlab", |config| forge::gitlab::Driver {
url: config.section::<forge::gitlab::GitlabConfig>().url.clone(),
});
})
.with_middleware(|middleware, _| {
middleware.prepend(http::hosts::route_by_host);
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const DEFAULT_PRECISION: u64 = 100;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const DEFAULT_ROUNDING_MODE: RoundingMode = RoundingMode::HalfEven;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const EXPONENTIAL_FORMAT_LEADING_ZERO_THRESHOLD: usize = 5;
const EXPONENTIAL_FORMAT_TRAILING_ZERO_THRESHOLD: usize = 15;
const FMT_MAX_INTEGER_PADDING: usize = 1000;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const SERDE_SCALE_LIMIT: i64 = 150000;

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions app/target/debug/build/serde-07b13cbb0fd598fc/out/private.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#[doc(hidden)]
pub mod __private229 {
#[doc(hidden)]
pub use crate::private::*;
}
use serde_core::__private229 as serde_core_private;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[doc(hidden)]
pub mod __private229 {
#[doc(hidden)]
pub use crate::private::*;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[doc(hidden)]
pub mod __private21 {
#[doc(hidden)]
pub use crate::private::*;
}
62 changes: 62 additions & 0 deletions app/tests/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,65 @@ async fn signing_out_from_another_site_is_refused(app: Application) -> laravel::
app.post("/auth/logout").with_cookies_from(&signed_in).header("sec-fetch-site", "same-origin").await.assert_ok();
Ok(())
}

#[laravel::test]
async fn gitlab_sign_in_reads_a_confirmed_address_and_the_projects(app: Application) -> laravel::Result<()> {
let _gitlab = client::fake().with(
"gitlab.com/api/v4/projects*",
json!([
{ "id": 5, "web_url": "https://gitlab.com/acme/web", "permissions": { "project_access": { "access_level": 30 } } },
{ "id": 6, "web_url": "https://gitlab.com/acme/guest", "permissions": { "project_access": { "access_level": 10 } } },
]),
);
let _social = social::fake().with(
"gitlab",
social::User::fake("gl-7").name("Grace Hopper").raw(json!({
"username": "grace", "email": "Grace@Example.com", "confirmed_at": "2020-01-01T00:00:00Z",
})),
);
app.get("/auth/gitlab/callback").await.assert_redirect_to("/");
let user = User::first_where(User::email.eq("grace@example.com")).await?.expect("an account");
let user_id = user.id;
let login: Option<String> =
db::query!("SELECT login FROM identities WHERE forge = 'gitlab' AND user_id = {user_id}").scalar().await?;
assert_eq!(login.as_deref(), Some("grace"));
Ok(())
}

#[laravel::test]
async fn an_unconfirmed_gitlab_address_matches_no_account(app: Application) -> laravel::Result<()> {
let _gitlab = client::fake().with("gitlab.com/api/v4/projects*", json!([]));
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
let _social = social::fake().with(
"gitlab",
social::User::fake("gl-8").name("Not Ada").raw(json!({ "username": "notada", "email": "ada@example.com" })),
);
app.get("/auth/gitlab/callback").await.assert_redirect_to("/");
let ada_id = ada.id;
let linked: Option<i64> = db::query!("SELECT count(*) FROM identities WHERE user_id = {ada_id}").scalar().await?;
assert_eq!(linked, Some(0), "an address GitLab hasn't confirmed never signs in as its owner");
Ok(())
}

fn self_managed() -> Application {
app::testing::configure().with_env("VISUALCI_GITLAB_URL", "https://gitlab.example.com").create()
}

#[laravel::test(app = self_managed)]
async fn a_self_managed_gitlabs_addresses_match_no_account(app: Application) -> laravel::Result<()> {
let _gitlab = client::fake().with("gitlab.example.com/api/v4/projects*", json!([]));
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
let _social = social::fake().with(
"gitlab",
social::User::fake("gl-9").name("Not Ada").raw(json!({
"username": "notada", "email": "ada@example.com", "confirmed_at": "2020-01-01T00:00:00Z",
})),
);
app.get("/auth/gitlab/callback").await.assert_redirect_to("/");
let ada_id = ada.id;
let linked: Option<i64> = db::query!("SELECT count(*) FROM identities WHERE user_id = {ada_id}").scalar().await?;
assert_eq!(linked, Some(0), "its admins can set any address");
let site: Option<String> = db::query!("SELECT site FROM identities WHERE forge_user_id = 'gl-9'").scalar().await?;
assert_eq!(site.as_deref(), Some("https://gitlab.example.com"));
Ok(())
}
Loading