Plan: Input Validation Hardening
Status
| Step | Description | Status |
|---|---|---|
1 |
SSN regex validation (digits-only enforcement) |
Done (2026-04-06) |
2 |
Expense frequency normalization in canopy-snap determine |
Done (2026-04-06) |
3 |
Program name validation against known enum values |
Done (2026-04-06) |
4 |
submitted_by_role validation |
Done (2026-04-06) |
5 |
Tests for all validation changes |
Done (2026-04-06) |
Epic: TBD
Issues: #283
Branch: fix/input-validation
Context
A security audit of input validation revealed four gaps that could allow malformed data to enter the system:
-
SSN accepts non-digit characters. The
CreatePersonandUpdatePersonstructs inservices/canopy-persons/src/store/models.rsvalidate SSN length only (#[validate(length(equal = 9))]at line 105) but do not enforce that the value contains only digits. A value like"12345678a"passes validation, gets encrypted, and corrupts the SSN store. IEVS queries and SSA SOLQ/BINDEX lookups would fail or return wrong data. -
Expenses are not frequency-normalized. In
services/canopy-snap/src/determine.rslines 139-168, expenses are summed by rawamountwithout any frequency conversion. Income records are correctly normalized viaIncomeRecord::monthly_amount()(lines 52-60), butExpenseRecordhas no equivalent. A weekly rent payment of $300 would be summed as $300 instead of the correct monthly equivalent of $1,300, dramatically understating shelter deductions and overstating net income. -
Program names are unvalidated. The
CreateApplicationRequestinservices/canopy-applications/src/domain.rsacceptsprograms_requested: Vec<String>at line 55 without validating values against thecanopy_reference::enums::Programenum. Invalid program names like"ssnap"(typo) silently create application_program rows that will never be processed by any program service. -
submitted_by_roleis unvalidated. The same struct accepts any string forsubmitted_by_role(line 58). This field feeds audit logs and RBAC downstream; arbitrary values undermine compliance tracing.
Scope
In scope:
-
Add regex validation to SSN fields on
CreatePersonandUpdatePerson -
Add
monthly_amount()method toExpenseRecordand use it indetermine() -
Add validation of
programs_requestedagainst knownProgramenum variants -
Add validation of
submitted_by_roleagainst an allowed set
Out of scope:
-
Migrating existing database records with bad SSN values (separate data cleanup task)
-
Validating other free-text fields (income_type, expense_type, etc.) — these accept open vocabularies intentionally
-
Changing the
canopy_reference::enums::Programenum itself
Design
SSN regex validation
Add a #[validate(regex(path = SSN_REGEX))] attribute alongside the existing length check. The regex enforces exactly 9 ASCII digits:
use once_cell::sync::Lazy; // or std::sync::LazyLock on Rust 2024 edition
use regex::Regex;
static SSN_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\d{9}$").expect("valid regex"));
Applied to both CreatePerson.ssn and UpdatePerson.ssn in services/canopy-persons/src/store/models.rs. The regex check subsumes the length check but we keep both for clarity of the error message (length gives "must be 9 characters", regex gives "must be digits only").
Expense frequency normalization
Add a monthly_amount() method to ExpenseRecord in services/canopy-snap/src/determine.rs that mirrors IncomeRecord::monthly_amount():
impl ExpenseRecord {
pub fn monthly_amount(&self) -> Decimal {
match self.frequency.as_str() {
"monthly" => self.amount,
"biweekly" => self.amount * Decimal::from(26) / Decimal::from(12),
"weekly" => self.amount * Decimal::from(52) / Decimal::from(12),
"annual" => self.amount / Decimal::from(12),
_ => self.amount, // unknown frequency treated as monthly (safe default)
}
}
}
Update the four expense aggregation blocks (lines 140-168) to call e.monthly_amount() instead of e.amount:
let dependent_care_total: Decimal = context
.expenses
.iter()
.filter(|e| e.expense_type == "dependent_care")
.map(|e| e.monthly_amount())
.sum();
Same change for shelter_costs, medical_expenses, and child_support_paid.
Program name validation
Add a validation function to services/canopy-applications/src/domain.rs (or a handler-level check in the API layer) that rejects unknown program names:
fn validate_programs(programs: &[String]) -> Result<(), ApiError> {
let valid = ["snap", "tanf", "medicaid", "chip", "caps", "wic"];
for p in programs {
if !valid.contains(&p.to_lowercase().as_str()) {
return Err(ApiError::BadRequest(
format!("unknown program: {p}. Valid programs: {}", valid.join(", "))
));
}
}
if programs.is_empty() {
return Err(ApiError::BadRequest(
"programs_requested must contain at least one program".into()
));
}
Ok(())
}
This validation runs in the create_application handler before persisting.
submitted_by_role validation
Add a check for submitted_by_role against an allowed set:
const VALID_ROLES: &[&str] = &[
"applicant", "authorized_representative", "caseworker", "supervisor", "system"
];
fn validate_submitted_by_role(role: &str) -> Result<(), ApiError> {
if !VALID_ROLES.contains(&role) {
return Err(ApiError::BadRequest(
format!("invalid submitted_by_role: {role}. Valid roles: {}", VALID_ROLES.join(", "))
));
}
Ok(())
}
Steps
Step 1: SSN regex validation
Files: services/canopy-persons/src/store/models.rs
-
Add
regextocanopy-personsdependencies if not already present (it is likely already a transitive dep viavalidator). -
Add a
Lazy<Regex>static for^\d{9}$. -
Add
#[validate(regex(path = SSN_REGEX))]toCreatePerson.ssn(line 105) andUpdatePerson.ssn(line 131). -
Verify the existing integration test
create_person_invalid_ssn_returns_400still passes (it tests length). -
Add a new test
create_person_non_digit_ssn_returns_400with SSN"12345678a".
Step 2: Expense frequency normalization
Files: services/canopy-snap/src/determine.rs
-
Add
monthly_amount()method toExpenseRecord(after line 76). -
Replace
e.amountwithe.monthly_amount()in the four expense aggregation blocks (lines 141, 150, 158, 164). -
Add unit tests mirroring the existing
IncomeRecord::monthly_amounttests:-
expense_monthly_amount_monthly() -
expense_monthly_amount_biweekly() -
expense_monthly_amount_weekly() -
expense_monthly_amount_annual()
-
Step 3: Program name validation
Files: services/canopy-applications/src/domain.rs, services/canopy-applications/src/api.rs (or wherever create_application handler lives)
-
Add
validate_programs()function indomain.rs. -
Call it in the
create_applicationhandler before persisting the application. -
Add integration test
create_application_invalid_program_returns_400that sendsprograms_requested: ["ssnap"]. -
Add integration test
create_application_empty_programs_returns_400that sendsprograms_requested: [].
Step 4: submitted_by_role validation
Files: services/canopy-applications/src/domain.rs, services/canopy-applications/src/api.rs
-
Add
VALID_ROLESconstant andvalidate_submitted_by_role()indomain.rs. -
Call it in the
create_applicationhandler. -
Add integration test
create_application_invalid_role_returns_400that sendssubmitted_by_role: "hacker".
Step 5: Tests for all validation changes
Files: services/canopy-persons/tests/persons_test.rs, services/canopy-snap/src/determine.rs (unit tests module), services/canopy-applications/tests/applications_test.rs
Ensure all new validation paths have both positive (valid input succeeds) and negative (invalid input returns 400) test coverage.
Files Touched
| File | Change |
|---|---|
|
Add SSN regex validation to |
|
Add |
|
Add |
|
Call validation functions in |
|
Add non-digit SSN test |
|
Add invalid program and invalid role tests |
|
Add |
Verification
-
cargo nextest run --workspace --lib— unit tests pass (including new expense frequency tests) -
cargo xtask dev reload -
cargo nextest run --workspace— integration tests pass (including new validation tests) -
Manual smoke test: POST to
/v1/personswith SSN"12345678a"— expect 400 -
Manual smoke test: POST to
/v1/applicationswithprograms_requested: ["ssnap"]— expect 400 -
cargo xtask test— full test battery passes