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
2 changes: 1 addition & 1 deletion app/src/auth/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result<Res

/// The organization by slug and the person's role there; a 404 when they aren't a member. Staff are no exception:
/// their tools are the admin MCP's, with its audit log, never the customer pages.
async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> {
pub(crate) async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> {
let user_id = user.id;
let row = db::query!(
"SELECT o.id, o.name, m.role FROM organizations o \
Expand Down
43 changes: 43 additions & 0 deletions app/src/auth/me.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub fn routes(route: &mut Router) {
route.get("/api/ui/me", me);
route.patch("/api/ui/me/notifications", update_notifications);
route.post("/api/ui/me/heard-about", heard_about);
route.post("/api/ui/requests", create_request);
route.put("/api/ui/orgs/{org}/billing-email", update_billing_email);
}

Expand Down Expand Up @@ -457,3 +458,45 @@ mod tests {
assert!(text.contains("Buildkite with Cypress"));
}
}

#[laravel::input]
#[validate(authenticated)]
pub struct RequestInput {
text: Option<String>,
}

/// `POST /api/ui/requests`, "What do you need from VisualCI?": kept as feedback of kind `request`, which emails the
/// team; they reply by email, to the address it returns.
pub async fn create_request(
Authenticated(user): Authenticated<User>,
Valid(p): Valid<RequestInput>,
) -> laravel::Result<Json<Value>> {
use crate::domain::feedback::{self, FeedbackError, Report, Sender};
let text = p.text.as_deref().unwrap_or_default().trim();
if text.is_empty() {
return Err(laravel::abort_with(422, "write what you need"));
}
let mut title: String = text.lines().next().unwrap_or(text).chars().take(120).collect();
if title.chars().count() < 3 {
title = format!("Request: {title}");
}
let report = Report {
title: Some(title),
kind: Some("request".into()),
description: Some(text.chars().take(4000).collect()),
source: Some("user".into()),
..Default::default()
};
let sender = Sender {
user_id: Some(user.id),
project_id: None,
account: format!("user:{}", user.id),
channel: "web",
client: None,
};
match feedback::record(sender, report).await {
Ok(_) => Ok(Json(json!({ "ok": true, "email": user.email }))),
Err(FeedbackError::Invalid(m) | FeedbackError::RateLimited(m)) => Err(laravel::abort_with(422, m)),
Err(FeedbackError::Server(e)) => Err(e),
}
}
96 changes: 95 additions & 1 deletion app/src/auth/orgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ use laravel::db;
use laravel::prelude::*;
use serde_json::{Value, json};

use crate::models::User;
use super::Role;
use crate::models::valid_slug;
use crate::models::{Build, Organization, User};

pub fn routes(route: &mut Router) {
route.post("/api/ui/orgs", create);
route.get("/api/ui/orgs/{org}", show);
route.get("/api/ui/org-exists/{slug}", exists);
}

/// Organizations someone may create in a day.
Expand Down Expand Up @@ -112,3 +115,94 @@ pub async fn create_org(user: &User, slug: &str, name: &str) -> laravel::Result<
}
Ok(slug)
}

/// `GET /api/ui/org-exists/{slug}`: whether an organization has the slug, for the new-organization form.
pub async fn exists(Params(slug): Params<String>) -> laravel::Result<Json<Value>> {
let found: Option<i64> = db::query!("SELECT id FROM organizations WHERE slug = {slug}").scalar().await?;
Ok(Json(json!({ "exists": found.is_some() })))
}

/// A build as the organization's page lists it: its project's newest.
fn build_summary(b: &Build) -> Value {
json!({
"number": b.number, "name": b.name, "branch": b.branch, "commit_sha": b.commit_sha, "pr_number": b.pr_number,
"mode": b.mode, "environment": b.environment,
"environment_info": crate::domain::builds::environment_info_for(b, true),
"state": b.state, "review_state": b.review_state, "conclusion": b.conclusion,
"stats": crate::domain::builds::stats(b), "created_at": b.created_at.to_string(),
})
}

/// This month's credits per project, with how much came from the open source pool, for the Usage tab.
async fn usage_by_project(org_id: i64) -> laravel::Result<Vec<Value>> {
let since = crate::domain::credits::month_start();
let rows = db::query!(
"SELECT p.slug, p.name, (p.open_source AND p.public AND NOT p.open_source_withdrawn) AS open_source, \
COALESCE(-SUM(t.amount), 0)::bigint AS credits, COALESCE(SUM(t.open_source_credits), 0)::bigint AS pool \
FROM projects p LEFT JOIN credit_transactions t ON t.project_id = p.id AND t.created_at >= {since} \
AND t.kind IN ('build', 'render', 'gallery') \
WHERE p.organization_id = {org_id} GROUP BY p.id ORDER BY credits DESC, p.slug"
)
.select()
.await?;
rows.iter()
.map(|r| {
Ok(json!({
"project": r.try_get::<String>("slug")?, "name": r.try_get::<String>("name")?,
"open_source": r.try_get::<bool>("open_source")?, "credits": r.try_get::<i64>("credits")?,
"open_source_credits": r.try_get::<i64>("pool")?,
}))
})
.collect()
}

/// `GET /api/ui/orgs/{org}`: the organization's page for a member: its projects with their newest build, the last 50
/// charges, this month's usage (in all and by project), its members, and for admins its billing email and pending
/// invitations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden.
pub async fn show(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
) -> laravel::Result<Json<Value>> {
let (org_id, _, role) = super::invitations::org_role(&user, &org).await?;
let org = Organization::find_or_fail(org_id).await?;
let admin = role == Role::Admin;
let projects: Vec<(i64, String, String)> =
db::query!("SELECT id, slug, name FROM projects WHERE organization_id = {org_id} ORDER BY slug")
.select()
.await?
.iter()
.map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?)))
.collect::<laravel::Result<_>>()?;
let mut list = Vec::new();
for (id, slug, name) in projects {
let last = crate::domain::builds::recent(id, None, false, 1).await?;
list.push(json!({ "slug": slug, "name": name, "last_build": last.first().map(build_summary) }));
}
let history: Vec<Value> = db::query!(
"SELECT -amount AS credits, kind, reference, \
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS created_at FROM credit_transactions \
WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50"
)
.select()
.await?
.iter()
.map(|r| {
Ok(json!({
"credits": r.try_get::<i64>("credits")?, "kind": r.try_get::<String>("kind")?,
"reference": r.try_get::<Option<String>>("reference")?,
"created_at": r.try_get::<String>("created_at")?,
}))
})
.collect::<laravel::Result<_>>()?;
let invitations = if admin { super::invitations::pending(org_id).await? } else { Vec::new() };
Ok(Json(json!({
"slug": org.slug, "name": org.name, "role": role.as_str(),
"usage": crate::domain::credits::usage(&org).await?,
"subscribed": org.stripe_subscription_id.is_some(),
"billing_email": if admin { org.billing_email.clone() } else { None },
"projects": list, "history": history, "usage_by_project": usage_by_project(org_id).await?,
"members": super::invitations::members_json(org_id, admin).await?, "invitations": invitations,
"setup": super::setup::state(org_id, Some(user.pid)).await?,
"gitlab_instances": [], "gitlab_instances_enabled": false,
})))
}
93 changes: 91 additions & 2 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use laravel::auth::Auth;
use laravel::auth::social::{self, Provider};
use laravel::config::app::Environment;
use laravel::db;
use laravel::model::create;
use laravel::prelude::*;
Expand Down Expand Up @@ -249,8 +250,96 @@ impl ForgeApps {
}

/// `GET /auth/providers`: the sign-in buttons the web app shows.
pub async fn providers(apps: laravel::config::Section<ForgeApps>) -> Json<serde_json::Value> {
Json(serde_json::json!({ "forges": apps.forges(), "dev_login": false }))
pub async fn providers(
apps: laravel::config::Section<ForgeApps>,
dev: laravel::config::Section<DevLogin>,
) -> Json<serde_json::Value> {
Json(serde_json::json!({ "forges": apps.forges(), "dev_login": dev.allowed() }))
}

/// Development and tests only: sign in as anyone by email (`DEV_LOGIN=true`), for local work and CI's screenshots.
/// Only where `APP_ENV` is `local` or `testing`: an unset `APP_ENV` is production, and so is a misspelt one here.
#[derive(Clone, Debug, laravel::config::Section)]
pub struct DevLogin {
#[env("DEV_LOGIN", default = false)]
pub enabled: bool,
}

/// Whether `env` is a development one (`local` or `testing`), where the development sign-in may run.
fn development(env: &Environment) -> bool {
matches!(env, Environment::Local | Environment::Testing)
}

impl DevLogin {
/// Whether the development sign-in is on here: the flag, in development.
#[must_use]
pub fn allowed(&self) -> bool {
self.enabled && development(&laravel::config().app.env)
}

/// Whether to register `POST /auth/dev-login` at all: only in development, with the flag on. Anywhere else the
/// route doesn't exist.
#[must_use]
pub fn routable(config: &laravel::config::Config) -> bool {
config.section::<Self>().enabled && development(&config.app.env)
}

/// Anything but development refuses to boot with `DEV_LOGIN` on: it would let anyone sign in as anyone.
///
/// # Errors
/// That.
pub fn check(&self, env: &Environment) -> laravel::Result<()> {
if self.enabled && !development(env) {
return Err(laravel::Error::msg(format!(
"DEV_LOGIN is on with APP_ENV={}: it lets anyone sign in as anyone, so it runs only in local or \
testing. Remove it from the environment.",
env.as_str()
)));
}
Ok(())
}
}

#[laravel::input]
#[validate(anyone)]
pub struct DevLoginInput {
#[validate(required, email)]
email: String,
}

/// `POST /auth/dev-login` (development and tests only, registered only when [`DevLogin::routable`]): signs in as the
/// user with this email, made if there's none (verified, and asked how they heard about VisualCI like any new
/// account). It checks [`DevLogin::allowed`] again itself.
pub async fn dev_login(
dev: laravel::config::Section<DevLogin>,
auth: Auth<User>,
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
Valid(p): Valid<DevLoginInput>,
) -> laravel::Result<laravel::http::Response> {
if !dev.allowed() {
return Err(laravel::abort(404));
}
let email = p.email.trim().to_lowercase();
let user = match User::query().filter(User::email.eq(&email)).first().await? {
Some(user) => user,
None => {
let name = email.split('@').next().unwrap_or("dev").to_string();
let user = create!(User {
pid: laravel::str::uuid7(),
name: name,
email: email.clone(),
email_verified_at: Some(laravel::now()),
staff: false,
})
.await?;
let user_id = user.id;
db::query!("UPDATE users SET heard_about_pending = true WHERE id = {user_id}").update().await?;
SignedUp { user_id, via: "dev".to_string() }.dispatch().await?;
user
}
};
auth.login(&user).await?;
Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, true)))
}

/// `POST /auth/logout`: the session ends, and so does the site's hint.
Expand Down
39 changes: 39 additions & 0 deletions app/src/auth/staff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub fn routes(route: &mut Router) {
route.get("/api/ui/staff/signups", signups);
route.get("/api/ui/staff/emails", emails);
route.post("/api/ui/staff/emails/{id}/resolve", resolve);
route.get("/api/ui/staff/feedback", feedback);
}

fn staff_only(user: &User) -> laravel::Result<()> {
Expand Down Expand Up @@ -128,3 +129,41 @@ pub async fn resolve(
}
Ok(Json(json!({ "id": id })))
}

#[laravel::query]
pub struct FeedbackQuery {
/// The next page: feedback older than this ID.
before: Option<i64>,
}

/// `GET /api/ui/staff/feedback`: customers' feedback, newest first, 100 at a time (`?before=<id>` for the next
/// page), with who sent it and whether someone handled it.
pub async fn feedback(
Authenticated(user): Authenticated<User>,
Query(q): Query<FeedbackQuery>,
) -> laravel::Result<Json<Value>> {
staff_only(&user)?;
let before = q.before;
let rows = db::query!(
"SELECT json_build_object('id', f.id, 'pid', f.pid::text, 'title', f.title, 'kind', f.kind, \
'description', f.description, 'impact', f.impact, 'task', f.task, 'tool', f.tool, 'error', f.error, \
'suggestion', f.suggestion, 'session', f.session, 'channel', f.channel, 'client', f.client, \
'request_ids', f.request_ids, 'agent', f.agent, \
'user', CASE WHEN u.id IS NULL THEN NULL ELSE json_build_object('email', u.email, 'name', u.name) END, \
'project', CASE WHEN p.id IS NULL THEN NULL ELSE o.slug || '/' || p.slug END, \
'created_at', to_char(f.created_at AT TIME ZONE 'UTC', {TIME}), \
'notified_at', to_char(f.notified_at AT TIME ZONE 'UTC', {TIME}), \
'handled_at', to_char(f.handled_at AT TIME ZONE 'UTC', {TIME}), \
'handled_by', h.email, 'handled_note', f.handled_note)::text AS j \
FROM feedback f LEFT JOIN users u ON u.id = f.user_id LEFT JOIN users h ON h.id = f.handled_by \
LEFT JOIN projects p ON p.id = f.project_id LEFT JOIN organizations o ON o.id = p.organization_id \
WHERE ({before}::bigint IS NULL OR f.id < {before}) ORDER BY f.id DESC LIMIT 100"
)
.select()
.await?;
let items = rows
.iter()
.map(|r| Ok(serde_json::from_str::<Value>(&r.try_get::<String>("j")?)?))
.collect::<laravel::Result<Vec<_>>>()?;
Ok(Json(json!({ "feedback": items })))
}
12 changes: 11 additions & 1 deletion app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pub fn configure() -> ApplicationBuilder {
http::hosts::check(config.section::<http::hosts::HostUrls>(), config.app.env.is_production())?;
billing::check(config.section::<billing::Stripe>(), config.app.env.is_production())?;
http::security::check(config, config.app.env.is_production())?;
config.section::<auth::sign_in::DevLogin>().check(&config.app.env)?;
Ok(())
})
.with_middleware(|middleware, _| {
Expand All @@ -61,10 +62,19 @@ pub fn configure() -> ApplicationBuilder {
// addresses (probes). `route_by_host` is the host check instead: each configured host reaches only its
// own paths, and in production any other host only `/up` and the renderers' paths.
middleware.trust_hosts(["*"]);
// The development sign-in (refused in production and unless DEV_LOGIN is on) is posted by CI's screenshot
// scripts, which send no Sec-Fetch-Site and hold no CSRF token yet
middleware.replace(laravel::http::middleware::PreventRequestForgery::new().except(["auth/dev-login"]));
// Outermost, so every response gets the security headers, the host check's 404s included
middleware.prepend(http::security::security_headers);
})
.with_routing(|routing, _| {
.with_routing(|routing, config| {
// The development sign-in exists only in local and testing, with DEV_LOGIN on
if auth::sign_in::DevLogin::routable(config) {
routing.web(|route| {
route.post("/auth/dev-login", auth::sign_in::dev_login);
});
}
routing
.web(auth::routes)
.api(http::api::routes)
Expand Down
33 changes: 33 additions & 0 deletions app/tests/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,36 @@ async fn every_response_carries_the_security_headers(app: Application) {
.assert_status(404)
.assert_header("x-frame-options", "DENY");
}

/// The development sign-in can't exist in production: production won't boot with DEV_LOGIN on, and without it the
/// route isn't there (a 404, not a refusal) and the providers don't offer it.
#[tokio::test(flavor = "multi_thread")]
async fn production_has_no_development_sign_in() {
let hosts = [
("VISUALCI_SITE_URL", "https://visualci.test"),
("VISUALCI_APP_URL", "https://app.visualci.test"),
("VISUALCI_API_URL", "https://api.visualci.test"),
("VISUALCI_MCP_URL", "https://mcp.visualci.test"),
("OAUTH_ISSUER", "https://mcp.visualci.test"),
("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"),
];
let flagged = in_production().with_envs(hosts).with_env("DEV_LOGIN", "true").create();
let refused = flagged.boot().await.expect_err("production doesn't boot with DEV_LOGIN on");
assert!(format!("{refused:?}").contains("DEV_LOGIN"), "{refused:?}");
// A misspelt environment counts as production: the development sign-in runs only in local and testing
let misspelt = in_production().with_envs(hosts).with_env("APP_ENV", "prod").with_env("DEV_LOGIN", "true").create();
let refused = misspelt.boot().await.expect_err("APP_ENV=prod doesn't boot with DEV_LOGIN on");
assert!(format!("{refused:?}").contains("APP_ENV=prod"), "{refused:?}");

let app = in_production().with_envs(hosts).create();
app.boot().await.expect("it boots");
let host = "app.visualci.test";
app.get("/auth/providers").header("host", host).await.assert_ok().assert_json_path("dev_login", false);
app.post("/auth/dev-login")
.header("host", host)
.header("sec-fetch-site", "same-origin")
.json(json!({ "email": "owner@visualci.test" }))
.await
// No such route: only the sign-in start, GET /auth/{forge}, matches the path
.assert_status(405);
}
Loading
Loading