File: agent_process_broker_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (398 lines) | stat: -rw-r--r-- 15,038 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/mac/agent_process_broker.h"

#include <inttypes.h>

#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/memory/ptr_util.h"
#include "base/process/process.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/test/multiprocess_test.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/named_mojo_ipc_server/connection_info.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/platform/named_platform_channel.h"
#include "remoting/host/chromoting_host_services_client.h"
#include "remoting/host/mac/agent_process_broker_client.h"
#include "remoting/host/mojom/agent_process_broker.mojom.h"
#include "remoting/host/mojom/remoting_host.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

namespace remoting {

namespace {

using testing::_;
using testing::Return;

static constexpr char kRemotingTestAgentProcessName[] =
    "RemotingTestAgentProcess";
static constexpr char kRemotingTestChromotingHostServicesClientProcessName[] =
    "RemotingTestChromotingHostServicesClientProcess";

static constexpr char kServerNameSwitch[] = "server-name";
static constexpr char kAgentStateFilePathSwitch[] = "state-file";

static constexpr char kAgentStateAwaiting[] = "awaiting";
static constexpr char kAgentStateResumed[] = "resumed";
static constexpr char kAgentStateSuspended[] = "suspended";
static constexpr char kAgentStateChromotingHostServicesBound[] =
    "chromotingHostServicesBound";

static constexpr int kAgentExitCodeTerminatedByBroker = 1;
static constexpr int kAgentExitCodeBrokerDisconnected = 2;

// A struct that holds both the real process object and the path of the agent
// state file.
struct Process {
  base::Process process;
  base::FilePath agent_state_file_path;
};

// A test AgentProcess implementation that simply writes state changes to
// `agent_state_file_path`. It will immediately write `kAgentStateAwaiting`
// when the object is constructed.
class TestAgentProcess : public mojom::AgentProcess,
                         public mojom::RemotingHostControl {
 public:
  explicit TestAgentProcess(const base::FilePath& agent_state_file_path);
  ~TestAgentProcess() override;

  void ResumeProcess() override;
  void SuspendProcess() override;
  void BindRemotingHostControl(
      mojo::PendingReceiver<mojom::RemotingHostControl> receiver) override;
  void BindChromotingHostServices(
      mojo::PendingReceiver<mojom::ChromotingHostServices> receiver,
      int32_t peer_pid) override;

 private:
  void WriteAgentState(std::string_view state);

  base::File agent_state_file_;
  mojo::Receiver<mojom::RemotingHostControl> remoting_host_control_{this};
};

TestAgentProcess::TestAgentProcess(
    const base::FilePath& agent_state_file_path) {
  agent_state_file_ = base::File(
      agent_state_file_path, base::File::FLAG_OPEN | base::File::FLAG_WRITE);
  EXPECT_TRUE(agent_state_file_.IsValid());
  WriteAgentState(kAgentStateAwaiting);
}

TestAgentProcess::~TestAgentProcess() = default;

void TestAgentProcess::ResumeProcess() {
  WriteAgentState(kAgentStateResumed);
}

void TestAgentProcess::SuspendProcess() {
  WriteAgentState(kAgentStateSuspended);
}

void TestAgentProcess::BindRemotingHostControl(
    mojo::PendingReceiver<mojom::RemotingHostControl> receiver) {
  remoting_host_control_.Bind(std::move(receiver));
}

void TestAgentProcess::BindChromotingHostServices(
    mojo::PendingReceiver<mojom::ChromotingHostServices> receiver,
    int32_t peer_pid) {
  WriteAgentState(kAgentStateChromotingHostServicesBound);
}

void TestAgentProcess::WriteAgentState(std::string_view state) {
  agent_state_file_.SetLength(state.size());
  agent_state_file_.Write(0, base::as_byte_span(state));
  agent_state_file_.Flush();
}

}  // namespace

class AgentProcessBrokerTest : public testing::Test {
 public:
  AgentProcessBrokerTest();
  ~AgentProcessBrokerTest() override;

 protected:
  Process LaunchTestAgentProcess(bool is_root);
  // Returns nullopt if the process has exited.
  std::optional<std::string> GetTestAgentState(const Process& process);
  // Returns false if the process has exited.
  bool WaitForTestAgentState(const Process& process, std::string_view state);

  base::MockCallback<AgentProcessBroker::IsRootProcessGetter>
      is_root_process_getter_;
  std::unique_ptr<AgentProcessBroker> agent_process_broker_;
  mojo::NamedPlatformChannel::ServerName chromoting_host_services_server_name_;

 private:
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::MainThreadType::IO};
  mojo::NamedPlatformChannel::ServerName server_name_;
  base::ScopedTempDir temp_dir_;
};

AgentProcessBrokerTest::AgentProcessBrokerTest() {
  EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
  server_name_ = mojo::NamedPlatformChannel::ServerNameFromUTF8(
      base::StringPrintf("remoting_agent_process_broker_test_server.%" PRIu64,
                         base::RandUint64()));
  chromoting_host_services_server_name_ =
      mojo::NamedPlatformChannel::ServerNameFromUTF8(base::StringPrintf(
          "chromoting_host_services_test_server.%" PRIu64, base::RandUint64()));
  agent_process_broker_ = base::WrapUnique(new AgentProcessBroker(
      server_name_,
      base::BindRepeating(
          [](const named_mojo_ipc_server::ConnectionInfo&) { return true; }),
      is_root_process_getter_.Get()));
  agent_process_broker_->chromoting_host_services_server_ =
      std::make_unique<ChromotingHostServicesServer>(
          chromoting_host_services_server_name_,
          /* validator= */
          base::BindRepeating([](const named_mojo_ipc_server::ConnectionInfo&) {
            return true;
          }),
          base::BindRepeating(&AgentProcessBroker::BindChromotingHostServices,
                              base::Unretained(agent_process_broker_.get())));
  agent_process_broker_->Start();
}

AgentProcessBrokerTest::~AgentProcessBrokerTest() = default;

Process AgentProcessBrokerTest::LaunchTestAgentProcess(bool is_root) {
  base::FilePath agent_state_file_path;
  EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(),
                                             &agent_state_file_path));
  EXPECT_CALL(is_root_process_getter_, Run(_)).WillOnce(Return(is_root));
  base::CommandLine cmd_line = base::GetMultiProcessTestChildBaseCommandLine();
  cmd_line.AppendSwitchNative(kServerNameSwitch, server_name_);
  cmd_line.AppendSwitchPath(kAgentStateFilePathSwitch, agent_state_file_path);
  base::RunLoop run_loop;
  agent_process_broker_->set_on_agent_process_launched_for_testing(
      run_loop.QuitClosure());
  base::Process process = base::SpawnMultiProcessTestChild(
      kRemotingTestAgentProcessName, cmd_line, /* options= */ {});
  run_loop.Run();
  return {
      .process = std::move(process),
      .agent_state_file_path = agent_state_file_path,
  };
}

std::optional<std::string> AgentProcessBrokerTest::GetTestAgentState(
    const Process& process) {
  if (process.process.WaitForExitWithTimeout(base::TimeDelta(), nullptr)) {
    // Process has exited.
    return std::nullopt;
  }
  base::File file(process.agent_state_file_path,
                  base::File::FLAG_OPEN | base::File::FLAG_READ);
  std::vector<char> buffer(
      std::max({sizeof(kAgentStateAwaiting), sizeof(kAgentStateResumed),
                sizeof(kAgentStateSuspended),
                sizeof(kAgentStateChromotingHostServicesBound)}));
  std::optional<size_t> num_bytes_read =
      file.Read(0, base::as_writable_byte_span(buffer));
  if (!num_bytes_read.has_value()) {
    return std::nullopt;
  }
  return std::string(buffer.data(), *num_bytes_read);
}

bool AgentProcessBrokerTest::WaitForTestAgentState(const Process& process,
                                                   std::string_view state) {
  base::RunLoop run_loop;
  bool result;
  base::RepeatingClosure quit_loop_on_state = base::BindLambdaForTesting([&]() {
    std::optional<std::string> agent_state = GetTestAgentState(process);
    if (!agent_state.has_value() || *agent_state == state) {
      result = agent_state.has_value();
      run_loop.Quit();
      return;
    }
    base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE, quit_loop_on_state, base::Milliseconds(10));
  });
  quit_loop_on_state.Run();
  run_loop.Run();
  return result;
}

TEST_F(AgentProcessBrokerTest, UserAgentProcessOnly_ResumedImmediately) {
  auto process = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(process, kAgentStateResumed));
}

TEST_F(AgentProcessBrokerTest, RootAgentProcessOnly_ResumedImmediately) {
  auto process = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(process, kAgentStateResumed));
}

TEST_F(AgentProcessBrokerTest,
       UserAgentProcessCloseAndRelaunch_ResumedImmediately) {
  auto p1 = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(p1, kAgentStateResumed));
  ASSERT_TRUE(p1.process.Terminate(0, true));

  auto p2 = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(p2, kAgentStateResumed));
}

TEST_F(AgentProcessBrokerTest,
       RootAgentProcessCloseAndRelaunch_ResumedImmediately) {
  auto p1 = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(p1, kAgentStateResumed));
  ASSERT_TRUE(p1.process.Terminate(0, true));

  auto p2 = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(p2, kAgentStateResumed));
}

TEST_F(
    AgentProcessBrokerTest,
    UserAgentProcessAfterUserAgentProcess_SecondProcessTerminatedImmediately) {
  auto p1 = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(p1, kAgentStateResumed));

  auto p2 = LaunchTestAgentProcess(/* is_root= */ false);
  int exit_code;
  ASSERT_TRUE(p2.process.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, kAgentExitCodeTerminatedByBroker);
}

TEST_F(
    AgentProcessBrokerTest,
    RootAgentProcessAfterRootAgentProcess_SecondProcessTerminatedImmediately) {
  auto p1 = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(p1, kAgentStateResumed));

  auto p2 = LaunchTestAgentProcess(/* is_root= */ true);
  int exit_code;
  ASSERT_TRUE(p2.process.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, kAgentExitCodeTerminatedByBroker);
}

TEST_F(AgentProcessBrokerTest,
       UserAgentProcessAfterRootAgentProcess_RootProcessSuspended) {
  auto root_process = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(root_process, kAgentStateResumed));

  auto user_process = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(user_process, kAgentStateResumed));
  ASSERT_TRUE(WaitForTestAgentState(root_process, kAgentStateSuspended));
}

TEST_F(
    AgentProcessBrokerTest,
    RootAgentProcessAfterUserAgentProcess_RootProcessResumedAfterUserProcessExited) {
  auto user_process = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(user_process, kAgentStateResumed));

  auto root_process = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(root_process, kAgentStateAwaiting));

  user_process.process.Terminate(0, true);
  ASSERT_TRUE(WaitForTestAgentState(root_process, kAgentStateResumed));
}

TEST_F(AgentProcessBrokerTest,
       DestroyServer_ClientProcessesObserveDisconnectEvents) {
  auto user_process = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(user_process, kAgentStateResumed));

  auto root_process = LaunchTestAgentProcess(/* is_root= */ true);
  ASSERT_TRUE(WaitForTestAgentState(root_process, kAgentStateAwaiting));

  agent_process_broker_.reset();

  int exit_code;
  ASSERT_TRUE(user_process.process.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, kAgentExitCodeBrokerDisconnected);
  ASSERT_TRUE(root_process.process.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, kAgentExitCodeBrokerDisconnected);
}

TEST_F(AgentProcessBrokerTest, BindChromotingHostServices) {
  auto user_process = LaunchTestAgentProcess(/* is_root= */ false);
  ASSERT_TRUE(WaitForTestAgentState(user_process, kAgentStateResumed));

  base::CommandLine services_client_cmd_line =
      base::GetMultiProcessTestChildBaseCommandLine();
  services_client_cmd_line.AppendSwitchNative(
      kServerNameSwitch, chromoting_host_services_server_name_);
  base::Process process = base::SpawnMultiProcessTestChild(
      kRemotingTestChromotingHostServicesClientProcessName,
      services_client_cmd_line,
      /* options= */ {});

  ASSERT_TRUE(WaitForTestAgentState(user_process,
                                    kAgentStateChromotingHostServicesBound));
}

MULTIPROCESS_TEST_MAIN(RemotingTestAgentProcess) {
  base::test::TaskEnvironment task_environment{
      base::test::TaskEnvironment::MainThreadType::IO};
  base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
  mojo::NamedPlatformChannel::ServerName server_name =
      cmd_line->GetSwitchValueNative(kServerNameSwitch);
  base::RunLoop run_loop;
  int exit_code;
  AgentProcessBrokerClient broker_client(
      base::BindLambdaForTesting([&]() {
        exit_code = kAgentExitCodeTerminatedByBroker;
        run_loop.Quit();
      }),
      base::BindLambdaForTesting([&]() {
        exit_code = kAgentExitCodeBrokerDisconnected;
        run_loop.Quit();
      }));
  EXPECT_TRUE(broker_client.ConnectToServer(server_name));
  base::FilePath state_file_path =
      cmd_line->GetSwitchValuePath(kAgentStateFilePathSwitch);
  TestAgentProcess test_process(state_file_path);
  broker_client.OnAgentProcessLaunched(&test_process);
  run_loop.Run();
  return exit_code;
}

MULTIPROCESS_TEST_MAIN(RemotingTestChromotingHostServicesClientProcess) {
  base::test::TaskEnvironment task_environment{
      base::test::TaskEnvironment::MainThreadType::IO};
  base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
  mojo::NamedPlatformChannel::ServerName server_name =
      cmd_line->GetSwitchValueNative(kServerNameSwitch);
  ChromotingHostServicesClient::Initialize();
  ChromotingHostServicesClient client{server_name};
  client.GetSessionServices();
  base::RunLoop().Run();
  return 0;
}

}  // namespace remoting