diff --git a/docs/PLAN.md b/docs/PLAN.md index 95baa04..5cb31d9 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -762,6 +762,22 @@ cases in the tests. failed every time. Such a file now prints as a note page (`pack::pdf::copies`). +## The public demo (Nov 23, 2026) + +`https://demoapp.lannadesk.com`, for pitches and the website (Alex: anyone, +no login; visitors may change things; uploads and mail off; everything +starts over every night). The app's demo mode, `VISA_DEMO=1` +(`config::Auth::Demo`): no login on any address, everyone is "Demo +visitor" (actor `demo`), a note on every page (`#demo-note`, the client's +pages too), the invented data added at start when the database is empty, +every file upload refused (`DEMO_NO_UPLOADS`; a contract version keeps its +text), and a mail server in its settings refused, so nothing leaves it. +It needs a place for the files and a key, for its own demo files and the +signed copies. The server side (cnx-network-clan `cnx.visa.demo`): the +service `visa-demo` on port 8042 runs the live release, its own database +`visa_demo` and files, and `visa-demo-reset` at 04:00 drops and recreates +the database. Test: `tests/demo.rs`. + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay diff --git a/src/config.rs b/src/config.rs index 933bba1..93e5903 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,6 +12,7 @@ //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | +//! | `VISA_DEMO` | `1`: the public demo (demoapp.lannadesk.com) | //! | `VISA_S3_BUCKET` | the bucket the encrypted documents lie in | //! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) | //! | `VISA_S3_REGION` | default `garage` | @@ -30,6 +31,12 @@ //! With the login on, documents are required: a place for them (the bucket, //! or a directory) and the file key. Local development may go without them; //! uploads are then off. +//! +//! The demo (`VISA_DEMO=1`) has no login on any address, since it holds only +//! the invented demo data, which it adds itself to an empty database and +//! which the server puts back every night. It needs a place for the +//! documents and the key (for the demo files and the signed copies), takes +//! no uploads, and refuses a mail server, so nothing leaves it. use std::net::SocketAddr; use std::path::PathBuf; @@ -133,6 +140,8 @@ pub enum Auth { Oidc(OidcConfig), /// Local development: everyone is "local"; loopback addresses only. Disabled, + /// The public demo: everyone is "demo", on any address. + Demo, } #[derive(Clone)] @@ -197,6 +206,7 @@ impl Config { group: var("VISA_OIDC_GROUP").unwrap_or_else(|| "visa".into()), }) } + None if var("VISA_DEMO").as_deref() == Some("1") => Auth::Demo, None if var("VISA_INSECURE_NO_LOGIN").as_deref() == Some("1") => { if !listen.ip().is_loopback() { bail!("VISA_INSECURE_NO_LOGIN=1 works only with a loopback VISA_LISTEN"); @@ -240,6 +250,20 @@ impl Config { S3 settings, or VISA_FILES_DIR" ), }; + if matches!(auth, Auth::Demo) { + ensure!( + files.is_some(), + "the demo needs a place for its documents and the file key (VISA_FILES_DIR and \ + VISA_FILES_KEY_FILE)" + ); + if let Some(v) = ["VISA_SMTP_HOST"] + .iter() + .chain(MAIL_VARS.iter()) + .find(|v| var(v).is_some()) + { + bail!("{v} is set, but the demo sends no mail"); + } + } if matches!(auth, Auth::Oidc(_)) && files.is_none() { bail!( "documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \ @@ -274,6 +298,11 @@ impl Config { pub fn login_enabled(&self) -> bool { matches!(self.auth, Auth::Oidc(_)) } + + /// The public demo, with its invented data only. + pub fn demo(&self) -> bool { + matches!(self.auth, Auth::Demo) + } } /// The bucket's settings; the secret from its file or the credential @@ -404,6 +433,36 @@ mod tests { assert!(e.to_string().contains("loopback"), "{e}"); } + #[test] + fn the_demo_runs_on_any_address_with_its_files_and_without_mail() { + let key = std::env::temp_dir().join(format!("visa-demo-key-{}", std::process::id())); + std::fs::write(&key, "ab".repeat(32)).unwrap(); + let key = key.to_string_lossy().into_owned(); + let base = [ + ("VISA_DATABASE_URL", "postgres://x/y"), + ("VISA_DEMO", "1"), + ("VISA_LISTEN", "[::]:8042"), + ]; + let with = |extra: &[(&str, &str)]| { + let mut v = base.to_vec(); + v.extend_from_slice(extra); + cfg(&v) + }; + let e = with(&[]).unwrap_err(); + assert!(e.to_string().contains("needs a place"), "{e}"); + let files = [ + ("VISA_FILES_DIR", "/tmp/demo"), + ("VISA_FILES_KEY_FILE", key.as_str()), + ]; + let ok = with(&files).unwrap(); + assert!(ok.demo() && !ok.login_enabled()); + let mut mailing = files.to_vec(); + mailing.push(("VISA_SMTP_HOST", "mail.lannadesk.com")); + let e = with(&mailing).unwrap_err(); + assert!(e.to_string().contains("sends no mail"), "{e}"); + let _ = std::fs::remove_file(&key); + } + #[test] fn mail_needs_its_server_and_its_password() { let base = [ diff --git a/src/main.rs b/src/main.rs index 37dbf2e..b699ce7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,7 +19,8 @@ Usage: visa [COMMAND] Commands: serve run the web server (default); applies pending migrations first migrate apply pending database migrations and exit - seed-demo add invented demo people and documents (local development only) + seed-demo add invented demo people and documents (local development and the + demo; the demo also does it itself at start) files-check read every document's file back and compare it with its upload; list files without a document (exit status 1 on any problem) files-migrate --from DIR @@ -91,29 +92,13 @@ async fn run(cmd: &str) -> Result<()> { let cfg = Config::from_env()?; ensure!( !cfg.login_enabled(), - "seed-demo writes invented people and runs only in local development \ - (VISA_INSECURE_NO_LOGIN=1, no VISA_OIDC_ISSUER)" + "seed-demo writes invented people and runs only in local development or the \ + demo (VISA_INSECURE_NO_LOGIN=1 or VISA_DEMO=1, no VISA_OIDC_ISSUER)" ); let pool = db::connect(&cfg).await?; db::migrate(&pool).await?; - if seed::demo(&pool, dates::today()).await? { - println!("demo people added"); - } else { - println!("demo people are there already"); - } - match &cfg.files { - Some(_) => { - let store = store(&cfg)?; - let n = seed::demo_documents(&pool, &store, dates::today()).await?; - println!("demo documents added: {n}"); - } - None => println!("no demo documents: documents are off (no place for them)"), - } - let store = cfg.files.as_ref().map(|_| store(&cfg)).transpose()?; - if seed::legal::demo(&pool, store.as_ref(), dates::today()).await? { - println!("demo clients and contracts added"); - } else { - println!("demo clients and contracts are there already"); + for line in seed_demo(&cfg, &pool).await? { + println!("{line}"); } Ok(()) } @@ -189,8 +174,15 @@ async fn serve() -> Result<()> { let cfg = Config::from_env()?; let pool = db::connect(&cfg).await?; db::migrate(&pool).await?; + if cfg.demo() { + // an empty database (the server's nightly reset) gets the demo data + for line in seed_demo(&cfg, &pool).await? { + info!("demo: {line}"); + } + } let listen = cfg.listen; let login = cfg.login_enabled(); + let demo = cfg.demo(); let st = web::AppState::new(cfg, pool)?; match &st.files { Some(s) => { @@ -215,7 +207,9 @@ async fn serve() -> Result<()> { let listener = tokio::net::TcpListener::bind(listen) .await .with_context(|| format!("cannot listen on {listen}"))?; - if !login { + if demo { + info!("the public demo: no login, invented data, no uploads, no mail (VISA_DEMO)"); + } else if !login { info!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)"); } info!("listening on http://{listen}"); @@ -226,6 +220,33 @@ async fn serve() -> Result<()> { Ok(()) } +/// Adds the invented demo data where it is missing: people, their +/// documents, clients and contracts. What it did, a line each. +async fn seed_demo(cfg: &Config, pool: &sqlx::PgPool) -> Result> { + let mut out = Vec::new(); + out.push(if seed::demo(pool, dates::today()).await? { + "demo people added".to_string() + } else { + "demo people are there already".to_string() + }); + let store = cfg.files.as_ref().map(|_| store(cfg)).transpose()?; + match &store { + Some(s) => { + let n = seed::demo_documents(pool, s, dates::today()).await?; + out.push(format!("demo documents added: {n}")); + } + None => out.push("no demo documents: documents are off (no place for them)".into()), + } + out.push( + if seed::legal::demo(pool, store.as_ref(), dates::today()).await? { + "demo clients and contracts added".to_string() + } else { + "demo clients and contracts are there already".to_string() + }, + ); + Ok(out) +} + async fn shutdown() { let ctrl_c = async { let _ = tokio::signal::ctrl_c().await; diff --git a/src/session.rs b/src/session.rs index 2e625ff..418202b 100644 --- a/src/session.rs +++ b/src/session.rs @@ -36,6 +36,16 @@ pub struct User { } impl User { + /// Every visitor of the public demo. + pub fn demo(csrf: &str) -> User { + User { + login: "demo".into(), + name: "Demo visitor".into(), + local: false, + csrf: csrf.to_string(), + } + } + pub fn local(csrf: &str) -> User { User { login: "local".into(), diff --git a/src/web/auth.rs b/src/web/auth.rs index 9941e1b..8273cb9 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -216,7 +216,7 @@ pub async fn logout( Extension(user): Extension, headers: HeaderMap, ) -> Result { - if user.local { + if user.local || st.cfg.demo() { return Ok(Redirect::to(HOME).into_response()); } if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) { diff --git a/src/web/documents.rs b/src/web/documents.rs index 64fd2fc..1aa4f50 100644 --- a/src/web/documents.rs +++ b/src/web/documents.rs @@ -693,6 +693,10 @@ pub(crate) struct Checked { sha256: String, } +/// What an upload in the demo says: it takes no one's files. +pub(crate) const DEMO_NO_UPLOADS: &str = "Uploads are off in the demo, so nobody's files land here. \ + The demo's own documents are on the Documents tabs, and they print in the packs."; + /// The files, checked: a type the app takes (by the file's first bytes), /// not empty, not too large, not uploaded before for this person or company. pub(crate) async fn check_files( @@ -702,6 +706,11 @@ pub(crate) async fn check_files( errors: &mut Errors, ) -> anyhow::Result> { let mut problems: Vec = Vec::new(); + if st.cfg.demo() { + // the demo keeps no one's files: only the ones it came with + forms::err(errors, "file", DEMO_NO_UPLOADS); + return Ok(Vec::new()); + } if up.files.is_empty() && up.too_big.is_empty() && up.empty.is_empty() { problems.push("Choose a file to upload.".into()); } diff --git a/src/web/legal.rs b/src/web/legal.rs index 036439a..9d527ae 100644 --- a/src/web/legal.rs +++ b/src/web/legal.rs @@ -1036,6 +1036,13 @@ pub async fn add_version( "Say what this version is, such as: the label's changes of Nov 21.", ); } + if st.cfg.demo() && form.file.is_some() { + err( + &mut errors, + "file", + "Uploads are off in the demo. Paste the text instead; it is kept as the version.", + ); + } if form.too_big { err( &mut errors, diff --git a/src/web/mod.rs b/src/web/mod.rs index c7b4537..73853ce 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -43,7 +43,8 @@ pub struct AppState { templates: Environment<'static>, pub flows: Flows, provider: RwLock>>, - /// The form token of local development, which has no sessions. + /// The form token of local development and of the demo, which have no + /// sessions. local_csrf: String, /// The documents' files; none in local development without a place /// and a key for them. @@ -58,8 +59,11 @@ impl AppState { .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) .build()?; let files = cfg.files.as_ref().map(Store::open).transpose()?; + let mut templates = templates()?; + // the demo's note on every page, the back office's and the client's + templates.add_global("demo", cfg.demo()); Ok(Arc::new(AppState { - templates: templates()?, + templates, files, cfg, db, @@ -493,6 +497,7 @@ async fn gate(State(st): State>, mut req: Request, next: Next) -> } let user = match &st.cfg.auth { Auth::Disabled => Some(User::local(&st.local_csrf)), + Auth::Demo => Some(User::demo(&st.local_csrf)), Auth::Oidc(_) => match session::cookie_value(req.headers(), SESSION_COOKIE) { Some(id) => match session::get(&st.db, &id).await { Ok(u) => u, diff --git a/static/app.css b/static/app.css index de804cc..eeef153 100644 --- a/static/app.css +++ b/static/app.css @@ -492,6 +492,18 @@ main { border: 1px solid var(--line); margin: 0 0 14px; } +/* the public demo's note at the top of every page */ +.demo-note { + padding: 8px 14px; + border-radius: 10px; + border: 1px dashed var(--label); + color: var(--fg2); + font-size: 0.92rem; + margin: 0 0 16px; +} +.demo-note b { + color: var(--label); +} .notice.warn { background: var(--warn-s); border-color: transparent; diff --git a/templates/base.html b/templates/base.html index c5b3d78..dfaa147 100644 --- a/templates/base.html +++ b/templates/base.html @@ -37,7 +37,11 @@ Notifications
- {% if user.local %} + {% if demo %} + Demo + No login +

Everyone here is a demo visitor. The people, companies and contracts are invented.

+ {% elif user.local %} Local development No login

VISA_INSECURE_NO_LOGIN is set; this only runs on a loopback address.

@@ -50,6 +54,7 @@
+ {% if demo %}

Demo. Everything here is invented. Add, change and sign what you like: it all starts over every night. Uploads and mail are off.

{% endif %} {% block main %}{% endblock %}
Lanna Desk {{ version }}{% if commit %}, commit {% if commit_url %}{{ commit }}{% else %}{{ commit }}{% endif %}{% endif %}. Every view and change of a person's record is written to the Activity log. Dates are in Chiang Mai time.
diff --git a/templates/client_base.html b/templates/client_base.html index 6514b29..76bdf6f 100644 --- a/templates/client_base.html +++ b/templates/client_base.html @@ -23,6 +23,7 @@
+ {% if demo %}

Demo. This is the page a client sees on their link, with invented details. It starts over every night; uploads are off.

{% endif %} {% block main %}{% endblock %} {% if until %}{% endif %}
diff --git a/tests/demo.rs b/tests/demo.rs new file mode 100644 index 0000000..48fa3e7 --- /dev/null +++ b/tests/demo.rs @@ -0,0 +1,93 @@ +//! The public demo (`VISA_DEMO=1`, demoapp.lannadesk.com): no login, a +//! note on every page, everything can be changed, but no file comes in. + +use axum::http::StatusCode; +use sqlx::PgPool; +use visa::config::Auth; + +use crate::common::{pdf, with_auth}; + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_demo_says_so_and_takes_no_uploads(pool: PgPool) { + let app = with_auth(pool.clone(), Auth::Demo); + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + visa::seed::legal::demo(&pool, app.st.files.as_ref(), today) + .await + .unwrap(); + + let t = app.get("/desk").await.text(); + assert!(t.contains("id=\"demo-note\""), "{t}"); + assert!(t.contains("Everyone here is a demo visitor")); + assert!(!t.contains("Sign out")); + + // a document upload is refused, and nothing is kept + let person: i64 = sqlx::query_scalar("SELECT min(id) FROM people") + .fetch_one(&pool) + .await + .unwrap(); + let docs = || async { + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM documents") + .fetch_one(&pool) + .await + .unwrap() + }; + let before = docs().await; + let scan = pdf("not in the demo"); + let r = app + .upload( + &format!("/people/{person}/documents"), + &[("kind", "passport-photo-page")], + &[("scan.pdf", &scan)], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + r.text().contains("Uploads are off in the demo"), + "{}", + r.text() + ); + assert_eq!(docs().await, before); + + // a contract's new version: the text is taken, a file is not + let contract: i64 = sqlx::query_scalar("SELECT min(id) FROM contracts") + .fetch_one(&pool) + .await + .unwrap(); + let base = format!("/contracts/{contract}/versions"); + let r = app + .upload( + &base, + &[("note", "Signed scan"), ("body", "# 1. Term\nOne year.")], + &[("signed.pdf", &scan)], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + r.text() + .contains("Uploads are off in the demo. Paste the text") + ); + let r = app + .upload( + &base, + &[ + ("note", "A visitor's change"), + ("body", "# 1. Term\nOne year."), + ], + &[], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + assert_eq!(docs().await, before); + + // changes are the demo visitor's + let actor: String = sqlx::query_scalar("SELECT actor FROM journal ORDER BY seq DESC LIMIT 1") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(actor, "demo"); + // there is nobody to sign out + let r = app.post("/logout", &[]).await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert_eq!(r.location(), "/desk"); +} diff --git a/tests/main.rs b/tests/main.rs index 8551c0e..044bcec 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -9,6 +9,7 @@ mod client; mod common; mod companies; mod deadlines; +mod demo; mod documents; mod fuzz_cases; mod garage;