K1: card purchases on the server (schema 4, Enable Banking adapter, E-36 to E-44)
Build Kvitt images / build (push) Failing after 8m17s

Contract (SPEC §14.8): migration 0004_card_purchases.sql (server schema 4, byte-identical
contract and server copies), E-36 to E-44 in contracts/openapi.yaml with the four new error
codes and a 502 response, examples for every card body and error code, the
match_card_purchase vectors (17 cases) with their Python reference in tools/contracts-check.py
(157 checks), web/src/api/schema.d.ts regenerated; web/src/lib/vectors.test.ts lists
match_card_purchase as not ported until K3 ports it (orchestrator's allowance).

Server: src/cards/ with the provider registry (CP-1), the CardSource trait and its
Enable Banking adapter (JWT RS256 kid = application id, /aspsps, /auth, /sessions,
transactions with PSU headers for user-present fetches, CP-14 error mapping, CP-7 mapping),
the windowed fetch (30-day windows newest first, split at the 100-row cap down to a day,
de-duplication by provider_ref, continuation keys, WRONG_TRANSACTIONS_PERIOD ends the walk),
CP-8 matching with the secondary rule, the background poller (06:45, 11:45, 16:45, 21:45,
4 per 24 hours, 2-hour skip, no backlog), the bilingual callback page (E-39), E-36 to E-38
and E-40 to E-44, link clearing in sync push step 7, attempt pruning at 04:00, the card_fetch
log line with aggregates only, KVITT_EB_* configuration. Tests against a local stub
(tests/cards_api/, 34 tests); the real API is never called.

Infra: Pi compose mounts secrets/cards read-only and passes the two application ids;
.env.example keys; dev stack stages infra/secrets/cards/; NPM block with the /cards/callback
gate line and unlogged location (kvitt.conf and README step 4); README "Card purchases".

Pre-commit hook bypassed (--no-verify, orchestrator's decision): the Android fast tests fail
in :domain VectorFilesTest (and the full check in :data ExampleRoundTripTest) because they pin
the contract's vector and example sets; matchCardPurchase and the card DTOs are K2's by design
(contract-first landing; K2 lands next). Server, contracts-check and web gates are green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TQd3pEP9UeN2uifbHknQ7B
This commit is contained in:
2026-10-24 16:43:26 +02:00
parent ae73f58079
commit 671c00d0d8
67 changed files with 9515 additions and 47 deletions
@@ -24,6 +24,9 @@ const STATUS: &[(&str, u16)] = &[
("cannot_revoke_current_device", 409),
("no_accounts", 409),
("cursor_ahead", 409),
("cards_unavailable", 409),
("card_consent_expired", 409),
("expense_already_linked", 409),
("payload_too_large", 413),
("unsupported_media_type", 415),
("validation_failed", 422),
@@ -32,6 +35,7 @@ const STATUS: &[(&str, u16)] = &[
("protocol_unsupported", 426),
("rate_limited", 429),
("internal", 500),
("card_bank_unavailable", 502),
("not_implemented", 501),
("unavailable", 503),
];
@@ -1,7 +1,8 @@
//! The migrations are the contract texts byte for byte (`0001_init.sql` = `server-v1.sql`, SPEC §14.1;
//! `0002_categories_v2.sql` and `0003_device_version_name.sql` = their copies in `contracts/schema/migrations/`,
//! §14.1.1), connections carry the §8.9 pragmas, a fresh database holds the fourteen defaults of AC-7.2, a v1
//! database in use upgrades to schema 2 and a v2 database to schema 3 without losing or changing a row.
//! `0002_categories_v2.sql`, `0003_device_version_name.sql` and `0004_card_purchases.sql` = their copies in
//! `contracts/schema/migrations/`, §14.1.1, §14.1.3), connections carry the §8.9 pragmas, a fresh database holds the
//! fourteen defaults of AC-7.2, a v1 database in use upgrades to schema 2, a v2 database to schema 3 and a v3
//! database to schema 4 without losing or changing a row.
use std::path::PathBuf;
@@ -79,6 +80,19 @@ fn migration_0003_is_byte_identical_to_contract_migration() {
);
}
#[test]
fn migration_0004_is_byte_identical_to_contract_migration() {
let migration = std::fs::read(manifest("migrations/0004_card_purchases.sql")).unwrap();
let contract = std::fs::read(manifest(
"../../../contracts/schema/migrations/0004_card_purchases.sql",
))
.unwrap();
assert!(
migration == contract,
"migrations/0004_card_purchases.sql differs from contracts/schema/migrations/0004_card_purchases.sql"
);
}
#[test]
fn the_embedded_migrator_holds_exactly_those_migrations() {
let v1 = std::fs::read_to_string(manifest("../../../contracts/schema/server-v1.sql")).unwrap();
@@ -90,17 +104,23 @@ fn the_embedded_migrator_holds_exactly_those_migrations() {
"../../../contracts/schema/migrations/0003_device_version_name.sql",
))
.unwrap();
let v4 = std::fs::read_to_string(manifest(
"../../../contracts/schema/migrations/0004_card_purchases.sql",
))
.unwrap();
let migrations: Vec<_> = db::MIGRATOR.iter().collect();
assert_eq!(migrations.len(), 3);
assert_eq!(migrations.len(), 4);
assert_eq!(migrations[0].version, 1);
assert_eq!(migrations[0].sql.as_ref(), v1.as_str());
assert_eq!(migrations[1].version, 2);
assert_eq!(migrations[1].sql.as_ref(), v2.as_str());
assert_eq!(migrations[2].version, 3);
assert_eq!(migrations[2].sql.as_ref(), v3.as_str());
assert_eq!(migrations[3].version, 4);
assert_eq!(migrations[3].sql.as_ref(), v4.as_str());
// sqlx wraps each migration in one transaction unless it opts out (SPEC §14.1.1 relies on it).
assert!(migrations.iter().all(|m| !m.no_tx));
assert_eq!(db::SCHEMA_VERSION, 3);
assert_eq!(db::SCHEMA_VERSION, 4);
}
/// Every row of `table` in a stable order, each rendered with SQLite's `quote()` per column (type-exact).
@@ -468,7 +488,7 @@ async fn a_v2_database_in_use_upgrades_to_schema_3_keeping_every_row() {
}
}
db::migrate(pool).await.unwrap();
db::MIGRATOR.run_to(3, pool).await.unwrap();
assert_eq!(foreign_key_violations(pool).await, 0);
assert_eq!(
@@ -515,6 +535,97 @@ async fn a_v2_database_in_use_upgrades_to_schema_3_keeping_every_row() {
"33 characters rejected"
);
// A second run is a no-op.
db::MIGRATOR.run_to(3, pool).await.unwrap();
}
#[tokio::test]
async fn a_v3_database_in_use_upgrades_to_schema_4_keeping_every_row() {
let app = TestApp::at_v3().await;
let pool = &app.state.db;
assert_eq!(
sqlx::query_scalar::<_, String>("SELECT value FROM meta WHERE key = 'schema_version'")
.fetch_one(pool)
.await
.unwrap(),
"3"
);
fill_v1(&app).await;
sqlx::query(
"INSERT INTO audit_log (id, entity_type, entity_id, action, source, actor_user_id, actor_device_id, \
client_at, server_at, changes, server_version) VALUES ('0192f000-0000-7000-8000-000000000001', 'expense', \
'0192e000-0000-7000-8000-000000000002', 'create', 'app', '0192a000-0000-7000-8000-000000000002', NULL, \
'2026-10-17T09:06:00.000Z', '2026-10-17T09:06:00.000Z', '[]', 24)",
)
.execute(pool)
.await
.unwrap();
sqlx::query("UPDATE sync_sequence SET value = 24 WHERE id = 1")
.execute(pool)
.await
.unwrap();
sqlx::query("UPDATE devices SET app_version_code = 41, app_version_name = '1.4', fcm_token = 'fcm-1' WHERE id = ?")
.bind(crate::support::ADMIN_DEVICE_ID)
.execute(pool)
.await
.unwrap();
let tables = user_tables(pool).await;
let mut before = Vec::new();
for table in &tables {
if table != "meta" {
before.push((table.clone(), dump(pool, table, "").await));
}
}
assert!(
before
.iter()
.any(|(t, rows)| t == "audit_log" && rows.len() == 1)
);
assert!(
before
.iter()
.any(|(t, rows)| t == "expenses" && rows.len() == 2)
);
db::migrate(pool).await.unwrap();
assert_eq!(foreign_key_violations(pool).await, 0);
assert_eq!(
sqlx::query_scalar::<_, String>("SELECT value FROM meta WHERE key = 'schema_version'")
.fetch_one(pool)
.await
.unwrap(),
"4"
);
assert_eq!(
scalar_i64(pool, "SELECT value FROM sync_sequence WHERE id = 1").await,
24,
"0004 writes no synced row"
);
for (table, rows) in &before {
assert_eq!(&dump(pool, table, "").await, rows, "{table} changed");
}
let mut want = tables.clone();
want.extend(
[
"card_auth_attempts",
"card_connections",
"card_purchases",
"card_sequence",
]
.map(String::from),
);
want.sort();
assert_eq!(
user_tables(pool).await,
want,
"exactly the four card tables added"
);
for table in ["card_auth_attempts", "card_connections", "card_purchases"] {
assert!(dump(pool, table, "").await.is_empty(), "{table} is empty");
}
assert_eq!(dump(pool, "card_sequence", "").await, ["1|0"]);
// A second run is a no-op.
db::migrate(pool).await.unwrap();
}
@@ -104,7 +104,7 @@ async fn health_reports_ok_with_versions() {
assert_eq!(reply.status, StatusCode::OK);
assert_eq!(
reply.json,
json!({"status": "ok", "server_version": env!("CARGO_PKG_VERSION"), "schema_version": 3, "db_ok": true})
json!({"status": "ok", "server_version": env!("CARGO_PKG_VERSION"), "schema_version": 4, "db_ok": true})
);
assert_eq!(
reply.headers["x-kvitt-server-version"],
@@ -124,7 +124,7 @@ async fn health_is_503_degraded_when_the_database_is_gone() {
assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(reply.json["status"], "degraded");
assert_eq!(reply.json["db_ok"], false);
assert_eq!(reply.json["schema_version"], 3);
assert_eq!(reply.json["schema_version"], 4);
}
#[tokio::test]
@@ -45,6 +45,11 @@ impl TestApp {
Self::migrated_to(Some(2)).await
}
/// A database migrated to schema 3 only (before 0004).
pub async fn at_v3() -> Self {
Self::migrated_to(Some(3)).await
}
async fn migrated_to(target: Option<i64>) -> Self {
let dir = TempDir::new();
let config = Config::from_lookup(|k| match k {
@@ -72,6 +72,17 @@ fn check(name: &str, example: &Value) -> bool {
"E-33-settlement-proposal/response.json" => ProposalResponse,
"E-34-analytics-trends/response.json" => TrendsResponse,
"E-35-analytics-forecast/response.json" => ForecastResponse,
"E-36-card-providers/response.json" => CardProviderList,
"E-37-card-auth/request.json" => CreateCardAuthRequest,
"E-37-card-auth/response.json" => CardAttempt,
"E-38-card-attempt/response.json" => CardAttempt,
"E-40-card-sync/response.json" => CardSyncResponse,
"E-41-card-connection-update/request.json" => PatchCardConnectionRequest,
"E-41-card-connection-update/response.json" => CardConnection,
"E-42-card-refresh/response.json" => CardRefreshResponse,
"E-43-card-disconnect/response.json" => CardConnection,
"E-44-card-purchase-update/request.json" => PutCardPurchaseRequest,
"E-44-card-purchase-update/response.json" => CardPurchase,
"sync/pull-empty-page.json" => SyncPullResponse,
"sync/pull-page.json" => SyncPullResponse,
"sync/pull-page-categories-v2.json" => SyncPullResponse,
@@ -133,4 +144,9 @@ fn absent_and_null_are_distinct_where_the_contract_says_so() {
// E-12: target_user_id may be absent.
let invite: CreateInviteRequest = serde_json::from_str(r#"{"kind": "partner"}"#).unwrap();
assert_eq!(invite.target_user_id, None);
// E-44: both keys required, expense_id nullable.
assert!(serde_json::from_str::<PutCardPurchaseRequest>(r#"{"ignored": true}"#).is_err());
let unlink: PutCardPurchaseRequest =
serde_json::from_str(r#"{"expense_id": null, "ignored": false}"#).unwrap();
assert_eq!(unlink.expense_id, None);
}