Plan: Test Coverage Phase 2

Status

Step Description Status

1

Integration tests for persons GET endpoints (income, assets, expenses, addresses)

Done (2026-04-19)

2

Integration tests for P1 fixes (JWKS forced refresh, audit hash chain concurrency, rate limiter proxy trust, healthz production mode, encryption startup, expedited deadline)

Done (2026-04-19)

3

Silent test skip warning in infrastructure_available()

Done (2026-04-19)

Epic: TBD
Issues: #284, #286, #275
Branch: test/coverage-phase2

Context

The Phase 1 test coverage remediation (chore/test-coverage-remediation) brought the test count from ~107 to 403. However, several areas remain uncovered:

  1. Persons GET sub-resource endpoints (#284): The existing integration tests in services/canopy-persons/tests/persons_test.rs cover POST for income (via add_income_to_person) but never exercise the GET (list) endpoints for GET /v1/persons/{id}/income, /assets, /expenses, or /addresses. These are critical read paths used by both the eligibility orchestrator (services/canopy-eligibility/src/orchestrator.rs lines 112-130) and the worker portal.

  2. P1 fix coverage (#286): Several security-critical fixes shipped in the chore/security-ci-remediation branch without dedicated integration tests: JWKS forced refresh on unknown kid (crates/canopy-auth/src/jwks.rs line 104-118), audit hash chain advisory lock concurrency (services/canopy-security/src/store/mod.rs lines 33-38), rate limiter trusted proxy parsing (crates/canopy-api/src/lib.rs lines 323-355), healthz error suppression in production mode, encryption key startup enforcement, and expedited SNAP deadline calculation.

  3. Silent test skip (#275): When infrastructure is unavailable locally, infrastructure_available() in crates/canopy-test-lib/src/infrastructure.rs returns false and tests silently pass. Developers get no feedback that integration tests were skipped, leading to false confidence.

Scope

In scope:

  • Integration tests for GET /v1/persons/{id}/income, GET /v1/persons/{id}/assets, GET /v1/persons/{id}/expenses, GET /v1/persons/{id}/addresses

  • Integration tests for JWKS forced refresh, audit hash chain concurrency, rate limiter proxy trust, healthz production mode, encryption startup, expedited deadline

  • Visible eprintln! warning when infrastructure_available() returns false outside CI

Out of scope:

  • E2E Playwright tests (separate plan)

  • Increasing unit test coverage for already-tested pure functions

  • Load testing or performance benchmarks

Design

Persons GET endpoint tests

Follow the existing pattern in services/canopy-persons/tests/persons_test.rs: create a person, POST a sub-resource (income/asset/expense/address), then GET the list endpoint and assert the created resource appears. The TestClient from canopy-test-lib provides post_json() and get() with Keycloak JWT auth.

Pattern:

#[tokio::test]
async fn get_income_returns_created_income() {
    if !canopy_test_lib::infrastructure_available().await { return; }
    let Some(c) = client().await else { return; };

    // Create person
    let person = c.post_json("/v1/persons", &serde_json::json!({...})).await;
    person.assert_status(201);
    let person_id = person.json::<serde_json::Value>()["id"].as_str().expect("id").to_owned();

    // Add income
    c.post_json(&format!("/v1/persons/{person_id}/income"), &serde_json::json!({
        "income_type": "wages", "amount": "2500.00", "frequency": "monthly",
        "source": "Test Corp", "effective_date": "2026-01-01"
    })).await.assert_status(201);

    // GET list
    let list = c.get(&format!("/v1/persons/{person_id}/income")).await;
    list.assert_status(200);
    let items: Vec<serde_json::Value> = list.json();
    assert!(!items.is_empty(), "should return at least one income record");
}

P1 fix tests

JWKS forced refresh: Unit test in crates/canopy-auth/src/jwks.rs that injects a JWK set with kid=A, creates a token with kid=B, verifies that validate_token triggers try_forced_refresh. Since forced refresh hits the network, test the debounce logic and the retry path using inject_keys to simulate rotation.

Audit hash chain concurrency: Integration test in services/canopy-security/tests/ that spawns multiple concurrent insert_audit_event calls and verifies the chain remains valid via verify_chain(). The advisory lock (pg_advisory_xact_lock(1)) at services/canopy-security/src/store/mod.rs line 37 should serialize writes.

Rate limiter proxy trust: Unit test in crates/canopy-api/src/lib.rs that verifies: (a) without CANOPY_TRUSTED_PROXIES, socket IP is used; (b) with a matching proxy IP, x-forwarded-for header is respected; (c) with a non-matching proxy IP, socket IP is used.

Healthz production mode: Unit test that verifies health_check does not expose error details when CANOPY_ENV is unset (secure by default). The is_dev_env() function at line 187-192 already covers this.

Encryption startup: Test that canopy-persons main rejects startup without CANOPY_ENCRYPTION_KEY when CANOPY_ENV is not set (defaults to production behavior). This is the logic at services/canopy-persons/src/main.rs lines 39-53.

Expedited deadline: Test the expedited SNAP screening deadline calculation in services/canopy-applications/src/domain.rs ExpeditedScreeningData.

Silent test skip warning

Change crates/canopy-test-lib/src/infrastructure.rs infrastructure_available() to print a warning before returning false:

if !available {
    eprintln!(
        "\n=== WARNING: Infrastructure unavailable — integration test SKIPPED ===\n\
         Start devstack with `cargo xtask dev start` to run integration tests.\n"
    );
}

This prints to stderr (visible in cargo nextest output) without failing the test, preserving the current skip-and-pass behavior for local development.

Steps

Step 1: Integration tests for persons GET endpoints

Files: services/canopy-persons/tests/persons_test.rs

Add four new test functions following the existing add_income_to_person pattern:

  • get_income_returns_created_income() — POST income, GET /v1/persons/{id}/income, assert list contains the created record

  • get_assets_returns_created_asset() — POST asset ({"asset_type": "checking", "value": "5000.00"}), GET /v1/persons/{id}/assets, assert non-empty

  • get_expenses_returns_created_expense() — POST expense ({"expense_type": "rent", "amount": "1200.00", "frequency": "monthly"}), GET /v1/persons/{id}/expenses, assert non-empty

  • get_addresses_returns_created_address() — POST address ({"address_type": "home", "line_1": "123 Main St", "city": "Atlanta", "state": "GA", "zip": "30301", "effective_date": "2026-01-01"}), GET /v1/persons/{id}/addresses, assert non-empty

Each test: create person (unique SSN), POST sub-resource, GET list, assert 200, assert at least one item with expected field values.

Step 2: Integration tests for P1 fixes

Files: crates/canopy-auth/src/jwks.rs (unit tests module), services/canopy-security/tests/security_test.rs (new or extend), crates/canopy-api/src/lib.rs (unit tests module)

JWKS forced refresh debounce test (crates/canopy-auth/src/jwks.rs):

#[tokio::test]
async fn forced_refresh_debounce_within_30_seconds() {
    let provider = test_provider(TEST_ISSUER);
    provider.inject_keys(test_jwk_set("old-kid")).await;
    // First call should attempt refresh (returns false since no network)
    let first = provider.try_forced_refresh().await;
    // Second call within 30s should be debounced
    let second = provider.try_forced_refresh().await;
    assert!(!second, "second forced refresh should be debounced");
}

Rate limiter proxy trust test (crates/canopy-api/src/lib.rs): Test rate_limit_middleware by constructing requests with/without CANOPY_TRUSTED_PROXIES set and verifying the correct IP is rate-limited.

Healthz production mode test (crates/canopy-api/src/lib.rs): Verify is_dev_env() returns false when CANOPY_ENV is unset.

Audit hash chain concurrency test (services/canopy-security/tests/security_test.rs): Use TestClient or direct DB access to insert 10 events concurrently via tokio::spawn, then call verify_chain and assert success.

Step 3: Silent test skip warning

Files: crates/canopy-test-lib/src/infrastructure.rs

Add eprintln! warning before returning false from infrastructure_available():

pub async fn infrastructure_available() -> bool {
    let available = tokio::net::TcpStream::connect("127.0.0.1:5432")
        .await
        .is_ok()
        || tokio::net::TcpStream::connect("127.0.0.1:2375")
            .await
            .is_ok()
        || {
            std::process::Command::new("docker")
                .arg("info")
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };

    if !available {
        if std::env::var("CANOPY_CI")
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
        {
            panic!(
                "CANOPY_CI=true but infrastructure is not available. \
                 Integration tests must not be silently skipped in CI."
            );
        }
        eprintln!(
            "\n=== WARNING: Infrastructure unavailable — integration test SKIPPED ===\n\
             Start devstack with `cargo xtask dev start` to run integration tests.\n"
        );
    }

    available
}

Files Touched

File Change

services/canopy-persons/tests/persons_test.rs

Add 4 integration tests for GET income/assets/expenses/addresses

crates/canopy-auth/src/jwks.rs

Add forced refresh debounce unit test

crates/canopy-api/src/lib.rs

Add rate limiter proxy trust and healthz production mode unit tests

services/canopy-security/tests/security_test.rs

Add audit hash chain concurrency integration test — initial version only checked for duplicate previous_hash in existing events (fork detection). Real concurrent-insert coverage added by audit-events-hash-chain-verification-tests (see store::tests::chain_stays_valid_under_concurrent_inserts, along with append-N-verify and tamper-detection companions).

crates/canopy-test-lib/src/infrastructure.rs

Add eprintln! warning when skipping integration tests

Verification

  1. cargo nextest run --workspace --lib — unit tests pass

  2. cargo xtask dev start — devstack running

  3. cargo nextest run --workspace — all integration tests pass, new tests exercise GET endpoints

  4. Stop devstack, run cargo nextest run --workspace — verify eprintln! warning is visible in output

  5. cargo xtask test — full test battery passes

Documentation Updates

  • .claude/docs/services.md — no new endpoints, but note test coverage increase

  • CHANGELOG.adoc — entry under == Unreleased

  • .claude/CLAUDE.md — update test count if significantly changed

Edit this page · default