Dates: four-digit years from 1900 to 2100
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 20s

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).
This commit is contained in:
grabowski committed 2026-11-17 21:15:14 +07:00
1 parent 38070ee135
commit d543c929e9
6 files changed
+147 -10

No files matched your search

+43
View File
@@ -29,6 +29,23 @@ pub fn parse_date(s: &str) -> Option<NaiveDate> {
NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok() 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<NaiveDate, &'static str> {
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`. /// Full years from `born` to `on`.
pub fn age(born: NaiveDate, on: NaiveDate) -> i32 { pub fn age(born: NaiveDate, on: NaiveDate) -> i32 {
let mut years = on.year() - born.year(); let mut years = on.year() - born.year();
@@ -114,6 +131,32 @@ mod tests {
assert_eq!(parse_date(" 2026-02-30 "), None); 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] #[test]
fn ages() { fn ages() {
assert_eq!(age(d("1984-08-12"), d("2026-08-11")), 41); assert_eq!(age(d("1984-08-12"), d("2026-08-11")), 41);
+6 -4
View File
@@ -280,11 +280,13 @@ fn optional_date(value: &str, field: &str, e: &mut Errors) -> Option<NaiveDate>
if value.is_empty() { if value.is_empty() {
return None; return None;
} }
let d = dates::parse_date(value); match dates::parse_form_date(value) {
if d.is_none() { Ok(d) => Some(d),
err(e, field, "Enter a date (year-month-day)."); Err(msg) => {
err(e, field, msg);
None
}
} }
d
} }
pub async fn get_person(db: &PgPool, id: i64) -> Result<Option<Person>> { pub async fn get_person(db: &PgPool, id: i64) -> Result<Option<Person>> {
+6 -5
View File
@@ -8,7 +8,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use anyhow::Result; use anyhow::Result;
use chrono::{Datelike, NaiveDate, TimeDelta}; use chrono::{NaiveDate, TimeDelta};
use serde::Serialize; use serde::Serialize;
use sqlx::postgres::PgRow; use sqlx::postgres::PgRow;
use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row}; use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row};
@@ -670,10 +670,11 @@ pub fn validate(kind: &Kind, v: &Values, opts: &Options) -> Errors {
continue; continue;
} }
match fl.input { match fl.input {
Input::Date => match dates::parse_date(value) { Input::Date => {
Some(d) if (1900..=2100).contains(&d.year()) => {} if let Err(msg) = dates::parse_form_date(value) {
_ => err(&mut e, fl.name, "Enter a date such as 2026-11-17."), err(&mut e, fl.name, msg);
}, }
}
Input::Choice(list) => { Input::Choice(list) => {
if label(list, value).is_none() { if label(list, value).is_none() {
err(&mut e, fl.name, "Choose from the list."); err(&mut e, fl.name, "Choose from the list.");
+1 -1
View File
@@ -4,7 +4,7 @@
{% macro text(name, label, value="", err="", hint="", req=false, type="text", list="", auto="off", cls="", ph="") -%} {% macro text(name, label, value="", err="", hint="", req=false, type="text", list="", auto="off", cls="", ph="") -%}
<div class="field{% if err %} has-err{% endif %}{% if cls %} {{ cls }}{% endif %}"> <div class="field{% if err %} has-err{% endif %}{% if cls %} {{ cls }}{% endif %}">
<label for="f-{{ name }}">{{ label }}{% if req %} <span class="req" aria-hidden="true">*</span>{% endif %}</label> <label for="f-{{ name }}">{{ label }}{% if req %} <span class="req" aria-hidden="true">*</span>{% endif %}</label>
<input id="f-{{ name }}" name="{{ name }}" type="{{ type }}" value="{{ value }}"{% if req %} required{% endif %}{% if list %} list="{{ list }}"{% endif %} autocomplete="{{ auto }}"{% if ph %} placeholder="{{ ph }}"{% endif %}{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% elif hint %} aria-describedby="h-{{ name }}"{% endif %}> <input id="f-{{ name }}" name="{{ name }}" type="{{ type }}" value="{{ value }}"{% if req %} required{% endif %}{% if list %} list="{{ list }}"{% endif %} autocomplete="{{ auto }}"{% if type == "date" %} min="1900-01-01" max="2100-12-31"{% endif %}{% if ph %} placeholder="{{ ph }}"{% endif %}{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% elif hint %} aria-describedby="h-{{ name }}"{% endif %}>
{%- if hint %} {%- if hint %}
<p class="hint" id="h-{{ name }}">{{ hint }}</p> <p class="hint" id="h-{{ name }}">{{ hint }}</p>
{%- endif %} {%- endif %}
+20
View File
@@ -5,6 +5,23 @@ use sqlx::PgPool;
use crate::common::{assert_unique_ids, local}; 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("<input").skip(1) {
let tag = &tag[..tag.find('>').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")] #[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn every_page_renders_with_demo_data(pool: PgPool) { async fn every_page_renders_with_demo_data(pool: PgPool) {
assert!(visa::seed::demo(&pool, visa::dates::today()).await.unwrap()); 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"), (format!("/activity?person={erika}"), "MUSTERMANN, Erika"),
]; ];
pages.extend(older.into_iter().map(|(p, e)| (p, e.to_string()))); pages.extend(older.into_iter().map(|(p, e)| (p, e.to_string())));
let mut date_inputs = 0;
for (path, expect) in &pages { for (path, expect) in &pages {
let r = app.get(path).await; let r = app.get(path).await;
assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body); 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_unique_ids(&r.body, path);
assert_eq!(r.headers["cache-control"], "no-store", "{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 // 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 // has no TM.30 receipt, Tomas's passport has under a year
+71
View File
@@ -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"); 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")] #[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn archive_and_restore(pool: PgPool) { async fn archive_and_restore(pool: PgPool) {
let app = local(pool.clone()); let app = local(pool.clone());