Plan: Startup Hardening

Status

Step Description Status

1

DATABASE_URL database name validation on startup

Done (2026-04-09) — validate_database_name() in canopy-db, called by all services at startup

2

SPDX header check in pre-commit hook

Done (2026-04-09) — .githooks/pre-commit checks SPDX headers on staged .rs files

3

Tests

Done (2026-04-09) — unit tests for validate_database_name() in canopy-db

Epic: TBD
Issues: #270, #260
Branch: chore/startup-hardening

Context

Two startup-time safety gaps exist:

  1. Cross-database connection (#270): Each Canopy service has its own PostgreSQL database (ADR-001: program service isolation). The DATABASE_URL is set per service via environment variables (e.g., CANOPY_PERSONS__DATABASE_URL). However, nothing validates that the URL actually points to the expected database. A misconfiguration like pointing canopy-snap at the canopy-persons database would silently succeed (migrations would run against the wrong database) and corrupt data. The DbPool::connect_with() function in crates/canopy-db/src/lib.rs (line 46) accepts any valid PostgreSQL URL without checking the database name.

  2. Missing SPDX headers (#260): The project convention requires // SPDX-License-Identifier: AGPL-3.0-or-later on all new .rs files (documented in .claude/CLAUDE.md). The current pre-commit hook at .githooks/pre-commit enforces a protocol checklist but does not check for SPDX headers. The commit-msg hook at .githooks/commit-msg validates commit message format only. Missing headers are caught only during code review.

Scope

In scope:

  • Add validate_database_name() function to canopy-db that extracts the database name from the URL and compares it to an expected value

  • Call this validation in the bootstrap sequence (crates/canopy-api/src/bootstrap.rs) after connecting

  • Add SPDX header check to .githooks/pre-commit for staged .rs files

Out of scope:

  • Retroactively fixing any existing files missing SPDX headers (address in a separate chore)

  • Validating other environment variables (RABBITMQ_URL, KEYCLOAK_ISSUER)

  • Database schema version validation (migrations handle this)

Design

DATABASE_URL validation

Add a function to crates/canopy-db/src/lib.rs:

/// Validate that `database_url` targets the expected database.
///
/// Extracts the database name from the PostgreSQL URL path component
/// and compares it to `expected_db_name`. Panics on mismatch to prevent
/// cross-database data corruption (ADR-001).
pub fn validate_database_name(database_url: &str, expected_db_name: &str) {
    // PostgreSQL URLs: postgres://user:pass@host:port/dbname?params
    let db_name = database_url
        .split('?')
        .next()
        .unwrap_or(database_url)
        .rsplit('/')
        .next()
        .unwrap_or("");

    if db_name.is_empty() {
        panic!(
            "DATABASE_URL does not contain a database name. \
             Expected database: {expected_db_name}"
        );
    }

    if db_name != expected_db_name {
        panic!(
            "DATABASE_URL targets database '{db_name}' but this service expects \
             '{expected_db_name}'. Cross-database connections are not allowed (ADR-001). \
             Check your environment configuration."
        );
    }
}

Call it in crates/canopy-api/src/bootstrap.rs after loading settings but before connecting:

let expected_db = match service_name {
    "canopy-persons" => "canopy_persons",
    "canopy-applications" => "canopy_applications",
    "canopy-rules" => "canopy_rules",
    "canopy-eligibility" => "canopy_eligibility",
    "canopy-snap" => "canopy_snap",
    "canopy-verification" => "canopy_verification",
    "canopy-enrollment" => "canopy_enrollment",
    "canopy-renewals" => "canopy_renewals",
    "canopy-notices" => "canopy_notices",
    "canopy-appeals" => "canopy_appeals",
    "canopy-reporting" => "canopy_reporting",
    "canopy-security" => "canopy_security",
    _ => "", // skip validation for unknown services
};
if !expected_db.is_empty() {
    canopy_db::validate_database_name(&settings.database_url, expected_db);
}

The mapping uses the convention that service canopy-foo uses database canopy_foo (hyphens replaced with underscores).

Alternative design (simpler): derive the expected database name from the service name automatically:

let expected_db = service_name.replace('-', "_");
canopy_db::validate_database_name(&settings.database_url, &expected_db);

This is preferred as it requires no hardcoded mapping and automatically works for new services.

SPDX header check in pre-commit

Add a check to .githooks/pre-commit that inspects staged .rs files for the SPDX header:

# Check SPDX headers on staged .rs files
MISSING_SPDX=""
for file in $(git diff --cached --name-only --diff-filter=ACM -- '*.rs'); do
    if [ -f "$file" ] && ! head -5 "$file" | grep -q "SPDX-License-Identifier"; then
        MISSING_SPDX="$MISSING_SPDX\n  $file"
    fi
done
if [ -n "$MISSING_SPDX" ]; then
    echo ""
    echo "=== MISSING SPDX HEADER ==="
    echo ""
    echo "The following .rs files are missing the SPDX license header:"
    echo -e "$MISSING_SPDX"
    echo ""
    echo "Add this line as the first line of each file:"
    echo "  // SPDX-License-Identifier: AGPL-3.0-or-later"
    echo ""
    # This is a blocking check — prevents commit until headers are added
    HAS_ERRORS=1
fi

This check runs before the protocol checklist, so developers see the issue immediately. It only checks files that are Added, Copied, or Modified (--diff-filter=ACM) to avoid checking deleted files.

Steps

Step 1: DATABASE_URL database name validation

Files: crates/canopy-db/src/lib.rs, crates/canopy-api/src/bootstrap.rs

  1. Add pub fn validate_database_name(database_url: &str, expected_db_name: &str) to crates/canopy-db/src/lib.rs.

  2. The function extracts the database name from the URL path, panics if empty or mismatched.

  3. In crates/canopy-api/src/bootstrap.rs bootstrap(), after ServiceSettings::load() (line 28), derive expected database name from service_name using service_name.replace('-', "_") and call validate_database_name().

  4. Handle edge case: if database_url contains query parameters (?sslmode=require), strip them before extracting the database name.

Step 2: SPDX header check in pre-commit hook

Files: .githooks/pre-commit

  1. Add the SPDX check after the token validation block (after line 13) but before the protocol checklist (line 19).

  2. Use git diff --cached --name-only --diff-filter=ACM — '*.rs' to list staged Rust files.

  3. Check the first 5 lines of each file for SPDX-License-Identifier.

  4. If any files are missing the header, print the list and set exit code to 1 (blocking).

  5. If the SPDX check fails, still show the protocol checklist so developers can fix all issues in one pass.

Step 3: Tests

Files: crates/canopy-db/src/lib.rs (unit tests module)

Add unit tests for validate_database_name:

#[test]
fn validate_database_name_correct() {
    validate_database_name("postgres://user:pass@localhost:5432/canopy_persons", "canopy_persons");
}

#[test]
#[should_panic(expected = "targets database 'canopy_snap'")]
fn validate_database_name_mismatch() {
    validate_database_name("postgres://user:pass@localhost:5432/canopy_snap", "canopy_persons");
}

#[test]
fn validate_database_name_with_query_params() {
    validate_database_name(
        "postgres://user:pass@localhost:5432/canopy_persons?sslmode=require",
        "canopy_persons",
    );
}

#[test]
#[should_panic(expected = "does not contain a database name")]
fn validate_database_name_empty() {
    validate_database_name("postgres://user:pass@localhost:5432/", "canopy_persons");
}

Files Touched

File Change

crates/canopy-db/src/lib.rs

Add validate_database_name() function and unit tests

crates/canopy-api/src/bootstrap.rs

Call validate_database_name() during bootstrap

.githooks/pre-commit

Add SPDX header check for staged .rs files

Verification

  1. cargo nextest run --workspace --lib — unit tests pass (including validate_database_name tests)

  2. cargo xtask dev restart — all services start successfully (DATABASE_URL matches expected names)

  3. Manually set a wrong DATABASE_URL for one service, verify it panics with a clear message

  4. Stage a .rs file without SPDX header, run git commit — verify pre-commit blocks with helpful message

  5. cargo xtask test — full test battery passes

Documentation Updates

  • .claude/docs/local-dev.md — note DATABASE_URL naming convention requirement

  • CHANGELOG.adoc — entry under == Unreleased

  • .claude/docs/security.md — document cross-database protection

Edit this page · default