From 060e7a03bb2d63ed4000839ba576ee0a17f77d68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janier=20Rodr=C3=ADguez?= Date: Wed, 8 Jul 2026 14:25:34 +0200 Subject: [PATCH 1/3] fix(managed): report OS-config failures to broker instead of dying silently During the OS-config phase (rename / join domain) the managed actor had no local websocket client yet, so a failed rename or NetJoinDomain was swallowed by `?` and the service just restart-looped with an empty "Registros" panel and nothing in the local logs. Add `report_fatal` to forward these failures to BOTH the local log and the broker /log endpoint (token/secret are already set after initialize()), and turn the rename / join-domain branches into explicit matches that abort with an error instead of rebooting on failure. Tests: inject rename/join failures via OperationsMock error flags and assert the failure reaches broker::log and that reboot()/ready() are NOT called. --- crates/service/src/actors/managed/mod.rs | 64 +++++++++++++++---- crates/service/src/actors/managed/tests.rs | 74 ++++++++++++++++++++++ crates/service/src/actors/testing.rs | 3 + crates/service/src/testing/mock.rs | 5 +- crates/shared/src/testing/mock.rs | 22 +++++-- 5 files changed, 149 insertions(+), 19 deletions(-) diff --git a/crates/service/src/actors/managed/mod.rs b/crates/service/src/actors/managed/mod.rs index 1ece4d8..481921f 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 restart-loops silently. 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"); @@ -41,32 +58,51 @@ pub async fn run(platform: platform::Platform) -> Result<()> { } ActorOsAction::Rename => { log::info!("OS action requested: Rename to '{}'", os_data.name); - 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 dying, otherwise + // the service just restart-loops 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) MUST reach the admin panel + // instead of vanishing into a silent restart loop. + 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 04372cd..af09d06 100644 --- a/crates/service/src/actors/managed/tests.rs +++ b/crates/service/src/actors/managed/tests.rs @@ -131,6 +131,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()); + // Invariant: a failed OS action MUST hit broker /log and abort BEFORE reboot + // or ready() — otherwise it restart-loops with an empty "Registros" panel. + assert!(test_setup.calls.count_calls("operations::join_domain") == 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/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 961f43b..31c2bff 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(()) } From e88c34eb5fa8e617cb62ab8f9b5a416426fd47c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janier=20Rodr=C3=ADguez?= Date: Thu, 9 Jul 2026 15:55:54 +0200 Subject: [PATCH 2/3] style(managed): align comment register with codebase idiom Plain declaratives instead of caps-for-emphasis and dramatic phrasing; Invariant: -> Note: on the join-domain failure test. No behavior change. --- crates/service/src/actors/managed/mod.rs | 18 +++++++++--------- crates/service/src/actors/managed/tests.rs | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/service/src/actors/managed/mod.rs b/crates/service/src/actors/managed/mod.rs index a8c26f3..bd3aa75 100644 --- a/crates/service/src/actors/managed/mod.rs +++ b/crates/service/src/actors/managed/mod.rs @@ -4,13 +4,13 @@ use shared::{broker::api::types::LogLevel, config::ActorOsAction, log, ws::serve use crate::{common, platform, workers}; -/// Report a fatal OS-config error to BOTH the local log and the broker. +/// 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 +/// 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 restart-loops silently. 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. +/// 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 @@ -71,8 +71,8 @@ pub async fn run(platform: platform::Platform) -> Result<()> { } Ok(false) => {} // Already has the correct name, skips reboot Err(e) => { - // Surface the failure on the admin panel before dying, otherwise - // the service just restart-loops with an empty "Registros" panel. + // 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)); @@ -100,8 +100,8 @@ pub async fn run(platform: platform::Platform) -> Result<()> { 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) MUST reach the admin panel - // instead of vanishing into a silent restart loop. + // 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)); diff --git a/crates/service/src/actors/managed/tests.rs b/crates/service/src/actors/managed/tests.rs index 31c11fd..85b0df5 100644 --- a/crates/service/src/actors/managed/tests.rs +++ b/crates/service/src/actors/managed/tests.rs @@ -188,8 +188,8 @@ async fn test_managed_join_domain_failure_reports_to_broker() -> Result<()> { test_setup.stop_and_wait_task(1).await?; log::info!("Calls: {:?}", test_setup.calls.dump()); - // Invariant: a failed OS action MUST hit broker /log and abort BEFORE reboot - // or ready() — otherwise it restart-loops with an empty "Registros" panel. + // 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"); From d65f2258bc23eaec480e23e9ac81624fa0886296 Mon Sep 17 00:00:00 2001 From: aschumann-virtualcable Date: Wed, 15 Jul 2026 12:38:26 +0200 Subject: [PATCH 3/3] fix(windows): retry domain join with new name when account already exists A managed actor renames the machine and then joins the domain in the same run, before the rename reboot. When the machine account already exists in AD, NetJoinDomain returns 2224 (NERR_UserExists) and the retry dropped NETSETUP_JOIN_WITH_NEW_NAME, so the join looked up an account for the still-active OLD name and failed with 1332 (ERROR_NONE_MAPPED). Keep JOIN_WITH_NEW_NAME on the retry so it reuses the existing account under the new name; only drop ACCT_CREATE and the OU. Fix the stale comment/log: 2224 is NERR_UserExists, not ERROR_JOINED_TO_OU. Also normalize an empty "ou" from the broker to None so we pass a NULL OU pointer instead of an empty-string LDAP path to NetJoinDomain. --- crates/service/src/computer.rs | 1 + crates/shared/src/windows/system/mod.rs | 17 ++++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/service/src/computer.rs b/crates/service/src/computer.rs index cf32e74..fa911f7 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/shared/src/windows/system/mod.rs b/crates/shared/src/windows/system/mod.rs index 7c76bf9..71d8b57 100644 --- a/crates/shared/src/windows/system/mod.rs +++ b/crates/shared/src/windows/system/mod.rs @@ -352,16 +352,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()),