From aabaa3a0d4dba0c21c3e837afda8a27582b25a62 Mon Sep 17 00:00:00 2001 From: Echo Date: Mon, 18 May 2026 13:18:44 +0000 Subject: [PATCH] fix: reorder host insert before cert issuance, add migration for missing columns --- crates/pm-web/src/routes/enrollment.rs | 55 +++++++++++----------- migrations/017_enrollment_host_columns.sql | 5 ++ 2 files changed, 32 insertions(+), 28 deletions(-) create mode 100644 migrations/017_enrollment_host_columns.sql diff --git a/crates/pm-web/src/routes/enrollment.rs b/crates/pm-web/src/routes/enrollment.rs index 4ab816e..c223f7a 100644 --- a/crates/pm-web/src/routes/enrollment.rs +++ b/crates/pm-web/src/routes/enrollment.rs @@ -225,7 +225,33 @@ async fn approve_enrollment( )); } - // Generate PKI bundle using CA + // Move to hosts table FIRST (certificates table has FK reference to hosts) + let os_name = enrollment_request + .os_details + .get("name") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()); + sqlx::query( + r#" + INSERT INTO hosts (id, fqdn, ip_address, os_name, registered_at, updated_at) + VALUES ($1, $2, $3::inet, $4, NOW(), NOW()) + "#, + ) + .bind(enrollment_request.id) + .bind(&enrollment_request.fqdn) + .bind(&enrollment_request.ip_address.to_string()) + .bind(os_name) + .execute(&state.db) + .await + .map_err(|e| { + tracing::error!(error = %e, "Failed to insert host after approval"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Database error" })), + ) + })?; + + // Generate PKI bundle using CA (after host row exists) let issued = state .ca .issue_client_cert( @@ -243,33 +269,6 @@ async fn approve_enrollment( ) })?; - // Move to hosts table - let os_name = enrollment_request - .os_details - .get("name") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - sqlx::query( - r#" - INSERT INTO hosts (id, fqdn, ip_address, os_name, registered_at, updated_at, machine_id) - VALUES ($1, $2, $3::inet, $4, NOW(), NOW(), $5) - "#, - ) - .bind(enrollment_request.id) - .bind(&enrollment_request.fqdn) - .bind(&enrollment_request.ip_address.to_string()) - .bind(os_name) - .bind(enrollment_request.machine_id) - .execute(&state.db) - .await - .map_err(|e| { - tracing::error!(error = %e, "Failed to insert host after approval"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Database error" })), - ) - })?; - // Delete from enrollment_requests table db::delete_enrollment_request(&state.db, id) .await diff --git a/migrations/017_enrollment_host_columns.sql b/migrations/017_enrollment_host_columns.sql new file mode 100644 index 0000000..e33775d --- /dev/null +++ b/migrations/017_enrollment_host_columns.sql @@ -0,0 +1,5 @@ +-- Migration: 017_enrollment_host_columns +-- Add missing columns for enrollment support +ALTER TABLE hosts ADD COLUMN IF NOT EXISTS machine_id TEXT; +ALTER TABLE certificates ADD COLUMN IF NOT EXISTS ip_address INET; +ALTER TABLE certificates ADD COLUMN IF NOT EXISTS key_pem TEXT;