Demo mode (VISA_DEMO=1) for demoapp.lannadesk.com
CI / secret scan (push) Successful in 8s
CI / fmt, clippy, tests (push) Successful in 1m23s
CI / release (push) Skipped

For a public demo: no login on any address, everyone is "Demo visitor"
(actor demo), a note at the top of every page, the back office's and the
client's (#demo-note), and the invented demo data added at start when
the database is empty (the server drops it every night). Every file
upload is refused with a message (documents, the office photo, the
client's uploads; a contract version keeps its text without the file),
a mail server in its settings is refused, so nothing leaves it, and it
needs a place for the files and their key (the demo's own files and the
signed copies). seed-demo also runs in it. Sign out leads home.

Checked: config test (address, files, no mail), tests/demo.rs (the note,
an upload refused and nothing kept, a version with text only, the
journal's actor), a local run on an empty database (seeds itself: 27
documents, the clients and contracts) and screenshots light and dark,
desk and phone (PROBLEMS: 0).
This commit is contained in:
grabowski committed 2026-11-23 11:03:40 +07:00
1 parent 422ee2ec2c
commit 329b181c4f
13 files changed
+265 -26

No files matched your search

+16
View File
@@ -762,6 +762,22 @@ cases in the tests.
failed every time. Such a file now prints as a note page failed every time. Such a file now prints as a note page
(`pack::pdf::copies`). (`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 ## Open questions
1. B4L's BOI application: once B4L is promoted, its staff extend their stay 1. B4L's BOI application: once B4L is promoted, its staff extend their stay
+59
View File
@@ -12,6 +12,7 @@
//! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` |
//! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_OIDC_GROUP` | default `visa` |
//! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | //! | `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_BUCKET` | the bucket the encrypted documents lie in |
//! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) | //! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) |
//! | `VISA_S3_REGION` | default `garage` | //! | `VISA_S3_REGION` | default `garage` |
@@ -30,6 +31,12 @@
//! With the login on, documents are required: a place for them (the bucket, //! 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; //! or a directory) and the file key. Local development may go without them;
//! uploads are then off. //! 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::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
@@ -133,6 +140,8 @@ pub enum Auth {
Oidc(OidcConfig), Oidc(OidcConfig),
/// Local development: everyone is "local"; loopback addresses only. /// Local development: everyone is "local"; loopback addresses only.
Disabled, Disabled,
/// The public demo: everyone is "demo", on any address.
Demo,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -197,6 +206,7 @@ impl Config {
group: var("VISA_OIDC_GROUP").unwrap_or_else(|| "visa".into()), 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") => { None if var("VISA_INSECURE_NO_LOGIN").as_deref() == Some("1") => {
if !listen.ip().is_loopback() { if !listen.ip().is_loopback() {
bail!("VISA_INSECURE_NO_LOGIN=1 works only with a loopback VISA_LISTEN"); 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" 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() { if matches!(auth, Auth::Oidc(_)) && files.is_none() {
bail!( bail!(
"documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \ "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 { pub fn login_enabled(&self) -> bool {
matches!(self.auth, Auth::Oidc(_)) 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 /// 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}"); 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] #[test]
fn mail_needs_its_server_and_its_password() { fn mail_needs_its_server_and_its_password() {
let base = [ let base = [
+43 -22
View File
@@ -19,7 +19,8 @@ Usage: visa [COMMAND]
Commands: Commands:
serve run the web server (default); applies pending migrations first serve run the web server (default); applies pending migrations first
migrate apply pending database migrations and exit 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; 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) list files without a document (exit status 1 on any problem)
files-migrate --from DIR files-migrate --from DIR
@@ -91,29 +92,13 @@ async fn run(cmd: &str) -> Result<()> {
let cfg = Config::from_env()?; let cfg = Config::from_env()?;
ensure!( ensure!(
!cfg.login_enabled(), !cfg.login_enabled(),
"seed-demo writes invented people and runs only in local development \ "seed-demo writes invented people and runs only in local development or the \
(VISA_INSECURE_NO_LOGIN=1, no VISA_OIDC_ISSUER)" demo (VISA_INSECURE_NO_LOGIN=1 or VISA_DEMO=1, no VISA_OIDC_ISSUER)"
); );
let pool = db::connect(&cfg).await?; let pool = db::connect(&cfg).await?;
db::migrate(&pool).await?; db::migrate(&pool).await?;
if seed::demo(&pool, dates::today()).await? { for line in seed_demo(&cfg, &pool).await? {
println!("demo people added"); println!("{line}");
} 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");
} }
Ok(()) Ok(())
} }
@@ -189,8 +174,15 @@ async fn serve() -> Result<()> {
let cfg = Config::from_env()?; let cfg = Config::from_env()?;
let pool = db::connect(&cfg).await?; let pool = db::connect(&cfg).await?;
db::migrate(&pool).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 listen = cfg.listen;
let login = cfg.login_enabled(); let login = cfg.login_enabled();
let demo = cfg.demo();
let st = web::AppState::new(cfg, pool)?; let st = web::AppState::new(cfg, pool)?;
match &st.files { match &st.files {
Some(s) => { Some(s) => {
@@ -215,7 +207,9 @@ async fn serve() -> Result<()> {
let listener = tokio::net::TcpListener::bind(listen) let listener = tokio::net::TcpListener::bind(listen)
.await .await
.with_context(|| format!("cannot listen on {listen}"))?; .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!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)");
} }
info!("listening on http://{listen}"); info!("listening on http://{listen}");
@@ -226,6 +220,33 @@ async fn serve() -> Result<()> {
Ok(()) 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<Vec<String>> {
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() { async fn shutdown() {
let ctrl_c = async { let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await; let _ = tokio::signal::ctrl_c().await;
+10
View File
@@ -36,6 +36,16 @@ pub struct User {
} }
impl 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 { pub fn local(csrf: &str) -> User {
User { User {
login: "local".into(), login: "local".into(),
+1 -1
View File
@@ -216,7 +216,7 @@ pub async fn logout(
Extension(user): Extension<User>, Extension(user): Extension<User>,
headers: HeaderMap, headers: HeaderMap,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
if user.local { if user.local || st.cfg.demo() {
return Ok(Redirect::to(HOME).into_response()); return Ok(Redirect::to(HOME).into_response());
} }
if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) { if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) {
+9
View File
@@ -693,6 +693,10 @@ pub(crate) struct Checked {
sha256: String, 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), /// 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. /// not empty, not too large, not uploaded before for this person or company.
pub(crate) async fn check_files( pub(crate) async fn check_files(
@@ -702,6 +706,11 @@ pub(crate) async fn check_files(
errors: &mut Errors, errors: &mut Errors,
) -> anyhow::Result<Vec<Checked>> { ) -> anyhow::Result<Vec<Checked>> {
let mut problems: Vec<String> = Vec::new(); let mut problems: Vec<String> = 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() { if up.files.is_empty() && up.too_big.is_empty() && up.empty.is_empty() {
problems.push("Choose a file to upload.".into()); problems.push("Choose a file to upload.".into());
} }
+7
View File
@@ -1036,6 +1036,13 @@ pub async fn add_version(
"Say what this version is, such as: the label's changes of Nov 21.", "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 { if form.too_big {
err( err(
&mut errors, &mut errors,
+7 -2
View File
@@ -43,7 +43,8 @@ pub struct AppState {
templates: Environment<'static>, templates: Environment<'static>,
pub flows: Flows, pub flows: Flows,
provider: RwLock<Option<Arc<oidc::Provider>>>, provider: RwLock<Option<Arc<oidc::Provider>>>,
/// 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, local_csrf: String,
/// The documents' files; none in local development without a place /// The documents' files; none in local development without a place
/// and a key for them. /// and a key for them.
@@ -58,8 +59,11 @@ impl AppState {
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
.build()?; .build()?;
let files = cfg.files.as_ref().map(Store::open).transpose()?; 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 { Ok(Arc::new(AppState {
templates: templates()?, templates,
files, files,
cfg, cfg,
db, db,
@@ -493,6 +497,7 @@ async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
} }
let user = match &st.cfg.auth { let user = match &st.cfg.auth {
Auth::Disabled => Some(User::local(&st.local_csrf)), 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) { Auth::Oidc(_) => match session::cookie_value(req.headers(), SESSION_COOKIE) {
Some(id) => match session::get(&st.db, &id).await { Some(id) => match session::get(&st.db, &id).await {
Ok(u) => u, Ok(u) => u,
+12
View File
@@ -492,6 +492,18 @@ main {
border: 1px solid var(--line); border: 1px solid var(--line);
margin: 0 0 14px; 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 { .notice.warn {
background: var(--warn-s); background: var(--warn-s);
border-color: transparent; border-color: transparent;
+6 -1
View File
@@ -37,7 +37,11 @@
<a href="/notifications"{% if nav == "notifications" %} class="on" aria-current="page"{% endif %}>Notifications</a> <a href="/notifications"{% if nav == "notifications" %} class="on" aria-current="page"{% endif %}>Notifications</a>
</nav> </nav>
<div class="who"> <div class="who">
{% if user.local %} {% if demo %}
<span class="k">Demo</span>
<b>No login</b>
<p>Everyone here is a demo visitor. The people, companies and contracts are invented.</p>
{% elif user.local %}
<span class="k">Local development</span> <span class="k">Local development</span>
<b>No login</b> <b>No login</b>
<p>VISA_INSECURE_NO_LOGIN is set; this only runs on a loopback address.</p> <p>VISA_INSECURE_NO_LOGIN is set; this only runs on a loopback address.</p>
@@ -50,6 +54,7 @@
</div> </div>
</aside> </aside>
<main id="main"> <main id="main">
{% if demo %}<p class="demo-note" id="demo-note"><b>Demo.</b> Everything here is invented. Add, change and sign what you like: it all starts over every night. Uploads and mail are off.</p>{% endif %}
{% block main %}{% endblock %} {% block main %}{% endblock %}
<footer class="ft">Lanna Desk {{ version }}{% if commit %}, commit {% if commit_url %}<a href="{{ commit_url }}">{{ commit }}</a>{% 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.</footer> <footer class="ft">Lanna Desk {{ version }}{% if commit %}, commit {% if commit_url %}<a href="{{ commit_url }}">{{ commit }}</a>{% 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.</footer>
</main> </main>
+1
View File
@@ -23,6 +23,7 @@
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">&#9680;</button> <button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">&#9680;</button>
</header> </header>
<main class="cmain" id="main"> <main class="cmain" id="main">
{% if demo %}<p class="demo-note" id="demo-note"><b>Demo.</b> This is the page a client sees on their link, with invented details. It starts over every night; uploads are off.</p>{% endif %}
{% block main %}{% endblock %} {% block main %}{% endblock %}
{% if until %}<footer class="ft">This link works until {{ until }}. What you save here goes to Lanna Desk, which looks after your visa and stay in Thailand; nobody else sees it.</footer>{% endif %} {% if until %}<footer class="ft">This link works until {{ until }}. What you save here goes to Lanna Desk, which looks after your visa and stay in Thailand; nobody else sees it.</footer>{% endif %}
</main> </main>
+93
View File
@@ -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");
}
+1
View File
@@ -9,6 +9,7 @@ mod client;
mod common; mod common;
mod companies; mod companies;
mod deadlines; mod deadlines;
mod demo;
mod documents; mod documents;
mod fuzz_cases; mod fuzz_cases;
mod garage; mod garage;