diff --git a/crates/service/src/actors/managed/mod.rs b/crates/service/src/actors/managed/mod.rs index 8710d40..9c1795e 100644 --- a/crates/service/src/actors/managed/mod.rs +++ b/crates/service/src/actors/managed/mod.rs @@ -1,9 +1,26 @@ use anyhow::Result; -use shared::{config::ActorOsAction, log, ws::server}; +use shared::{broker::api::types::LogLevel, config::ActorOsAction, log, ws::server}; use crate::{common, platform, workers}; +/// Report a fatal OS-config error to both the local log and the broker. +/// +/// During the OS-config phase (rename/join domain) the actor has no local +/// websocket client yet, so failures never reach the admin "Registros" panel +/// and the service just keeps restarting. The broker token/secret are already +/// set at this point (initialize() has run), so we can POST /log here. +/// Best-effort: if the broker call fails, we keep the original error anyway. +async fn report_fatal(platform: &platform::Platform, message: &str) { + log::error!("{}", message); + let _ = platform + .broker_api() + .write() + .await + .log(LogLevel::Error, message) + .await; +} + pub async fn run(platform: platform::Platform) -> Result<()> { log::info!("Managed service starting"); @@ -130,32 +147,51 @@ pub async fn run(platform: platform::Platform) -> Result<()> { } } - if crate::computer::rename_computer(&platform, os_data.name.as_str()).await? { - // Reboot to apply changes - log::info!("Rebooting system to apply rename"); - platform.system().reboot(None)?; - return Ok(()); // We can exit here, system is rebooting + match crate::computer::rename_computer(&platform, os_data.name.as_str()).await { + Ok(true) => { + // Reboot to apply changes + log::info!("Rebooting system to apply rename"); + platform.system().reboot(None)?; + return Ok(()); // We can exit here, system is rebooting + } + Ok(false) => {} // Already has the correct name, skips reboot + Err(e) => { + // Surface the failure on the admin panel before returning, otherwise + // the service just restarts with an empty "Registros" panel. + let msg = format!("Rename to '{}' failed: {}", os_data.name, e); + report_fatal(&platform, &msg).await; + return Err(anyhow::anyhow!(msg)); + } } - // Already has the correct name, skips reboot } ActorOsAction::JoinDomain => { log::info!( "OS action requested: Join domain with name '{}'", os_data.name ); - if crate::computer::join_domain( + match crate::computer::join_domain( &platform, os_data.name.as_str(), os_data.custom.clone(), ) - .await? + .await { - // Reboot to apply changes - log::info!("Rebooting system to apply domain join"); - platform.system().reboot(None)?; - return Ok(()); // We can exit here, system is rebooting + Ok(true) => { + // Reboot to apply changes + log::info!("Rebooting system to apply domain join"); + platform.system().reboot(None)?; + return Ok(()); // We can exit here, system is rebooting + } + Ok(false) => {} // Already has the correct name and domain, skips reboot + Err(e) => { + // Same reasoning as rename: a failed NetJoinDomain (e.g. Win32 error 2, + // ERROR_FILE_NOT_FOUND -> DC/OU not found) should reach the admin panel + // instead of a silent restart. + let msg = format!("Domain join for '{}' failed: {}", os_data.name, e); + report_fatal(&platform, &msg).await; + return Err(anyhow::anyhow!(msg)); + } } - // Already has the correct name and domain, skips reboot } } } else { diff --git a/crates/service/src/actors/managed/tests.rs b/crates/service/src/actors/managed/tests.rs index 2c28b5d..ac07588 100644 --- a/crates/service/src/actors/managed/tests.rs +++ b/crates/service/src/actors/managed/tests.rs @@ -195,6 +195,80 @@ async fn test_managed_join_domain_should_join() -> Result<()> { Ok(()) } +#[tokio::test] +#[serial_test::serial(server)] +async fn test_managed_join_domain_failure_reports_to_broker() -> Result<()> { + use std::sync::atomic::Ordering; + + let mut test_setup = TestSetup::new(run).await; + // Force the OS-level join to fail (mimics NetJoinDomain Win32 error 2). + test_setup + .operations + .fail_join_domain + .store(true, Ordering::SeqCst); + test_setup.broker_api.write().await.init_response = + shared::broker::api::types::InitializationResponse { + master_token: Some("mastertoken".into()), + token: Some("owntoken".into()), + unique_id: Some("uniqueid".into()), + os: Some(shared::config::ActorOsConfiguration { + action: shared::config::ActorOsAction::JoinDomain, + name: "new_actor_name".into(), + custom: Some(json!({ + "domain": "domain.local", + "ou": "OU=Computers,DC=domain,DC=local", + "account": "admin", + "password": "password" + })), + }), + }; + // Signal the run function to start + test_setup.notify.notify_one(); + test_setup.stop_and_wait_task(1).await?; + + log::info!("Calls: {:?}", test_setup.calls.dump()); + // Note: a failed OS action should hit broker /log and abort before reboot + // or ready(), otherwise it just restarts with an empty "Registros" panel. + assert!(test_setup.calls.count_calls("operations::ensure_domain_membership") == 1); + assert!(test_setup.calls.count_calls("broker_api::log") == 1); + test_setup.calls.assert_not_called("operations::reboot"); + test_setup.calls.assert_not_called("broker_api::ready"); + Ok(()) +} + +#[tokio::test] +#[serial_test::serial(server)] +async fn test_managed_rename_failure_reports_to_broker() -> Result<()> { + use std::sync::atomic::Ordering; + + let mut test_setup = TestSetup::new(run).await; + test_setup + .operations + .fail_rename + .store(true, Ordering::SeqCst); + test_setup.broker_api.write().await.init_response = + shared::broker::api::types::InitializationResponse { + master_token: Some("mastertoken".into()), + token: Some("owntoken".into()), + unique_id: Some("uniqueid".into()), + os: Some(shared::config::ActorOsConfiguration { + action: shared::config::ActorOsAction::Rename, + name: "new_actor_name".into(), + custom: None, + }), + }; + // Signal the run function to start + test_setup.notify.notify_one(); + test_setup.stop_and_wait_task(1).await?; + + log::info!("Calls: {:?}", test_setup.calls.dump()); + assert!(test_setup.calls.count_calls("operations::rename_computer") == 1); + test_setup.calls.assert_not_called("operations::reboot"); + assert!(test_setup.calls.count_calls("broker_api::log") == 1); + test_setup.calls.assert_not_called("broker_api::ready"); + Ok(()) +} + #[tokio::test] #[serial_test::serial(server)] async fn test_managed_join_domain_should_not_join() -> Result<()> { diff --git a/crates/service/src/actors/testing.rs b/crates/service/src/actors/testing.rs index b279601..4edb05b 100644 --- a/crates/service/src/actors/testing.rs +++ b/crates/service/src/actors/testing.rs @@ -11,6 +11,7 @@ pub struct TestSetup { pub platform: platform::Platform, pub calls: shared::testing::mock::Calls, pub broker_api: Arc>, + pub operations: Arc, pub handle: Option>, pub notify: Arc, } @@ -30,6 +31,7 @@ impl TestSetup { let platform = mocked_platform.platform.clone(); let calls = mocked_platform.calls.clone(); let broker_api = mocked_platform.broker_api.clone(); + let operations = mocked_platform.operations.clone(); let notify = Arc::new(Notify::new()); // Run the managed run function in a separate task @@ -51,6 +53,7 @@ impl TestSetup { platform, calls, broker_api, + operations, handle: Some(handle), notify, } diff --git a/crates/service/src/computer.rs b/crates/service/src/computer.rs index b311028..cf742f1 100644 --- a/crates/service/src/computer.rs +++ b/crates/service/src/computer.rs @@ -91,6 +91,7 @@ pub async fn join_domain( ou: custom .get("ou") .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) .map(|s| s.to_string()), client_software: custom .get("client_software") diff --git a/crates/service/src/testing/mock.rs b/crates/service/src/testing/mock.rs index 698dc2c..489f53e 100644 --- a/crates/service/src/testing/mock.rs +++ b/crates/service/src/testing/mock.rs @@ -17,6 +17,8 @@ pub struct MockedPlatform { pub platform: Platform, pub calls: Calls, pub broker_api: Arc>, + // Concrete mock kept so tests can flip its error-injection flags. + pub operations: Arc, } pub async fn mock_platform() -> MockedPlatform { @@ -40,13 +42,14 @@ pub async fn mock_platform() -> MockedPlatform { let platform = crate::platform::Platform::new_with_params( Some(config), - Some(operations), + Some(operations.clone()), Some(broker_api.clone()), ); MockedPlatform { platform, calls, broker_api, + operations, } } diff --git a/crates/shared/src/testing/mock.rs b/crates/shared/src/testing/mock.rs index 2b5b411..f133ad3 100644 --- a/crates/shared/src/testing/mock.rs +++ b/crates/shared/src/testing/mock.rs @@ -5,6 +5,7 @@ use crate::{ system::{NetworkInterface, System}, tls::CertificateInfo, }; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use super::test_certs; @@ -69,19 +70,26 @@ impl Calls { pub struct OperationsMock { pub calls: Calls, + // Error-injection flags. Shared (Arc) so a test can flip them AFTER the mock + // is already wrapped in the platform's `Arc`. Default off, so + // existing happy-path tests are unaffected. + pub fail_rename: Arc, + pub fail_join_domain: Arc, } impl OperationsMock { pub fn new(calls: Calls) -> Self { - Self { calls } + Self { + calls, + fail_rename: Arc::new(AtomicBool::new(false)), + fail_join_domain: Arc::new(AtomicBool::new(false)), + } } } impl Default for OperationsMock { fn default() -> Self { - Self { - calls: Calls::new(), - } + Self::new(Calls::new()) } } @@ -105,6 +113,9 @@ impl System for OperationsMock { self.calls .push(format!("operations::rename_computer({})", new_name)); crate::log::info!("Renaming computer to {}", new_name); + if self.fail_rename.load(Ordering::SeqCst) { + return Err(anyhow::anyhow!("Injected rename_computer failure")); + } Ok(()) } @@ -112,6 +123,9 @@ impl System for OperationsMock { self.calls .push(format!("operations::join_domain({:?})", options)); crate::log::info!("Joining domain: {:?}", options); + if self.fail_join_domain.load(Ordering::SeqCst) { + return Err(anyhow::anyhow!("Injected join_domain failure")); + } Ok(()) } @@ -124,6 +138,11 @@ impl System for OperationsMock { options )); crate::log::info!("Ensuring domain membership: {:?}", options); + if self.fail_join_domain.load(Ordering::SeqCst) { + return Err(anyhow::anyhow!( + "Injected ensure_domain_membership failure" + )); + } Ok(false) } diff --git a/crates/shared/src/windows/system/mod.rs b/crates/shared/src/windows/system/mod.rs index 5b22742..44b5555 100644 --- a/crates/shared/src/windows/system/mod.rs +++ b/crates/shared/src/windows/system/mod.rs @@ -360,16 +360,19 @@ impl System for WindowsOperations { flags, ); - // If the error is "already joined", try again with less flags (no create account, no - // new name flag) AND drop the OU. The v4.0 python actor does exactly this because - // error 2224 typically means the machine account already exists in another OU of - // the same domain, so re-issuing NetJoinDomain with a non-null OU keeps failing. + // 2224 (NERR_UserExists) means the machine account already exists in the domain, + // so retry reusing it: drop NETSETUP_ACCT_CREATE (stop trying to create it) and + // drop the OU. Keep NETSETUP_JOIN_WITH_NEW_NAME: the machine has been renamed but + // not yet rebooted, so the active name is still the old one; without this flag the + // join looks up an account for the OLD name and fails with 1332 (ERROR_NONE_MAPPED). if res == 2224 { log::warn!( - "NetJoinDomain returned 2224 (ERROR_JOINED_TO_OU), retrying without OU \ - and without NETSETUP_ACCT_CREATE / NETSETUP_JOIN_WITH_NEW_NAME" + "NetJoinDomain returned 2224 (NERR_UserExists), retrying without OU \ + and without NETSETUP_ACCT_CREATE (reusing existing account)" ); - let flags = NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN; + let flags = NETSETUP_DOMAIN_JOIN_IF_JOINED + | NETSETUP_JOIN_DOMAIN + | NETSETUP_JOIN_WITH_NEW_NAME; res = NetJoinDomain( PCWSTR::null(), PCWSTR(lp_domain.as_ptr()),