From 7fb0b88d1748ab54b185b33fcbcb0a8e6e60803d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 05:21:21 +1300 Subject: [PATCH] app/: one typed config read from VISUALCI_ variables, with generated docs and warnings for unknown ones (sc-9026) Every setting app/ reads is now declared once in app/src/config.rs, a struct derived with the new crates/envschema (typed settings from prefixed environment variables). Its doc comments, types, defaults and required / required-in-production / secret flags drive loading, boot checks, secret masking in logs, warnings for unknown VISUALCI_ variables (naming the closest known one) and the generated docs: the new self-hosting/environment-variables page and app/.env.example, checked by a test. App-owned settings that had other names now start with VISUALCI_ (S3_*, RENDERER_*, METRICS_TOKEN, GITHUB_APP_*, GITHUB_WEBHOOK_SECRET, STRIPE_*, POSTMARK_SERVER_TOKEN, MAIL_*, DEV_LOGIN, TRUSTED_PROXIES, DB_ACQUIRE_TIMEOUT, DB_APPLICATION_NAME). Laravel Rust's and the OAuth server's variables keep their names. --- Cargo.lock | 18 + app/.env.example | 319 +++++++ app/Cargo.toml | 4 + app/src/auth/device.rs | 8 +- app/src/auth/installations.rs | 3 +- app/src/auth/me.rs | 47 +- app/src/auth/oauth.rs | 2 +- app/src/auth/sign_in.rs | 94 +-- app/src/auth/staff.rs | 6 +- app/src/billing/mod.rs | 38 +- app/src/billing/routes.rs | 17 +- app/src/billing/webhook.rs | 3 +- app/src/config.rs | 682 +++++++++++++-- app/src/console/demo.rs | 2 +- app/src/console/mod.rs | 2 +- app/src/console/retention.rs | 4 +- app/src/forge/github_app.rs | 51 +- app/src/forge/gitlab.rs | 20 - app/src/forge/installations.rs | 3 +- app/src/forge/link.rs | 13 +- app/src/forge/open_source.rs | 3 +- app/src/forge/outbound.rs | 14 +- app/src/forge/report.rs | 11 +- app/src/forge/sync.rs | 10 +- app/src/forge/webhooks.rs | 3 +- app/src/heartbeat.rs | 56 +- app/src/http/api/builds.rs | 2 +- app/src/http/app_shell.rs | 3 +- app/src/http/gallery.rs | 2 +- app/src/http/hosts.rs | 20 +- app/src/http/mod.rs | 2 +- app/src/http/security.rs | 10 +- app/src/http/ui/projects.rs | 2 +- app/src/lib.rs | 39 +- app/src/live.rs | 20 +- app/src/mcp/mod.rs | 8 +- app/src/notify/outbox.rs | 16 +- app/src/notify/postmark.rs | 28 +- app/src/testing.rs | 18 +- app/tests/billing.rs | 12 +- app/tests/emails.rs | 4 +- app/tests/forge_reports.rs | 14 +- app/tests/forge_sync.rs | 2 +- app/tests/hosts.rs | 74 +- app/tests/installations.rs | 10 +- app/tests/link.rs | 4 +- app/tests/mcp.rs | 4 +- app/tests/oauth.rs | 2 +- app/tests/proxies.rs | 2 +- app/tests/sign_in.rs | 4 +- app/tests/ui.rs | 4 +- app/tests/webhooks.rs | 12 +- crates/envschema-derive/Cargo.toml | 16 + crates/envschema-derive/src/lib.rs | 310 +++++++ crates/envschema/Cargo.toml | 14 + crates/envschema/src/lib.rs | 784 ++++++++++++++++++ crates/envschema/tests/settings.rs | 177 ++++ docker/app.Dockerfile | 2 +- docs/deploy.md | 28 +- docs/design.md | 7 + frontend/content/docs/self-hosting.md | 17 +- .../self-hosting/environment-variables.md | 207 +++++ frontend/src/docs/nav.ts | 2 +- frontend/vite.config.ts | 4 +- scripts/ci/visual.sh | 22 +- scripts/journeys/run.sh | 22 +- 66 files changed, 2815 insertions(+), 548 deletions(-) create mode 100644 app/.env.example create mode 100644 crates/envschema-derive/Cargo.toml create mode 100644 crates/envschema-derive/src/lib.rs create mode 100644 crates/envschema/Cargo.toml create mode 100644 crates/envschema/src/lib.rs create mode 100644 crates/envschema/tests/settings.rs create mode 100644 frontend/content/docs/self-hosting/environment-variables.md diff --git a/Cargo.lock b/Cargo.lock index 795d640f..d7e8d5f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -988,6 +988,22 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "envschema" +version = "0.1.0" +dependencies = [ + "envschema-derive", +] + +[[package]] +name = "envschema-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -4976,6 +4992,7 @@ version = "0.0.0" dependencies = [ "axum", "base64 0.22.1", + "envschema", "globset", "hex", "hmac 0.12.1", @@ -4999,6 +5016,7 @@ dependencies = [ "tokio", "tower", "tracing", + "tracing-subscriber", "url", "visualci-core", ] diff --git a/app/.env.example b/app/.env.example new file mode 100644 index 00000000..c9dd52a2 --- /dev/null +++ b/app/.env.example @@ -0,0 +1,319 @@ +# VisualCI's server: every environment variable it reads. Generated from app/src/config.rs (run app/'s tests with +# VISUALCI_GOLDEN_UPDATE=1); the reference is https://visualci.com/docs/self-hosting/environment-variables/ + +###################################################################################################################### +# Blob storage +###################################################################################################################### + +# Required. The store's S3 endpoint. Example: https://.r2.cloudflarestorage.com. +VISUALCI_S3_ENDPOINT=https://.r2.cloudflarestorage.com + +# The endpoint browsers and the CLI upload to and download from, when it differs from the one the server uses (a store +# the server reaches on a cluster-internal address). Images in the web app's Content-Security-Policy come from here +# too. +# VISUALCI_S3_PUBLIC_ENDPOINT= + +# Required. The bucket. +VISUALCI_S3_BUCKET= + +# The bucket's region. R2 takes auto. +# VISUALCI_S3_REGION=auto + +# Required. Secret. The access key's ID. +VISUALCI_S3_ACCESS_KEY_ID= + +# Required. Secret. The access key's secret. +VISUALCI_S3_SECRET_ACCESS_KEY= + +###################################################################################################################### +# Renderers +###################################################################################################################### + +# Required. Secret. The token every renderer sends: the same value as the renderers' own VISUALCI_RENDERER_TOKEN. +VISUALCI_RENDERER_TOKEN= + +# Required. The renderer version documents are drawn with: part of every render's cache key, and what a renderer's +# claim must match exactly. The image sets it from docker/renderer.version; don't set it yourself. +VISUALCI_RENDERER_VERSION= + +# Secret. The token for /internal/renderer/metrics (Prometheus). Never give it to the renderers. Empty turns the +# endpoint off: no token matches it. +# VISUALCI_METRICS_TOKEN= + +###################################################################################################################### +# Hosts +###################################################################################################################### + +# The marketing site's address. Signed-out visitors to the app's front page go there. Example: https://visualci.com. +# VISUALCI_SITE_URL=https://visualci.com + +# The web app's address, also used for the links in emails (http://localhost when unset). Example: +# https://app.visualci.com. +# VISUALCI_APP_URL=https://app.visualci.com + +# The API's address, where the CLI and CI send builds. The CLI's own VISUALCI_API_URL names the same address. Example: +# https://api.visualci.com. +# VISUALCI_API_URL=https://api.visualci.com + +# The MCP server's address, where coding agents connect, and the OAuth issuer (OAUTH_ISSUER must match it). Example: +# https://mcp.visualci.com. +# VISUALCI_MCP_URL=https://mcp.visualci.com + +###################################################################################################################### +# Network and database +###################################################################################################################### + +# The proxies in front of the app whose X-Forwarded-For is believed, as addresses or CIDR ranges. Behind them, a +# request's address is the nearest one that isn't a trusted proxy. Never include addresses untrusted code can send +# from, such as the renderers'. +# VISUALCI_TRUSTED_PROXIES=10.0.0.0/8 + +# More host names the MCP endpoint answers for, besides the configured hosts, the app's address and localhost (DNS +# rebinding protection). For a development server reached by another name. +# VISUALCI_MCP_HOSTS= + +# How long, in seconds, a request waits for a pooled database connection before it fails with a 503 and Retry-After, +# rather than hanging while the queue grows. +# VISUALCI_DB_ACQUIRE_TIMEOUT=5 + +# The application_name of this process's database connections, in Postgres's metrics and pg_stat_activity, such as +# visualci-web or visualci-worker. Letters, digits, dashes and underscores, at most 63 characters; anything else is +# ignored. +# VISUALCI_DB_APPLICATION_NAME= + +###################################################################################################################### +# Sign-ups +###################################################################################################################### + +# Required in production. true keeps sign-ups closed: someone new goes on the waitlist instead of getting an account. +# Production must set it either way, so a dropped setting never opens sign-ups by surprise; elsewhere they're open +# unless it's set. +VISUALCI_WAITLIST= + +###################################################################################################################### +# Development sign-in +###################################################################################################################### + +# Lets anyone sign in as anyone by email, for local work and CI's screenshots. Only where APP_ENV is local or testing: +# anywhere else the app refuses to start with it on. +# VISUALCI_DEV_LOGIN=false + +###################################################################################################################### +# GitHub App +###################################################################################################################### + +# Required in production. The App's ID. +VISUALCI_GITHUB_APP_ID= + +# Required in production. Secret. The App's private key: its PEM file, base64-encoded to fit on one line. +VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64= + +# Required in production. Secret. The App's webhook secret. Without it, the webhook (/webhooks/github) answers 404. +VISUALCI_GITHUB_WEBHOOK_SECRET= + +###################################################################################################################### +# GitLab +###################################################################################################################### + +# The GitLab VisualCI's OAuth application and bot are on. +# VISUALCI_GITLAB_URL=https://gitlab.com + +# Secret. The bot's personal access token, with the api scope: access checks, commit statuses and merge request notes. +# VISUALCI_GITLAB_BOT_TOKEN= + +# The bot's username, for telling people whom to invite. +# VISUALCI_GITLAB_BOT_USERNAME=visualci + +# Lets requests to an organization's server reach private addresses. Development only, for a local GitLab. +# VISUALCI_FORGE_PRIVATE_ADDRESSES=false + +###################################################################################################################### +# Email +###################################################################################################################### + +# Required in production. Secret. The Postmark server's API token. +VISUALCI_POSTMARK_SERVER_TOKEN= + +# Who emails come from. +# VISUALCI_MAIL_FROM="VisualCI " + +# Where replies go. +# VISUALCI_MAIL_REPLY_TO=support@visualci.com + +###################################################################################################################### +# Team +###################################################################################################################### + +# Where new sign-ups and feedback are sent. +# VISUALCI_TEAM_EMAIL=support@visualci.com + +###################################################################################################################### +# Payments +###################################################################################################################### + +# Required in production. Secret. Stripe's secret or restricted key: a live one (sk_live_, rk_live_) in production. +VISUALCI_STRIPE_SECRET_KEY= + +# Required in production. Secret. The webhook's signing secret. Stripe's endpoint is /webhooks/stripe on the API host. +VISUALCI_STRIPE_WEBHOOK_SECRET= + +###################################################################################################################### +# Cloudflare +###################################################################################################################### + +# The zone the gallery's URLs are served from. +# VISUALCI_CLOUDFLARE_ZONE_ID= + +# Secret. An API token that may purge that zone's cache. +# VISUALCI_CLOUDFLARE_PURGE_TOKEN= + +###################################################################################################################### +# Gallery +###################################################################################################################### + +# The most gallery credits one project is charged in a day: images past it are served free. +# VISUALCI_GALLERY_DAILY_CREDITS=50000 + +###################################################################################################################### +# Heartbeats +###################################################################################################################### + +# Email delivery (the worker, every five minutes). +# VISUALCI_EMAILS_HEARTBEAT_URL= + +# Secret. Email delivery's token. +# VISUALCI_EMAILS_HEARTBEAT_TOKEN= + +# Sign-up notices to the team. +# VISUALCI_SIGNUPS_HEARTBEAT_URL= + +# Secret. Sign-up notices' token. +# VISUALCI_SIGNUPS_HEARTBEAT_TOKEN= + +# The live-update check (every minute): a notification reaches each process's listener. +# VISUALCI_LIVE_HEARTBEAT_URL= + +# Secret. The live-update check's token. +# VISUALCI_LIVE_HEARTBEAT_TOKEN= + +# Pruning expired device sign-ins. +# VISUALCI_DEVICE_PRUNE_HEARTBEAT_URL= + +# Secret. Device sign-in pruning's token. +# VISUALCI_DEVICE_PRUNE_HEARTBEAT_TOKEN= + +# Syncing access from GitHub (the hourly recheck). +# VISUALCI_FORGE_SYNC_HEARTBEAT_URL= + +# Secret. Forge access sync's token. +# VISUALCI_FORGE_SYNC_HEARTBEAT_TOKEN= + +# Image retention (daily). +# VISUALCI_RETENTION_HEARTBEAT_URL= + +# Secret. Image retention's token. +# VISUALCI_RETENTION_HEARTBEAT_TOKEN= + +# The demo organization's daily reset. +# VISUALCI_DEMO_HEARTBEAT_URL= + +# Secret. The demo reset's token. +# VISUALCI_DEMO_HEARTBEAT_TOKEN= + +# The sweep of abandoned builds (every five minutes). +# VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL= + +# Secret. The builds sweep's token. +# VISUALCI_BUILDS_EXPIRE_HEARTBEAT_TOKEN= + +# The daily check of snapshot groups. +# VISUALCI_GROUPS_CHECK_HEARTBEAT_URL= + +# Secret. The groups check's token. +# VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN= + +###################################################################################################################### +# Laravel Rust +###################################################################################################################### + +# production, local or testing. The image sets production. +# APP_ENV=production + +# Required in production. Secret. Laravel's encryption key for sessions and cookies: 32 random characters. A new key +# signs everyone out. +APP_KEY= + +# The server's address, for URLs the framework builds. On one host, the only address you set. Example: +# https://visualci.example.com. +# APP_URL=https://visualci.example.com + +# Where the app's files are (public/, storage/). The image sets /app. +# APP_BASE_PATH= + +# The address the web server listens on. The image sets 0.0.0.0. +# SERVER_HOST= + +# The web server's port. The image sets 5150. +# SERVER_PORT= + +# Where logs go. The image sets stderr. +# LOG_CHANNEL= + +# Secret. The Postgres URL, with its credentials. Example: postgres://visualci:secret@db:5432/visualci. +# DATABASE_URL=postgres://visualci:secret@db:5432/visualci + +# pgsql. +# DB_CONNECTION=pgsql + +# The most database connections each process holds. Keep the sum across processes within Postgres's limit. +# DB_MAX_CONNECTIONS=10 + +# database: the cache in Postgres, shared by every process. +# CACHE_STORE= + +# database: sign-in sessions in Postgres, shared by every process. +# SESSION_DRIVER= + +# database: the job queue in Postgres, worked by queue:work. +# QUEUE_CONNECTION= + +# Required in production. The GitHub App's OAuth client ID, for signing in with GitHub. +GITHUB_CLIENT_ID= + +# Required in production. Secret. The GitHub App's OAuth client secret. +GITHUB_CLIENT_SECRET= + +# The GitLab OAuth application's ID, for signing in with GitLab. +# GITLAB_CLIENT_ID= + +# Secret. The GitLab OAuth application's secret. +# GITLAB_CLIENT_SECRET= + +###################################################################################################################### +# OAuth for MCP clients +###################################################################################################################### + +# The OAuth issuer: VISUALCI_MCP_URL. With the four hosts set, production refuses to start when it differs. Example: +# https://mcp.visualci.com. +# OAUTH_ISSUER=https://mcp.visualci.com + +# The consent page: /oauth/authorize on VISUALCI_APP_URL, checked like OAUTH_ISSUER. Example: +# https://app.visualci.com/oauth/authorize. +# OAUTH_AUTHORIZATION_ENDPOINT=https://app.visualci.com/oauth/authorize + +###################################################################################################################### +# Development and tests +###################################################################################################################### + +# Stands in for the clock in credit allowances (RFC 3339), for screenshots of seeded data. +# VISUALCI_NOW= + +# The tests' Postgres (each test borrows a copy of it). Default: CI's, +# postgres://visualci:visualci@127.0.0.1:55433/visualci_app_test. +# VISUALCI_APP_TEST_DATABASE_URL= + +# A folder the email tests write each email's HTML to, for review. +# VISUALCI_EMAIL_SNAPSHOTS= + +# 1 makes the tests write their golden files (this page among them) instead of comparing. +# VISUALCI_GOLDEN_UPDATE= diff --git a/app/Cargo.toml b/app/Cargo.toml index 4fc33d50..8afa4694 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -45,11 +45,15 @@ rmcp = { version = "3.12", features = ["server", "transport-streamable-http-serv tower = { version = "0.5", features = ["util"] } url = "2" regex = "1" +# Typed settings from VISUALCI_ variables, with their docs (config.rs) +envschema = { path = "../crates/envschema" } # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core", features = ["bundle"] } snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] regex = "1" +# Capturing logs in config.rs's tests +tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] } # A GitHub App key made at test time, so no private key is committed rsa = { version = "0.9", features = ["pem"] } diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs index b914b479..c3f0b8dd 100644 --- a/app/src/auth/device.rs +++ b/app/src/auth/device.rs @@ -18,8 +18,8 @@ use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; use serde_json::{Value, json}; +use crate::config::HostUrls; use crate::models::{User, token_hash}; -use crate::notify::outbox::AppUrl; use crate::notify::{self, Kind, To}; /// The CLI's side, on the `api` group: no session, no CSRF. @@ -104,7 +104,7 @@ pub struct CodeInput { /// `POST /api/v1/device/code`: a code pair. The person opens `verification_uri_complete` (or `verification_uri` and /// types `user_code`) and approves; the CLI polls `/api/v1/device/token` with `device_code` every `interval` seconds. pub async fn code( - app: laravel::config::Section, + app: laravel::config::Section, requester: Option>, Valid(p): Valid, ) -> laravel::Result> { @@ -124,7 +124,7 @@ pub async fn code( .scalar() .await?; if inserted.is_some() { - let uri = format!("{}/device", app.url.trim_end_matches('/')); + let uri = format!("{}/device", app.app_url()); return Ok(Json(json!({ "device_code": device, "user_code": user, @@ -252,7 +252,7 @@ impl PruneDeviceLogins { async fn handle(self) -> laravel::Result<()> { let pruned = prune().await; let health = pruned.as_ref().map(|_| ()).map_err(ToString::to_string); - crate::heartbeat::push("VISUALCI_DEVICE_PRUNE_HEARTBEAT", health).await; + crate::heartbeat::push(crate::heartbeat::Heartbeat::DevicePrune, health).await; pruned.map(|_| ()) } } diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs index 94937528..e24ee498 100644 --- a/app/src/auth/installations.rs +++ b/app/src/auth/installations.rs @@ -15,7 +15,8 @@ use laravel::auth::{Auth, Authenticated}; use laravel::prelude::*; use laravel::session::Session; -use crate::forge::github_app::{self, GithubApp}; +use crate::config::GithubApp; +use crate::forge::github_app; use crate::forge::installations::{self, SetUp}; use crate::models::User; diff --git a/app/src/auth/me.rs b/app/src/auth/me.rs index 72f95b4e..8e6ba8dd 100644 --- a/app/src/auth/me.rs +++ b/app/src/auth/me.rs @@ -12,8 +12,8 @@ use serde_json::{Value, json}; use super::Role; use super::invitations::{self, Invitee}; +use crate::config::{HostUrls, Team}; use crate::models::User; -use crate::notify::outbox::AppUrl; use crate::notify::{self, Kind, To}; pub fn routes(route: &mut Router) { @@ -99,37 +99,9 @@ pub fn summary(source: Option<&str>, detail: Option<&str>) -> Option { } /// `GET /api/ui/me`. -/// The forges a person can sign in with here: those whose OAuth application has its ID and secret. -#[derive(Clone, laravel::config::Section)] -pub struct SignInApps { - #[env("GITHUB_CLIENT_ID")] - pub github_id: Option, - #[env("GITHUB_CLIENT_SECRET")] - pub github_secret: Option, - #[env("GITLAB_CLIENT_ID")] - pub gitlab_id: Option, - #[env("GITLAB_CLIENT_SECRET")] - pub gitlab_secret: Option, -} - -impl SignInApps { - #[must_use] - pub fn forges(&self) -> Vec<&'static str> { - let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); - let mut forges = Vec::new(); - if set(&self.github_id) && set(&self.github_secret) { - forges.push("github"); - } - if set(&self.gitlab_id) && set(&self.gitlab_secret) { - forges.push("gitlab"); - } - forges - } -} - pub async fn me( Authenticated(user): Authenticated, - apps: laravel::config::Section, + social: laravel::config::Section, ) -> laravel::Result> { let user_id = user.id; let row = db::query!( @@ -165,7 +137,7 @@ pub async fn me( "name": user.name, "email": user.email, "avatar_url": user.avatar_url, "login": identities.get(0).and_then(|i| i.get("login")).cloned(), "identities": identities, }, - "forges": apps.forges(), + "forges": crate::auth::sign_in::forges(&social), "organizations": organizations, "invitations": invitations::pending_for(&user).await?, "staff": row.try_get::("staff")?, @@ -278,13 +250,6 @@ pub async fn update_billing_email( Ok(Json(json!({ "billing_email": email }))) } -/// The team's address for sign-up emails. -#[derive(Clone, laravel::config::Section)] -pub struct Team { - #[env("VISUALCI_TEAM_EMAIL", default = "support@visualci.com")] - pub email: String, -} - /// How long after sign-up the team's email waits for "How did you hear". pub const WAIT_MINUTES: i64 = 10; @@ -396,9 +361,9 @@ impl NotifySignups { async fn handle( self, team: laravel::config::Section, - app: laravel::config::Section, + app: laravel::config::Section, ) -> laravel::Result<()> { - let result = queue_signups(&team, &app.url).await; + let result = queue_signups(&team, app.app_url()).await; let stale = WAIT_MINUTES + STALE_MINUTES; let waiting = db::query!( "SELECT count(*) FROM users WHERE signup_notified_at IS NULL \ @@ -415,7 +380,7 @@ impl NotifySignups { } _ => Ok(()), }; - crate::heartbeat::push("VISUALCI_SIGNUPS_HEARTBEAT", health).await; + crate::heartbeat::push(crate::heartbeat::Heartbeat::SignUps, health).await; result.map(|_| ()) } } diff --git a/app/src/auth/oauth.rs b/app/src/auth/oauth.rs index 859298ad..ef2887a9 100644 --- a/app/src/auth/oauth.rs +++ b/app/src/auth/oauth.rs @@ -23,7 +23,7 @@ use laravel::prelude::*; use oauth_provider_laravel::{OAuth, OAuthConfig, OAuthServiceProvider, OAuthTokens}; use serde_json::{Value, json}; -use crate::http::hosts::HostUrls; +use crate::config::HostUrls; use crate::models::{User, Users}; /// The guard MCP routes put behind `RequireToken`: `Authenticate::via::()`. diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 869ff841..ba38b291 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -11,11 +11,13 @@ use laravel::auth::Auth; use laravel::auth::social::{self, Provider}; use laravel::config::app::Environment; +use laravel::config::social::Social; use laravel::db; use laravel::model::create; use laravel::prelude::*; use laravel::session::Session; +use crate::config::{DevLogin, SignUps}; use crate::forge::{self, ForgeKind, Identity, Permission, Repository}; use crate::models::User; @@ -84,7 +86,7 @@ fn is_page(to: &str) -> bool { /// The page Laravel's `Authenticate` remembered (`url.intended`, the full URL of the page that sent a guest to sign /// in) as a path on this app, if it's one a person should land on. -fn intended_page(url: &str, hosts: &crate::http::hosts::HostUrls) -> Option { +fn intended_page(url: &str, hosts: &crate::config::HostUrls) -> Option { let parsed = url::Url::parse(url).ok()?; // Configured hosts: only the app's own pages. Without them one origin serves everything, and the URL is the // request's own. @@ -104,8 +106,8 @@ fn intended_page(url: &str, hosts: &crate::http::hosts::HostUrls) -> Option) -> laravel::http::Response { - let forges = apps.forges(); +pub async fn login_page(social: laravel::config::Section) -> laravel::http::Response { + let forges = forges(&social); let gitlab = if forges.contains(&"gitlab") { "

Sign in with GitLab

" } else { "" }; let head = ", auth: Auth, sign_ups: laravel::config::Section, - gitlab: laravel::config::Section, - hosts: laravel::config::Section, + gitlab: laravel::config::Section, + hosts: laravel::config::Section, session: Session, ) -> laravel::Result { let provider = provider(&forge)?; @@ -218,7 +220,7 @@ pub async fn callback( /// (`VISUALCI_SITE_URL`, exactly), never a reflected one, and is never cached. pub async fn session( auth: Auth, - hosts: laravel::config::Section, + hosts: laravel::config::Section, headers: axum::http::HeaderMap, ) -> laravel::Result { let user = auth.user().await?; @@ -266,49 +268,20 @@ pub async fn session( Ok(response) } -/// The forges a person can sign in with here: those whose OAuth application is configured. -#[derive(Clone, laravel::config::Section)] -pub struct ForgeApps { - #[env("GITHUB_CLIENT_ID")] - pub github: Option, - #[env("GITHUB_CLIENT_SECRET")] - pub github_secret: Option, - #[env("GITLAB_CLIENT_ID")] - pub gitlab: Option, - #[env("GITLAB_CLIENT_SECRET")] - pub gitlab_secret: Option, -} - -impl ForgeApps { - /// The forges whose OAuth application has both its ID and its secret. - #[must_use] - pub fn forges(&self) -> Vec<&'static str> { - let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); - let mut forges = Vec::new(); - if set(&self.github) && set(&self.github_secret) { - forges.push("github"); - } - if set(&self.gitlab) && set(&self.gitlab_secret) { - forges.push("gitlab"); - } - forges - } +/// The forges a person can sign in with here: those whose OAuth application has both its ID and its secret +/// (`GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, `GITLAB_CLIENT_ID` and `GITLAB_CLIENT_SECRET`, which the framework's +/// social login reads). +#[must_use] +pub fn forges(social: &Social) -> Vec<&'static str> { + ["github", "gitlab"].into_iter().filter(|forge| social.client(forge).is_some()).collect() } /// `GET /auth/providers`: the sign-in buttons the web app shows. pub async fn providers( - apps: laravel::config::Section, + social: laravel::config::Section, dev: laravel::config::Section, ) -> Json { - 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, + Json(serde_json::json!({ "forges": forges(&social), "dev_login": dev.allowed() })) } /// Whether `env` is a development one (`local` or `testing`), where the development sign-in may run. @@ -330,14 +303,14 @@ impl DevLogin { config.section::().enabled && development(&config.app.env) } - /// Anything but development refuses to boot with `DEV_LOGIN` on: it would let anyone sign in as anyone. + /// Anything but development refuses to boot with `VISUALCI_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 \ + "VISUALCI_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() ))); @@ -359,7 +332,7 @@ pub struct DevLoginInput { pub async fn dev_login( dev: laravel::config::Section, auth: Auth, - hosts: laravel::config::Section, + hosts: laravel::config::Section, Valid(p): Valid, ) -> laravel::Result { if !dev.allowed() { @@ -391,7 +364,7 @@ pub async fn dev_login( /// `POST /auth/logout`: the session ends, and so does the site's hint. pub async fn logout( auth: Auth, - hosts: laravel::config::Section, + hosts: laravel::config::Section, ) -> laravel::Result { auth.logout().await?; Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, false))) @@ -405,7 +378,7 @@ pub const SIGNED_IN_HINT: &str = "vci_signed_in"; const HINT_DAYS: i64 = 30; /// The hint, set (`on`) or cleared. -pub fn signed_in_hint(hosts: &crate::http::hosts::HostUrls, on: bool) -> laravel::cookie::Cookie { +pub fn signed_in_hint(hosts: &crate::config::HostUrls, on: bool) -> laravel::cookie::Cookie { use laravel::time::ToSpan; let host = |url: &Option| { let url = url.as_deref()?.trim(); @@ -438,34 +411,13 @@ fn mcp_client(return_to: &str) -> Option { .flatten() } -/// Sign-ups: closed (`VISUALCI_WAITLIST=true`) until VisualCI opens, when someone new goes on the waitlist instead. -/// Production sets it explicitly, either way, or refuses to boot ([`SignUps::check`]): a dropped setting would open -/// sign-ups by surprise. Elsewhere it's open unless set. -#[derive(Clone, laravel::config::Section)] -pub struct SignUps { - #[env("VISUALCI_WAITLIST")] - waitlist: Option, -} - impl SignUps { - /// Whether someone new goes on the waitlist instead of getting an account. + /// Whether someone new goes on the waitlist instead of getting an account (`VISUALCI_WAITLIST`, which production + /// must set either way). #[must_use] pub fn closed(&self) -> bool { self.waitlist.unwrap_or(false) } - - /// Boot check: production says whether sign-ups are open. - /// - /// # Errors - /// In production, when `VISUALCI_WAITLIST` isn't set. - pub fn check(&self, production: bool) -> laravel::Result<()> { - if production && self.waitlist.is_none() { - return Err(laravel::Error::msg( - "VISUALCI_WAITLIST isn't set: production needs it explicitly (true keeps sign-ups closed, false opens them)", - )); - } - Ok(()) - } } /// The user who owns this forge identity, if anyone. diff --git a/app/src/auth/staff.rs b/app/src/auth/staff.rs index f226a220..e69a0a24 100644 --- a/app/src/auth/staff.rs +++ b/app/src/auth/staff.rs @@ -7,8 +7,8 @@ use laravel::prelude::*; use serde_json::{Value, json}; use super::me::summary; +use crate::config::HostUrls; use crate::models::User; -use crate::notify::outbox::AppUrl; use crate::notify::{About, DeliverEmails, render, render::samples}; pub fn routes(route: &mut Router) { @@ -52,10 +52,10 @@ pub async fn signups(Authenticated(user): Authenticated) -> laravel::Resul /// retried or dismissed yet, newest first. pub async fn emails( Authenticated(user): Authenticated, - app: laravel::config::Section, + app: laravel::config::Section, ) -> laravel::Result> { staff_only(&user)?; - let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.app_url() }; let list: Vec = samples() .into_iter() .map(|(label, kind)| { diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs index edadcbf7..a80653db 100644 --- a/app/src/billing/mod.rs +++ b/app/src/billing/mod.rs @@ -59,15 +59,7 @@ pub fn plan_by_id(id: &str) -> Plan { [TEAM, STAFF].into_iter().find(|p| p.id == id).unwrap_or(FREE) } -/// Stripe (`STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`). Production's keys come only from the cluster's -/// ExternalSecrets; tests fake Stripe. -#[derive(Clone, laravel::config::Section)] -pub struct Stripe { - #[env("STRIPE_SECRET_KEY")] - pub secret_key: Option, - #[env("STRIPE_WEBHOOK_SECRET")] - pub webhook_secret: Option, -} +use crate::config::Stripe; impl Stripe { /// Whether the secret key is a live one (`sk_live_`, `rk_live_`); `None` without a key. @@ -78,32 +70,16 @@ impl Stripe { } } -/// At boot: production needs Stripe's key and webhook secret, and never runs on a test key (`sk_test_`, `rk_test_`), -/// which would take no real payments while granting real plans and credits. +/// At boot: production never runs on a test key (`sk_test_`, `rk_test_`), which would take no real payments while +/// granting real plans and credits. (Production can't start without the key and the webhook secret at all: +/// `config::Stripe`.) /// /// # Errors -/// In production, when either is missing or the key isn't a live one. +/// In production, when the key isn't a live one. pub fn check(stripe: &Stripe, production: bool) -> laravel::Result<()> { - if !production { - return Ok(()); - } - let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); - let missing: Vec<&str> = - [("STRIPE_SECRET_KEY", &stripe.secret_key), ("STRIPE_WEBHOOK_SECRET", &stripe.webhook_secret)] - .into_iter() - .filter(|(_, v)| !set(v)) - .map(|(name, _)| name) - .collect(); - if !missing.is_empty() { - return Err(laravel::Error::msg(format!( - "Stripe isn't configured: {} not set. Production needs both: without them nobody can pay, and Stripe's \ - events (payments, subscriptions) are refused.", - missing.join(", ") - ))); - } - if stripe.live() == Some(false) { + if production && stripe.live() == Some(false) { return Err(laravel::Error::msg( - "STRIPE_SECRET_KEY is a test key; production needs a live one (sk_live_ or rk_live_)", + "VISUALCI_STRIPE_SECRET_KEY is a test key; production needs a live one (sk_live_ or rk_live_)", )); } Ok(()) diff --git a/app/src/billing/routes.rs b/app/src/billing/routes.rs index 1120757f..20e395b3 100644 --- a/app/src/billing/routes.rs +++ b/app/src/billing/routes.rs @@ -8,9 +8,10 @@ use laravel::prelude::*; use serde_json::{Value, json}; use super::stripe::{self, Method, catalog, checkout_tax_fields, ensure_customer}; -use super::{CREDIT_PACK, FREE, MAX_AUTO_RELOAD_PACKS, STAFF, Stripe, TEAM, plan_by_id}; +use super::{CREDIT_PACK, FREE, MAX_AUTO_RELOAD_PACKS, STAFF, TEAM, plan_by_id}; +use crate::config::HostUrls; +use crate::config::Stripe; use crate::models::User; -use crate::notify::outbox::AppUrl; /// The routes, on the `web` group. pub fn routes(route: &mut Router) { @@ -68,8 +69,8 @@ fn key(stripe: &Stripe) -> laravel::Result<&str> { .ok_or_else(|| laravel::abort_with(400, "payments aren't set up yet")) } -fn app_url(app: &AppUrl) -> String { - app.url.trim_end_matches('/').to_string() +fn app_url(app: &HostUrls) -> String { + app.app_url().to_string() } /// `GET /api/ui/billing/plans`: the plans anyone can choose, the pack, and whether payments are on. @@ -99,7 +100,7 @@ pub async fn checkout( Authenticated(user): Authenticated, Params(org): Params, stripe: laravel::config::Section, - app: laravel::config::Section, + app: laravel::config::Section, Valid(p): Valid, ) -> laravel::Result> { let key = key(&stripe)?; @@ -145,7 +146,7 @@ pub async fn buy_packs( Authenticated(user): Authenticated, Params(org): Params, stripe: laravel::config::Section, - app: laravel::config::Section, + app: laravel::config::Section, Valid(p): Valid, ) -> laravel::Result> { let key = key(&stripe)?; @@ -213,7 +214,7 @@ pub async fn portal( Authenticated(user): Authenticated, Params(org): Params, stripe: laravel::config::Section, - app: laravel::config::Section, + app: laravel::config::Section, ) -> laravel::Result> { let key = key(&stripe)?; let org = billing_org(&user, &org).await?; @@ -297,7 +298,7 @@ pub async fn add_payment_method( Authenticated(user): Authenticated, Params(org): Params, stripe: laravel::config::Section, - app: laravel::config::Section, + app: laravel::config::Section, ) -> laravel::Result> { let key = key(&stripe)?; let org = billing_org(&user, &org).await?; diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs index de0deb86..7dfa1ff9 100644 --- a/app/src/billing/webhook.rs +++ b/app/src/billing/webhook.rs @@ -16,7 +16,8 @@ use laravel::prelude::*; use serde_json::{Value, json}; use sha2::Sha256; -use super::{CREDIT_PACK, FREE, Stripe, TEAM, plan_by_id}; +use super::{CREDIT_PACK, FREE, TEAM, plan_by_id}; +use crate::config::Stripe; use crate::domain::credits::add_purchased_credits; use crate::notify::{self, Kind, To}; diff --git a/app/src/config.rs b/app/src/config.rs index 619378c2..6b2fa2d6 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -1,72 +1,531 @@ -//! The app's own configuration sections, read from the environment. +//! VisualCI's configuration: every setting the server reads, in one typed struct ([`Config`]), read from +//! `VISUALCI_`-prefixed environment variables. The variables that Laravel Rust and the OAuth server read themselves keep +//! their own names and are described here too ([`schema`]), so the reference docs list everything one server needs. +//! +//! Each setting's doc comment, type, default, and whether it's required, required in production or secret are its +//! entry in the docs: `frontend/content/docs/self-hosting/environment-variables.md` and `app/.env.example` are +//! generated from them, and a test fails when either differs (`VISUALCI_GOLDEN_UPDATE=1` writes them). +//! +//! At boot ([`check`]) a missing or invalid setting, or one production needs, stops the app with every problem listed. +//! Then ([`report`]) the app logs what it runs with, secrets masked, and warns about each `VISUALCI_` variable nothing +//! reads, naming the closest one it knows. -use laravel::config::Section; +use envschema::{Group, Settings, Variable}; -/// S3-compatible blob storage: R2 in production, RustFS or MinIO in development and CI. Every setting is required: -/// the app doesn't start without them, so production never falls back to a development store or its credentials. -#[derive(Clone, Debug, Section)] +/// The prefix of every VisualCI setting. +pub const PREFIX: &str = "VISUALCI_"; + +/// Every VisualCI setting. Each group is also a config section of its own (`Section`, `Section`). +#[derive(Clone, Settings)] +pub struct Config { + #[settings(nested)] + pub storage: Storage, + #[settings(nested)] + pub renderer: Renderer, + #[settings(nested)] + pub hosts: HostUrls, + #[settings(nested)] + pub network: Network, + #[settings(nested)] + pub sign_ups: SignUps, + #[settings(nested)] + pub dev_login: DevLogin, + #[settings(nested)] + pub github_app: GithubApp, + #[settings(nested)] + pub gitlab: Gitlab, + #[settings(nested)] + pub postmark: Postmark, + #[settings(nested)] + pub team: Team, + #[settings(nested)] + pub stripe: Stripe, + #[settings(nested)] + pub cloudflare: Cloudflare, + #[settings(nested)] + pub gallery: Gallery, + #[settings(nested)] + pub heartbeats: Heartbeats, +} + +/// S3-compatible storage for uploads, rendered pages and diff images: R2 in production, RustFS or MinIO in +/// development and CI. The app doesn't start without its endpoint, bucket and keys, so production never falls back +/// to a development store. +#[derive(Clone, Settings)] +#[settings(title = "Blob storage")] pub struct Storage { - /// Such as `https://.r2.cloudflarestorage.com`, or `http://127.0.0.1:59000`. - #[env("S3_ENDPOINT", required)] + /// The store's S3 endpoint. + #[env("VISUALCI_S3_ENDPOINT", required, example = "https://.r2.cloudflarestorage.com")] pub endpoint: String, - /// The endpoint clients upload to, when it differs from the one the server uses (a cluster-internal store). - #[env("S3_PUBLIC_ENDPOINT")] + /// The endpoint browsers and the CLI upload to and download from, when it differs from the one the server uses + /// (a store the server reaches on a cluster-internal address). Images in the web app's Content-Security-Policy + /// come from here too. + #[env("VISUALCI_S3_PUBLIC_ENDPOINT")] pub public_endpoint: Option, - #[env("S3_BUCKET", required)] + /// The bucket. + #[env("VISUALCI_S3_BUCKET", required)] pub bucket: String, - #[env("S3_REGION", default = "auto")] + /// The bucket's region. R2 takes `auto`. + #[env("VISUALCI_S3_REGION", default = "auto")] pub region: String, - #[env("S3_ACCESS_KEY_ID", required)] + /// The access key's ID. + #[env("VISUALCI_S3_ACCESS_KEY_ID", required, secret)] pub access_key_id: String, - #[env("S3_SECRET_ACCESS_KEY", required)] + /// The access key's secret. + #[env("VISUALCI_S3_SECRET_ACCESS_KEY", required, secret)] pub secret_access_key: String, } -/// The renderers' API (`/internal/renderer`): the shared token renderers claim work with, the metrics scraper's own -/// token, and the renderer image's version, part of every render's cache key. -#[derive(Clone, Debug, Section)] +/// The renderers' API (`/internal/renderer`): the renderers claim PDFs to draw with a shared token, and a metrics +/// scraper reads their numbers with a token of its own. +#[derive(Clone, Settings)] +#[settings(title = "Renderers")] pub struct Renderer { - /// Required: without it, nobody could claim renders, and an empty token would match nothing anyway. - #[env("RENDERER_TOKEN", required)] + /// The token every renderer sends: the same value as the renderers' own `VISUALCI_RENDERER_TOKEN`. + #[env("VISUALCI_RENDERER_TOKEN", required, secret)] pub token: String, - /// The renderer version documents are drawn with: part of the render cache key, and what a renderer's claim must - /// match exactly. Required: the app doesn't start without it. - #[env("RENDERER_VERSION", required)] + /// The renderer version documents are drawn with: part of every render's cache key, and what a renderer's claim + /// must match exactly. The image sets it from `docker/renderer.version`; don't set it yourself. + #[env("VISUALCI_RENDERER_VERSION", required)] pub version: String, - /// Empty turns the metrics endpoint off (no token matches it). - #[env("METRICS_TOKEN", default = "")] + /// The token for `/internal/renderer/metrics` (Prometheus). Never give it to the renderers. Empty turns the + /// endpoint off: no token matches it. + #[env("VISUALCI_METRICS_TOKEN", default = "", secret)] pub metrics_token: String, } -/// Cloudflare, for purging public gallery URLs after a change (`jobs::purge_gallery`). Empty in development: nothing is -/// purged. -#[derive(Clone, Debug, Section)] +/// Routing by hostname: one server answers for the app, the API and the MCP server, and each host serves only its own +/// paths. Set all four, each its own host, or none: a self-hosted server on one host serves everything there. +#[derive(Clone, Settings)] +#[settings(title = "Hosts")] +pub struct HostUrls { + /// The marketing site's address. Signed-out visitors to the app's front page go there. + #[env("VISUALCI_SITE_URL", example = "https://visualci.com")] + pub site: Option, + /// The web app's address, also used for the links in emails (`http://localhost` when unset). + #[env("VISUALCI_APP_URL", example = "https://app.visualci.com")] + pub app: Option, + /// The API's address, where the CLI and CI send builds. The CLI's own `VISUALCI_API_URL` names the same address. + #[env("VISUALCI_API_URL", example = "https://api.visualci.com")] + pub api: Option, + /// The MCP server's address, where coding agents connect, and the OAuth issuer (`OAUTH_ISSUER` must match it). + #[env("VISUALCI_MCP_URL", example = "https://mcp.visualci.com")] + pub mcp: Option, +} + +/// Behind a load balancer: which proxies' `X-Forwarded-For` to believe, and how the database pool behaves. +#[derive(Clone, Settings)] +#[settings(title = "Network and database")] +pub struct Network { + /// The proxies in front of the app whose `X-Forwarded-For` is believed, as addresses or CIDR ranges. Behind them, + /// a request's address is the nearest one that isn't a trusted proxy. Never include addresses untrusted code can + /// send from, such as the renderers'. + #[env("VISUALCI_TRUSTED_PROXIES", default = "10.0.0.0/8")] + pub trusted_proxies: Vec, + /// More host names the MCP endpoint answers for, besides the configured hosts, the app's address and localhost + /// (DNS rebinding protection). For a development server reached by another name. + #[env("VISUALCI_MCP_HOSTS", default = "")] + pub mcp_hosts: Vec, + /// How long, in seconds, a request waits for a pooled database connection before it fails with a 503 and + /// Retry-After, rather than hanging while the queue grows. + #[env("VISUALCI_DB_ACQUIRE_TIMEOUT", default = 5)] + pub db_acquire_timeout: u64, + /// The `application_name` of this process's database connections, in Postgres's metrics and + /// `pg_stat_activity`, such as `visualci-web` or `visualci-worker`. Letters, digits, dashes and underscores, at + /// most 63 characters; anything else is ignored. + #[env("VISUALCI_DB_APPLICATION_NAME")] + pub db_application_name: Option, +} + +/// Whether new people can sign up. +#[derive(Clone, Settings)] +#[settings(title = "Sign-ups")] +pub struct SignUps { + /// `true` keeps sign-ups closed: someone new goes on the waitlist instead of getting an account. Production + /// must set it either way, so a dropped setting never opens sign-ups by surprise; elsewhere they're open unless + /// it's set. + #[env("VISUALCI_WAITLIST", required_in_production)] + pub waitlist: Option, +} + +/// Development and tests only. +#[derive(Clone, Settings)] +#[settings(title = "Development sign-in")] +pub struct DevLogin { + /// Lets anyone sign in as anyone by email, for local work and CI's screenshots. Only where `APP_ENV` is `local` or + /// `testing`: anywhere else the app refuses to start with it on. + #[env("VISUALCI_DEV_LOGIN", default = false)] + pub enabled: bool, +} + +/// The VisualCI GitHub App: checks and comments on pull requests, its webhook, and access that follows GitHub. +/// Sign-in with GitHub is its OAuth client, `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` (Laravel Rust, below). +#[derive(Clone, Settings)] +#[settings(title = "GitHub App")] +pub struct GithubApp { + /// The App's ID. + #[env("VISUALCI_GITHUB_APP_ID", required_in_production)] + pub app_id: Option, + /// The App's private key: its PEM file, base64-encoded to fit on one line. + #[env("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", secret, required_in_production)] + pub private_key_base64: Option, + /// The App's webhook secret. Without it, the webhook (`/webhooks/github`) answers 404. + #[env("VISUALCI_GITHUB_WEBHOOK_SECRET", secret, required_in_production)] + pub webhook_secret: Option, +} + +/// GitLab, on gitlab.com or a GitLab of your own. Sign-in is its OAuth application, `GITLAB_CLIENT_ID` and +/// `GITLAB_CLIENT_SECRET` (Laravel Rust, below). GitLab has no app installations: a project gives VisualCI access by +/// adding its bot as a member. +#[derive(Clone, Settings)] +#[settings(title = "GitLab")] +pub struct Gitlab { + /// The GitLab VisualCI's OAuth application and bot are on. + #[env("VISUALCI_GITLAB_URL", default = "https://gitlab.com")] + pub url: String, + /// The bot's personal access token, with the `api` scope: access checks, commit statuses and merge request notes. + #[env("VISUALCI_GITLAB_BOT_TOKEN", secret)] + pub bot_token: Option, + /// The bot's username, for telling people whom to invite. + #[env("VISUALCI_GITLAB_BOT_USERNAME", default = "visualci")] + pub bot_username: String, + /// Lets requests to an organization's server reach private addresses. Development only, for a local GitLab. + #[env("VISUALCI_FORGE_PRIVATE_ADDRESSES", default = false)] + pub private_addresses: bool, +} + +/// Email through Postmark's API. Without a token nothing is sent, and the outbox keeps the emails pending. +#[derive(Clone, Settings)] +#[settings(title = "Email")] +pub struct Postmark { + /// The Postmark server's API token. + #[env("VISUALCI_POSTMARK_SERVER_TOKEN", secret, required_in_production)] + pub token: Option, + /// Who emails come from. + #[env("VISUALCI_MAIL_FROM", default = "VisualCI ")] + pub from: String, + /// Where replies go. + #[env("VISUALCI_MAIL_REPLY_TO", default = "support@visualci.com")] + pub reply_to: String, +} + +/// The people running this VisualCI. +#[derive(Clone, Settings)] +#[settings(title = "Team")] +pub struct Team { + /// Where new sign-ups and feedback are sent. + #[env("VISUALCI_TEAM_EMAIL", default = "support@visualci.com")] + pub email: String, +} + +/// Payments through Stripe. Production refuses to start on a test key, which would take no real payments while +/// granting real plans and credits. +#[derive(Clone, Settings)] +#[settings(title = "Payments")] +pub struct Stripe { + /// Stripe's secret or restricted key: a live one (`sk_live_`, `rk_live_`) in production. + #[env("VISUALCI_STRIPE_SECRET_KEY", secret, required_in_production)] + pub secret_key: Option, + /// The webhook's signing secret. Stripe's endpoint is `/webhooks/stripe` on the API host. + #[env("VISUALCI_STRIPE_WEBHOOK_SECRET", secret, required_in_production)] + pub webhook_secret: Option, +} + +/// Cloudflare, for purging public gallery URLs from its cache after a change. Unset, nothing is purged. +#[derive(Clone, Settings)] +#[settings(title = "Cloudflare")] pub struct Cloudflare { + /// The zone the gallery's URLs are served from. #[env("VISUALCI_CLOUDFLARE_ZONE_ID", default = "")] pub zone_id: String, - #[env("VISUALCI_CLOUDFLARE_PURGE_TOKEN", default = "")] + /// An API token that may purge that zone's cache. + #[env("VISUALCI_CLOUDFLARE_PURGE_TOKEN", default = "", secret)] pub purge_token: String, } -/// The public gallery (`http::gallery`). -#[derive(Clone, Debug, Section)] +/// Public galleries. +#[derive(Clone, Settings)] +#[settings(title = "Gallery")] pub struct Gallery { /// The most gallery credits one project is charged in a day: images past it are served free. #[env("VISUALCI_GALLERY_DAILY_CREDITS", default = 50_000)] pub daily_credits: i64, } -/// The proxies in front of the app whose `X-Forwarded-For` is believed (`TRUSTED_PROXIES`, comma-separated; the -/// cluster's network by default). Behind them, a request's address is the nearest one that isn't a trusted proxy: -/// Cloudflare's edge, or a client that reached the ingress directly. +/// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no +/// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. +#[derive(Clone, Settings)] +#[settings(title = "Heartbeats")] +pub struct Heartbeats { + /// Email delivery (the worker, every five minutes). + #[env("VISUALCI_EMAILS_HEARTBEAT_URL")] + pub emails_url: Option, + /// Email delivery's token. + #[env("VISUALCI_EMAILS_HEARTBEAT_TOKEN", secret)] + pub emails_token: Option, + /// Sign-up notices to the team. + #[env("VISUALCI_SIGNUPS_HEARTBEAT_URL")] + pub signups_url: Option, + /// Sign-up notices' token. + #[env("VISUALCI_SIGNUPS_HEARTBEAT_TOKEN", secret)] + pub signups_token: Option, + /// The live-update check (every minute): a notification reaches each process's listener. + #[env("VISUALCI_LIVE_HEARTBEAT_URL")] + pub live_url: Option, + /// The live-update check's token. + #[env("VISUALCI_LIVE_HEARTBEAT_TOKEN", secret)] + pub live_token: Option, + /// Pruning expired device sign-ins. + #[env("VISUALCI_DEVICE_PRUNE_HEARTBEAT_URL")] + pub device_prune_url: Option, + /// Device sign-in pruning's token. + #[env("VISUALCI_DEVICE_PRUNE_HEARTBEAT_TOKEN", secret)] + pub device_prune_token: Option, + /// Syncing access from GitHub (the hourly recheck). + #[env("VISUALCI_FORGE_SYNC_HEARTBEAT_URL")] + pub forge_sync_url: Option, + /// Forge access sync's token. + #[env("VISUALCI_FORGE_SYNC_HEARTBEAT_TOKEN", secret)] + pub forge_sync_token: Option, + /// Image retention (daily). + #[env("VISUALCI_RETENTION_HEARTBEAT_URL")] + pub retention_url: Option, + /// Image retention's token. + #[env("VISUALCI_RETENTION_HEARTBEAT_TOKEN", secret)] + pub retention_token: Option, + /// The demo organization's daily reset. + #[env("VISUALCI_DEMO_HEARTBEAT_URL")] + pub demo_url: Option, + /// The demo reset's token. + #[env("VISUALCI_DEMO_HEARTBEAT_TOKEN", secret)] + pub demo_token: Option, + /// The sweep of abandoned builds (every five minutes). + #[env("VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL")] + pub builds_expire_url: Option, + /// The builds sweep's token. + #[env("VISUALCI_BUILDS_EXPIRE_HEARTBEAT_TOKEN", secret)] + pub builds_expire_token: Option, + /// The daily check of snapshot groups. + #[env("VISUALCI_GROUPS_CHECK_HEARTBEAT_URL")] + pub groups_check_url: Option, + /// The groups check's token. + #[env("VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN", secret)] + pub groups_check_token: Option, +} + +/// The variables Laravel Rust reads itself. VisualCI keeps the framework's names for them. +const FRAMEWORK: &[Variable] = &[ + Variable::new("APP_ENV", "`production`, `local` or `testing`. The image sets `production`.").default("production"), + Variable::new( + "APP_KEY", + "Laravel's encryption key for sessions and cookies: 32 random characters. A new key signs everyone out.", + ) + .secret() + .required_in_production(), + Variable::new( + "APP_URL", + "The server's address, for URLs the framework builds. On one host, the only address you set.", + ) + .example("https://visualci.example.com"), + Variable::new("APP_BASE_PATH", "Where the app's files are (`public/`, `storage/`). The image sets `/app`."), + Variable::new("SERVER_HOST", "The address the web server listens on. The image sets `0.0.0.0`."), + Variable::new("SERVER_PORT", "The web server's port. The image sets `5150`.").kind("integer"), + Variable::new("LOG_CHANNEL", "Where logs go. The image sets `stderr`."), + Variable::new("DATABASE_URL", "The Postgres URL, with its credentials.") + .secret() + .example("postgres://visualci:secret@db:5432/visualci"), + Variable::new("DB_CONNECTION", "`pgsql`.").default("pgsql"), + Variable::new( + "DB_MAX_CONNECTIONS", + "The most database connections each process holds. Keep the sum across processes within Postgres's limit.", + ) + .kind("integer") + .default("10"), + Variable::new("CACHE_STORE", "`database`: the cache in Postgres, shared by every process."), + Variable::new("SESSION_DRIVER", "`database`: sign-in sessions in Postgres, shared by every process."), + Variable::new("QUEUE_CONNECTION", "`database`: the job queue in Postgres, worked by `queue:work`."), + Variable::new("GITHUB_CLIENT_ID", "The GitHub App's OAuth client ID, for signing in with GitHub.") + .required_in_production(), + Variable::new("GITHUB_CLIENT_SECRET", "The GitHub App's OAuth client secret.").secret().required_in_production(), + Variable::new("GITLAB_CLIENT_ID", "The GitLab OAuth application's ID, for signing in with GitLab."), + Variable::new("GITLAB_CLIENT_SECRET", "The GitLab OAuth application's secret.").secret(), +]; + +/// The OAuth server's variables (oauth-provider-laravel), for MCP clients' sign-in. +const OAUTH: &[Variable] = &[ + Variable::new( + "OAUTH_ISSUER", + "The OAuth issuer: `VISUALCI_MCP_URL`. With the four hosts set, production refuses to start when it differs.", + ) + .example("https://mcp.visualci.com"), + Variable::new( + "OAUTH_AUTHORIZATION_ENDPOINT", + "The consent page: `/oauth/authorize` on `VISUALCI_APP_URL`, checked like `OAUTH_ISSUER`.", + ) + .example("https://app.visualci.com/oauth/authorize"), +]; + +/// Variables only development machines and the test suite read. Never set them in production. +const DEVELOPMENT: &[Variable] = &[ + Variable::new( + "VISUALCI_NOW", + "Stands in for the clock in credit allowances (RFC 3339), for screenshots of seeded data.", + ), + Variable::new( + "VISUALCI_APP_TEST_DATABASE_URL", + "The tests' Postgres (each test borrows a copy of it). Default: CI's, \ + `postgres://visualci:visualci@127.0.0.1:55433/visualci_app_test`.", + ), + Variable::new("VISUALCI_EMAIL_SNAPSHOTS", "A folder the email tests write each email's HTML to, for review."), + Variable::new( + "VISUALCI_GOLDEN_UPDATE", + "`1` makes the tests write their golden files (this page among them) instead of comparing.", + ), +]; + +/// `VISUALCI_` variables that other programs read: the CLI and its clients, the renderers, the frontend's build and +/// CI's scripts. +/// The server ignores them, so a shell with a CLI token set gets no warning. +pub const OTHER_PROGRAMS: &[&str] = &[ + "VISUALCI_TOKEN", + "VISUALCI_PROJECT", + "VISUALCI_BUILD_ID", + "VISUALCI_MODE", + "VISUALCI_BRANCH", + "VISUALCI_COMMIT", + "VISUALCI_PR", + "VISUALCI_ENVIRONMENT", + "VISUALCI_GROUPS", + "VISUALCI_CONFIG", + "VISUALCI_VERSION", + "VISUALCI_INSTALL_DIR", + "VISUALCI_FAIL_FAST", + "VISUALCI_SHARD", + "VISUALCI_DISABLED", + "VISUALCI_CLI", + "VISUALCI_HEARTBEAT_FILE", + "VISUALCI_ONCE", + "VISUALCI_ANALYTICS", + "VISUALCI_REQUIRE_WASM", + "VISUALCI_APP_BIN", +]; + +/// Every variable the server reads or knows: VisualCI's settings, then the framework's, the OAuth server's and the +/// ones only development and tests use. +#[must_use] +pub fn schema() -> envschema::Schema { + Config::schema() + .with_group(Group::external( + "Laravel Rust", + "The framework reads these itself, under its own names.", + FRAMEWORK, + )) + .with_group(Group::external( + "OAuth for MCP clients", + "The OAuth server MCP clients sign in through (oauth-provider-laravel) reads these.", + OAUTH, + )) + .with_group(Group::external("Development and tests", "Never set these in production.", DEVELOPMENT)) + .ignoring(OTHER_PROGRAMS) +} + +/// Read every setting from Laravel's environment and set it: the whole [`Config`], and each group as a section of its +/// own. Each missing or invalid setting, and each one production needs and doesn't have, is kept for [`check`]. +pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env) { + let production = config.app.env.is_production(); + let source = |name: &str| env.get::(name); + let (settings, mut problems) = Config::load_reporting(&source, production); + if production { + problems.extend(schema().missing_in_production(&source)); + } + + tune_database(&mut config.database, &settings.network); + config + .set(Problems(problems)) + .set(settings.storage.clone()) + .set(settings.renderer.clone()) + .set(settings.hosts.clone()) + .set(settings.network.clone()) + .set(settings.sign_ups.clone()) + .set(settings.dev_login.clone()) + .set(settings.github_app.clone()) + .set(settings.gitlab.clone()) + .set(settings.postmark.clone()) + .set(settings.team.clone()) + .set(settings.stripe.clone()) + .set(settings.cloudflare.clone()) + .set(settings.gallery.clone()) + .set(settings.heartbeats.clone()) + .set(settings); +} + +/// What [`install`] found wrong. +struct Problems(Vec); + +/// At boot, first: the app doesn't start with a required setting missing, a value its type can't take, or (in +/// production) a setting production needs unset. The error lists them all. +/// +/// # Errors +/// Those problems. +pub fn check(config: &laravel::config::Config) -> laravel::Result<()> { + match config.get::() { + Some(Problems(problems)) if !problems.is_empty() => { + Err(laravel::Error::msg(envschema::Problems(problems.clone()).to_string())) + } + _ => Ok(()), + } +} + +/// At boot: log the settings the app runs with, secrets masked, and warn about each `VISUALCI_` variable in the +/// process's environment that nothing reads. +pub fn report(config: &laravel::config::Config) { + if let Some(settings) = config.get::() { + tracing::info!(settings = %settings.summary(), "VisualCI configuration"); + } + warn_unknown(std::env::vars_os().filter_map(|(name, _)| name.into_string().ok())); +} + +/// Warn about each `VISUALCI_` variable in `names` that nothing reads (a typo, or a renamed or removed setting), +/// naming the closest known one. Returns the warnings. +pub fn warn_unknown(names: impl IntoIterator) -> Vec { + let names: Vec = names.into_iter().collect(); + let unknown = schema().unknown(PREFIX, names.iter().map(String::as_str)); + for variable in &unknown { + tracing::warn!(variable = %variable.name, closest = variable.closest.unwrap_or(""), "{variable}"); + } + unknown +} + +/// The reference page, `frontend/content/docs/self-hosting/environment-variables.md`. #[must_use] -pub fn trusted_proxies() -> Vec { - std::env::var("TRUSTED_PROXIES") - .unwrap_or_else(|_| "10.0.0.0/8".to_string()) - .split(',') - .map(|p| p.trim().to_string()) - .filter(|p| !p.is_empty()) - .collect() +pub fn docs_page() -> String { + format!( + "---\ntitle: Environment variables\ndescription: Every environment variable VisualCI's server reads: its \ + settings, the framework's and the OAuth server's, with their types, defaults and which ones production \ + needs.\n---\n\n\n\nThe server reads its settings from environment variables. VisualCI's own all \ + start with `VISUALCI_`; the framework's and the OAuth server's keep their own names. Set them for every \ + process (`serve`, `queue:work`, `schedule:work` and `migrate`); [Self-hosting](/docs/self-hosting/) says \ + which ones a first server needs. `app/.env.example` in the repository lists the same variables as a file \ + to fill in.\n\nThe server refuses to start when a required variable is missing or any variable has a value \ + its type can't take, and lists every such problem at once. With `APP_ENV=production` the variables marked \ + *required in production* are required too. At startup it logs the settings it runs with, secrets masked, \ + and warns about each `VISUALCI_` variable it doesn't read, naming the closest one it knows: a typo, or a \ + setting that was renamed. The CLI's variables (`VISUALCI_TOKEN`, `VISUALCI_PROJECT` and the rest) are \ + ignored.\n\nA boolean takes `true` or `false` (or `1`/`0`, `yes`/`no`, `on`/`off`). An empty value, or \ + `null`, is the same as not setting the variable.\n\n{}", + schema().markdown() + ) +} + +/// `app/.env.example`. +#[must_use] +pub fn dotenv_example() -> String { + format!( + "# VisualCI's server: every environment variable it reads. Generated from app/src/config.rs (run app/'s tests \ + with\n# VISUALCI_GOLDEN_UPDATE=1); the reference is https://visualci.com/docs/self-hosting/environment-variables/\n\n{}", + schema().dotenv_example() + ) } /// A safe `application_name`: letters, digits, dashes and underscores, at most 63 characters; anything else is ignored. @@ -76,32 +535,28 @@ fn application_name(name: &str) -> Option { .then(|| name.to_string()) } -/// The database: `Database::from_env` (`DATABASE_URL`, `DB_MAX_CONNECTIONS`, default 10 per process), with a short wait -/// for a pooled connection (`DB_ACQUIRE_TIMEOUT`, seconds, default 5). A burst of CI builds that takes every -/// connection then answers 503 with Retry-After at once (`http::busy`), rather than holding each request for the -/// framework's default 30 seconds while the queue grows (today's server hung on 3 Dec 2026, 16:02-16:07 UTC). -#[laravel::config::section] -fn database(env: &laravel::config::Env) -> laravel::config::database::Database { - let mut database = laravel::config::database::Database::from_env(env); - let seconds: u64 = env.get("DB_ACQUIRE_TIMEOUT").unwrap_or(5); +/// The database connection's pool: a short wait for a pooled connection (`VISUALCI_DB_ACQUIRE_TIMEOUT`), so a burst of +/// CI builds that takes every connection answers 503 with Retry-After at once (`http::busy`) rather than holding each +/// request for the framework's default 30 seconds while the queue grows (today's server hung on 3 Dec 2026, +/// 16:02-16:07 UTC), and the processes' names in Postgres (`VISUALCI_DB_APPLICATION_NAME`). +fn tune_database(database: &mut laravel::config::database::Database, network: &Network) { let default = database.default.clone(); - if let Some(connection) = database.connections.remove(&default) { - let seconds = i64::try_from(seconds).unwrap_or(5); - let mut connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); - // Which process a connection belongs to, in Postgres's metrics and pg_stat_activity (`visualci-web`, - // `visualci-worker`, `visualci-scheduler`). The deploy sets it beside the URL from the database's Secret. - if let Some(name) = env.get::("DB_APPLICATION_NAME").and_then(|n| application_name(&n)) { - connection = - connection.initialize(laravel::db::sqlx::AssertSqlSafe(format!("SET application_name = '{name}'"))); - } - database.connections.insert(default, connection); + let Some(connection) = database.connections.remove(&default) else { return }; + let seconds = i64::try_from(network.db_acquire_timeout).unwrap_or(5); + let mut connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); + if let Some(name) = network.db_application_name.as_deref().and_then(application_name) { + connection = + connection.initialize(laravel::db::sqlx::AssertSqlSafe(format!("SET application_name = '{name}'"))); } - database + database.connections.insert(default, connection); } #[cfg(test)] mod tests { - use super::application_name; + use std::io::Write; + use std::sync::{Arc, Mutex}; + + use super::*; #[test] fn an_application_name_is_used_only_when_it_is_safe() { @@ -111,4 +566,113 @@ mod tests { assert_eq!(application_name("web'; DROP TABLE x; --"), None); assert_eq!(application_name(&"a".repeat(64)), None); } + + #[test] + fn the_schema_has_no_mistakes() { + assert_eq!(schema().mistakes(PREFIX), Vec::::new()); + } + + /// The CLI and the renderers share the prefix: a server setting may share a name with one of theirs only when it + /// means the same thing (`VISUALCI_API_URL` is the API's address to both; the renderer token and version are the + /// renderers' own values). + #[test] + fn no_setting_takes_another_programs_name() { + let schema = schema(); + for name in OTHER_PROGRAMS { + assert!(schema.variables().all(|v| v.name != *name), "{name} is another program's"); + } + } + + #[test] + fn every_default_is_valid() { + let (_, problems) = Config::load_reporting(&|_: &str| None, false); + assert!(problems.iter().all(|p| !p.message.contains("default")), "{problems:?}"); + } + + /// A captured log, for asserting what was logged. + #[derive(Clone, Default)] + struct Captured(Arc>>); + + impl Write for Captured { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn captured(f: impl FnOnce()) -> String { + let log = Captured::default(); + let writer = log.clone(); + let subscriber = + tracing_subscriber::fmt().with_writer(move || writer.clone()).with_ansi(false).without_time().finish(); + tracing::subscriber::with_default(subscriber, f); + String::from_utf8(log.0.lock().unwrap().clone()).unwrap() + } + + #[test] + fn an_unknown_variable_is_warned_about_with_the_closest_known_one() { + let names = ["VISUALCI_S3_BUKET", "VISUALCI_TOKEN", "VISUALCI_S3_BUCKET", "PATH", "S3_BUCKET"]; + let log = captured(|| { + let unknown = warn_unknown(names.map(String::from)); + assert_eq!(unknown.len(), 1, "{unknown:?}"); + }); + assert!(log.contains("WARN"), "{log}"); + assert!( + log.contains("VISUALCI_S3_BUKET is set, but nothing reads it (did you mean VISUALCI_S3_BUCKET?)"), + "{log}" + ); + assert!(!log.contains("VISUALCI_TOKEN"), "the CLI's: {log}"); + } + + #[test] + fn secrets_are_masked_when_the_configuration_is_logged() { + let env = [ + ("VISUALCI_S3_ENDPOINT", "http://127.0.0.1:59000"), + ("VISUALCI_S3_BUCKET", "visualci-test"), + ("VISUALCI_S3_ACCESS_KEY_ID", "key-id-not-for-logs"), + ("VISUALCI_S3_SECRET_ACCESS_KEY", "s3-secret-not-for-logs"), + ("VISUALCI_RENDERER_TOKEN", "renderer-secret-not-for-logs"), + ("VISUALCI_RENDERER_VERSION", "7"), + ("VISUALCI_STRIPE_SECRET_KEY", "sk_live_secret-not-for-logs"), + ("VISUALCI_EMAILS_HEARTBEAT_TOKEN", "heartbeat-secret-not-for-logs"), + ]; + let settings = Config::load(&env, false).expect("valid"); + let summary = settings.summary().to_string(); + let debug = format!("{settings:?}"); + let log = captured(|| tracing::info!(settings = %settings.summary(), "VisualCI configuration")); + for shown in [&summary, &debug, &log] { + assert!(!shown.contains("not-for-logs"), "{shown}"); + } + assert!(summary.contains("VISUALCI_S3_BUCKET=visualci-test"), "{summary}"); + assert!(summary.contains("VISUALCI_RENDERER_TOKEN="), "{summary}"); + assert!(summary.contains("VISUALCI_RENDERER_VERSION=7"), "{summary}"); + } + + /// The docs page and `.env.example` are generated from the schema: CI fails when they differ. + #[test] + fn the_generated_docs_match_the_schema() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let files = [ + (root.join("../frontend/content/docs/self-hosting/environment-variables.md"), docs_page()), + (root.join(".env.example"), dotenv_example()), + ]; + let update = std::env::var("VISUALCI_GOLDEN_UPDATE").is_ok_and(|v| v == "1"); + for (path, expected) in files { + if update { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, &expected).unwrap(); + continue; + } + let committed = std::fs::read_to_string(&path).unwrap_or_default(); + assert!( + committed == expected, + "{} differs from app/src/config.rs's settings: run app/'s tests with VISUALCI_GOLDEN_UPDATE=1 and \ + commit it", + path.display() + ); + } + } } diff --git a/app/src/console/demo.rs b/app/src/console/demo.rs index 01698d44..fb952645 100644 --- a/app/src/console/demo.rs +++ b/app/src/console/demo.rs @@ -20,7 +20,7 @@ impl DemoReset { Box::pin(demo::reset(&store, &crate::http::api::builds::renderer_version())).await } .await; - heartbeat::push("VISUALCI_DEMO_HEARTBEAT", result.as_ref().map(|_| ()).map_err(ToString::to_string)).await; + heartbeat::push(heartbeat::Heartbeat::Demo, result.as_ref().map(|_| ()).map_err(ToString::to_string)).await; let builds = result?; console.line(format!("demo reset: {}/{} has {builds} builds", demo::ORG, demo::PROJECT)); Ok(()) diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs index aceb8069..64cb643c 100644 --- a/app/src/console/mod.rs +++ b/app/src/console/mod.rs @@ -25,7 +25,7 @@ async fn sweep_builds() -> laravel::Result<()> { Ok(swept) => tracing::info!(?swept, "builds swept"), Err(e) => tracing::error!(error = %e, "sweeping builds failed"), } - heartbeat::push("VISUALCI_BUILDS_EXPIRE_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)) + heartbeat::push(heartbeat::Heartbeat::BuildsExpire, outcome.as_ref().map(|_| ()).map_err(ToString::to_string)) .await; outcome.map(|_| ()) } diff --git a/app/src/console/retention.rs b/app/src/console/retention.rs index 959311de..dc23a63c 100644 --- a/app/src/console/retention.rs +++ b/app/src/console/retention.rs @@ -43,7 +43,7 @@ impl RetentionPrune { if let Ok(n) = &pruned { console.line(format!("downloads: deleted {n}")); } - heartbeat::push("VISUALCI_RETENTION_HEARTBEAT", outcome.clone()).await; + heartbeat::push(heartbeat::Heartbeat::Retention, outcome.clone()).await; console.line(format!("retention ({} days): deleted {}", self.days, result?)); outcome.map_err(laravel::Error::msg) } @@ -68,7 +68,7 @@ impl GroupsCheck { } Err(e) => Err(e.to_string()), }; - heartbeat::push("VISUALCI_GROUPS_CHECK_HEARTBEAT", outcome.clone()).await; + heartbeat::push(heartbeat::Heartbeat::GroupsCheck, outcome.clone()).await; outcome.map_err(laravel::Error::msg)?; console.line("groups:check: every sourced group has its rows"); Ok(()) diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 78086582..f795c97e 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -6,57 +6,12 @@ use laravel::http::client; use serde_json::Value; use super::Permission; +use crate::config::GithubApp; fn api() -> String { super::github_api() } -/// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its -/// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. -#[derive(Clone, laravel::config::Section)] -pub struct GithubApp { - #[env("GITHUB_APP_ID")] - pub app_id: Option, - #[env("GITHUB_APP_PRIVATE_KEY_BASE64")] - pub private_key_base64: Option, - #[env("GITHUB_WEBHOOK_SECRET")] - pub webhook_secret: Option, -} - -/// At boot: production runs only with GitHub fully configured. Sign-in needs the OAuth application -/// (`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`), and checks, pull request comments and the webhook need the App -/// (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`, `GITHUB_WEBHOOK_SECRET`). Without them the app would start -/// with no way to sign in and nothing reported to GitHub, and say so nowhere (3 Dec 2026: the cutover's manifests -/// read the wrong Secret keys, and the sign-in page offered no forge). -/// -/// # Errors -/// In production, naming each setting that's missing. -pub fn check(app: &GithubApp, apps: &crate::auth::sign_in::ForgeApps, production: bool) -> laravel::Result<()> { - if !production { - return Ok(()); - } - let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); - let missing: Vec<&str> = [ - ("GITHUB_CLIENT_ID", &apps.github), - ("GITHUB_CLIENT_SECRET", &apps.github_secret), - ("GITHUB_APP_ID", &app.app_id), - ("GITHUB_APP_PRIVATE_KEY_BASE64", &app.private_key_base64), - ("GITHUB_WEBHOOK_SECRET", &app.webhook_secret), - ] - .into_iter() - .filter(|(_, v)| !set(v)) - .map(|(name, _)| name) - .collect(); - if missing.is_empty() { - return Ok(()); - } - Err(laravel::Error::msg(format!( - "GitHub isn't configured: {} not set. Production needs all five: without them nobody can sign in, and no \ - check or pull request comment reaches GitHub.", - missing.join(", ") - ))) -} - fn err(e: impl std::fmt::Display) -> laravel::Error { laravel::Error::msg(format!("GitHub: {e}")) } @@ -72,7 +27,9 @@ struct AppClaims { fn app_jwt(app: &GithubApp) -> laravel::Result { use base64::Engine; let (Some(id), Some(key)) = (app.app_id.as_deref(), app.private_key_base64.as_deref()) else { - return Err(err("the GitHub App isn't configured (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY_BASE64)")); + return Err(err( + "the GitHub App isn't configured (VISUALCI_GITHUB_APP_ID, VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64)", + )); }; let now = laravel::now().timestamp().as_second(); let claims = AppClaims { iat: now - 60, exp: now + 540, iss: id.to_string() }; diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 0aadecb5..8ac41c19 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -9,14 +9,6 @@ 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, @@ -158,18 +150,6 @@ fn level_of(project: &Value) -> i64 { .unwrap_or(0) } -/// VisualCI's bot user on the GitLab of [`GitlabConfig`] (`VISUALCI_GITLAB_BOT_TOKEN`, a personal access token with -/// the `api` scope). GitLab has no app installations: a project gives VisualCI access by adding the bot as a member, -/// and every server-side call about it (access checks, commit statuses, merge request notes) uses the bot's token. -#[derive(Clone, laravel::config::Section)] -pub struct GitlabBot { - #[env("VISUALCI_GITLAB_BOT_TOKEN")] - pub token: Option, - /// The bot's username, for telling people whom to invite. - #[env("VISUALCI_GITLAB_BOT_USERNAME", default = "visualci")] - pub username: String, -} - /// The `installation` of a project VisualCI reaches through its bot. pub const BOT: &str = "bot"; diff --git a/app/src/forge/installations.rs b/app/src/forge/installations.rs index 1abc797c..606b9dd1 100644 --- a/app/src/forge/installations.rs +++ b/app/src/forge/installations.rs @@ -17,9 +17,10 @@ use laravel::db; use serde::Serialize; use serde_json::{Value, json}; -use super::github_app::{self, GithubApp}; +use super::github_app; use super::{Installation, Permission, Repository}; use crate::auth::Role; +use crate::config::GithubApp; use crate::models::{Membership, Organization, Project, User}; use crate::models::{slug_from, valid_slug}; diff --git a/app/src/forge/link.rs b/app/src/forge/link.rs index e98f514e..e8d48989 100644 --- a/app/src/forge/link.rs +++ b/app/src/forge/link.rs @@ -11,9 +11,11 @@ use laravel::db; -use super::github_app::{self, GithubApp}; -use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::github_app; +use super::gitlab; use super::{ForgeKind, Permission, Repository}; +use crate::config::GithubApp; +use crate::config::Gitlab; use crate::models::{Project, User}; use crate::notify::{self, Kind, To}; @@ -91,19 +93,20 @@ pub async fn link_repository( Reached { installation, permission, repository_id } } ForgeKind::Gitlab => { - let (Some(gitlab), Some(bot)) = (config.get::(), config.get::()) else { + let Some(gitlab) = config.get::() else { return Err(bad(format!("{label} isn't set up on this server"))); }; let base = gitlab.url.trim_end_matches('/'); // A project on another GitLab is one an organization added: not ported yet - let (true, Some(token)) = (repository.site_url().eq_ignore_ascii_case(base), bot.token.as_deref()) else { + let (true, Some(token)) = (repository.site_url().eq_ignore_ascii_case(base), gitlab.bot_token.as_deref()) + else { return Err(bad(format!("{label} isn't set up on this server"))); }; let Some(installation) = gitlab::installation_for(base, token, &repository.path).await? else { return Err(bad(format!( "VisualCI can't reach {} on {label} yet: {}", repository.path, - gitlab::install_hint(base, &bot.username, &repository.path) + gitlab::install_hint(base, &gitlab.bot_username, &repository.path) ))); }; let forge_user = identity(&gitlab::site_of(base)).await?.ok_or_else(|| signed_out(label, &repository))?; diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs index 9ac5ae12..1fe70edc 100644 --- a/app/src/forge/open_source.rs +++ b/app/src/forge/open_source.rs @@ -18,7 +18,8 @@ use serde_json::Value; use super::Repository; use super::events::RepositoryVisibilityChanged; -use super::github_app::{self, GithubApp}; +use super::github_app; +use crate::config::GithubApp; use crate::notify::{self, Kind, To}; /// OSI-approved licences, by the SPDX ids GitHub reports (the common ones; GitHub names only licences it recognises). diff --git a/app/src/forge/outbound.rs b/app/src/forge/outbound.rs index 8a6cb1fe..856fcdb6 100644 --- a/app/src/forge/outbound.rs +++ b/app/src/forge/outbound.rs @@ -21,17 +21,10 @@ use laravel::stream::StreamExt; /// The largest response body read from an organization's server. pub const MAX_BODY: usize = 8 * 1024 * 1024; -#[derive(Clone, Debug, laravel::config::Section)] -pub struct Outbound { - /// `1` lets requests reach private addresses: a development server's local GitLab only. - #[env("VISUALCI_FORGE_PRIVATE_ADDRESSES")] - pub private_addresses: Option, -} - -/// Whether requests may reach private addresses (`VISUALCI_FORGE_PRIVATE_ADDRESSES=1`, development only). +/// Whether requests may reach private addresses (`VISUALCI_FORGE_PRIVATE_ADDRESSES`, development only). #[must_use] pub fn private_allowed() -> bool { - laravel::config().get::().is_some_and(|o| o.private_addresses.as_deref() == Some("1")) + laravel::config().get::().is_some_and(|g| g.private_addresses) } /// Whether an address is on the public internet: not private, loopback, link-local (169.254.0.0/16: cloud metadata), @@ -100,8 +93,7 @@ impl reqwest::dns::Resolve for PublicOnly { /// Whether a base URL is one this server chose (its GitLab, GitHub), not an organization. fn trusted(base: &str) -> bool { let base = base.trim_end_matches('/'); - let gitlab = - laravel::config().get::().map(|g| g.url.trim_end_matches('/').to_string()); + let gitlab = laravel::config().get::().map(|g| g.url.trim_end_matches('/').to_string()); base.eq_ignore_ascii_case(&super::github_api()) || base.eq_ignore_ascii_case(&super::github_web()) || gitlab.is_some_and(|g| base.eq_ignore_ascii_case(&g)) diff --git a/app/src/forge/report.rs b/app/src/forge/report.rs index 20809fc8..5a6bde54 100644 --- a/app/src/forge/report.rs +++ b/app/src/forge/report.rs @@ -5,10 +5,12 @@ use laravel::http::client; use serde_json::{Value, json}; -use super::github_app::{self, GithubApp}; -use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::github_app; +use super::gitlab; use super::outbound::{self, Reply}; use super::{ForgeKind, Repository}; +use crate::config::GithubApp; +use crate::config::Gitlab; use crate::models::Project; fn github() -> String { @@ -63,8 +65,9 @@ fn gitlab_target(project: &Project) -> Option<(Target, Repository)> { let repository = Repository::parse(project.repository_url.as_deref()?).map(|r| r.with_id(project.repository_id.clone()))?; let config = laravel::config(); - let base = config.get::()?.url.trim_end_matches('/').to_string(); - let token = config.get::()?.token.clone()?; + let gitlab = config.get::()?; + let base = gitlab.url.trim_end_matches('/').to_string(); + let token = gitlab.bot_token.clone()?; (project.forge_installation.as_deref() == Some(gitlab::BOT) && repository.site_url().eq_ignore_ascii_case(&base)) .then_some((Target::Gitlab { base, token }, repository)) } diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index cc211a16..11e0e93a 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -18,8 +18,9 @@ use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; use super::Permission; -use super::github_app::{self, GithubApp}; +use super::github_app; use super::webhooks::{self, Reach}; +use crate::config::GithubApp; /// What a run did. #[derive(Debug, Default, PartialEq, Eq)] @@ -205,8 +206,9 @@ pub struct SyncForges; impl SyncForges { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { if app.app_id.as_deref().is_none_or(str::is_empty) { - let health = Err("the GitHub App isn't configured (GITHUB_APP_ID), so nobody's access is rechecked".into()); - crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; + let health = + Err("the GitHub App isn't configured (VISUALCI_GITHUB_APP_ID), so nobody's access is rechecked".into()); + crate::heartbeat::push(crate::heartbeat::Heartbeat::ForgeSync, health).await; return Ok(()); } let result = sync_github(&app).await; @@ -225,7 +227,7 @@ impl SyncForges { Ok(()) } }; - crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; + crate::heartbeat::push(crate::heartbeat::Heartbeat::ForgeSync, health).await; result.map(|_| ()) } } diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index 23f5114e..92d51dde 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -19,8 +19,9 @@ use serde_json::{Value, json}; use sha2::Sha256; use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; -use super::github_app::{self, GithubApp}; +use super::github_app; use super::{ForgeKind, Permission, Repository}; +use crate::config::GithubApp; /// One delivery, as VisualCI acts on it. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs index abc91f2a..10b3aea3 100644 --- a/app/src/heartbeat.rs +++ b/app/src/heartbeat.rs @@ -1,16 +1,50 @@ -//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`_URL` and -//! `_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported -//! from today's server. +//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (each job's +//! `VISUALCI__HEARTBEAT_URL` and `_TOKEN`, [`crate::config::Heartbeats`]), so a run that failed, or no run at all, +//! alerts. Ported from today's server. use laravel::http::client; -/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead. -pub async fn push(prefix: &str, result: Result<(), String>) { - let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return }; - if url.is_empty() { - return; +use crate::config::Heartbeats; + +/// The jobs that push a heartbeat. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Heartbeat { + Emails, + SignUps, + Live, + DevicePrune, + ForgeSync, + Retention, + Demo, + BuildsExpire, + GroupsCheck, +} + +impl Heartbeats { + /// A job's endpoint and token. + #[must_use] + pub fn of(&self, heartbeat: Heartbeat) -> (Option<&str>, Option<&str>) { + let (url, token) = match heartbeat { + Heartbeat::Emails => (&self.emails_url, &self.emails_token), + Heartbeat::SignUps => (&self.signups_url, &self.signups_token), + Heartbeat::Live => (&self.live_url, &self.live_token), + Heartbeat::DevicePrune => (&self.device_prune_url, &self.device_prune_token), + Heartbeat::ForgeSync => (&self.forge_sync_url, &self.forge_sync_token), + Heartbeat::Retention => (&self.retention_url, &self.retention_token), + Heartbeat::Demo => (&self.demo_url, &self.demo_token), + Heartbeat::BuildsExpire => (&self.builds_expire_url, &self.builds_expire_token), + Heartbeat::GroupsCheck => (&self.groups_check_url, &self.groups_check_token), + }; + (url.as_deref(), token.as_deref()) } - let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default(); +} + +/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead. +pub async fn push(heartbeat: Heartbeat, result: Result<(), String>) { + let config = laravel::config(); + let (url, token) = config.section::().of(heartbeat); + let Some(url) = url.map(str::to_string) else { return }; + let token = token.unwrap_or_default().to_string(); let (success, error) = match result { Ok(()) => ("true", String::new()), Err(e) => ("false", e), @@ -18,7 +52,7 @@ pub async fn push(prefix: &str, result: Result<(), String>) { let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await; match sent { Ok(response) if response.successful() => {} - Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"), - Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"), + Ok(response) => tracing::warn!(?heartbeat, status = %response.status(), "heartbeat refused"), + Err(e) => tracing::warn!(?heartbeat, error = %e, "heartbeat failed"), } } diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 09ebd0d1..e7599ea8 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -23,7 +23,7 @@ pub fn routes(route: &mut Router) { route.get("/v1/builds/{pid}/snapshots", list_snapshots); } -/// The renderer version documents are drawn with: part of the render cache key (`RENDERER_VERSION`, required). +/// The renderer version documents are drawn with: part of the render cache key (`VISUALCI_RENDERER_VERSION`, required). #[must_use] pub fn renderer_version() -> String { laravel::config().section::().version.clone() diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs index 14e9f69c..8b8ef8d2 100644 --- a/app/src/http/app_shell.rs +++ b/app/src/http/app_shell.rs @@ -5,7 +5,8 @@ use axum::http::{Method, Uri}; -use super::hosts::{Host, HostUrls}; +use super::hosts::Host; +use crate::config::HostUrls; /// Whether the path's last segment names a file (`logo.png`), other than an HTML page. #[must_use] diff --git a/app/src/http/gallery.rs b/app/src/http/gallery.rs index 73dc950c..7ed74d83 100644 --- a/app/src/http/gallery.rs +++ b/app/src/http/gallery.rs @@ -70,7 +70,7 @@ fn guard(request: &Request) -> Option { if request.uri().query().is_some() { return Some(status(StatusCode::NOT_FOUND, "not found")); } - // The caller: the request's address resolved through the trusted proxies (`TRUSTED_PROXIES`). Behind Cloudflare's + // The caller: the request's address resolved through the trusted proxies (`VISUALCI_TRUSTED_PROXIES`). Behind Cloudflare's // tunnel and Envoy, that's the client Cloudflare names (no hop comes from Cloudflare's own ranges), and a client // can't choose it by sending headers of its own. if !allowed(&request.ip().to_string()) { diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index d3605a72..b0ef4807 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -16,19 +16,7 @@ use laravel::config::Section; use laravel::http::{Next, Request, Response, middleware}; -/// The four hosts' URLs (`VISUALCI_SITE_URL`, `VISUALCI_APP_URL`, `VISUALCI_API_URL`, `VISUALCI_MCP_URL`). Without -/// all four, every host serves every path. -#[derive(Clone, laravel::config::Section)] -pub struct HostUrls { - #[env("VISUALCI_SITE_URL")] - pub site: Option, - #[env("VISUALCI_APP_URL")] - pub app: Option, - #[env("VISUALCI_API_URL")] - pub api: Option, - #[env("VISUALCI_MCP_URL")] - pub mcp: Option, -} +use crate::config::HostUrls; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Host { @@ -63,6 +51,12 @@ impl HostUrls { pub fn site(&self) -> &str { self.site.as_deref().unwrap_or("").trim_end_matches('/') } + + /// The web app's address for links in emails and redirects: `VISUALCI_APP_URL`, else `http://localhost`. + #[must_use] + pub fn app_url(&self) -> &str { + self.app.as_deref().filter(|u| !u.trim().is_empty()).unwrap_or("http://localhost").trim_end_matches('/') + } } fn under(path: &str, prefix: &str) -> bool { diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index ce900178..e6badc34 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -8,7 +8,7 @@ pub mod renderer; pub mod status; pub mod ui; -/// Whether a request failed because every pooled database connection was in use for `DB_ACQUIRE_TIMEOUT`: the +/// Whether a request failed because every pooled database connection was in use for `VISUALCI_DB_ACQUIRE_TIMEOUT`: the /// answer is a 503 with Retry-After, so clients (the CLI retries) back off instead of piling on. #[must_use] pub fn busy(e: &laravel::Error) -> bool { diff --git a/app/src/http/security.rs b/app/src/http/security.rs index e23a5285..4b1a3664 100644 --- a/app/src/http/security.rs +++ b/app/src/http/security.rs @@ -77,13 +77,6 @@ pub fn policy(hashes: &[String], storage: Option<&str>) -> String { ) } -/// The storage's public endpoint, for the policy's images. -#[derive(Clone, laravel::config::Section)] -pub struct Frontend { - #[env("S3_PUBLIC_ENDPOINT")] - pub storage_endpoint: Option, -} - /// An origin (`scheme://host[:port]`) from a URL. fn origin(url: &str) -> Option { let (scheme, rest) = url.trim().split_once("://")?; @@ -109,7 +102,8 @@ pub fn policy_for(page: &std::path::Path, storage: Option<&str>) -> Result laravel::Result<()> { - let storage = config.section::().storage_endpoint.as_deref().and_then(origin); + // The storage's public endpoint, for the policy's images + let storage = config.section::().public_endpoint.as_deref().and_then(origin); let page = config.app.public_path("index.html"); if let Ok(html) = std::fs::read_to_string(&page) { let _ = INDEX.set(html); diff --git a/app/src/http/ui/projects.rs b/app/src/http/ui/projects.rs index 0f8426a0..046d6057 100644 --- a/app/src/http/ui/projects.rs +++ b/app/src/http/ui/projects.rs @@ -128,7 +128,7 @@ pub async fn show_project(auth: Auth, Params((org, project)): Params<(Stri /// The API host's URL (`VISUALCI_API_URL`), else the app's. fn api_url() -> String { let settings = laravel::config(); - let hosts = settings.section::(); + let hosts = settings.section::(); hosts.api.as_deref().map_or_else(app_url, |u| u.trim_end_matches('/').to_string()) } diff --git a/app/src/lib.rs b/app/src/lib.rs index 9b2c2b55..86439384 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -33,35 +33,34 @@ pub fn configure() -> ApplicationBuilder { .with_auth(|auth, _| { auth.session::(); }) + // Every VisualCI setting, from the environment (config.rs) + .with_config(config::install) .with_services(|app| { app.social().extend("gitlab", |config| forge::gitlab::Driver { - url: config.section::().url.clone(), + url: config.section::().url.clone(), }); }) .booted(async |app| { let config = app.config(); + let production = config.app.env.is_production(); + config::check(config)?; + config::report(config); auth::oauth::check( config.section::(), - config.section::(), - config.app.env.is_production(), + config.section::(), + production, )?; - http::hosts::check(config.section::(), config.app.env.is_production())?; + http::hosts::check(config.section::(), production)?; forge::check_github(config)?; - config.section::().check(config.app.env.is_production())?; - billing::check(config.section::(), config.app.env.is_production())?; - http::security::check(config, config.app.env.is_production())?; - config.section::().check(&config.app.env)?; - notify::postmark::check(config.section::(), config.app.env.is_production())?; - forge::github_app::check( - config.section::(), - config.section::(), - config.app.env.is_production(), - )?; + billing::check(config.section::(), production)?; + http::security::check(config, production)?; + config.section::().check(&config.app.env)?; Ok(()) }) - .with_middleware(|middleware, _| { - if let Err(e) = middleware.try_trust_proxies(config::trusted_proxies()) { - tracing::error!(error = %e, "TRUSTED_PROXIES: trusting no proxies"); + .with_middleware(|middleware, config| { + let proxies = config.section::().trusted_proxies.clone(); + if let Err(e) = middleware.try_trust_proxies(proxies) { + tracing::error!(error = %e, "VISUALCI_TRUSTED_PROXIES: trusting no proxies"); } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted @@ -70,15 +69,15 @@ 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 + // The development sign-in (refused in production and unless VISUALCI_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, config| { - // The development sign-in exists only in local and testing, with DEV_LOGIN on - if auth::sign_in::DevLogin::routable(config) { + // The development sign-in exists only in local and testing, with VISUALCI_DEV_LOGIN on + if config::DevLogin::routable(config) { routing.web(|route| { route.post("/auth/dev-login", auth::sign_in::dev_login); }); diff --git a/app/src/live.rs b/app/src/live.rs index e12b3d12..0c252824 100644 --- a/app/src/live.rs +++ b/app/src/live.rs @@ -38,11 +38,14 @@ pub const MAX_TOPIC: usize = 1000; const PROBE_EVERY: Duration = Duration::from_secs(60); const PROBE_WITHIN: Duration = Duration::from_secs(10); -/// Where the listener connects: the application's database. -#[derive(Clone, laravel::config::Section)] -pub struct LiveDatabase { - #[env("DATABASE_URL")] - pub url: Option, +/// Where the listener connects: the application's database, as its URL (`DATABASE_URL`). +#[must_use] +pub fn database_url(config: &laravel::config::Config) -> Option { + let database = &config.database; + match &database.connections.get(&database.default)?.source { + laravel::config::database::Source::Url(url) if !url.is_empty() => Some(url.clone()), + _ => None, + } } /// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. @@ -202,8 +205,9 @@ pub struct CheckLive; #[job] impl CheckLive { - async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { - let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; + async fn handle(self) -> laravel::Result<()> { + let Some(url) = database_url(&laravel::config()) else { return Ok(()) }; + let url = url.as_str(); let mut rx = subscribe(url); let health = if ready(url, PROBE_WITHIN).await { let probe = format!("probe:{}", laravel::str::random(12)); @@ -215,7 +219,7 @@ impl CheckLive { } else { Err("the listener isn't LISTENing".to_string()) }; - crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; + crate::heartbeat::push(crate::heartbeat::Heartbeat::Live, health.clone()).await; health.map_err(laravel::Error::msg) } } diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 8b1a1cb9..ebebb69e 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -2252,7 +2252,7 @@ fn service() -> Service { .get_or_init(|| { let mut hosts = vec!["localhost".to_string(), "127.0.0.1".to_string()]; let config = laravel::config(); - let configured = config.section::(); + let configured = config.section::(); let urls = [&configured.mcp, &configured.api, &configured.app, &configured.site] .into_iter() .flatten() @@ -2263,9 +2263,7 @@ fn service() -> Service { hosts.push(host); } } - if let Ok(extra) = std::env::var("VISUALCI_MCP_HOSTS") { - hosts.extend(extra.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_string)); - } + hosts.extend(config.section::().mcp_hosts.iter().cloned()); hosts.sort(); hosts.dedup(); StreamableHttpService::new( @@ -2319,7 +2317,7 @@ fn unauthorized(sent: bool) -> Response { fn resource() -> String { let config = laravel::config(); let base = config - .get::() + .get::() .and_then(|h| h.mcp.clone()) .filter(|u| !u.trim().is_empty()) .unwrap_or_else(|| config.app.url.clone()); diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs index a6638095..968c44be 100644 --- a/app/src/notify/outbox.rs +++ b/app/src/notify/outbox.rs @@ -4,8 +4,9 @@ use laravel::db; use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; -use super::postmark::{self, Postmark}; +use super::postmark; use super::render::{About, Kind, Preference, render}; +use crate::config::Postmark; /// Who gets an email. #[derive(Clone, Debug)] @@ -111,9 +112,9 @@ impl DeliverEmails { async fn handle( self, postmark: laravel::config::Section, - app: laravel::config::Section, + hosts: laravel::config::Section, ) -> laravel::Result<()> { - let delivered = deliver(&postmark, &app.url).await; + let delivered = deliver(&postmark, hosts.app_url()).await; // The heartbeat checks the work, not just the run: an email waiting more than half an hour fails it let health = match &delivered { Err(e) => Err(e.to_string()), @@ -123,7 +124,7 @@ impl DeliverEmails { Err(e) => Err(e.to_string()), }, }; - crate::heartbeat::push("VISUALCI_EMAILS_HEARTBEAT", health).await; + crate::heartbeat::push(crate::heartbeat::Heartbeat::Emails, health).await; delivered?; Ok(()) } @@ -132,13 +133,6 @@ impl DeliverEmails { /// How long an email may wait unsent before the heartbeat fails. pub const STALE_SECONDS: i64 = 30 * 60; -/// The web app's URL, for the links in emails. -#[derive(Clone, laravel::config::Section)] -pub struct AppUrl { - #[env("VISUALCI_APP_URL", default = "http://localhost")] - pub url: String, -} - /// Anything left over (a failed send, a worker that stopped) goes out within five minutes. #[schedule::tasks] fn schedule(schedule: &mut Schedule) { diff --git a/app/src/notify/postmark.rs b/app/src/notify/postmark.rs index 3dbfe8b8..b6c0d0d6 100644 --- a/app/src/notify/postmark.rs +++ b/app/src/notify/postmark.rs @@ -1,32 +1,10 @@ -//! Sending one email through Postmark's API (`POSTMARK_SERVER_TOKEN`, `MAIL_FROM`, `MAIL_REPLY_TO`). Without a token, -//! nothing is sent and the outbox keeps the emails pending. +//! Sending one email through Postmark's API (`VISUALCI_POSTMARK_SERVER_TOKEN`, `VISUALCI_MAIL_FROM`, +//! `VISUALCI_MAIL_REPLY_TO`). Without a token, nothing is sent and the outbox keeps the emails pending. use laravel::http::client; use serde_json::json; -#[derive(Clone, laravel::config::Section)] -pub struct Postmark { - #[env("POSTMARK_SERVER_TOKEN")] - pub token: Option, - #[env("MAIL_FROM", default = "VisualCI ")] - pub from: String, - #[env("MAIL_REPLY_TO", default = "support@visualci.com")] - pub reply_to: String, -} - -/// At boot: production sends email, so it needs `POSTMARK_SERVER_TOKEN`. Without it, every email (invitations, -/// receipts, sign-in notices) would wait in the outbox for good, and say so nowhere. -/// -/// # Errors -/// In production, when the token isn't set. -pub fn check(postmark: &Postmark, production: bool) -> laravel::Result<()> { - if production && postmark.token.as_deref().is_none_or(|t| t.trim().is_empty()) { - return Err(laravel::Error::msg( - "POSTMARK_SERVER_TOKEN isn't set: production needs it, or no email is ever sent", - )); - } - Ok(()) -} +use crate::config::Postmark; /// Send one email with its text and HTML bodies. /// diff --git a/app/src/testing.rs b/app/src/testing.rs index 4882bb72..7fc11e6a 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -39,14 +39,14 @@ pub fn configure() -> ApplicationBuilder { ("WORKFLOW_STORE", "memory"), ("DB_CONNECTION", "pgsql"), // The test blob store: RustFS in CI, MinIO on a development machine, both on port 59000. - ("S3_ENDPOINT", "http://127.0.0.1:59000"), - ("S3_BUCKET", "visualci-test"), - ("S3_ACCESS_KEY_ID", "visualci"), - ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), + ("VISUALCI_S3_ENDPOINT", "http://127.0.0.1:59000"), + ("VISUALCI_S3_BUCKET", "visualci-test"), + ("VISUALCI_S3_ACCESS_KEY_ID", "visualci"), + ("VISUALCI_S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), ("APP_URL", "https://app.visualci.test"), - ("RENDERER_TOKEN", "renderer-test-token"), - ("RENDERER_VERSION", "1"), - ("METRICS_TOKEN", "metrics-test-token"), + ("VISUALCI_RENDERER_TOKEN", "renderer-test-token"), + ("VISUALCI_RENDERER_VERSION", "1"), + ("VISUALCI_METRICS_TOKEN", "metrics-test-token"), ]) .with_env("DATABASE_URL", url) .refresh_database() @@ -73,12 +73,12 @@ pub mod fixtures { /// The blob store, with its bucket made. Fails, naming the store, when it isn't running: a test never skips. /// /// # Errors - /// When the store (`S3_ENDPOINT`, RustFS or MinIO on port 59000 in development and CI) isn't reachable. + /// When the store (`VISUALCI_S3_ENDPOINT`, RustFS or MinIO on port 59000 in development and CI) isn't reachable. pub async fn blob_store() -> laravel::Result { let store = crate::storage::BlobStore::current().await?; store.ensure_bucket().await.map_err(|e| { laravel::Error::msg(format!( - "the blob store isn't reachable (S3_ENDPOINT, RustFS or MinIO on 127.0.0.1:59000 in CI): {e}" + "the blob store isn't reachable (VISUALCI_S3_ENDPOINT, RustFS or MinIO on 127.0.0.1:59000 in CI): {e}" )) })?; Ok(store) diff --git a/app/tests/billing.rs b/app/tests/billing.rs index 6f4beda9..5cac8161 100644 --- a/app/tests/billing.rs +++ b/app/tests/billing.rs @@ -14,7 +14,7 @@ use sha2::Sha256; const SECRET: &str = "whsec_test"; fn stripe() -> Application { - app::testing::configure().with_env("STRIPE_WEBHOOK_SECRET", SECRET).create() + app::testing::configure().with_env("VISUALCI_STRIPE_WEBHOOK_SECRET", SECRET).create() } fn signed(body: &str, t: i64) -> String { @@ -107,7 +107,7 @@ async fn a_paid_pack_is_credited_once(app: Application) -> laravel::Result<()> { fn with_stripe_key() -> Application { app::testing::configure() - .with_envs([("STRIPE_SECRET_KEY", "sk_test_x"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) + .with_envs([("VISUALCI_STRIPE_SECRET_KEY", "sk_test_x"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) .create() } @@ -154,19 +154,19 @@ async fn only_admins_check_out_and_get_a_stripe_url(app: Application) -> laravel #[test] fn production_never_runs_on_a_test_key() { let stripe = - |key: &str| app::billing::Stripe { secret_key: Some(key.into()), webhook_secret: Some("whsec_x".into()) }; + |key: &str| app::config::Stripe { secret_key: Some(key.into()), webhook_secret: Some("whsec_x".into()) }; assert!(app::billing::check(&stripe("sk_test_x"), true).is_err()); assert!(app::billing::check(&stripe("rk_test_x"), true).is_err()); assert!(app::billing::check(&stripe("rk_live_x"), true).is_ok()); assert!(app::billing::check(&stripe("sk_test_x"), false).is_ok()); - let unset = app::billing::Stripe { secret_key: None, webhook_secret: None }; - assert!(app::billing::check(&unset, true).is_err(), "production needs Stripe"); + // Unset, production doesn't start at all (tests/hosts.rs): there's no key to check + let unset = app::config::Stripe { secret_key: None, webhook_secret: None }; assert!(app::billing::check(&unset, false).is_ok()); } fn stripe_test_key() -> Application { app::testing::configure() - .with_envs([("STRIPE_WEBHOOK_SECRET", SECRET), ("STRIPE_SECRET_KEY", "sk_test_x")]) + .with_envs([("VISUALCI_STRIPE_WEBHOOK_SECRET", SECRET), ("VISUALCI_STRIPE_SECRET_KEY", "sk_test_x")]) .create() } diff --git a/app/tests/emails.rs b/app/tests/emails.rs index e6042fb7..0830b544 100644 --- a/app/tests/emails.rs +++ b/app/tests/emails.rs @@ -61,7 +61,7 @@ async fn org_with_admins() -> laravel::Result<(i64, User, User)> { } fn postmark() -> Application { - app::testing::configure().with_env("POSTMARK_SERVER_TOKEN", "test-token").create() + app::testing::configure().with_env("VISUALCI_POSTMARK_SERVER_TOKEN", "test-token").create() } #[laravel::test(app = postmark)] @@ -123,7 +123,7 @@ async fn claims_are_per_email_and_attempts_end_at_five(_app: Application) -> lar ) .insert() .await?; - let config = app::notify::postmark::Postmark { + let config = app::config::Postmark { token: Some("test-token".into()), from: "VisualCI ".into(), reply_to: "support@visualci.com".into(), diff --git a/app/tests/forge_reports.rs b/app/tests/forge_reports.rs index 3ee28e72..ec615723 100644 --- a/app/tests/forge_reports.rs +++ b/app/tests/forge_reports.rs @@ -1,6 +1,6 @@ //! What VisualCI posts to a linked project's forge: a check per suite and one comment per pull request, kept up to //! date as builds change. The comment's Markdown is compared with golden files in `tests/goldens/`; run with -//! `UPDATE_GOLDENS=1` to rewrite them after a change you meant, and read the diff. +//! `VISUALCI_GOLDEN_UPDATE=1` to rewrite them after a change you meant, and read the diff. use app::domain::builds::Stats; use app::domain::reviews::Shown; @@ -14,17 +14,17 @@ use laravel::http::client; use laravel::model::create; use laravel::testing::prelude::*; -/// The golden file `tests/goldens/` says `body`, or is rewritten with it under `UPDATE_GOLDENS=1`. +/// The golden file `tests/goldens/` says `body`, or is rewritten with it under `VISUALCI_GOLDEN_UPDATE=1`. fn golden(name: &str, body: &str) { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens").join(name); - if std::env::var("UPDATE_GOLDENS").is_ok_and(|v| v == "1") { + if std::env::var("VISUALCI_GOLDEN_UPDATE").is_ok_and(|v| v == "1") { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, body).unwrap(); return; } let expected = std::fs::read_to_string(&path) - .unwrap_or_else(|_| panic!("no golden {name}: run with UPDATE_GOLDENS=1 to write it, then read it")); - assert_eq!(body, expected, "the {name} golden differs: run with UPDATE_GOLDENS=1 if the change is meant"); + .unwrap_or_else(|_| panic!("no golden {name}: run with VISUALCI_GOLDEN_UPDATE=1 to write it, then read it")); + assert_eq!(body, expected, "the {name} golden differs: run with VISUALCI_GOLDEN_UPDATE=1 if the change is meant"); } fn suite(state: &str, stats: Stats) -> Suite { @@ -133,8 +133,8 @@ fn app_key() -> &'static str { fn github_app() -> Application { app::testing::configure() - .with_env("GITHUB_APP_ID", "1") - .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .with_env("VISUALCI_GITHUB_APP_ID", "1") + .with_env("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) .create() } diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs index 29a4aada..e872b6b9 100644 --- a/app/tests/forge_sync.rs +++ b/app/tests/forge_sync.rs @@ -1,7 +1,7 @@ //! The hourly sync rechecks everyone with a GitHub identity: a membership GitHub no longer grants (here, its //! organization's repository was unlinked) goes, one made by an invitation stays. -use app::forge::github_app::GithubApp; +use app::config::GithubApp; use app::forge::sync::{Synced, sync_github}; use app::models::User; use laravel::db; diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 836d98e8..c69ab98f 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -43,20 +43,20 @@ fn in_production_with_no_sign_ups_setting() -> laravel::foundation::ApplicationB ("QUEUE_CONNECTION", "sync"), ("DB_CONNECTION", "pgsql"), ("DATABASE_URL", app::testing::database_url().as_str()), - ("S3_ENDPOINT", "http://127.0.0.1:59000"), - ("S3_BUCKET", "visualci-test"), - ("S3_ACCESS_KEY_ID", "visualci"), - ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), - ("RENDERER_TOKEN", "renderer-test-token"), - ("RENDERER_VERSION", "1"), + ("VISUALCI_S3_ENDPOINT", "http://127.0.0.1:59000"), + ("VISUALCI_S3_BUCKET", "visualci-test"), + ("VISUALCI_S3_ACCESS_KEY_ID", "visualci"), + ("VISUALCI_S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), + ("VISUALCI_RENDERER_TOKEN", "renderer-test-token"), + ("VISUALCI_RENDERER_VERSION", "1"), ("GITHUB_CLIENT_ID", "Iv1.test"), ("GITHUB_CLIENT_SECRET", "github-test-secret"), - ("GITHUB_APP_ID", "1"), - ("GITHUB_APP_PRIVATE_KEY_BASE64", "dGVzdA=="), - ("GITHUB_WEBHOOK_SECRET", "github-webhook-test-secret"), - ("STRIPE_SECRET_KEY", "rk_live_test"), - ("STRIPE_WEBHOOK_SECRET", "whsec_test"), - ("POSTMARK_SERVER_TOKEN", "postmark-test-token"), + ("VISUALCI_GITHUB_APP_ID", "1"), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", "dGVzdA=="), + ("VISUALCI_GITHUB_WEBHOOK_SECRET", "github-webhook-test-secret"), + ("VISUALCI_STRIPE_SECRET_KEY", "rk_live_test"), + ("VISUALCI_STRIPE_WEBHOOK_SECRET", "whsec_test"), + ("VISUALCI_POSTMARK_SERVER_TOKEN", "postmark-test-token"), ]) } @@ -104,9 +104,8 @@ async fn production_doesnt_boot_with_a_host_url_that_names_no_host() { /// caught at deploy time instead of opening sign-ups (3 Dec 2026). #[tokio::test] async fn production_doesnt_boot_without_saying_whether_sign_ups_are_open() { - let app = in_production_with_no_sign_ups_setting().create(); - let error = app.boot().await.expect_err("no VISUALCI_WAITLIST"); - assert!(error.to_string().contains("VISUALCI_WAITLIST"), "{error}"); + let error = in_production_with_no_sign_ups_setting().create().boot().await.expect_err("no VISUALCI_WAITLIST"); + assert!(error.to_string().contains("VISUALCI_WAITLIST is required in production, but isn't set"), "{error}"); in_production_with_no_sign_ups_setting() .with_env("VISUALCI_WAITLIST", "false") .create() @@ -185,7 +184,7 @@ async fn every_response_carries_the_security_headers(app: Application) { .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 +/// The development sign-in can't exist in production: production won't boot with VISUALCI_DEV_LOGIN on, and without it the /// route isn't there (a 405: only GET /auth/{forge} matches the path) and the providers don't offer it. #[tokio::test(flavor = "multi_thread")] async fn production_has_no_development_sign_in() { @@ -197,12 +196,13 @@ async fn production_has_no_development_sign_in() { ("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:?}"); + let flagged = in_production().with_envs(hosts).with_env("VISUALCI_DEV_LOGIN", "true").create(); + let refused = flagged.boot().await.expect_err("production doesn't boot with VISUALCI_DEV_LOGIN on"); + assert!(format!("{refused:?}").contains("VISUALCI_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"); + let misspelt = + in_production().with_envs(hosts).with_env("APP_ENV", "prod").with_env("VISUALCI_DEV_LOGIN", "true").create(); + let refused = misspelt.boot().await.expect_err("APP_ENV=prod doesn't boot with VISUALCI_DEV_LOGIN on"); assert!(format!("{refused:?}").contains("APP_ENV=prod"), "{refused:?}"); let app = in_production().with_envs(hosts).create(); @@ -228,18 +228,30 @@ async fn production_needs_github_stripe_and_email_configured() { ("OAUTH_ISSUER", "https://mcp.visualci.test"), ("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"), ]; - // The cutover's mistake: the GitHub settings empty, as an optional secret key that doesn't exist leaves them - let unset = in_production().with_envs(hosts).with_envs([("GITHUB_CLIENT_ID", ""), ("GITHUB_WEBHOOK_SECRET", "")]); - let refused = unset.create().boot().await.expect_err("production doesn't boot without GitHub"); - let message = format!("{refused:?}"); - assert!(message.contains("GITHUB_CLIENT_ID, GITHUB_WEBHOOK_SECRET not set"), "{message}"); - - // Stripe and Postmark the same way - for name in ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "POSTMARK_SERVER_TOKEN"] { + // The cutover's mistake: the GitHub settings empty, as an optional secret key that doesn't exist leaves them. + // Production doesn't start, and lists every setting it needs at once (app/src/config.rs). + let unset = + in_production().with_envs(hosts).with_envs([("GITHUB_CLIENT_ID", ""), ("VISUALCI_GITHUB_WEBHOOK_SECRET", "")]); + let message = unset.create().boot().await.expect_err("production doesn't start without GitHub").to_string(); + assert!(message.contains("GITHUB_CLIENT_ID is required in production, but isn't set"), "{message}"); + assert!(message.contains("VISUALCI_GITHUB_WEBHOOK_SECRET is required in production, but isn't set"), "{message}"); + + // Stripe, Postmark and the waitlist the same way + for name in [ + "VISUALCI_STRIPE_SECRET_KEY", + "VISUALCI_STRIPE_WEBHOOK_SECRET", + "VISUALCI_POSTMARK_SERVER_TOKEN", + "VISUALCI_GITHUB_APP_ID", + "VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", + "GITHUB_CLIENT_SECRET", + ] { let refused = in_production().with_envs(hosts).with_env(name, "").create().boot().await; - let message = format!("{:?}", refused.expect_err("production doesn't boot without it")); - assert!(message.contains(name), "{name}: {message}"); + let message = refused.expect_err("production doesn't start without it").to_string(); + assert!(message.contains(&format!("{name} is required in production")), "{name}: {message}"); } + // Outside production they're optional + let testing = app::testing::configure().with_envs([("VISUALCI_STRIPE_SECRET_KEY", "")]).create(); + testing.boot().await.expect("testing starts without Stripe"); let app = in_production().with_envs(hosts).create(); app.boot().await.expect("it boots with all five"); diff --git a/app/tests/installations.rs b/app/tests/installations.rs index 73360497..d911de4d 100644 --- a/app/tests/installations.rs +++ b/app/tests/installations.rs @@ -28,15 +28,15 @@ fn app_key() -> &'static str { fn github() -> Application { app::testing::configure() .with_envs([ - ("GITHUB_WEBHOOK_SECRET", SECRET), - ("GITHUB_APP_ID", "1"), - ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET), + ("VISUALCI_GITHUB_APP_ID", "1"), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), ]) .create() } -fn github_app() -> app::forge::github_app::GithubApp { - app::forge::github_app::GithubApp { +fn github_app() -> app::config::GithubApp { + app::config::GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None, diff --git a/app/tests/link.rs b/app/tests/link.rs index 814eb8ad..3f4747f5 100644 --- a/app/tests/link.rs +++ b/app/tests/link.rs @@ -25,8 +25,8 @@ fn app_key() -> &'static str { /// The GitHub App and the gitlab.com bot both set up. fn forges() -> Application { app::testing::configure() - .with_env("GITHUB_APP_ID", "1") - .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .with_env("VISUALCI_GITHUB_APP_ID", "1") + .with_env("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) .with_env("VISUALCI_GITLAB_BOT_TOKEN", "bot-token") .create() } diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index a5198e83..a5a9eacb 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1235,8 +1235,8 @@ fn app_key() -> &'static str { /// The GitHub App set up. fn forges() -> Application { app::testing::configure() - .with_env("GITHUB_APP_ID", "1") - .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .with_env("VISUALCI_GITHUB_APP_ID", "1") + .with_env("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) .create() } diff --git a/app/tests/oauth.rs b/app/tests/oauth.rs index cfc46edb..6b3afff9 100644 --- a/app/tests/oauth.rs +++ b/app/tests/oauth.rs @@ -3,7 +3,7 @@ //! the hosts. use app::auth::oauth::check; -use app::http::hosts::HostUrls; +use app::config::HostUrls; use app::models::User; use laravel::model::create; use laravel::testing::prelude::*; diff --git a/app/tests/proxies.rs b/app/tests/proxies.rs index c124f2e1..eeb923e6 100644 --- a/app/tests/proxies.rs +++ b/app/tests/proxies.rs @@ -1,4 +1,4 @@ -//! Behind the trusted proxies (`TRUSTED_PROXIES`, Envoy's nodes in production), a request's address is the right-most +//! Behind the trusted proxies (`VISUALCI_TRUSTED_PROXIES`, Envoy's nodes in production), a request's address is the right-most //! `X-Forwarded-For` entry that isn't a trusted proxy: the client Cloudflare appended, never an address the client //! sent itself. The public gallery's rate limit keys on it, so rotating a forged first entry doesn't dodge the limit. //! Its own test binary: the gallery's rate-limit counter is per process. diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index 18ae82cf..d041cfa1 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -294,11 +294,11 @@ async fn a_forge_without_its_secret_is_not_offered(app: Application) { } fn dev_login() -> Application { - app::testing::configure().with_env("DEV_LOGIN", "true").create() + app::testing::configure().with_env("VISUALCI_DEV_LOGIN", "true").create() } /// The development sign-in, for local work and CI's screenshots: signs in by email (making the account), posted -/// without a browser's same-origin header; the providers say it's there. Off unless DEV_LOGIN is set. +/// without a browser's same-origin header; the providers say it's there. Off unless VISUALCI_DEV_LOGIN is set. #[laravel::test(app = dev_login)] async fn the_development_sign_in_signs_in_by_email(app: Application) -> laravel::Result<()> { app.get("/auth/providers").await.assert_ok().assert_json_path("dev_login", true); diff --git a/app/tests/ui.rs b/app/tests/ui.rs index 9153c0f3..6cbdd7f5 100644 --- a/app/tests/ui.rs +++ b/app/tests/ui.rs @@ -364,8 +364,8 @@ fn app_key() -> &'static str { /// The GitHub App set up. fn forges() -> Application { app::testing::configure() - .with_env("GITHUB_APP_ID", "1") - .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .with_env("VISUALCI_GITHUB_APP_ID", "1") + .with_env("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) .create() } diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs index 27974837..e213d1fe 100644 --- a/app/tests/webhooks.rs +++ b/app/tests/webhooks.rs @@ -14,7 +14,7 @@ use sha2::Sha256; const SECRET: &str = "github-webhook-test"; -/// A GitHub App key made once per run (base64 of its PEM, as GITHUB_APP_PRIVATE_KEY_BASE64 holds it). +/// A GitHub App key made once per run (base64 of its PEM, as VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64 holds it). fn app_key() -> &'static str { static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); KEY.get_or_init(|| { @@ -29,15 +29,15 @@ fn app_key() -> &'static str { fn github() -> Application { app::testing::configure() .with_envs([ - ("GITHUB_WEBHOOK_SECRET", SECRET), - ("GITHUB_APP_ID", "1"), - ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET), + ("VISUALCI_GITHUB_APP_ID", "1"), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), ]) .create() } -fn github_app() -> app::forge::github_app::GithubApp { - app::forge::github_app::GithubApp { +fn github_app() -> app::config::GithubApp { + app::config::GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None, diff --git a/crates/envschema-derive/Cargo.toml b/crates/envschema-derive/Cargo.toml new file mode 100644 index 00000000..d83baa6a --- /dev/null +++ b/crates/envschema-derive/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "envschema-derive" +description = "The derive macro for envschema: typed settings read from environment variables" +version = "0.1.0" +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full"] } diff --git a/crates/envschema-derive/src/lib.rs b/crates/envschema-derive/src/lib.rs new file mode 100644 index 00000000..1679c447 --- /dev/null +++ b/crates/envschema-derive/src/lib.rs @@ -0,0 +1,310 @@ +//! `#[derive(Settings)]` for [envschema](https://github.com/DocSpring/visualci/tree/main/crates/envschema). The +//! attributes are documented on the derive's re-export, `envschema::Settings`. + +use proc_macro::TokenStream; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::quote; +use syn::parse::{Parse, ParseStream}; +use syn::{ + Attribute, Data, DeriveInput, Error, Expr, Fields, GenericArgument, Ident, Lit, LitStr, PathArguments, Token, Type, +}; + +#[proc_macro_derive(Settings, attributes(env, settings))] +pub fn derive_settings(input: TokenStream) -> TokenStream { + let input = syn::parse_macro_input!(input as DeriveInput); + match expand(&input) { + Ok(tokens) => tokens.into(), + Err(error) => error.to_compile_error().into(), + } +} + +/// One field's `#[env("NAME", ...)]`. +struct EnvAttr { + name: LitStr, + default: Option, + example: Option, + required: bool, + required_in_production: bool, + secret: bool, +} + +impl Parse for EnvAttr { + fn parse(input: ParseStream) -> syn::Result { + let name: LitStr = input.parse()?; + let mut attr = EnvAttr { + name, + default: None, + example: None, + required: false, + required_in_production: false, + secret: false, + }; + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let key: Ident = input.parse()?; + match key.to_string().as_str() { + "required" => attr.required = true, + "required_in_production" => attr.required_in_production = true, + "secret" => attr.secret = true, + "default" => { + input.parse::()?; + attr.default = Some(literal_text(&input.parse()?)?); + } + "example" => { + input.parse::()?; + let lit: LitStr = input.parse()?; + attr.example = Some(lit.value()); + } + other => { + return Err(Error::new( + key.span(), + format!( + "unknown `env` option `{other}`: expected default, example, required, \ + required_in_production or secret" + ), + )); + } + } + } + Ok(attr) + } +} + +/// A default's text, as the docs show it and the value parses it: a string's contents, a number's digits, or +/// `true`/`false`. +fn literal_text(lit: &Lit) -> syn::Result { + match lit { + Lit::Str(s) => Ok(s.value()), + Lit::Int(i) => Ok(i.base10_digits().to_string()), + Lit::Float(f) => Ok(f.base10_digits().to_string()), + Lit::Bool(b) => Ok(b.value.to_string()), + other => Err(Error::new(other.span(), "a default is a string, number or boolean literal")), + } +} + +/// `#[settings(nested)]` on a field, `#[settings(title = "...")]` on the struct. +#[derive(Default)] +struct SettingsAttr { + nested: bool, + title: Option, +} + +fn settings_attr(attrs: &[Attribute]) -> syn::Result { + let mut out = SettingsAttr::default(); + for attr in attrs.iter().filter(|a| a.path().is_ident("settings")) { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("nested") { + out.nested = true; + Ok(()) + } else if meta.path.is_ident("title") { + let lit: LitStr = meta.value()?.parse()?; + out.title = Some(lit.value()); + Ok(()) + } else { + Err(meta.error("expected `nested` or `title = \"...\"`")) + } + })?; + } + Ok(out) +} + +/// The doc comment's text: lines joined with spaces, a blank line kept as a paragraph break. +fn doc_text(attrs: &[Attribute]) -> String { + let mut lines = Vec::new(); + for attr in attrs.iter().filter(|a| a.path().is_ident("doc")) { + if let syn::Meta::NameValue(nv) = &attr.meta + && let Expr::Lit(expr) = &nv.value + && let Lit::Str(s) = &expr.lit + { + lines.push(s.value().trim().to_string()); + } + } + let mut text = String::new(); + for line in lines { + if line.is_empty() { + if !text.is_empty() && !text.ends_with("\n\n") { + text.push_str("\n\n"); + } + } else { + if !text.is_empty() && !text.ends_with('\n') { + text.push(' '); + } + text.push_str(&line); + } + } + text.trim().to_string() +} + +/// `T` when `ty` is `Option`. +fn option_inner(ty: &Type) -> Option<&Type> { + let Type::Path(path) = ty else { return None }; + let last = path.path.segments.last()?; + if last.ident != "Option" { + return None; + } + let PathArguments::AngleBracketed(args) = &last.arguments else { return None }; + match args.args.first()? { + GenericArgument::Type(inner) if args.args.len() == 1 => Some(inner), + _ => None, + } +} + +fn expand(input: &DeriveInput) -> syn::Result { + let ident = &input.ident; + if !input.generics.params.is_empty() { + return Err(Error::new_spanned(&input.generics, "Settings can't be derived for a generic struct")); + } + let Data::Struct(data) = &input.data else { + return Err(Error::new(Span::call_site(), "Settings can only be derived for a struct")); + }; + let Fields::Named(fields) = &data.fields else { + return Err(Error::new(Span::call_site(), "Settings needs a struct with named fields")); + }; + + let struct_attr = settings_attr(&input.attrs)?; + let title = struct_attr.title.unwrap_or_else(|| ident.to_string()); + let group_doc = doc_text(&input.attrs); + + let mut variables = Vec::new(); + let mut nested_groups = Vec::new(); + let mut reads = Vec::new(); + let mut shows = Vec::new(); + let mut debugs = Vec::new(); + + for field in &fields.named { + let name = field.ident.as_ref().expect("named field"); + let ty = &field.ty; + let field_attr = settings_attr(&field.attrs)?; + let env_attrs: Vec<&Attribute> = field.attrs.iter().filter(|a| a.path().is_ident("env")).collect(); + + if field_attr.nested { + if !env_attrs.is_empty() { + return Err(Error::new_spanned(name, "a nested field has no `env` attribute")); + } + nested_groups.push(quote! { <#ty as ::envschema::Settings>::groups(out); }); + reads.push(quote! { #name: <#ty as ::envschema::Settings>::read(loader), }); + shows.push(quote! { ::envschema::Settings::describe(&self.#name, out); }); + debugs.push(quote! { .field(stringify!(#name), &self.#name) }); + continue; + } + + let [attr] = env_attrs.as_slice() else { + return Err(Error::new_spanned( + name, + "each field needs one `#[env(\"NAME\", ...)]` attribute, or `#[settings(nested)]`", + )); + }; + let env: EnvAttr = attr.parse_args()?; + let description = doc_text(&field.attrs); + if description.is_empty() { + return Err(Error::new_spanned( + name, + "document the setting: its doc comment is its description in the docs", + )); + } + let var_name = env.name.value(); + if var_name.is_empty() || !var_name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') { + return Err(Error::new(env.name.span(), "a variable's name is upper case letters, digits and underscores")); + } + + let inner = option_inner(ty); + let value_ty = inner.unwrap_or(ty); + let read = match (inner.is_some(), env.default.is_some(), env.required) { + (true, false, false) => quote! { loader.optional::<#value_ty>(&VARIABLE) }, + (false, true, false) => quote! { loader.defaulted::<#value_ty>(&VARIABLE) }, + (false, false, true) => quote! { loader.required::<#value_ty>(&VARIABLE) }, + (true, _, _) => { + return Err(Error::new_spanned(ty, "an Option setting takes neither `default` nor `required`")); + } + (false, true, true) => { + return Err(Error::new_spanned(name, "a setting is either `required` or has a `default`")); + } + (false, false, false) => { + return Err(Error::new_spanned( + ty, + "a setting that isn't an Option needs `default = ...` or `required`", + )); + } + }; + if env.required_in_production && inner.is_none() { + return Err(Error::new_spanned(ty, "`required_in_production` is for Option settings")); + } + + let default = match &env.default { + Some(d) => quote! { ::core::option::Option::Some(#d) }, + None => quote! { ::core::option::Option::None }, + }; + let example = match &env.example { + Some(e) => quote! { ::core::option::Option::Some(#e) }, + None => quote! { ::core::option::Option::None }, + }; + let (required, required_in_production, secret) = (env.required, env.required_in_production, env.secret); + let variable = quote! { + ::envschema::Variable { + name: #var_name, + description: #description, + kind: <#value_ty as ::envschema::Value>::KIND, + default: #default, + example: #example, + required: #required, + required_in_production: #required_in_production, + secret: #secret, + } + }; + variables.push(variable.clone()); + reads.push(quote! { #name: { const VARIABLE: ::envschema::Variable = #variable; #read }, }); + + let shown = if inner.is_some() { + quote! { self.#name.as_ref().map(::envschema::Value::show) } + } else { + quote! { ::core::option::Option::Some(::envschema::Value::show(&self.#name)) } + }; + shows.push(quote! { + out.push(::envschema::Shown::new(#var_name, #secret, #shown)); + }); + debugs.push(match (secret, inner.is_some()) { + (true, true) => quote! { .field(stringify!(#name), &self.#name.as_ref().map(|_| ::envschema::Redacted)) }, + (true, false) => quote! { .field(stringify!(#name), &::envschema::Redacted) }, + (false, _) => quote! { .field(stringify!(#name), &self.#name) }, + }); + } + + let own_group = if variables.is_empty() { + quote! {} + } else { + quote! { + out.push(::envschema::Group { + title: #title, + description: #group_doc, + variables: ::std::vec![#(#variables),*], + external: false, + }); + } + }; + + Ok(quote! { + impl ::envschema::Settings for #ident { + fn groups(out: &mut ::std::vec::Vec<::envschema::Group>) { + #own_group + #(#nested_groups)* + } + + fn read(loader: &mut ::envschema::Loader<'_>) -> Self { + Self { #(#reads)* } + } + + fn describe(&self, out: &mut ::std::vec::Vec<::envschema::Shown>) { + #(#shows)* + } + } + + impl ::core::fmt::Debug for #ident { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(#ident)) #(#debugs)* .finish() + } + } + }) +} diff --git a/crates/envschema/Cargo.toml b/crates/envschema/Cargo.toml new file mode 100644 index 00000000..2a1f91ac --- /dev/null +++ b/crates/envschema/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "envschema" +description = "Typed settings from prefixed environment variables, with one schema for loading, checks, secret masking, warnings about unknown variables, and generated docs" +version = "0.1.0" +edition.workspace = true +license.workspace = true +repository.workspace = true +keywords = ["config", "environment", "env", "settings", "dotenv"] +categories = ["config"] +# Used by VisualCI's server for now; published once its API has settled. +publish = false + +[dependencies] +envschema-derive = { path = "../envschema-derive", version = "0.1.0" } diff --git a/crates/envschema/src/lib.rs b/crates/envschema/src/lib.rs new file mode 100644 index 00000000..df3e9446 --- /dev/null +++ b/crates/envschema/src/lib.rs @@ -0,0 +1,784 @@ +//! Typed settings from prefixed environment variables, described once. +//! +//! A struct with `#[derive(Settings)]` is the schema: each field names its variable, and its doc comment, type, +//! default, and whether it's required, required in production or secret come with it. From that one description, +//! envschema: +//! +//! - reads the struct from any [`Source`] (the process's environment, a map, a framework's own environment), listing +//! every missing or invalid variable at once instead of stopping at the first; +//! - checks the settings production can't run without ([`Loader::production`]); +//! - finds variables with the app's prefix that nothing reads, a typo or a renamed setting, and names the closest +//! known one ([`Schema::unknown`]); +//! - masks secrets in `Debug` output and in [`Summary`], for logging what the app runs with; +//! - writes the reference docs as Markdown and a `.env.example` ([`Schema::markdown`], [`Schema::dotenv_example`]). +//! +//! ``` +//! use envschema::Settings; +//! +//! /// Where uploads are kept. +//! #[derive(Settings)] +//! #[settings(title = "Storage")] +//! struct Storage { +//! /// The bucket's endpoint. +//! #[env("APP_S3_ENDPOINT", required)] +//! endpoint: String, +//! /// The bucket's region. +//! #[env("APP_S3_REGION", default = "auto")] +//! region: String, +//! /// The secret key. +//! #[env("APP_S3_SECRET", secret, required_in_production)] +//! secret: Option, +//! } +//! +//! let env = [("APP_S3_ENDPOINT", "http://127.0.0.1:9000"), ("APP_S3_SECRET", "shh"), ("APP_S3_REGOIN", "eu")]; +//! let storage = Storage::load(&env, true).unwrap(); +//! assert_eq!(storage.region, "auto"); +//! assert!(!format!("{storage:?}").contains("shh")); +//! +//! let unknown = Storage::schema().unknown("APP_", env.iter().map(|(name, _)| *name)); +//! assert_eq!(unknown[0].closest, Some("APP_S3_REGION")); +//! ``` + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; + +/// `#[derive(Settings)]`: the struct's fields are settings, each read from one environment variable. +/// +/// On a field: +/// +/// - `#[env("NAME")]` on an `Option` field: optional, `None` when unset. +/// - `#[env("NAME", default = "...")]`: the default when unset. A string, number or boolean literal, parsed like the +/// variable's value and shown as-is in the docs. +/// - `#[env("NAME", required)]`: loading fails when it's unset. +/// - `required_in_production` (on an `Option` field): loading fails when it's unset and the loader is in +/// production mode. +/// - `secret`: masked in `Debug` output and [`Summary`]. +/// - `example = "..."`: an example value for the docs and `.env.example`. +/// - `#[settings(nested)]`, instead of `#[env]`: another `Settings` struct, whose settings are its own group. +/// +/// Every `#[env]` field needs a doc comment: it's the setting's description in the docs. On the struct, +/// `#[settings(title = "...")]` titles the group in the docs (the struct's name otherwise), and the struct's doc +/// comment introduces it. The derive also implements `Debug`, with secrets masked, so don't derive `Debug` as well. +pub use envschema_derive::Settings; + +/// Where variables are read from. +pub trait Source { + /// The variable's value, or `None` when it's unset. An empty value counts as unset. + fn get(&self, name: &str) -> Option; +} + +/// The process's environment. +#[derive(Clone, Copy, Debug, Default)] +pub struct ProcessEnv; + +impl Source for ProcessEnv { + fn get(&self, name: &str) -> Option { + std::env::var(name).ok() + } +} + +impl Option> Source for F { + fn get(&self, name: &str) -> Option { + self(name) + } +} + +impl Source for HashMap { + fn get(&self, name: &str) -> Option { + HashMap::get(self, name).cloned() + } +} + +impl Source for BTreeMap { + fn get(&self, name: &str) -> Option { + BTreeMap::get(self, name).cloned() + } +} + +/// Pairs, as tests write them. A name given twice reads its last value. +impl Source for [(&str, &str); N] { + fn get(&self, name: &str) -> Option { + self.iter().rev().find(|(key, _)| *key == name).map(|(_, value)| (*value).to_string()) + } +} + +impl Source for Vec<(&str, &str)> { + fn get(&self, name: &str) -> Option { + self.iter().rev().find(|(key, _)| *key == name).map(|(_, value)| (*value).to_string()) + } +} + +/// A setting's type: how a variable's text becomes a value, and back for the logs. +pub trait Value: Sized { + /// The type's name in the docs, such as `string` or `integer`. + const KIND: &'static str; + + /// Parse a variable's (non-empty) value. + /// + /// # Errors + /// Why the text isn't a valid value, such as "expected a whole number". + fn parse(raw: &str) -> Result; + + /// The value as a variable would hold it. + fn show(&self) -> String; +} + +impl Value for String { + const KIND: &'static str = "string"; + + fn parse(raw: &str) -> Result { + Ok(raw.to_string()) + } + + fn show(&self) -> String { + self.clone() + } +} + +/// `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are false, in any case. +impl Value for bool { + const KIND: &'static str = "boolean"; + + fn parse(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "true" | "1" | "yes" | "on" => Ok(true), + "false" | "0" | "no" | "off" => Ok(false), + _ => Err("expected true or false (or 1/0, yes/no, on/off)".to_string()), + } + } + + fn show(&self) -> String { + self.to_string() + } +} + +macro_rules! integers { + ($($t:ty),*) => {$( + impl Value for $t { + const KIND: &'static str = "integer"; + + fn parse(raw: &str) -> Result { + raw.trim().replace('_', "").parse().map_err(|e| format!("expected a whole number ({e})")) + } + + fn show(&self) -> String { + self.to_string() + } + } + )*}; +} +integers!(i16, i32, i64, u8, u16, u32, u64, usize); + +impl Value for f64 { + const KIND: &'static str = "number"; + + fn parse(raw: &str) -> Result { + raw.trim().parse().map_err(|e| format!("expected a number ({e})")) + } + + fn show(&self) -> String { + self.to_string() + } +} + +/// A comma-separated list. Items are trimmed, and empty ones dropped. +impl Value for Vec { + const KIND: &'static str = "comma-separated list"; + + fn parse(raw: &str) -> Result { + raw.split(',').map(str::trim).filter(|item| !item.is_empty()).map(T::parse).collect() + } + + fn show(&self) -> String { + self.iter().map(Value::show).collect::>().join(",") + } +} + +/// One setting, as the schema describes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Variable { + pub name: &'static str, + pub description: &'static str, + /// The type's name ([`Value::KIND`]). + pub kind: &'static str, + pub default: Option<&'static str>, + pub example: Option<&'static str>, + pub required: bool, + pub required_in_production: bool, + pub secret: bool, +} + +impl Variable { + /// A string variable read by something else (a framework, a library), described for the docs. Set the rest with + /// the builder methods. + #[must_use] + pub const fn new(name: &'static str, description: &'static str) -> Self { + Self { + name, + description, + kind: "string", + default: None, + example: None, + required: false, + required_in_production: false, + secret: false, + } + } + + #[must_use] + pub const fn kind(mut self, kind: &'static str) -> Self { + self.kind = kind; + self + } + + #[must_use] + pub const fn default(mut self, default: &'static str) -> Self { + self.default = Some(default); + self + } + + #[must_use] + pub const fn example(mut self, example: &'static str) -> Self { + self.example = Some(example); + self + } + + #[must_use] + pub const fn required(mut self) -> Self { + self.required = true; + self + } + + #[must_use] + pub const fn required_in_production(mut self) -> Self { + self.required_in_production = true; + self + } + + #[must_use] + pub const fn secret(mut self) -> Self { + self.secret = true; + self + } +} + +/// The settings of one struct, or variables something else reads ([`Group::external`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Group { + pub title: &'static str, + pub description: &'static str, + pub variables: Vec, + /// Read by something else (a framework, a library, the test suite), and described here so the docs and the + /// unknown-variable check cover them too. + pub external: bool, +} + +impl Group { + /// Variables something else reads, described alongside the app's own. + #[must_use] + pub fn external(title: &'static str, description: &'static str, variables: &[Variable]) -> Self { + Self { title, description, variables: variables.to_vec(), external: true } + } +} + +/// Every group of settings, in order: what the docs list, and what the unknown-variable check knows. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Schema { + pub groups: Vec, + /// Names with the prefix that belong to other programs (a CLI sharing the prefix), so they're never unknown. Not + /// in the docs. + pub ignored: Vec<&'static str>, +} + +/// A variable with the prefix that nothing reads. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unknown { + pub name: String, + /// The known variable whose name is closest. + pub closest: Option<&'static str>, +} + +impl fmt::Display for Unknown { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} is set, but nothing reads it", self.name)?; + if let Some(closest) = self.closest { + write!(f, " (did you mean {closest}?)")?; + } + Ok(()) + } +} + +impl Schema { + /// Add variables something else reads, after the struct's own groups. + #[must_use] + pub fn with_group(mut self, group: Group) -> Self { + self.groups.push(group); + self + } + + /// Names with the prefix that other programs read. + #[must_use] + pub fn ignoring(mut self, names: &[&'static str]) -> Self { + self.ignored.extend_from_slice(names); + self + } + + /// Every variable, in the docs' order. + pub fn variables(&self) -> impl Iterator { + self.groups.iter().flat_map(|group| group.variables.iter()) + } + + /// Mistakes in the schema itself: a name used twice, or one of the struct's own settings without the prefix. + /// Worth a unit test. + #[must_use] + pub fn mistakes(&self, prefix: &str) -> Vec { + let mut seen = BTreeSet::new(); + let mut mistakes = Vec::new(); + for group in &self.groups { + for variable in &group.variables { + if !seen.insert(variable.name) { + mistakes.push(format!("{} is described twice", variable.name)); + } + if !group.external && !variable.name.starts_with(prefix) { + mistakes.push(format!("{} ({}) doesn't start with {prefix}", variable.name, group.title)); + } + if self.ignored.contains(&variable.name) { + mistakes.push(format!("{} is both a setting and ignored as another program's", variable.name)); + } + } + } + mistakes + } + + /// The variables in `names` that start with `prefix` but that the schema doesn't know (described nowhere, and + /// not ignored), each with the known variable whose name is closest. + pub fn unknown<'a>(&self, prefix: &str, names: impl IntoIterator) -> Vec { + let known: Vec<&'static str> = self.variables().map(|v| v.name).collect(); + let mut unknown: Vec = names + .into_iter() + .filter(|name| name.starts_with(prefix) && !known.contains(name) && !self.ignored.contains(name)) + .map(|name| Unknown { name: name.to_string(), closest: closest(name, &known) }) + .collect(); + unknown.sort_by(|a, b| a.name.cmp(&b.name)); + unknown.dedup(); + unknown + } + + /// The external variables production needs that `source` doesn't set. The struct's own are checked as it loads. + #[must_use] + pub fn missing_in_production(&self, source: &dyn Source) -> Vec { + self.groups + .iter() + .filter(|group| group.external) + .flat_map(|group| group.variables.iter()) + .filter(|v| v.required_in_production && present(source, v.name).is_none()) + .map(|v| Problem::missing_in_production(v.name)) + .collect() + } + + /// The reference docs: a section per group with a table of its variables. + #[must_use] + pub fn markdown(&self) -> String { + let mut out = String::new(); + for group in &self.groups { + out.push_str(&format!("## {}\n\n", group.title)); + if !group.description.is_empty() { + out.push_str(group.description); + out.push_str("\n\n"); + } + out.push_str("| Variable | Type | Default | Description |\n| --- | --- | --- | --- |\n"); + for v in &group.variables { + let default = + v.default.map_or_else(String::new, |d| if d.is_empty() { "(empty)".into() } else { code(d) }); + out.push_str(&format!( + "| {} | {} | {} | {} |\n", + code(v.name), + v.kind, + cell(&default), + cell(&describe(v)), + )); + } + out.push('\n'); + } + out.truncate(out.trim_end().len()); + out.push('\n'); + out + } + + /// A `.env.example`: every variable with its description, the required ones to fill in, the rest commented out + /// with their defaults. + #[must_use] + pub fn dotenv_example(&self) -> String { + let mut out = String::new(); + for group in &self.groups { + let rule = "#".repeat(118); + out.push_str(&format!("{rule}\n# {}\n{rule}\n\n", group.title)); + for v in &group.variables { + for line in wrap(&describe(v).replace("**", "").replace('`', ""), 116) { + out.push_str(&format!("# {line}\n")); + } + let value = v.example.or(v.default).unwrap_or(""); + if v.required || v.required_in_production { + out.push_str(&format!("{}={}\n\n", v.name, quote_env(value))); + } else { + out.push_str(&format!("# {}={}\n\n", v.name, quote_env(value))); + } + } + } + out.truncate(out.trim_end().len()); + out.push('\n'); + out + } +} + +/// A variable's description with what the docs say first: required, required in production, secret, an example. +fn describe(v: &Variable) -> String { + let mut notes = Vec::new(); + if v.required { + notes.push("**Required.**".to_string()); + } else if v.required_in_production { + notes.push("**Required in production.**".to_string()); + } + if v.secret { + notes.push("Secret.".to_string()); + } + notes.push(v.description.replace("\n\n", " ")); + if let Some(example) = v.example { + notes.push(format!("Example: {}.", code(example))); + } + notes.join(" ") +} + +fn code(text: &str) -> String { + if text.contains('`') { format!("`` {text} ``") } else { format!("`{text}`") } +} + +/// Text for a Markdown table cell. +fn cell(text: &str) -> String { + text.replace('|', "\\|").replace('\n', " ") +} + +/// A value for a `.env` line, quoted when it has spaces or quotes. +fn quote_env(value: &str) -> String { + if value.chars().any(|c| c.is_whitespace() || c == '"' || c == '#' || c == '\'') { + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) + } else { + value.to_string() + } +} + +fn wrap(text: &str, width: usize) -> Vec { + let mut lines = Vec::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + if !line.is_empty() && line.len() + 1 + word.len() > width { + lines.push(std::mem::take(&mut line)); + } + if !line.is_empty() { + line.push(' '); + } + line.push_str(word); + } + if !line.is_empty() { + lines.push(line); + } + lines +} + +/// The known name closest to `name` by edit distance. +fn closest(name: &str, known: &[&'static str]) -> Option<&'static str> { + known.iter().copied().min_by_key(|candidate| distance(name, candidate)) +} + +/// Levenshtein distance, by characters. +fn distance(a: &str, b: &str) -> usize { + let b: Vec = b.chars().collect(); + let mut previous: Vec = (0..=b.len()).collect(); + for (i, ca) in a.chars().enumerate() { + let mut current = vec![i + 1; b.len() + 1]; + for (j, cb) in b.iter().enumerate() { + let substitution = previous[j] + usize::from(ca != *cb); + current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1); + } + previous = current; + } + previous[b.len()] +} + +fn present(source: &dyn Source, name: &str) -> Option { + source.get(name).filter(|value| !value.is_empty()) +} + +/// Something wrong with one variable. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Problem { + pub variable: &'static str, + pub message: String, +} + +impl Problem { + fn missing_in_production(variable: &'static str) -> Self { + Self { variable, message: format!("{variable} is required in production, but isn't set") } + } +} + +impl fmt::Display for Problem { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +/// Every problem found while loading, one per line. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Problems(pub Vec); + +impl fmt::Display for Problems { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("the environment is invalid:")?; + for problem in &self.0 { + write!(f, "\n - {problem}")?; + } + Ok(()) + } +} + +impl std::error::Error for Problems {} + +/// Reads settings from a [`Source`], noting every problem instead of stopping at the first. The derived +/// [`Settings::read`] calls it. +pub struct Loader<'a> { + source: &'a dyn Source, + production: bool, + problems: Vec, +} + +impl<'a> Loader<'a> { + #[must_use] + pub fn new(source: &'a dyn Source) -> Self { + Self { source, production: false, problems: Vec::new() } + } + + /// In production, `required_in_production` settings are required. + #[must_use] + pub fn production(mut self, production: bool) -> Self { + self.production = production; + self + } + + /// The problems found so far. + #[must_use] + pub fn problems(&self) -> &[Problem] { + &self.problems + } + + #[must_use] + pub fn into_problems(self) -> Vec { + self.problems + } + + fn parse(&mut self, variable: &Variable, raw: &str) -> Option { + match T::parse(raw) { + Ok(value) => Some(value), + Err(error) => { + let shown = if variable.secret { "a value".to_string() } else { format!("`{raw}`") }; + self.problems.push(Problem { + variable: variable.name, + message: format!("{} is set to {shown}, which is invalid: {error}", variable.name), + }); + None + } + } + } + + /// An `Option` setting. + pub fn optional(&mut self, variable: &Variable) -> Option { + match present(self.source, variable.name) { + Some(raw) => self.parse(variable, &raw), + None => { + if self.production && variable.required_in_production { + self.problems.push(Problem::missing_in_production(variable.name)); + } + None + } + } + } + + /// A setting with a default. An invalid value is a problem, and the default stands in for it. + pub fn defaulted(&mut self, variable: &Variable) -> T { + if let Some(raw) = present(self.source, variable.name) + && let Some(value) = self.parse(variable, &raw) + { + return value; + } + let default = variable.default.unwrap_or(""); + if default.is_empty() { + return T::parse(default).unwrap_or_default(); + } + match T::parse(default) { + Ok(value) => value, + Err(error) => { + self.problems.push(Problem { + variable: variable.name, + message: format!("{}'s default `{default}` is invalid: {error}", variable.name), + }); + T::default() + } + } + } + + /// A required setting. Missing or invalid is a problem, and `T::default()` stands in for it. + pub fn required(&mut self, variable: &Variable) -> T { + match present(self.source, variable.name) { + Some(raw) => self.parse(variable, &raw).unwrap_or_default(), + None => { + self.problems.push(Problem { + variable: variable.name, + message: format!("{} is required, but isn't set", variable.name), + }); + T::default() + } + } + } +} + +/// A struct of settings. Derive it with `#[derive(Settings)]`. +pub trait Settings: Sized { + /// Push this struct's group of settings, then its nested structs' groups. + fn groups(out: &mut Vec); + + /// Read every setting, noting problems in `loader`. + fn read(loader: &mut Loader<'_>) -> Self; + + /// Push each setting's name and value, secrets masked. + fn describe(&self, out: &mut Vec); + + /// The schema: every group, in order. + #[must_use] + fn schema() -> Schema { + let mut groups = Vec::new(); + Self::groups(&mut groups); + Schema { groups, ignored: Vec::new() } + } + + /// Read the settings from `source`, with what `loader` found wrong. Missing and invalid settings get their + /// defaults (or the type's), so the app can still say everything that's wrong at once. + #[must_use] + fn load_reporting(source: &dyn Source, production: bool) -> (Self, Vec) { + let mut loader = Loader::new(source).production(production); + let settings = Self::read(&mut loader); + (settings, loader.into_problems()) + } + + /// Read the settings from `source`. + /// + /// # Errors + /// Every missing or invalid setting, at once. + fn load(source: &dyn Source, production: bool) -> Result { + let (settings, problems) = Self::load_reporting(source, production); + if problems.is_empty() { Ok(settings) } else { Err(Problems(problems)) } + } + + /// The settings that are set, secrets masked: for a log line at boot. + #[must_use] + fn summary(&self) -> Summary { + let mut shown = Vec::new(); + self.describe(&mut shown); + Summary(shown) + } +} + +/// A setting's name and value for logs, a secret's value masked. +#[derive(Clone, PartialEq, Eq)] +pub struct Shown { + pub name: &'static str, + /// `None` when unset; `` for a secret that's set. + pub value: Option, +} + +impl Shown { + #[must_use] + pub fn new(name: &'static str, secret: bool, value: Option) -> Self { + let value = value.filter(|v| !v.is_empty()).map(|v| if secret { Redacted.to_string() } else { v }); + Self { name, value } + } +} + +impl fmt::Debug for Shown { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.value { + Some(value) => write!(f, "{}={value}", self.name), + None => write!(f, "{} unset", self.name), + } + } +} + +/// The settings that are set, as `NAME=value` pairs separated by spaces, secrets masked. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Summary(pub Vec); + +impl fmt::Display for Summary { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut first = true; + for shown in &self.0 { + let Some(value) = &shown.value else { continue }; + if !first { + f.write_str(" ")?; + } + first = false; + if value.chars().any(char::is_whitespace) { + write!(f, "{}={value:?}", shown.name)?; + } else { + write!(f, "{}={value}", shown.name)?; + } + } + Ok(()) + } +} + +/// What `Debug` and [`Summary`] show for a secret that's set. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Redacted; + +impl fmt::Debug for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +impl fmt::Display for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn distance_counts_edits() { + assert_eq!(distance("kitten", "sitting"), 3); + assert_eq!(distance("", "abc"), 3); + assert_eq!(distance("same", "same"), 0); + } + + #[test] + fn wrapping_keeps_words_whole() { + assert_eq!(wrap("one two three four", 9), vec!["one two", "three", "four"]); + } + + #[test] + fn env_values_are_quoted_only_when_they_need_it() { + assert_eq!(quote_env("auto"), "auto"); + assert_eq!(quote_env("VisualCI "), "\"VisualCI \""); + } + + #[test] + fn booleans_and_lists_parse_like_the_docs_say() { + assert_eq!(bool::parse("Yes"), Ok(true)); + assert_eq!(bool::parse("off"), Ok(false)); + assert!(bool::parse("maybe").is_err()); + assert_eq!(Vec::::parse(" a, b ,,c"), Ok(vec!["a".into(), "b".into(), "c".into()])); + assert_eq!(i64::parse("50_000"), Ok(50_000)); + } +} diff --git a/crates/envschema/tests/settings.rs b/crates/envschema/tests/settings.rs new file mode 100644 index 00000000..5df28a6c --- /dev/null +++ b/crates/envschema/tests/settings.rs @@ -0,0 +1,177 @@ +use envschema::{Group, Settings, Variable}; + +/// Where uploads go. +#[derive(Settings, Clone)] +#[settings(title = "Storage")] +struct Storage { + /// The bucket's endpoint. + #[env("APP_S3_ENDPOINT", required, example = "http://127.0.0.1:9000")] + endpoint: String, + /// The region. + #[env("APP_S3_REGION", default = "auto")] + region: String, + /// The secret key. + #[env("APP_S3_SECRET", secret, required_in_production)] + secret: Option, +} + +/// Limits. +#[derive(Settings, Clone)] +struct Limits { + /// Most uploads a day. + #[env("APP_DAILY_UPLOADS", default = 50_000)] + daily: i64, + /// Whether sign-ups are closed. + #[env("APP_WAITLIST", required_in_production)] + waitlist: Option, + /// Hosts allowed besides the configured ones. + #[env("APP_EXTRA_HOSTS", default = "")] + extra_hosts: Vec, + /// The webhook's secret, always needed. + #[env("APP_WEBHOOK_SECRET", secret, required)] + webhook_secret: String, +} + +#[derive(Settings, Clone)] +struct Config { + #[settings(nested)] + storage: Storage, + #[settings(nested)] + limits: Limits, +} + +const FULL: [(&str, &str); 5] = [ + ("APP_S3_ENDPOINT", "http://127.0.0.1:9000"), + ("APP_S3_SECRET", "s3-very-secret"), + ("APP_WAITLIST", "yes"), + ("APP_EXTRA_HOSTS", "a.test, b.test"), + ("APP_WEBHOOK_SECRET", "whsec-very-secret"), +]; + +#[test] +fn settings_load_with_their_defaults() { + let config = Config::load(&FULL, true).expect("valid"); + assert_eq!(config.storage.endpoint, "http://127.0.0.1:9000"); + assert_eq!(config.storage.region, "auto"); + assert_eq!(config.storage.secret.as_deref(), Some("s3-very-secret")); + assert_eq!(config.limits.daily, 50_000); + assert_eq!(config.limits.waitlist, Some(true)); + assert_eq!(config.limits.extra_hosts, ["a.test", "b.test"]); +} + +#[test] +fn every_problem_is_listed_at_once() { + let env = [("APP_DAILY_UPLOADS", "lots"), ("APP_WEBHOOK_SECRET", "")]; + let problems = Config::load(&env, false).expect_err("invalid").to_string(); + assert!(problems.contains("APP_S3_ENDPOINT is required, but isn't set"), "{problems}"); + assert!(problems.contains("APP_DAILY_UPLOADS is set to `lots`, which is invalid"), "{problems}"); + assert!(problems.contains("APP_WEBHOOK_SECRET is required, but isn't set"), "an empty value is unset: {problems}"); + assert!(!problems.contains("APP_WAITLIST"), "only production needs it: {problems}"); +} + +#[test] +fn production_needs_its_settings() { + let env = [("APP_S3_ENDPOINT", "http://s3"), ("APP_WEBHOOK_SECRET", "x")]; + let problems = Config::load(&env, true).expect_err("production").to_string(); + assert!(problems.contains("APP_S3_SECRET is required in production, but isn't set"), "{problems}"); + assert!(problems.contains("APP_WAITLIST is required in production, but isn't set"), "{problems}"); + assert!(Config::load(&env, false).is_ok()); +} + +#[test] +fn an_invalid_secret_is_never_echoed() { + #[derive(Settings)] + struct Port { + /// A secret number. + #[env("APP_PIN", secret, default = 0)] + pin: u16, + } + let problems = Port::load(&[("APP_PIN", "hunter2")], false).expect_err("invalid").to_string(); + assert!(!problems.contains("hunter2"), "{problems}"); +} + +#[test] +fn secrets_are_masked_in_debug_and_summaries() { + let config = Config::load(&FULL, true).expect("valid"); + for shown in [format!("{config:?}"), format!("{config:#?}"), config.summary().to_string()] { + assert!(!shown.contains("very-secret"), "{shown}"); + assert!(shown.contains(""), "{shown}"); + } + let summary = config.summary().to_string(); + assert!(summary.contains("APP_S3_REGION=auto"), "{summary}"); + assert!(summary.contains("APP_S3_SECRET="), "{summary}"); + assert!(format!("{:?}", config.storage).contains("http://127.0.0.1:9000")); +} + +#[test] +fn unknown_variables_name_the_closest_known_one() { + let schema = Config::schema().ignoring(&["APP_TOKEN"]); + let names = ["APP_S3_REGOIN", "APP_S3_REGION", "APP_TOKEN", "PATH", "APP_WAITLSIT", "APP_WAITLSIT"]; + let unknown = schema.unknown("APP_", names); + assert_eq!(unknown.len(), 2, "{unknown:?}"); + assert_eq!(unknown[0].name, "APP_S3_REGOIN"); + assert_eq!(unknown[0].closest, Some("APP_S3_REGION")); + assert_eq!(unknown[1].closest, Some("APP_WAITLIST")); + assert_eq!(unknown[1].to_string(), "APP_WAITLSIT is set, but nothing reads it (did you mean APP_WAITLIST?)"); +} + +#[test] +fn external_variables_are_known_and_documented() { + let schema = Config::schema().with_group(Group::external( + "Framework", + "Read by the framework.", + &[Variable::new("DATABASE_URL", "The database.").secret().required_in_production()], + )); + assert!(schema.unknown("", ["DATABASE_URL"]).is_empty()); + assert_eq!(schema.mistakes("APP_"), Vec::::new()); + let missing = schema.missing_in_production(&[("APP_S3_ENDPOINT", "x")]); + assert_eq!(missing.len(), 1); + assert_eq!(missing[0].variable, "DATABASE_URL"); + assert!(schema.markdown().contains("## Framework")); +} + +#[test] +fn schema_mistakes_are_found() { + #[derive(Settings)] + struct Wrong { + /// No prefix. + #[env("S3_BUCKET", default = "b")] + bucket: String, + } + let schema = Wrong::schema().ignoring(&["S3_BUCKET"]); + let mistakes = schema.mistakes("APP_"); + assert_eq!(mistakes.len(), 2, "{mistakes:?}"); +} + +#[test] +fn the_docs_come_from_the_schema() { + let markdown = Config::schema().markdown(); + let expected = "\ +## Storage + +Where uploads go. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `APP_S3_ENDPOINT` | string | | **Required.** The bucket's endpoint. Example: `http://127.0.0.1:9000`. | +| `APP_S3_REGION` | string | `auto` | The region. | +| `APP_S3_SECRET` | string | | **Required in production.** Secret. The secret key. | + +## Limits + +Limits. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `APP_DAILY_UPLOADS` | integer | `50000` | Most uploads a day. | +| `APP_WAITLIST` | boolean | | **Required in production.** Whether sign-ups are closed. | +| `APP_EXTRA_HOSTS` | comma-separated list | (empty) | Hosts allowed besides the configured ones. | +| `APP_WEBHOOK_SECRET` | string | | **Required.** Secret. The webhook's secret, always needed. | +"; + assert_eq!(markdown, expected); + + let example = Config::schema().dotenv_example(); + assert!(example.contains("# Required. The bucket's endpoint. Example: http://127.0.0.1:9000.\nAPP_S3_ENDPOINT=http://127.0.0.1:9000\n"), "{example}"); + assert!(example.contains("# APP_S3_REGION=auto\n"), "{example}"); + assert!(example.contains("\nAPP_WAITLIST=\n"), "{example}"); +} diff --git a/docker/app.Dockerfile b/docker/app.Dockerfile index 0b40f68a..546e34ed 100644 --- a/docker/app.Dockerfile +++ b/docker/app.Dockerfile @@ -50,7 +50,7 @@ ARG RENDERER_VERSION RUN test -n "$RENDERER_VERSION" USER visualci ENV APP_ENV=production APP_BASE_PATH=/app SERVER_HOST=0.0.0.0 SERVER_PORT=5150 LOG_CHANNEL=stderr \ - RENDERER_VERSION=${RENDERER_VERSION} + VISUALCI_RENDERER_VERSION=${RENDERER_VERSION} EXPOSE 5150 ENTRYPOINT ["/usr/local/bin/visualci-app"] CMD ["serve"] diff --git a/docs/deploy.md b/docs/deploy.md index 96f6035f..6c01a8ad 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -40,28 +40,30 @@ web, worker and scheduler tolerate `talira.ai/products=true:NoSchedule` and sele ## Environment -The ConfigMap `visualci-app-env` and the Secrets, the same for web, worker, scheduler and migrate: +The ConfigMap `visualci-app-env` and the Secrets, the same for web, worker, scheduler and migrate. Every variable the +app reads is in `app/src/config.rs`, and the generated reference is +`frontend/content/docs/self-hosting/environment-variables.md`: | Variable | Value | |---|---| -| `DATABASE_URL` | the CNPG app login; `DB_APPLICATION_NAME` and `DB_MAX_CONNECTIONS` per workload | +| `DATABASE_URL` | the CNPG app login; `VISUALCI_DB_APPLICATION_NAME` and `DB_MAX_CONNECTIONS` per workload | | `DB_CONNECTION`, `CACHE_STORE`, `SESSION_DRIVER`, `QUEUE_CONNECTION` | `pgsql`, then `database` for the rest: the cache, sessions and queue are in Postgres | | `APP_KEY` | random, generated in the cluster | | `APP_URL`, `VISUALCI_SITE_URL`, `VISUALCI_APP_URL`, `VISUALCI_API_URL`, `VISUALCI_MCP_URL` | `https://app.visualci.com`, then each host's address | | `OAUTH_ISSUER`, `OAUTH_AUTHORIZATION_ENDPOINT` | `https://mcp.visualci.com` and `https://app.visualci.com/oauth/authorize` (production refuses to boot without them) | -| `TRUSTED_PROXIES` | the cluster's pod networks | -| `RENDERER_TOKEN` | random, generated in the cluster; the same value in the renderer's `VISUALCI_RENDERER_TOKEN` | -| `METRICS_TOKEN` | random, generated in the cluster (Secret `visualci-metrics-token`); never given to the renderers. Without it, metrics refuse every request | -| `S3_ENDPOINT` | `https://.r2.cloudflarestorage.com` (DocSpring Products account) | -| `S3_BUCKET` | `visualci` | -| `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` | an R2 token scoped to that bucket | -| `GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_WEBHOOK_SECRET` | the VisualCI GitHub App (production refuses to boot without them) | -| `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` | payments; production refuses to boot without them or on a test key. The webhook endpoint is `https://api.visualci.com/webhooks/stripe` with `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed` | -| `POSTMARK_SERVER_TOKEN` | transactional email through the "VisualCI" Postmark server (1Password `talira-cluster/visualci-postmark`); production refuses to boot without it. `MAIL_FROM`, `MAIL_REPLY_TO` and `VISUALCI_TEAM_EMAIL` (support@visualci.com, which forwards to DocSpring's Intercom: new feedback and sign-ups go there) | +| `VISUALCI_TRUSTED_PROXIES` | the cluster's pod networks | +| `VISUALCI_RENDERER_TOKEN` | random, generated in the cluster (Secret `visualci-renderer-token`); the renderer reads the same variable | +| `VISUALCI_METRICS_TOKEN` | random, generated in the cluster (Secret `visualci-metrics-token`); never given to the renderers. Without it, metrics refuse every request | +| `VISUALCI_S3_ENDPOINT` | `https://.r2.cloudflarestorage.com` (DocSpring Products account) | +| `VISUALCI_S3_BUCKET` | `visualci` | +| `VISUALCI_S3_ACCESS_KEY_ID`, `VISUALCI_S3_SECRET_ACCESS_KEY` | an R2 token scoped to that bucket | +| `VISUALCI_GITHUB_APP_ID`, `VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `VISUALCI_GITHUB_WEBHOOK_SECRET` | the VisualCI GitHub App (production refuses to boot without them) | +| `VISUALCI_STRIPE_SECRET_KEY`, `VISUALCI_STRIPE_WEBHOOK_SECRET` | payments; production refuses to boot without them or on a test key. The webhook endpoint is `https://api.visualci.com/webhooks/stripe` with `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed` | +| `VISUALCI_POSTMARK_SERVER_TOKEN` | transactional email through the "VisualCI" Postmark server (1Password `talira-cluster/visualci-postmark`); production refuses to boot without it. `VISUALCI_MAIL_FROM`, `VISUALCI_MAIL_REPLY_TO` and `VISUALCI_TEAM_EMAIL` (support@visualci.com, which forwards to DocSpring's Intercom: new feedback and sign-ups go there) | | `VISUALCI_WAITLIST` | `true`: sign-ups join the waitlist | | `VISUALCI_*_HEARTBEAT_URL`, `_TOKEN` | the Gatus external endpoints the scheduled jobs push to (Monitoring, below) | -`RENDERER_VERSION` is baked into both images from `docker/renderer.version`; don't set it. +`VISUALCI_RENDERER_VERSION` is baked into both images from `docker/renderer.version`; don't set it. The renderer takes `VISUALCI_API_URL=http://web.visualci.svc:5150` and `VISUALCI_RENDERER_TOKEN`. @@ -118,7 +120,7 @@ GitLab is parked in app/: production sets none of its variables (`GITLAB_CLIENT_ (`LIVE`); daily, device sign-in pruning (`DEVICE_PRUNE`); - daily at 03:00 UTC, image retention (`retention:prune`, `RETENTION`); at 04:00, the groups check (`groups:check`, `GROUPS_CHECK`); at 05:00, the demo reset (`demo:reset`, `DEMO`). -- Render metrics: `/internal/renderer/metrics` (cluster-internal host, `METRICS_TOKEN`; the renderer token is refused), Prometheus text, scraped by +- Render metrics: `/internal/renderer/metrics` (cluster-internal host, `VISUALCI_METRICS_TOKEN`; the renderer token is refused), Prometheus text, scraped by the PodMonitor visualci-renders. Each web pod reports the same database's numbers: aggregate with `max`, not `sum`. - What's deployed: `curl -s https://api.visualci.com/status` gives the app's `commit`, and `curl -s https://visualci.com/version.txt` the static site's. diff --git a/docs/design.md b/docs/design.md index 939c5fef..0b89a54f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -552,6 +552,13 @@ scope (`app/src/auth/oauth.rs`) and the `admin_audit` table. This section is the - Backend: **Laravel Rust + Postgres** (app/; its own CNPG cluster: one instance, WAL and base backups to its own R2 bucket), with Laravel Rust's database queue, cache and sessions in the same Postgres. One image runs the web server (`serve`), the worker (`queue:work`), the scheduler (`schedule:work`) and the migrations (`migrate --force`). +- Configuration (sc-9026): every server setting is a `VISUALCI_` environment variable, declared once in + `app/src/config.rs` as a typed struct (`crates/envschema`'s derive): its description, type, default, and whether + it's required, required in production or secret. The framework's and the OAuth server's variables keep their own + names and are described there too. From that one schema: the app refuses to boot listing every missing or invalid + setting, logs its settings with secrets masked, warns about `VISUALCI_` variables nothing reads (naming the closest + known one), and the docs page `self-hosting/environment-variables` and `app/.env.example` are generated (a test + fails when they differ). - Frontend: React + TanStack (Router, Query), from the original note, in `frontend`: app/ serves its build as `public/`, and visualci.com is its static build. - Workers: app/'s queue worker (diffs) on products-1, and the renderer images (PDFBox/mutool, Chromium) on render-1 with diff --git a/frontend/content/docs/self-hosting.md b/frontend/content/docs/self-hosting.md index 2941cb9d..3dd583ca 100644 --- a/frontend/content/docs/self-hosting.md +++ b/frontend/content/docs/self-hosting.md @@ -23,20 +23,21 @@ Run the image four ways, with the same environment: | `schedule:work` | The scheduler: the build sweep every five minutes, and image retention daily. | | `migrate --force` | The migrations. Run it before each new version starts. | -Set these environment variables: +Set these environment variables. [Environment variables](/docs/self-hosting/environment-variables/) lists every one the server reads, with its type and default. | Variable | What it is | | --- | --- | | `DATABASE_URL` | The Postgres URL. Set `DB_CONNECTION=pgsql`, and `CACHE_STORE`, `SESSION_DRIVER` and `QUEUE_CONNECTION` to `database`. | | `APP_KEY` | A random secret of 32 characters. It signs sign-in sessions. | -| `S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` | The bucket. | -| `RENDERER_TOKEN` | A secret the renderers send with every request. | -| `APP_URL`, `VISUALCI_APP_URL`, `VISUALCI_API_URL`, `VISUALCI_MCP_URL`, `VISUALCI_SITE_URL` | The server's address, such as `https://visualci.example.com`. They can all be the same address. | -| `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`, `GITHUB_WEBHOOK_SECRET` | A GitHub App of your own: sign-in, and checks on pull requests. | +| `VISUALCI_S3_ENDPOINT`, `VISUALCI_S3_BUCKET`, `VISUALCI_S3_ACCESS_KEY_ID`, `VISUALCI_S3_SECRET_ACCESS_KEY` | The bucket. | +| `VISUALCI_RENDERER_TOKEN` | A secret the renderers send with every request. | +| `APP_URL` | The server's address, such as `https://visualci.example.com`. On one host, leave `VISUALCI_APP_URL`, `VISUALCI_API_URL`, `VISUALCI_MCP_URL` and `VISUALCI_SITE_URL` unset, or set all four to hosts of their own. | +| `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `VISUALCI_GITHUB_APP_ID`, `VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64`, `VISUALCI_GITHUB_WEBHOOK_SECRET` | A GitHub App of your own: sign-in, and checks on pull requests. | +| `VISUALCI_WAITLIST` | `false` to let people sign up, `true` to put them on a waitlist. | -The image sets `RENDERER_VERSION` (`docker/renderer.version`), which is part of every render cache key. +The image sets `VISUALCI_RENDERER_VERSION` (`docker/renderer.version`), which is part of every render cache key. -With `APP_ENV=production`, which the image sets, the server also refuses to start without email (`POSTMARK_SERVER_TOKEN`) and payments (`STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET`, a live key) configured. +With `APP_ENV=production`, which the image sets, the server also refuses to start without email (`VISUALCI_POSTMARK_SERVER_TOKEN`) and payments (`VISUALCI_STRIPE_SECRET_KEY` and `VISUALCI_STRIPE_WEBHOOK_SECRET`, a live key) configured, and lists everything that's missing. ## The renderers @@ -45,7 +46,7 @@ Each renderer asks the server for work, draws the PDF and uploads the pages: | Variable | What it is | | --- | --- | | `VISUALCI_API_URL` | The server's address. | -| `VISUALCI_RENDERER_TOKEN` | The server's `RENDERER_TOKEN`. | +| `VISUALCI_RENDERER_TOKEN` | The same value as the server's. | | `VISUALCI_RENDERER_VERSION` | Set by the image. | Run as many as you need: they share the queue. diff --git a/frontend/content/docs/self-hosting/environment-variables.md b/frontend/content/docs/self-hosting/environment-variables.md new file mode 100644 index 00000000..bd27c98c --- /dev/null +++ b/frontend/content/docs/self-hosting/environment-variables.md @@ -0,0 +1,207 @@ +--- +title: Environment variables +description: Every environment variable VisualCI's server reads: its settings, the framework's and the OAuth server's, with their types, defaults and which ones production needs. +--- + + + +The server reads its settings from environment variables. VisualCI's own all start with `VISUALCI_`; the framework's and the OAuth server's keep their own names. Set them for every process (`serve`, `queue:work`, `schedule:work` and `migrate`); [Self-hosting](/docs/self-hosting/) says which ones a first server needs. `app/.env.example` in the repository lists the same variables as a file to fill in. + +The server refuses to start when a required variable is missing or any variable has a value its type can't take, and lists every such problem at once. With `APP_ENV=production` the variables marked *required in production* are required too. At startup it logs the settings it runs with, secrets masked, and warns about each `VISUALCI_` variable it doesn't read, naming the closest one it knows: a typo, or a setting that was renamed. The CLI's variables (`VISUALCI_TOKEN`, `VISUALCI_PROJECT` and the rest) are ignored. + +A boolean takes `true` or `false` (or `1`/`0`, `yes`/`no`, `on`/`off`). An empty value, or `null`, is the same as not setting the variable. + +## Blob storage + +S3-compatible storage for uploads, rendered pages and diff images: R2 in production, RustFS or MinIO in development and CI. The app doesn't start without its endpoint, bucket and keys, so production never falls back to a development store. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_S3_ENDPOINT` | string | | **Required.** The store's S3 endpoint. Example: `https://.r2.cloudflarestorage.com`. | +| `VISUALCI_S3_PUBLIC_ENDPOINT` | string | | The endpoint browsers and the CLI upload to and download from, when it differs from the one the server uses (a store the server reaches on a cluster-internal address). Images in the web app's Content-Security-Policy come from here too. | +| `VISUALCI_S3_BUCKET` | string | | **Required.** The bucket. | +| `VISUALCI_S3_REGION` | string | `auto` | The bucket's region. R2 takes `auto`. | +| `VISUALCI_S3_ACCESS_KEY_ID` | string | | **Required.** Secret. The access key's ID. | +| `VISUALCI_S3_SECRET_ACCESS_KEY` | string | | **Required.** Secret. The access key's secret. | + +## Renderers + +The renderers' API (`/internal/renderer`): the renderers claim PDFs to draw with a shared token, and a metrics scraper reads their numbers with a token of its own. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_RENDERER_TOKEN` | string | | **Required.** Secret. The token every renderer sends: the same value as the renderers' own `VISUALCI_RENDERER_TOKEN`. | +| `VISUALCI_RENDERER_VERSION` | string | | **Required.** The renderer version documents are drawn with: part of every render's cache key, and what a renderer's claim must match exactly. The image sets it from `docker/renderer.version`; don't set it yourself. | +| `VISUALCI_METRICS_TOKEN` | string | (empty) | Secret. The token for `/internal/renderer/metrics` (Prometheus). Never give it to the renderers. Empty turns the endpoint off: no token matches it. | + +## Hosts + +Routing by hostname: one server answers for the app, the API and the MCP server, and each host serves only its own paths. Set all four, each its own host, or none: a self-hosted server on one host serves everything there. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_SITE_URL` | string | | The marketing site's address. Signed-out visitors to the app's front page go there. Example: `https://visualci.com`. | +| `VISUALCI_APP_URL` | string | | The web app's address, also used for the links in emails (`http://localhost` when unset). Example: `https://app.visualci.com`. | +| `VISUALCI_API_URL` | string | | The API's address, where the CLI and CI send builds. The CLI's own `VISUALCI_API_URL` names the same address. Example: `https://api.visualci.com`. | +| `VISUALCI_MCP_URL` | string | | The MCP server's address, where coding agents connect, and the OAuth issuer (`OAUTH_ISSUER` must match it). Example: `https://mcp.visualci.com`. | + +## Network and database + +Behind a load balancer: which proxies' `X-Forwarded-For` to believe, and how the database pool behaves. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_TRUSTED_PROXIES` | comma-separated list | `10.0.0.0/8` | The proxies in front of the app whose `X-Forwarded-For` is believed, as addresses or CIDR ranges. Behind them, a request's address is the nearest one that isn't a trusted proxy. Never include addresses untrusted code can send from, such as the renderers'. | +| `VISUALCI_MCP_HOSTS` | comma-separated list | (empty) | More host names the MCP endpoint answers for, besides the configured hosts, the app's address and localhost (DNS rebinding protection). For a development server reached by another name. | +| `VISUALCI_DB_ACQUIRE_TIMEOUT` | integer | `5` | How long, in seconds, a request waits for a pooled database connection before it fails with a 503 and Retry-After, rather than hanging while the queue grows. | +| `VISUALCI_DB_APPLICATION_NAME` | string | | The `application_name` of this process's database connections, in Postgres's metrics and `pg_stat_activity`, such as `visualci-web` or `visualci-worker`. Letters, digits, dashes and underscores, at most 63 characters; anything else is ignored. | + +## Sign-ups + +Whether new people can sign up. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_WAITLIST` | boolean | | **Required in production.** `true` keeps sign-ups closed: someone new goes on the waitlist instead of getting an account. Production must set it either way, so a dropped setting never opens sign-ups by surprise; elsewhere they're open unless it's set. | + +## Development sign-in + +Development and tests only. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_DEV_LOGIN` | boolean | `false` | Lets anyone sign in as anyone by email, for local work and CI's screenshots. Only where `APP_ENV` is `local` or `testing`: anywhere else the app refuses to start with it on. | + +## GitHub App + +The VisualCI GitHub App: checks and comments on pull requests, its webhook, and access that follows GitHub. Sign-in with GitHub is its OAuth client, `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` (Laravel Rust, below). + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_GITHUB_APP_ID` | string | | **Required in production.** The App's ID. | +| `VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64` | string | | **Required in production.** Secret. The App's private key: its PEM file, base64-encoded to fit on one line. | +| `VISUALCI_GITHUB_WEBHOOK_SECRET` | string | | **Required in production.** Secret. The App's webhook secret. Without it, the webhook (`/webhooks/github`) answers 404. | + +## GitLab + +GitLab, on gitlab.com or a GitLab of your own. Sign-in is its OAuth application, `GITLAB_CLIENT_ID` and `GITLAB_CLIENT_SECRET` (Laravel Rust, below). GitLab has no app installations: a project gives VisualCI access by adding its bot as a member. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_GITLAB_URL` | string | `https://gitlab.com` | The GitLab VisualCI's OAuth application and bot are on. | +| `VISUALCI_GITLAB_BOT_TOKEN` | string | | Secret. The bot's personal access token, with the `api` scope: access checks, commit statuses and merge request notes. | +| `VISUALCI_GITLAB_BOT_USERNAME` | string | `visualci` | The bot's username, for telling people whom to invite. | +| `VISUALCI_FORGE_PRIVATE_ADDRESSES` | boolean | `false` | Lets requests to an organization's server reach private addresses. Development only, for a local GitLab. | + +## Email + +Email through Postmark's API. Without a token nothing is sent, and the outbox keeps the emails pending. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_POSTMARK_SERVER_TOKEN` | string | | **Required in production.** Secret. The Postmark server's API token. | +| `VISUALCI_MAIL_FROM` | string | `VisualCI ` | Who emails come from. | +| `VISUALCI_MAIL_REPLY_TO` | string | `support@visualci.com` | Where replies go. | + +## Team + +The people running this VisualCI. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_TEAM_EMAIL` | string | `support@visualci.com` | Where new sign-ups and feedback are sent. | + +## Payments + +Payments through Stripe. Production refuses to start on a test key, which would take no real payments while granting real plans and credits. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_STRIPE_SECRET_KEY` | string | | **Required in production.** Secret. Stripe's secret or restricted key: a live one (`sk_live_`, `rk_live_`) in production. | +| `VISUALCI_STRIPE_WEBHOOK_SECRET` | string | | **Required in production.** Secret. The webhook's signing secret. Stripe's endpoint is `/webhooks/stripe` on the API host. | + +## Cloudflare + +Cloudflare, for purging public gallery URLs from its cache after a change. Unset, nothing is purged. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_CLOUDFLARE_ZONE_ID` | string | (empty) | The zone the gallery's URLs are served from. | +| `VISUALCI_CLOUDFLARE_PURGE_TOKEN` | string | (empty) | Secret. An API token that may purge that zone's cache. | + +## Gallery + +Public galleries. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_GALLERY_DAILY_CREDITS` | integer | `50000` | The most gallery credits one project is charged in a day: images past it are served free. | + +## Heartbeats + +Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_EMAILS_HEARTBEAT_URL` | string | | Email delivery (the worker, every five minutes). | +| `VISUALCI_EMAILS_HEARTBEAT_TOKEN` | string | | Secret. Email delivery's token. | +| `VISUALCI_SIGNUPS_HEARTBEAT_URL` | string | | Sign-up notices to the team. | +| `VISUALCI_SIGNUPS_HEARTBEAT_TOKEN` | string | | Secret. Sign-up notices' token. | +| `VISUALCI_LIVE_HEARTBEAT_URL` | string | | The live-update check (every minute): a notification reaches each process's listener. | +| `VISUALCI_LIVE_HEARTBEAT_TOKEN` | string | | Secret. The live-update check's token. | +| `VISUALCI_DEVICE_PRUNE_HEARTBEAT_URL` | string | | Pruning expired device sign-ins. | +| `VISUALCI_DEVICE_PRUNE_HEARTBEAT_TOKEN` | string | | Secret. Device sign-in pruning's token. | +| `VISUALCI_FORGE_SYNC_HEARTBEAT_URL` | string | | Syncing access from GitHub (the hourly recheck). | +| `VISUALCI_FORGE_SYNC_HEARTBEAT_TOKEN` | string | | Secret. Forge access sync's token. | +| `VISUALCI_RETENTION_HEARTBEAT_URL` | string | | Image retention (daily). | +| `VISUALCI_RETENTION_HEARTBEAT_TOKEN` | string | | Secret. Image retention's token. | +| `VISUALCI_DEMO_HEARTBEAT_URL` | string | | The demo organization's daily reset. | +| `VISUALCI_DEMO_HEARTBEAT_TOKEN` | string | | Secret. The demo reset's token. | +| `VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` | string | | The sweep of abandoned builds (every five minutes). | +| `VISUALCI_BUILDS_EXPIRE_HEARTBEAT_TOKEN` | string | | Secret. The builds sweep's token. | +| `VISUALCI_GROUPS_CHECK_HEARTBEAT_URL` | string | | The daily check of snapshot groups. | +| `VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN` | string | | Secret. The groups check's token. | + +## Laravel Rust + +The framework reads these itself, under its own names. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `APP_ENV` | string | `production` | `production`, `local` or `testing`. The image sets `production`. | +| `APP_KEY` | string | | **Required in production.** Secret. Laravel's encryption key for sessions and cookies: 32 random characters. A new key signs everyone out. | +| `APP_URL` | string | | The server's address, for URLs the framework builds. On one host, the only address you set. Example: `https://visualci.example.com`. | +| `APP_BASE_PATH` | string | | Where the app's files are (`public/`, `storage/`). The image sets `/app`. | +| `SERVER_HOST` | string | | The address the web server listens on. The image sets `0.0.0.0`. | +| `SERVER_PORT` | integer | | The web server's port. The image sets `5150`. | +| `LOG_CHANNEL` | string | | Where logs go. The image sets `stderr`. | +| `DATABASE_URL` | string | | Secret. The Postgres URL, with its credentials. Example: `postgres://visualci:secret@db:5432/visualci`. | +| `DB_CONNECTION` | string | `pgsql` | `pgsql`. | +| `DB_MAX_CONNECTIONS` | integer | `10` | The most database connections each process holds. Keep the sum across processes within Postgres's limit. | +| `CACHE_STORE` | string | | `database`: the cache in Postgres, shared by every process. | +| `SESSION_DRIVER` | string | | `database`: sign-in sessions in Postgres, shared by every process. | +| `QUEUE_CONNECTION` | string | | `database`: the job queue in Postgres, worked by `queue:work`. | +| `GITHUB_CLIENT_ID` | string | | **Required in production.** The GitHub App's OAuth client ID, for signing in with GitHub. | +| `GITHUB_CLIENT_SECRET` | string | | **Required in production.** Secret. The GitHub App's OAuth client secret. | +| `GITLAB_CLIENT_ID` | string | | The GitLab OAuth application's ID, for signing in with GitLab. | +| `GITLAB_CLIENT_SECRET` | string | | Secret. The GitLab OAuth application's secret. | + +## OAuth for MCP clients + +The OAuth server MCP clients sign in through (oauth-provider-laravel) reads these. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `OAUTH_ISSUER` | string | | The OAuth issuer: `VISUALCI_MCP_URL`. With the four hosts set, production refuses to start when it differs. Example: `https://mcp.visualci.com`. | +| `OAUTH_AUTHORIZATION_ENDPOINT` | string | | The consent page: `/oauth/authorize` on `VISUALCI_APP_URL`, checked like `OAUTH_ISSUER`. Example: `https://app.visualci.com/oauth/authorize`. | + +## Development and tests + +Never set these in production. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_NOW` | string | | Stands in for the clock in credit allowances (RFC 3339), for screenshots of seeded data. | +| `VISUALCI_APP_TEST_DATABASE_URL` | string | | The tests' Postgres (each test borrows a copy of it). Default: CI's, `postgres://visualci:visualci@127.0.0.1:55433/visualci_app_test`. | +| `VISUALCI_EMAIL_SNAPSHOTS` | string | | A folder the email tests write each email's HTML to, for review. | +| `VISUALCI_GOLDEN_UPDATE` | string | | `1` makes the tests write their golden files (this page among them) instead of comparing. | diff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.ts index 1b639d83..484f9621 100644 --- a/frontend/src/docs/nav.ts +++ b/frontend/src/docs/nav.ts @@ -27,7 +27,7 @@ export const docsSections: DocsSection[] = [ title: 'Visual tests', slugs: ['screenshots', 'screenshots/playwright', 'screenshots/cypress', 'screenshots/rspec', 'screenshots/mobile', 'screenshots/deterministic', 'pdfs', 'local-runs', 'gallery'], }, - { title: 'Reference', slugs: ['reference/cli', 'reference/config', 'reference/api', 'reference/access', 'reference/credits', 'self-hosting', 'support'] }, + { title: 'Reference', slugs: ['reference/cli', 'reference/config', 'reference/api', 'reference/access', 'reference/credits', 'self-hosting', 'self-hosting/environment-variables', 'support'] }, ] /** A page's URL: /docs/ for the index, /docs// for the rest. */ diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 013679a2..812ac521 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -42,9 +42,9 @@ export default defineConfig(({ mode, isSsrBuild }) => { '/auth': backend, '/status': backend, '/g/': backend, - // Images from MinIO for a browser on another machine (the server's S3_PUBLIC_ENDPOINT is this origin): the + // Images from MinIO for a browser on another machine (the server's VISUALCI_S3_PUBLIC_ENDPOINT is this origin): the // bucket's path goes to MinIO with the Host header kept, since presigned URLs are signed for this host. - [`/${env.S3_BUCKET || 'visualci-development'}/`]: { target: env.S3_ENDPOINT || 'http://127.0.0.1:59000', changeOrigin: false }, + [`/${env.VISUALCI_S3_BUCKET || 'visualci-development'}/`]: { target: env.VISUALCI_S3_ENDPOINT || 'http://127.0.0.1:59000', changeOrigin: false }, }, }, } diff --git a/scripts/ci/visual.sh b/scripts/ci/visual.sh index a644e4ff..a9958781 100755 --- a/scripts/ci/visual.sh +++ b/scripts/ci/visual.sh @@ -9,7 +9,7 @@ # # Needs: target/debug/visualci-app and target/debug/visualci (cargo build), frontend/dist (pnpm build), and # scripts/screenshots/node_modules with Playwright's Chromium. Settings: PORT (5151), DATABASE_URL (a database this -# script drops and recreates), S3_ENDPOINT and S3_BUCKET (made if missing), VISUAL_JSON_DIR (the request tests' JSON +# script drops and recreates), VISUALCI_S3_ENDPOINT and VISUALCI_S3_BUCKET (made if missing), VISUAL_JSON_DIR (the request tests' JSON # snapshots), VISUALCI_TOKEN. set -euo pipefail @@ -18,8 +18,8 @@ out=$root/tmp/visual run=$root/tmp/visual-app port=${PORT:-5151} export DATABASE_URL=${DATABASE_URL:-postgres://loco:loco@127.0.0.1:55433/visualci_screenshots} -s3=${S3_ENDPOINT:-http://127.0.0.1:59000} -bucket=${S3_BUCKET:-visualci-screenshots} +s3=${VISUALCI_S3_ENDPOINT:-http://127.0.0.1:59000} +bucket=${VISUALCI_S3_BUCKET:-visualci-screenshots} app=${VISUALCI_APP_BIN:-$root/target/debug/visualci-app} cli=$root/target/debug/visualci @@ -70,14 +70,14 @@ DATABASE_URL=$DATABASE_URL CACHE_STORE=database SESSION_DRIVER=database QUEUE_CONNECTION=database -S3_ENDPOINT=$s3 -S3_PUBLIC_ENDPOINT=$s3 -S3_BUCKET=$bucket -S3_ACCESS_KEY_ID=visualci -S3_SECRET_ACCESS_KEY=visualci-dev-secret -RENDERER_TOKEN=visual-renderer-token -RENDERER_VERSION=$(cat "$root/docker/renderer.version") -DEV_LOGIN=true +VISUALCI_S3_ENDPOINT=$s3 +VISUALCI_S3_PUBLIC_ENDPOINT=$s3 +VISUALCI_S3_BUCKET=$bucket +VISUALCI_S3_ACCESS_KEY_ID=visualci +VISUALCI_S3_SECRET_ACCESS_KEY=visualci-dev-secret +VISUALCI_RENDERER_TOKEN=visual-renderer-token +VISUALCI_RENDERER_VERSION=$(cat "$root/docker/renderer.version") +VISUALCI_DEV_LOGIN=true VISUALCI_NOW=2026-11-20T15:00:00Z EOF set -a diff --git a/scripts/journeys/run.sh b/scripts/journeys/run.sh index d67e2712..4ba133e8 100755 --- a/scripts/journeys/run.sh +++ b/scripts/journeys/run.sh @@ -9,7 +9,7 @@ # Needs: # - the five names resolving to 127.0.0.1 (/etc/hosts): visualci.test, app.visualci.test, api.visualci.test, # mcp.visualci.test, github.test; -# - DATABASE_URL (a Postgres it may drop and create the database of), and S3_ENDPOINT (RustFS or MinIO, default +# - DATABASE_URL (a Postgres it may drop and create the database of), and VISUALCI_S3_ENDPOINT (RustFS or MinIO, default # http://127.0.0.1:59000); # - the app built (VISUALCI_APP_BIN, default target/debug/visualci-app); # - the frontend built for these hosts: in frontend, @@ -27,8 +27,8 @@ run=$root/tmp/journeys-run port=${PORT:-5151} stub_port=${GITHUB_STUB_PORT:-5198} app=${VISUALCI_APP_BIN:-$root/target/debug/visualci-app} -s3=${S3_ENDPOINT:-http://127.0.0.1:59000} -bucket=${S3_BUCKET:-visualci-journeys} +s3=${VISUALCI_S3_ENDPOINT:-http://127.0.0.1:59000} +bucket=${VISUALCI_S3_BUCKET:-visualci-journeys} : "${DATABASE_URL:?DATABASE_URL is needed: a Postgres the journeys may drop and create the database of}" fail() { @@ -78,20 +78,20 @@ VISUALCI_MCP_URL=https://mcp.visualci.test VISUALCI_MCP_HOSTS=mcp.visualci.test,api.visualci.test OAUTH_ISSUER=https://mcp.visualci.test OAUTH_AUTHORIZATION_ENDPOINT=https://app.visualci.test/oauth/authorize -TRUSTED_PROXIES=127.0.0.1/32 +VISUALCI_TRUSTED_PROXIES=127.0.0.1/32 VISUALCI_WAITLIST=false DB_CONNECTION=pgsql DATABASE_URL=$DATABASE_URL CACHE_STORE=database SESSION_DRIVER=database QUEUE_CONNECTION=database -S3_ENDPOINT=$s3 -S3_PUBLIC_ENDPOINT=$s3 -S3_BUCKET=$bucket -S3_ACCESS_KEY_ID=visualci -S3_SECRET_ACCESS_KEY=visualci-dev-secret -RENDERER_TOKEN=journeys-renderer-token -RENDERER_VERSION=$(cat "$root/docker/renderer.version") +VISUALCI_S3_ENDPOINT=$s3 +VISUALCI_S3_PUBLIC_ENDPOINT=$s3 +VISUALCI_S3_BUCKET=$bucket +VISUALCI_S3_ACCESS_KEY_ID=visualci +VISUALCI_S3_SECRET_ACCESS_KEY=visualci-dev-secret +VISUALCI_RENDERER_TOKEN=journeys-renderer-token +VISUALCI_RENDERER_VERSION=$(cat "$root/docker/renderer.version") GITHUB_URL=http://github.test:$stub_port GITHUB_CLIENT_ID=journeys GITHUB_CLIENT_SECRET=journeys-secret