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:

  1. SSN accepts non-digit characters. The CreatePerson and UpdatePerson structs in services/canopy-persons/src/store/models.rs validate 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.

  2. Expenses are not frequency-normalized. In services/canopy-snap/src/determine.rs lines 139-168, expenses are summed by raw amount without any frequency conversion. Income records are correctly normalized via IncomeRecord::monthly_amount() (lines 52-60), but ExpenseRecord has 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.

  3. Program names are unvalidated. The CreateApplicationRequest in services/canopy-applications/src/domain.rs accepts programs_requested: Vec<String> at line 55 without validating values against the canopy_reference::enums::Program enum. Invalid program names like "ssnap" (typo) silently create application_program rows that will never be processed by any program service.

  4. submitted_by_role is unvalidated. The same struct accepts any string for submitted_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 CreatePerson and UpdatePerson

  • Add monthly_amount() method to ExpenseRecord and use it in determine()

  • Add validation of programs_requested against known Program enum variants

  • Add validation of submitted_by_role against 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::Program enum 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

  1. Add regex to canopy-persons dependencies if not already present (it is likely already a transitive dep via validator).

  2. Add a Lazy<Regex> static for ^\d{9}$.

  3. Add #[validate(regex(path = SSN_REGEX))] to CreatePerson.ssn (line 105) and UpdatePerson.ssn (line 131).

  4. Verify the existing integration test create_person_invalid_ssn_returns_400 still passes (it tests length).

  5. Add a new test create_person_non_digit_ssn_returns_400 with SSN "12345678a".

Step 2: Expense frequency normalization

Files: services/canopy-snap/src/determine.rs

  1. Add monthly_amount() method to ExpenseRecord (after line 76).

  2. Replace e.amount with e.monthly_amount() in the four expense aggregation blocks (lines 141, 150, 158, 164).

  3. Add unit tests mirroring the existing IncomeRecord::monthly_amount tests:

    • 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)

  1. Add validate_programs() function in domain.rs.

  2. Call it in the create_application handler before persisting the application.

  3. Add integration test create_application_invalid_program_returns_400 that sends programs_requested: ["ssnap"].

  4. Add integration test create_application_empty_programs_returns_400 that sends programs_requested: [].

Step 4: submitted_by_role validation

Files: services/canopy-applications/src/domain.rs, services/canopy-applications/src/api.rs

  1. Add VALID_ROLES constant and validate_submitted_by_role() in domain.rs.

  2. Call it in the create_application handler.

  3. Add integration test create_application_invalid_role_returns_400 that sends submitted_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

services/canopy-persons/src/store/models.rs

Add SSN regex validation to CreatePerson and UpdatePerson

services/canopy-snap/src/determine.rs

Add ExpenseRecord::monthly_amount(), update 4 expense aggregation sites

services/canopy-applications/src/domain.rs

Add validate_programs() and validate_submitted_by_role()

services/canopy-applications/src/api.rs

Call validation functions in create_application handler

services/canopy-persons/tests/persons_test.rs

Add non-digit SSN test

services/canopy-applications/tests/applications_test.rs

Add invalid program and invalid role tests

services/canopy-persons/Cargo.toml

Add regex dependency if not present

Verification

  1. cargo nextest run --workspace --lib — unit tests pass (including new expense frequency tests)

  2. cargo xtask dev reload

  3. cargo nextest run --workspace — integration tests pass (including new validation tests)

  4. Manual smoke test: POST to /v1/persons with SSN "12345678a" — expect 400

  5. Manual smoke test: POST to /v1/applications with programs_requested: ["ssnap"] — expect 400

  6. cargo xtask test — full test battery passes

Documentation Updates

  • .claude/docs/services.md — document validation rules for SSN, programs, roles

  • CHANGELOG.adoc — entry under == Unreleased

  • .claude/CLAUDE.md — update canopy-reference status if enum changes needed

Edit this page · default