Skip to content
Draft
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
1 change: 1 addition & 0 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ path = "src/main.rs"
laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] }
# The same axum Laravel Rust runs on, for extractors (auth::Principal)
axum = "0.8"
aes-gcm = "0.11"
base64 = "0.22"
hex = "0.4"
oauth-provider = "0.1.3"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use laravel::db::AnyTransaction;

/// Self-managed GitLab instances (ported as today's): an organization registers its instance's base URL and the OAuth
/// application its admin made there, the secret encrypted with `secrets::encrypt`. People sign in there (an identity's
/// `site` is the instance's base URL), and a project on it links with an access token, also encrypted.
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(
"CREATE TABLE gitlab_instances (
id BIGSERIAL PRIMARY KEY,
pid UUID NOT NULL UNIQUE,
organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
base_url TEXT NOT NULL,
client_id TEXT NOT NULL,
client_secret_enc TEXT NOT NULL,
created_by BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (organization_id, base_url)
);
CREATE INDEX gitlab_instances_base_url ON gitlab_instances (base_url);",
)
.unprepared()
.await?;
Ok(())
}
2 changes: 1 addition & 1 deletion app/src/auth/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role
}

/// The organization, when the person is an admin there: a member gets a 403, anyone else a 404.
async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> {
pub(crate) async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> {
let (id, name, role) = org_role(user, slug).await?;
if role < Role::Admin {
return Err(laravel::abort_with(403, format!("only admins can {action}")));
Expand Down
18 changes: 17 additions & 1 deletion app/src/auth/memberships.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,28 @@ pub async fn apply(
forge: ForgeKind,
site: &str,
repositories: &[(Repository, Permission)],
) -> laravel::Result<usize> {
apply_keeping(user_id, forge, site, repositories, &HashSet::new()).await
}

/// [`apply`], never removing the memberships of the organizations in `keep`: the hourly sync's, for organizations
/// with a linked repository the forge couldn't be asked about this time.
///
/// # Errors
/// On a database error.
pub async fn apply_keeping(
user_id: i64,
forge: ForgeKind,
site: &str,
repositories: &[(Repository, Permission)],
keep: &HashSet<i64>,
) -> laravel::Result<usize> {
let permissions: HashMap<String, Permission> =
repositories.iter().filter_map(|(r, p)| r.id.clone().map(|id| (id, *p))).collect();
let all = linked_projects(forge).await?;
let here: Vec<&LinkedProject> = all.iter().filter(|p| p.site == site).collect();
let elsewhere: HashSet<i64> = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect();
let mut elsewhere: HashSet<i64> = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect();
elsewhere.extend(keep);
let grants = grants_from(&here, &permissions);
let source = forge.as_str();

Expand Down
2 changes: 2 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ pub fn routes(route: &mut laravel::prelude::Router) {
me::routes(route);
device::routes(route);
staff::routes(route);
crate::forge::instances::routes(route);
crate::forge::gitlab_hooks::routes(route);
route.get("/auth/{forge}", sign_in::start);
route.post("/auth/{forge}/link", sign_in::link);
route.get("/auth/{forge}/callback", sign_in::callback);
Expand Down
74 changes: 64 additions & 10 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,35 @@ pub struct SignedIn {

const RETURN_TO: &str = "auth.return_to";
const LINKING: &str = "auth.linking";
/// A sign-in under way at a self-managed GitLab instance: social login's providers are fixed at boot, so these run
/// the OAuth code flow themselves (`forge::instances`).
const INSTANCE_LOGIN: &str = "auth.instance";

/// What the session keeps between going to an instance and coming back: the forge name the sign-in started at
/// (`gitlab-<instance id>`), so a state handed to one instance can't finish a sign-in at another, the state, and the
/// PKCE verifier.
#[derive(serde::Serialize, serde::Deserialize)]
struct InstanceLogin {
forge: String,
state: String,
verifier: String,
}

/// Off to a self-managed instance: the authorization URL, with the login remembered in the session.
fn instance_redirect(instance: &crate::models::GitlabInstance, forge: &str, session: &Session) -> String {
let login =
InstanceLogin { forge: forge.to_string(), state: laravel::str::random(40), verifier: laravel::str::random(64) };
let url = forge::instances::authorize_url(instance, &login.state, &login.verifier);
session.put(INSTANCE_LOGIN, login);
url
}

#[laravel::query]
pub struct CallbackQuery {
code: Option<String>,
state: Option<String>,
error: Option<String>,
}

#[laravel::query]
pub struct StartQuery {
Expand Down Expand Up @@ -85,15 +114,20 @@ pub async fn start(
Query(q): Query<StartQuery>,
session: Session,
) -> laravel::Result<Redirect> {
let provider = provider(&forge)?;
let instance = forge::instances::named(&forge).await?;
let provider = if instance.is_some() { None } else { Some(provider(&forge)?) };
match q.return_to.as_deref().and_then(safe_return) {
Some(to) => session.put(RETURN_TO, to),
None => {
let _: Option<String> = session.pull(RETURN_TO);
}
}
let _: Option<bool> = session.pull(LINKING);
social::redirect(provider)
match (instance, provider) {
(Some(instance), _) => Ok(Redirect::to(instance_redirect(&instance, &forge, &session))),
(None, Some(provider)) => social::redirect(provider),
(None, None) => Err(laravel::abort(404)),
}
}

/// `POST /auth/{forge}/link`: link another forge account to the signed-in user. A JSON POST, which a page on another
Expand All @@ -103,6 +137,10 @@ pub async fn link(
_user: laravel::auth::Authenticated<User>,
session: Session,
) -> laravel::Result<Json<serde_json::Value>> {
if let Some(instance) = forge::instances::named(&forge).await? {
session.put(LINKING, true);
return Ok(Json(serde_json::json!({ "url": instance_redirect(&instance, &forge, &session) })));
}
let provider = provider(&forge)?;
session.put(LINKING, true);
let redirect = laravel::http::Response::new(social::redirect(provider)?).into_http();
Expand All @@ -118,19 +156,35 @@ pub async fn callback(
gitlab: laravel::config::Section<forge::gitlab::GitlabConfig>,
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
session: Session,
Query(q): Query<CallbackQuery>,
) -> laravel::Result<laravel::http::Response> {
let provider = provider(&forge)?;
let instance = forge::instances::named(&forge).await?;
let provider = if instance.is_some() { None } else { Some(provider(&forge)?) };
let return_to: Option<String> = session.pull(RETURN_TO);
let linking: bool = session.pull(LINKING).unwrap_or(false);
let profile = match social::user(provider).await {
Ok(profile) => profile,
Err(social::Error::Denied) => {
return Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/"))));
let cancelled = || Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/"))));
let profile = match (&instance, provider) {
(Some(instance), _) => {
let login: Option<InstanceLogin> = session.pull(INSTANCE_LOGIN);
if q.error.is_some() {
return cancelled();
}
let login = login
.filter(|l| l.forge == forge && !l.state.is_empty() && q.state.as_deref() == Some(l.state.as_str()))
.ok_or_else(|| laravel::abort_with(400, "sign-in expired; try again"))?;
let code = q.code.as_deref().ok_or_else(|| laravel::abort_with(400, "sign-in expired; try again"))?;
forge::instances::profile(instance, code, &login.verifier).await?
}
Err(e) => return Err(e.into()),
(None, Some(provider)) => match social::user(provider).await {
Ok(profile) => profile,
Err(social::Error::Denied) => return cancelled(),
Err(e) => return Err(e.into()),
},
(None, None) => return Err(laravel::abort(404)),
};
let sign_in = match ForgeKind::parse(&forge) {
Some(ForgeKind::Gitlab) => forge::gitlab::sign_in(&gitlab.url, &profile).await?,
let sign_in = match (&instance, ForgeKind::parse(&forge)) {
(Some(instance), _) => forge::gitlab::sign_in(&instance.base_url, &profile).await?,
(None, Some(ForgeKind::Gitlab)) => forge::gitlab::sign_in(&gitlab.url, &profile).await?,
_ => forge::github::sign_in(&profile).await?,
};
let current = auth.user().await?;
Expand Down
93 changes: 80 additions & 13 deletions app/src/forge/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,25 @@ pub fn site_of(base: &str) -> String {
if base == "https://gitlab.com" { String::new() } else { base }
}

/// Every item of a paged API list, 100 a page, up to 50 pages.
/// The most a paged list may read in all, across its pages: an organization's own instance answers these.
const MAX_LIST_BYTES: usize = 16 * 1024 * 1024;

/// Every item of a paged API list, 100 a page, up to 50 pages and [`MAX_LIST_BYTES`] in all.
async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result<Vec<Value>> {
let mut items = Vec::new();
let mut read = 0;
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 url = format!("{}/api/v4{path}{sep}per_page=100&page={page}", base.trim_end_matches('/'));
let (status, body) = super::outbound::send(client::get(url).token(token).accept_json(), base).await?;
if !(200..300).contains(&status) {
return Err(laravel::Error::msg(format!("GitLab {path}: HTTP {status}")));
}
read += body.len();
if read > MAX_LIST_BYTES {
return Err(laravel::Error::msg(format!("GitLab {path}: more than {MAX_LIST_BYTES} bytes in all")));
}
let batch: Vec<Value> = response.json()?;
let batch: Vec<Value> = serde_json::from_str(&body).map_err(|e| laravel::Error::msg(e.to_string()))?;
let done = batch.len() < 100;
items.extend(batch);
if done {
Expand Down Expand Up @@ -179,15 +187,60 @@ fn project_id(path: &str) -> String {

/// GET an API path (`/projects/...`) as JSON; `None` on 404.
async fn get(base: &str, token: &str, path: &str) -> laravel::Result<Option<Value>> {
let base = base.trim_end_matches('/');
let response = client::get(format!("{base}/api/v4{path}")).token(token).accept_json().await?;
if response.status() == 404 {
return Ok(None);
let (status, body) = super::outbound::get_json(base, token, &format!("/api/v4{path}")).await?;
match status {
404 => Ok(None),
200..300 => Ok(Some(body)),
_ => Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {status}"))),
}
if !response.successful() {
return Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {}", response.status())));
}

/// A project's members, inherited ones included (a group's), by its ID.
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn members(base: &str, token: &str, project_id: &str) -> laravel::Result<Vec<Value>> {
all_pages(base, token, &format!("/projects/{project_id}/members/all")).await
}

/// Days until a personal access token expires (`None`: it never does).
///
/// # Errors
/// When the token is unknown to GitLab, revoked or already expired, or GitLab can't be reached.
pub async fn token_days_left(base: &str, token: &str) -> laravel::Result<Option<i64>> {
let me = get(base, token, "/personal_access_tokens/self")
.await?
.ok_or_else(|| laravel::Error::msg("it isn't known to GitLab"))?;
if me["active"] == false || me["revoked"] == true {
return Err(laravel::Error::msg("it's revoked or expired"));
}
Ok(Some(response.json()?))
let Some(expires) = me["expires_at"].as_str() else { return Ok(None) };
let day = days_since_epoch(expires).ok_or_else(|| laravel::Error::msg(format!("an expiry date {expires:?}")))?;
let today = laravel::now().timestamp().as_second().div_euclid(86_400);
Ok(Some(day - today))
}

/// Days from 1970-01-01 to a `YYYY-MM-DD` date (the proleptic Gregorian calendar).
fn days_since_epoch(date: &str) -> Option<i64> {
let mut parts = date.splitn(3, '-').map(str::parse::<i64>);
let (y, m, d) = (parts.next()?.ok()?, parts.next()?.ok()?, parts.next()?.ok()?);
if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some(era * 146_097 + doe - 719_468)
}

/// A project (`group/sub/project`, or its ID) with the licence GitLab detected; `None` when the token can't see it.
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn project_with_licence(base: &str, token: &str, path: &str) -> laravel::Result<Option<Value>> {
get(base, token, &format!("/projects/{}?license=true", project_id(path))).await
}

/// The bot's access level on a project (`group/sub/project`), when it's a member.
Expand Down Expand Up @@ -233,3 +286,17 @@ pub fn install_hint(base: &str, bot: &str, path: &str) -> String {
let base = base.trim_end_matches('/');
format!("invite @{bot} to {path} as a Developer ({base}/{path}/-/project_members), then link it")
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn counts_days_to_a_date() {
assert_eq!(days_since_epoch("1970-01-01"), Some(0));
assert_eq!(days_since_epoch("2000-03-01"), Some(11_017));
assert_eq!(days_since_epoch("2026-12-03"), Some(20_790));
assert_eq!(days_since_epoch("2026-13-01"), None);
assert_eq!(days_since_epoch("soon"), None);
}
}
Loading
Loading