From d543c929e906588044a0f6e3f23b7c697f776bb3 Mon Sep 17 00:00:00 2001 From: grabowski Date: Tue, 17 Nov 2026 21:15:14 +0700 Subject: [PATCH] Dates: four-digit years from 1900 to 2100 Chromium's date input lets the year part take six digits when the input has no max, so typing 2026 and then 11 for the month gave 202611-12-05 (reported on the live app). Every date input now carries min="1900-01-01" and max="2100-12-31", so the year part stops at four digits and moves on to the month. Checked in Edge: typing 20261112 gives 2026-11-12, where it left the field empty before. The server checks the same years for every date field (dates::parse_form_date). Person, passport and address dates were only parsed, so a two-digit year such as 0026-11-12 would have been saved; stay records had the range already. A six-digit year never parsed, so no such date can be in the database. Tests: the parser's cases; the person, passport and arrival forms refuse both years and save nothing; every date input on every page carries the limits (pages.rs). --- src/dates.rs | 43 +++++++++++++++++++++++++ src/people.rs | 10 +++--- src/records.rs | 11 ++++--- templates/_fields.html | 2 +- tests/pages.rs | 20 ++++++++++++ tests/people.rs | 71 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 10 deletions(-) diff --git a/src/dates.rs b/src/dates.rs index 6ea92d9..4dc87ca 100644 --- a/src/dates.rs +++ b/src/dates.rs @@ -29,6 +29,23 @@ pub fn parse_date(s: &str) -> Option { NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok() } +/// The years a date field accepts. Every date input carries the same limits +/// as `min` and `max` (`templates/_fields.html`); without a `max`, Chromium +/// lets the year part take six digits and never moves on to the month. +pub const FIRST_YEAR: i32 = 1900; +pub const LAST_YEAR: i32 = 2100; + +/// A date typed into a form: a calendar date from `FIRST_YEAR` to +/// `LAST_YEAR`, or the message to show next to the field. +pub fn parse_form_date(s: &str) -> Result { + let d = parse_date(s).ok_or("Enter a date such as 2026-11-17.")?; + if (FIRST_YEAR..=LAST_YEAR).contains(&d.year()) { + Ok(d) + } else { + Err("Enter a year from 1900 to 2100.") + } +} + /// Full years from `born` to `on`. pub fn age(born: NaiveDate, on: NaiveDate) -> i32 { let mut years = on.year() - born.year(); @@ -114,6 +131,32 @@ mod tests { assert_eq!(parse_date(" 2026-02-30 "), None); } + #[test] + fn form_dates_have_four_digit_years_in_range() { + assert_eq!(parse_form_date("2026-11-12"), Ok(d("2026-11-12"))); + assert_eq!(parse_form_date("1900-01-01"), Ok(d("1900-01-01"))); + assert_eq!(parse_form_date("2100-12-31"), Ok(d("2100-12-31"))); + // what Chromium sends when the year part took six digits + assert_eq!( + parse_form_date("202611-12-05"), + Err("Enter a date such as 2026-11-17.") + ); + // a two-digit year typed into the year part + assert_eq!( + parse_form_date("0026-11-12"), + Err("Enter a year from 1900 to 2100.") + ); + assert_eq!( + parse_form_date("2101-01-01"), + Err("Enter a year from 1900 to 2100.") + ); + let years = format!("{FIRST_YEAR} to {LAST_YEAR}"); + assert!( + parse_form_date("1899-12-31").unwrap_err().contains(&years), + "the message names the limits" + ); + } + #[test] fn ages() { assert_eq!(age(d("1984-08-12"), d("2026-08-11")), 41); diff --git a/src/people.rs b/src/people.rs index ee7c504..56c2d81 100644 --- a/src/people.rs +++ b/src/people.rs @@ -280,11 +280,13 @@ fn optional_date(value: &str, field: &str, e: &mut Errors) -> Option if value.is_empty() { return None; } - let d = dates::parse_date(value); - if d.is_none() { - err(e, field, "Enter a date (year-month-day)."); + match dates::parse_form_date(value) { + Ok(d) => Some(d), + Err(msg) => { + err(e, field, msg); + None + } } - d } pub async fn get_person(db: &PgPool, id: i64) -> Result> { diff --git a/src/records.rs b/src/records.rs index 3df18c8..8f97124 100644 --- a/src/records.rs +++ b/src/records.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use anyhow::Result; -use chrono::{Datelike, NaiveDate, TimeDelta}; +use chrono::{NaiveDate, TimeDelta}; use serde::Serialize; use sqlx::postgres::PgRow; use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row}; @@ -670,10 +670,11 @@ pub fn validate(kind: &Kind, v: &Values, opts: &Options) -> Errors { continue; } match fl.input { - Input::Date => match dates::parse_date(value) { - Some(d) if (1900..=2100).contains(&d.year()) => {} - _ => err(&mut e, fl.name, "Enter a date such as 2026-11-17."), - }, + Input::Date => { + if let Err(msg) = dates::parse_form_date(value) { + err(&mut e, fl.name, msg); + } + } Input::Choice(list) => { if label(list, value).is_none() { err(&mut e, fl.name, "Choose from the list."); diff --git a/templates/_fields.html b/templates/_fields.html index f357524..59194c5 100644 --- a/templates/_fields.html +++ b/templates/_fields.html @@ -4,7 +4,7 @@ {% macro text(name, label, value="", err="", hint="", req=false, type="text", list="", auto="off", cls="", ph="") -%}
- + {%- if hint %}

{{ hint }}

{%- endif %} diff --git a/tests/pages.rs b/tests/pages.rs index 484ba18..13eecb1 100644 --- a/tests/pages.rs +++ b/tests/pages.rs @@ -5,6 +5,23 @@ use sqlx::PgPool; use crate::common::{assert_unique_ids, local}; +/// Every date input carries `min` and `max` from `visa::dates`: without a +/// `max`, Chromium lets its year part take six digits (`202611-12-05`). +/// Returns how many date inputs the page has. +fn assert_date_limits(html: &str, page: &str) -> usize { + let min = format!("min=\"{}-01-01\"", visa::dates::FIRST_YEAR); + let max = format!("max=\"{}-12-31\"", visa::dates::LAST_YEAR); + let mut n = 0; + for tag in html.split("').unwrap_or(tag.len())]; + if tag.contains("type=\"date\"") { + assert!(tag.contains(&min) && tag.contains(&max), "{page}: {tag}"); + n += 1; + } + } + n +} + #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn every_page_renders_with_demo_data(pool: PgPool) { assert!(visa::seed::demo(&pool, visa::dates::today()).await.unwrap()); @@ -116,6 +133,7 @@ async fn every_page_renders_with_demo_data(pool: PgPool) { (format!("/activity?person={erika}"), "MUSTERMANN, Erika"), ]; pages.extend(older.into_iter().map(|(p, e)| (p, e.to_string()))); + let mut date_inputs = 0; for (path, expect) in &pages { let r = app.get(path).await; assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body); @@ -125,7 +143,9 @@ async fn every_page_renders_with_demo_data(pool: PgPool) { ); assert_unique_ids(&r.body, path); assert_eq!(r.headers["cache-control"], "no-store", "{path}"); + date_inputs += assert_date_limits(&r.body, path); } + assert!(date_inputs >= 20, "only {date_inputs} date inputs seen"); // warnings from the demo dates: Jane's passport runs out in 95 days, she // has no TM.30 receipt, Tomas's passport has under a year diff --git a/tests/people.rs b/tests/people.rs index db88fd5..eb9cb2b 100644 --- a/tests/people.rs +++ b/tests/people.rs @@ -164,6 +164,77 @@ async fn validation_and_edits_with_changed_fields(pool: PgPool) { assert_eq!(audit_rows(&pool, id).await.last().unwrap().0, "view"); } +/// Chromium sends `202611-12-05` when the year part took six digits, and +/// `0026-...` for a two-digit year; neither may reach the database. +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn dates_need_a_four_digit_year_from_1900_to_2100(pool: PgPool) { + let app = local(pool.clone()); + let r = app + .post( + "/people", + &[ + ("surname", "Doe"), + ("first_name", "Jane"), + ("date_of_birth", "0026-11-12"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + r.text().contains("Enter a year from 1900 to 2100."), + "{}", + r.text() + ); + + let r = app + .post("/people", &[("surname", "Doe"), ("first_name", "Jane")]) + .await; + let id = id_from(r.location()); + let r = app + .post( + &format!("/people/{id}/passports"), + &[ + ("number", "X1234567"), + ("issuing_country", "USA"), + ("issued_on", "202611-12-05"), + ("expires_on", "2036-11-11"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let t = r.text(); + assert!(t.contains("Enter a date such as 2026-11-17."), "{t}"); + assert!( + r.body.contains("value=\"202611-12-05\""), + "the typed value stays" + ); + + let r = app + .post( + &format!("/people/{id}/arrivals"), + &[ + ("arrived_on", "0026-09-01"), + ("admission", "exempt"), + ("permitted_until", "2026-10-30"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + r.text().contains("Enter a year from 1900 to 2100."), + "{}", + r.text() + ); + + let saved: i64 = sqlx::query_scalar( + "SELECT (SELECT count(*) FROM passports) + (SELECT count(*) FROM arrivals)", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(saved, 0); +} + #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn archive_and_restore(pool: PgPool) { let app = local(pool.clone());