Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 50 additions & 14 deletions crates/service/src/actors/managed/mod.rs
Original file line number Diff line number Diff line change
@@ -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");

Expand Down Expand Up @@ -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 {
Expand Down
74 changes: 74 additions & 0 deletions crates/service/src/actors/managed/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand Down
3 changes: 3 additions & 0 deletions crates/service/src/actors/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct TestSetup {
pub platform: platform::Platform,
pub calls: shared::testing::mock::Calls,
pub broker_api: Arc<tokio::sync::RwLock<shared::testing::mock::BrokerApiMock>>,
pub operations: Arc<shared::testing::mock::OperationsMock>,
pub handle: Option<tokio::task::JoinHandle<()>>,
pub notify: Arc<Notify>,
}
Expand All @@ -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
Expand All @@ -51,6 +53,7 @@ impl TestSetup {
platform,
calls,
broker_api,
operations,
handle: Some(handle),
notify,
}
Expand Down
1 change: 1 addition & 0 deletions crates/service/src/computer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
5 changes: 4 additions & 1 deletion crates/service/src/testing/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub struct MockedPlatform {
pub platform: Platform,
pub calls: Calls,
pub broker_api: Arc<tokio::sync::RwLock<BrokerApiMock>>,
// Concrete mock kept so tests can flip its error-injection flags.
pub operations: Arc<OperationsMock>,
}

pub async fn mock_platform() -> MockedPlatform {
Expand All @@ -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,
}
}

Expand Down
27 changes: 23 additions & 4 deletions crates/shared/src/testing/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<dyn System>`. Default off, so
// existing happy-path tests are unaffected.
pub fail_rename: Arc<AtomicBool>,
pub fail_join_domain: Arc<AtomicBool>,
}

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())
}
}

Expand All @@ -105,13 +113,19 @@ 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(())
}

fn join_domain(&self, options: &crate::system::JoinDomainOptions) -> anyhow::Result<()> {
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(())
}

Expand All @@ -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)
}

Expand Down
17 changes: 10 additions & 7 deletions crates/shared/src/windows/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
Loading