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
421 changes: 391 additions & 30 deletions app/Cargo.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,13 @@ path = "src/main.rs"
[dependencies]
# Pinned exactly: each 0.x minor of Laravel Rust may break, and upgrades are deliberate.
laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] }
# The same axum Laravel Rust runs on, for extractors (auth::Principal)
axum = "0.8"
hex = "0.4"
oauth-provider-laravel = { version = "0.1", features = ["postgres"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

[dev-dependencies]
Expand Down
10 changes: 9 additions & 1 deletion app/database/migrations/0001_01_01_000000_create_users_table.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
use laravel::db::AnyTransaction;

/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab): `password` stays empty, and the
/// forge accounts are in `identities`.
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("users", |table| {
table.id();
table.uuid("pid").unique();
table.string("name");
table.string("email").unique();
table.timestamp("email_verified_at").nullable();
table.string("password");
table.string("password").default("");
table.remember_token();
table.text("avatar_url").nullable();
// VisualCI's own team: the admin MCP endpoint and staff pages
table.boolean("staff").default(false);
// How they signed up ("github", "github, from an MCP client's sign-in"), for the team's sign-up notice
table.text("signup_via").nullable();
table.timestamps();
})
.await?;
Expand Down
63 changes: 63 additions & 0 deletions app/database/migrations/2026_12_03_000100_create_auth_tables.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use laravel::db::AnyTransaction;

/// Forge accounts, personal and project tokens, and the waitlist (sc-8900, the auth side). `project_tokens.project_id`
/// gets its foreign key once the domain tables exist.
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("identities", |table| {
table.id();
table.foreign_id("user_id").constrained().cascade_on_delete();
// "github" or "gitlab"; `site` is a self-managed GitLab's host, empty for gitlab.com and GitHub
table.string("forge");
table.string("site").default("");
table.string("forge_user_id");
table.string("login");
table.timestamps();
table.unique(["forge", "site", "forge_user_id"]);
})
.await?;

// Personal access tokens (`vcu_…`): whatever their user can do, in every organization they belong to
tx.schema()
.create("user_tokens", |table| {
table.id();
table.foreign_id("user_id").constrained().cascade_on_delete();
table.string("name");
// SHA-256 of the token, hex; the token itself is shown once
table.string("token_hash").unique();
table.string("token_prefix");
table.timestamp("last_used_at").nullable();
table.timestamps();
})
.await?;

// Project tokens (`vci_…`): CI's, for one project
tx.schema()
.create("project_tokens", |table| {
table.id();
table.big_integer("project_id").index();
table.string("name");
table.string("token_hash").unique();
table.string("token_prefix");
table.timestamp("last_used_at").nullable();
table.timestamps();
})
.await?;

// Closed sign-ups: someone new who signs in is written here instead of getting an account
tx.schema()
.create("waitlist", |table| {
table.id();
table.string("forge");
table.string("site").default("");
table.string("forge_user_id");
table.string("login");
table.text("name").nullable();
table.text("email").nullable();
// "web", or "mcp: <client name>"
table.text("source");
table.timestamps();
table.unique(["forge", "site", "forge_user_id"]);
})
.await
}
238 changes: 236 additions & 2 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,236 @@
//! Who a request acts for (owned by `visualci subdomains`, sc-8900): `Principal`, a user or a project token, with its
//! access checks. A placeholder until the auth stub lands.
//! Who a request acts for (owned by `visualci subdomains`, sc-8900): a [`Principal`], a person or a project token,
//! with the access checks every API, MCP and web handler uses.
//!
//! A handler takes `Principal` like any extractor. It's found, in order, from:
//! 1. the signed-in user: the session on web routes, or the OAuth token on MCP routes (behind `Authenticate::via`
//! with oauth-provider-laravel's guard, which also names the client, see [`Client`]);
//! 2. a bearer token: a personal token (`vcu_…`) acts as its user, a project token (`vci_…`) for its project.
//!
//! Nobody found: `401`.

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use laravel::auth::Auth;
use laravel::db;

use crate::models::{ProjectToken, User, UserToken, token_hash};

/// What someone may do in a project's organization, lowest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
/// Sees builds and snapshots; changes nothing.
Read,
/// Everything a build needs: uploads, review and approval.
Member,
/// Also settings, projects, tokens, billing and members.
Admin,
}

impl Role {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Read => "read",
Self::Member => "member",
Self::Admin => "admin",
}
}

#[must_use]
pub fn parse(s: &str) -> Option<Self> {
match s {
"read" => Some(Self::Read),
"member" => Some(Self::Member),
"admin" => Some(Self::Admin),
_ => None,
}
}
}

/// Anything that belongs to a project: the domain's `Project` model implements it (and builds or snapshots can, by
/// their project), so the checks here don't depend on those models.
pub trait InProject {
fn project_id(&self) -> i64;
fn organization_id(&self) -> i64;
}

/// A project as the checks need it, for callers that only have the IDs.
#[derive(Clone, Copy, Debug)]
pub struct ProjectRef {
pub id: i64,
pub organization_id: i64,
}

impl InProject for ProjectRef {
fn project_id(&self) -> i64 {
self.id
}
fn organization_id(&self) -> i64 {
self.organization_id
}
}

/// Who a request acts for.
#[derive(Clone, Debug)]
pub enum Principal {
/// A person: signed in, through an MCP client's OAuth token, or with a personal token.
User { user: Box<User>, via: Via },
/// A project token: CI, for one project.
Project { project_id: i64, token_id: i64, token_name: String },
}

/// How a person's request reached us.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Via {
/// The web app's session.
Session,
/// An MCP (or other OAuth) client they approved.
OAuth { client_id: String },
/// One of their personal tokens.
Token { token_id: i64, name: String },
}

/// What acted, for attributing a review or an upload (`reviews.source`, `client_id`, `token_name`): "Claude Code for
/// Ada", "a project token (CI)". The client's display name is looked up from `client_id` by whoever shows it.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Client {
/// `web`, `mcp`, `token` (a personal token) or `project_token`.
pub source: &'static str,
pub client_id: Option<String>,
pub token_name: Option<String>,
}

impl Principal {
/// The person, when it's one.
#[must_use]
pub fn user(&self) -> Option<&User> {
match self {
Self::User { user, .. } => Some(user),
Self::Project { .. } => None,
}
}

/// What acted.
#[must_use]
pub fn client(&self) -> Client {
match self {
Self::User { via: Via::Session, .. } => Client { source: "web", client_id: None, token_name: None },
Self::User { via: Via::OAuth { client_id }, .. } => {
Client { source: "mcp", client_id: Some(client_id.clone()), token_name: None }
}
Self::User { via: Via::Token { name, .. }, .. } => {
Client { source: "token", client_id: None, token_name: Some(name.clone()) }
}
Self::Project { token_name, .. } => {
Client { source: "project_token", client_id: None, token_name: Some(token_name.clone()) }
}
}
}

/// Their role in the project's organization, or `None` when they have none. A project token is a member of its
/// own project and nothing else.
///
/// # Errors
/// On a database error.
pub async fn role_in(&self, project: &impl InProject) -> laravel::Result<Option<Role>> {
match self {
Self::Project { project_id, .. } => Ok((*project_id == project.project_id()).then_some(Role::Member)),
Self::User { user, .. } => {
let (org, user_id) = (project.organization_id(), user.id);
let role: Option<String> =
db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {user_id}")
.scalar()
.await?;
Ok(role.as_deref().and_then(Role::parse))
}
}
}

/// Whether they have at least `role` in the project.
///
/// # Errors
/// On a database error.
pub async fn can(&self, role: Role, project: &impl InProject) -> laravel::Result<bool> {
Ok(self.role_in(project).await?.is_some_and(|r| r >= role))
}

/// The IDs of the projects they can see: every project of their organizations, or a project token's own.
///
/// # Errors
/// On a database error.
pub async fn project_ids_visible(&self) -> laravel::Result<Vec<i64>> {
match self {
Self::Project { project_id, .. } => Ok(vec![*project_id]),
Self::User { user, .. } => {
let user_id = user.id;
db::query!(
"SELECT p.id FROM projects p JOIN memberships m ON m.organization_id = p.organization_id \
WHERE m.user_id = {user_id} ORDER BY p.id"
)
.select_as::<i64>()
.await
}
}
}

/// The principal a request's bearer token names, if it names one.
///
/// # Errors
/// On a database error.
pub async fn from_token(token: &str) -> laravel::Result<Option<Self>> {
let hash = token_hash(token);
if token.starts_with("vci_") {
let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) };
return Ok(Some(Self::Project { project_id: t.project_id, token_id: t.id, token_name: t.name }));
}
if token.starts_with("vcu_") {
let Some(t) = UserToken::first_where(UserToken::token_hash.eq(&hash)).await? else { return Ok(None) };
let Some(user) = User::find(t.user_id).await? else { return Ok(None) };
return Ok(Some(Self::User { user: Box::new(user), via: Via::Token { token_id: t.id, name: t.name } }));
}
Ok(None)
}
}

impl laravel::auth::Authorizable for Principal {}

impl<S: Send + Sync> FromRequestParts<S> for Principal {
type Rejection = laravel::Error;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// The session's user, or the OAuth token's behind Authenticate::via (a route without a session or guard has
// no user here)
if let Ok(auth) = <Auth<User> as FromRequestParts<S>>::from_request_parts(parts, state).await
&& let Some(user) = auth.user().await?
{
let via = match parts.extensions.get::<oauth_provider_laravel::Grant>() {
Some(grant) => Via::OAuth { client_id: grant.client_id().to_string() },
None => Via::Session,
};
return Ok(Self::User { user: Box::new(user), via });
}
let bearer = parts
.headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::trim);
if let Some(token) = bearer
&& let Some(principal) = Self::from_token(token).await?
{
return Ok(principal);
}
Err(laravel::abort(401))
}
}

/// `GET /api/v1/whoami`: who the request acts for, and how.
pub async fn whoami(principal: Principal) -> laravel::Result<axum::Json<serde_json::Value>> {
let client = principal.client();
let who = match &principal {
Principal::User { user, .. } => serde_json::json!({ "kind": "user", "id": user.pid, "name": user.name }),
Principal::Project { project_id, .. } => serde_json::json!({ "kind": "project", "project_id": project_id }),
};
Ok(axum::Json(serde_json::json!({ "principal": who, "client": client })))
}
1 change: 1 addition & 0 deletions app/src/http/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ pub fn routes(route: &mut Router) {
route.get("/v1/version", async || {
Json(json!({ "visualci": env!("CARGO_PKG_VERSION"), "laravel": laravel::VERSION }))
});
route.get("/v1/whoami", crate::auth::whoami);
route.fallback(async || laravel::abort(404));
}
11 changes: 7 additions & 4 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ use laravel::Application;
use laravel::foundation::ApplicationBuilder;

pub fn configure() -> ApplicationBuilder {
Application::configure().with_migrations(laravel::db::migrations!("database/migrations")).with_routing(
|routing, _| {
Application::configure()
.with_migrations(laravel::db::migrations!("database/migrations"))
.with_auth(|auth, _| {
auth.session::<laravel::model::Users<models::User>>();
})
.with_routing(|routing, _| {
routing.api(http::api::routes).health("/up");
},
)
})
}
8 changes: 7 additions & 1 deletion app/src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
//! Models.
//! Models. The auth side's (users, tokens) are `visualci subdomains`'; the domain's are `visualci features'` (sc-8900).

mod tokens;
mod user;

pub use tokens::{ProjectToken, UserToken, token_hash};
pub use user::User;
Loading
Loading