File: it2me_native_messaging_host_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 (834 lines) | stat: -rw-r--r-- 30,780 bytes parent folder | download | duplicates (3)
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "remoting/host/it2me/it2me_native_messaging_host.h"

#include <cstdint>
#include <memory>
#include <string>
#include <utility>

#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/values_test_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/policy/core/common/fake_async_policy_loader.h"
#include "components/policy/policy_constants.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/base/oauth_token_getter.h"
#include "remoting/host/chromeos/chromeos_enterprise_params.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/it2me/it2me_constants.h"
#include "remoting/host/it2me/it2me_helpers.h"
#include "remoting/host/native_messaging/log_message_handler.h"
#include "remoting/host/native_messaging/native_messaging_constants.h"
#include "remoting/host/native_messaging/native_messaging_pipe.h"
#include "remoting/host/native_messaging/pipe_messaging_channel.h"
#include "remoting/host/policy_watcher.h"
#include "remoting/host/setup/test_util.h"
#include "remoting/protocol/errors.h"
#include "remoting/protocol/ice_config.h"
#include "services/network/test/test_shared_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace remoting {

using protocol::ErrorCode;

namespace {

constexpr char kTestAccessCode[] = "888888";
constexpr base::TimeDelta kTestAccessCodeLifetime = base::Seconds(666);
constexpr char kTestClientUsername[] = "some_user@gmail.com";
constexpr char kTestStunServer[] = "test_relay_server.com";
constexpr char kTestSignalingAccessToken[] = "signaling_token";
constexpr char kTestApiAccessToken[] = "api_token";

void VerifyId(const base::Value::Dict& response, int expected_value) {
  std::optional<int> value = response.FindInt(kMessageId);
  ASSERT_TRUE(value);
  EXPECT_EQ(expected_value, *value);
}

void VerifyStringProperty(const base::Value::Dict& response,
                          const std::string& name,
                          const std::string& expected_value) {
  const std::string* value = response.FindString(name);
  ASSERT_TRUE(value);
  EXPECT_EQ(expected_value, *value);
}

// Verity the values of the "type" and "id" properties
void VerifyCommonProperties(const base::Value::Dict& response,
                            const std::string& type,
                            int id) {
  const std::string* string_value = response.FindString(kMessageType);
  ASSERT_TRUE(string_value);
  EXPECT_EQ(type, *string_value);

  std::optional<int> int_value = response.FindInt(kMessageId);
  ASSERT_TRUE(int_value);
  EXPECT_EQ(id, *int_value);
}

base::Value::Dict CreateConnectMessage(int id) {
  base::Value::Dict connect_message;
  connect_message.Set(kMessageId, id);
  connect_message.Set(kMessageType, kConnectMessage);
  connect_message.Set(kUserName, kTestClientUsername);
  connect_message.Set(kSignalingAccessToken, kTestSignalingAccessToken);
  connect_message.Set(kApiAccessToken, kTestApiAccessToken);
  connect_message.Set(
      kIceConfig,
      base::test::ParseJsonDict("{ \"iceServers\": [ { \"urls\": [ \"stun:" +
                                std::string(kTestStunServer) + "\" ] } ] }"));

  return connect_message;
}

base::Value::Dict CreateDisconnectMessage(int id) {
  base::Value::Dict disconnect_message;
  disconnect_message.Set(kMessageId, id);
  disconnect_message.Set(kMessageType, kDisconnectMessage);
  return disconnect_message;
}

std::string GetOAuthAccessToken(OAuthTokenGetter& token_getter) {
  base::RunLoop run_loop;
  std::string access_token;
  token_getter.CallWithToken(base::BindLambdaForTesting(
      [&](OAuthTokenGetter::Status status, const OAuthTokenInfo& token_info) {
        access_token = token_info.access_token();
        run_loop.Quit();
      }));
  run_loop.Run();
  return access_token;
}

}  // namespace

class MockIt2MeHost : public It2MeHost {
 public:
  MockIt2MeHost() = default;

  MockIt2MeHost(const MockIt2MeHost&) = delete;
  MockIt2MeHost& operator=(const MockIt2MeHost&) = delete;

  // It2MeHost overrides
  void Connect(std::unique_ptr<ChromotingHostContext> context,
               base::Value::Dict policies,
               std::unique_ptr<It2MeConfirmationDialogFactory> dialog_factory,
               base::WeakPtr<It2MeHost::Observer> observer,
               CreateDeferredConnectContext create_connection_context,
               const std::string& username,
               const protocol::IceConfig& ice_config) override;
  void Disconnect() override;

  OAuthTokenGetter* signaling_token_getter() {
    return signaling_token_getter_.get();
  }

  OAuthTokenGetter* api_token_getter() { return api_token_getter_.get(); }

 private:
  ~MockIt2MeHost() override = default;

  void CreateConnectionContextOnNetworkThread(
      CreateDeferredConnectContext create_connection_context);

  void RunSetState(It2MeHostState state);

  std::unique_ptr<OAuthTokenGetter> signaling_token_getter_;
  std::unique_ptr<OAuthTokenGetter> api_token_getter_;
};

void MockIt2MeHost::Connect(
    std::unique_ptr<ChromotingHostContext> context,
    base::Value::Dict policies,
    std::unique_ptr<It2MeConfirmationDialogFactory> dialog_factory,
    base::WeakPtr<It2MeHost::Observer> observer,
    CreateDeferredConnectContext create_connection_context,
    const std::string& username,
    const protocol::IceConfig& ice_config) {
  DCHECK(context->ui_task_runner()->BelongsToCurrentThread());

  // Verify that parameters are passed correctly.
  EXPECT_EQ(username, kTestClientUsername);
  EXPECT_EQ(ice_config.stun_servers[0].hostname(), kTestStunServer);

  host_context_ = std::move(context);
  observer_ = std::move(observer);
  local_session_policies_provider_ =
      std::make_unique<LocalSessionPoliciesProvider>();

  host_context()->network_task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&MockIt2MeHost::CreateConnectionContextOnNetworkThread,
                     this, std::move(create_connection_context)));

  OnPolicyUpdate(std::move(policies));

  RunSetState(It2MeHostState::kStarting);
  RunSetState(It2MeHostState::kRequestedAccessCode);

  host_context()->ui_task_runner()->PostTask(
      FROM_HERE,
      base::BindOnce(&It2MeHost::Observer::OnStoreAccessCode, observer_,
                     kTestAccessCode, kTestAccessCodeLifetime));

  RunSetState(It2MeHostState::kReceivedAccessCode);
  RunSetState(It2MeHostState::kConnecting);

  host_context()->ui_task_runner()->PostTask(
      FROM_HERE, base::BindOnce(&It2MeHost::Observer::OnClientAuthenticated,
                                observer_, kTestClientUsername));

  RunSetState(It2MeHostState::kConnected);
}

void MockIt2MeHost::Disconnect() {
  if (!host_context()->network_task_runner()->BelongsToCurrentThread()) {
    DCHECK(host_context()->ui_task_runner()->BelongsToCurrentThread());
    host_context()->network_task_runner()->PostTask(
        FROM_HERE, base::BindOnce(&MockIt2MeHost::Disconnect, this));
    return;
  }

  register_request_.reset();
  signal_strategy_.reset();
  session_policies_finalized_ = false;
  last_reported_nat_traversal_enabled_.reset();
  last_reported_relay_connections_allowed_.reset();

  RunSetState(It2MeHostState::kDisconnected);
}

void MockIt2MeHost::CreateConnectionContextOnNetworkThread(
    CreateDeferredConnectContext create_connection_context) {
  DCHECK(host_context()->network_task_runner()->BelongsToCurrentThread());
  auto context = std::move(create_connection_context).Run(host_context());
  register_request_ = std::move(context->register_request);
  signal_strategy_ = std::move(context->signal_strategy);
  signaling_token_getter_ = std::move(context->signaling_token_getter);
  api_token_getter_ = std::move(context->api_token_getter);
}

void MockIt2MeHost::RunSetState(It2MeHostState state) {
  if (!host_context()->network_task_runner()->BelongsToCurrentThread()) {
    host_context()->network_task_runner()->PostTask(
        FROM_HERE, base::BindOnce(&It2MeHost::SetStateForTesting, this, state,
                                  ErrorCode::OK));
  } else {
    SetStateForTesting(state, ErrorCode::OK);
  }
}

class MockIt2MeHostFactory : public It2MeHostFactory {
 public:
  MockIt2MeHostFactory() : host(new MockIt2MeHost()) {}

  MockIt2MeHostFactory(const MockIt2MeHostFactory&) = delete;
  MockIt2MeHostFactory& operator=(const MockIt2MeHostFactory&) = delete;

  ~MockIt2MeHostFactory() override = default;

  scoped_refptr<It2MeHost> CreateIt2MeHost() override { return host; }

  scoped_refptr<MockIt2MeHost> host;
};

class It2MeNativeMessagingHostTest : public testing::Test {
 public:
  It2MeNativeMessagingHostTest() = default;

  It2MeNativeMessagingHostTest(const It2MeNativeMessagingHostTest&) = delete;
  It2MeNativeMessagingHostTest& operator=(const It2MeNativeMessagingHostTest&) =
      delete;

  ~It2MeNativeMessagingHostTest() override = default;

  void SetUp() override;
  void TearDown() override;

 protected:
  void SetPolicies(base::Value::Dict dict);
  std::optional<base::Value::Dict> ReadMessageFromOutputPipe();
  void WriteMessageToInputPipe(const base::Value::Dict& message);

  void VerifyHelloResponse(int request_id);
  void VerifyErrorResponse();
  void VerifyConnectResponses(int request_id);
  void VerifyDisconnectResponses(int request_id);
  void VerifyPolicyErrorResponse();

  // The Host process should shut down when it receives a malformed request.
  // This is tested by sending a known-good request, followed by |message|,
  // followed by the known-good request again. The response file should only
  // contain a single response from the first good request.
  void TestBadRequest(const base::Value::Dict& message,
                      bool expect_error_response);
  void TestConnect();

  MockIt2MeHost* mock_it2me_host() { return factory_raw_ptr_->host.get(); }

  const std::optional<ChromeOsEnterpriseParams>
  get_chrome_os_enterprise_params() {
    return factory_raw_ptr_->host->chrome_os_enterprise_params_;
  }

  // Raw pointer to host factory (owned by It2MeNativeMessagingHost).
  raw_ptr<MockIt2MeHostFactory, AcrossTasksDanglingUntriaged> factory_raw_ptr_ =
      nullptr;

 private:
  void StartHost();
  void ExitTest();
  void ExitPolicyRunLoop();

  // Each test creates two unidirectional pipes: "input" and "output".
  // It2MeNativeMessagingHost reads from input_read_file and writes to
  // output_write_file. The unittest supplies data to input_write_handle, and
  // verifies output from output_read_handle.
  //
  // unittest -> [input] -> It2MeNativeMessagingHost -> [output] -> unittest
  base::File input_write_file_;
  base::File output_read_file_;

  std::unique_ptr<base::test::TaskEnvironment> task_environment_;
  std::unique_ptr<base::RunLoop> test_run_loop_;

  std::unique_ptr<base::Thread> host_thread_;
  std::unique_ptr<base::RunLoop> host_run_loop_;

  std::unique_ptr<base::RunLoop> policy_run_loop_;

  // Retain a raw pointer to |policy_loader_| in order to control the policy
  // contents.
  raw_ptr<policy::FakeAsyncPolicyLoader, AcrossTasksDanglingUntriaged>
      policy_loader_ = nullptr;

  // Task runner of the host thread.
  scoped_refptr<AutoThreadTaskRunner> host_task_runner_;
  std::unique_ptr<remoting::NativeMessagingPipe> pipe_;

  scoped_refptr<network::TestSharedURLLoaderFactory> test_url_loader_factory_;
};

void It2MeNativeMessagingHostTest::SetUp() {
  task_environment_ = std::make_unique<base::test::TaskEnvironment>();
  test_run_loop_ = std::make_unique<base::RunLoop>();

  // Run the host on a dedicated thread.
  host_thread_ = std::make_unique<base::Thread>("host_thread");
  host_thread_->Start();

  host_task_runner_ = new AutoThreadTaskRunner(
      host_thread_->task_runner(),
      base::BindOnce(&It2MeNativeMessagingHostTest::ExitTest,
                     base::Unretained(this)));

#if BUILDFLAG(IS_CHROMEOS)
  test_url_loader_factory_ = new network::TestSharedURLLoaderFactory();
#endif

  host_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&It2MeNativeMessagingHostTest::StartHost,
                                base::Unretained(this)));

  // Wait until the host finishes starting.
  test_run_loop_->Run();
}

void It2MeNativeMessagingHostTest::TearDown() {
  // Release reference to AutoThreadTaskRunner, so the host thread can be shut
  // down.
  host_task_runner_ = nullptr;

  // Closing the write-end of the input will send an EOF to the native
  // messaging reader. This will trigger a host shutdown.
  input_write_file_.Close();

  // Start a new RunLoop and Wait until the host finishes shutting down.
  test_run_loop_ = std::make_unique<base::RunLoop>();
  test_run_loop_->Run();

  // Verify there are no more message in the output pipe.
  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  EXPECT_FALSE(response);

  // The It2MeNativeMessagingHost dtor closes the handles that are passed to it.
  // So the only handle left to close is |output_read_file_|.
  output_read_file_.Close();
}

void It2MeNativeMessagingHostTest::SetPolicies(base::Value::Dict dict) {
  DCHECK(task_environment_->GetMainThreadTaskRunner()
             ->RunsTasksInCurrentSequence());
  // Copy |dict| into |policy_bundle|.
  policy::PolicyNamespace policy_namespace =
      policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string());
  policy::PolicyBundle policy_bundle;
  policy::PolicyMap& policy_map = policy_bundle.Get(policy_namespace);
  policy_map.LoadFrom(dict, policy::POLICY_LEVEL_MANDATORY,
                      policy::POLICY_SCOPE_MACHINE,
                      policy::POLICY_SOURCE_CLOUD);

  // Simulate a policy update and wait for it to complete.
  policy_run_loop_ = std::make_unique<base::RunLoop>();
  policy_loader_->SetPolicies(policy_bundle);
  policy_loader_->PostReloadOnBackgroundThread(true /* force reload asap */);
  policy_run_loop_->Run();
  policy_run_loop_.reset(nullptr);
}

std::optional<base::Value::Dict>
It2MeNativeMessagingHostTest::ReadMessageFromOutputPipe() {
  while (true) {
    uint32_t length;
    int read_result = output_read_file_.ReadAtCurrentPos(
        reinterpret_cast<char*>(&length), sizeof(length));
    if (read_result != sizeof(length)) {
      // The output pipe has been closed, return an empty message.
      return std::nullopt;
    }

    std::string message_json(length, '\0');
    read_result =
        output_read_file_.ReadAtCurrentPos(std::data(message_json), length);
    if (read_result != static_cast<int>(length)) {
      LOG(ERROR) << "Message size (" << read_result
                 << ") doesn't match the header (" << length << ").";
      return std::nullopt;
    }

    std::optional<base::Value::Dict> message =
        base::JSONReader::ReadDict(message_json);
    if (!message) {
      LOG(ERROR) << "Malformed message:" << message_json;
      return std::nullopt;
    }

    // If this is a debug message log, ignore it, otherwise return it.
    const std::string* type = message->FindString(kMessageType);
    if (!type || *type != LogMessageHandler::kDebugMessageTypeName) {
      return std::move(*message);
    }
  }
}

void It2MeNativeMessagingHostTest::WriteMessageToInputPipe(
    const base::Value::Dict& message) {
  std::string message_json;
  base::JSONWriter::Write(message, &message_json);

  uint32_t length = base::checked_cast<uint32_t>(message_json.length());
  input_write_file_.WriteAtCurrentPos(base::byte_span_from_ref(length));
  input_write_file_.WriteAtCurrentPos(base::as_byte_span(message_json));
}

void It2MeNativeMessagingHostTest::VerifyHelloResponse(int request_id) {
  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  VerifyCommonProperties(*response, kHelloResponse, request_id);
}

void It2MeNativeMessagingHostTest::VerifyErrorResponse() {
  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  VerifyStringProperty(*response, kMessageType, kErrorMessage);
}

void It2MeNativeMessagingHostTest::VerifyConnectResponses(int request_id) {
  bool connect_response_received = false;
  bool nat_policy_received = false;
  bool starting_received = false;
  bool requestedAccessCode_received = false;
  bool receivedAccessCode_received = false;
  bool connecting_received = false;
  bool connected_received = false;

  // We expect a total of 7 messages: 1 connectResponse, 1 natPolicyChanged,
  // and 5 hostStateChanged.
  for (int i = 0; i < 7; ++i) {
    std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
    ASSERT_TRUE(response);

    const std::string* type = response->FindString(kMessageType);
    ASSERT_TRUE(type);

    if (*type == kConnectResponse) {
      EXPECT_FALSE(connect_response_received);
      connect_response_received = true;
      VerifyId(*response, request_id);
    } else if (*type == kNatPolicyChangedMessage) {
      EXPECT_FALSE(nat_policy_received);
      nat_policy_received = true;
    } else if (*type == kHostStateChangedMessage) {
      const std::string* state = response->FindString(kState);
      ASSERT_TRUE(state);

      if (*state == It2MeHostStateToString(It2MeHostState::kStarting)) {
        EXPECT_FALSE(starting_received);
        starting_received = true;
      } else if (*state ==
                 It2MeHostStateToString(It2MeHostState::kRequestedAccessCode)) {
        EXPECT_FALSE(requestedAccessCode_received);
        requestedAccessCode_received = true;
      } else if (*state ==
                 It2MeHostStateToString(It2MeHostState::kReceivedAccessCode)) {
        EXPECT_FALSE(receivedAccessCode_received);
        receivedAccessCode_received = true;

        const std::string* value = response->FindString(kAccessCode);
        ASSERT_TRUE(value);
        EXPECT_EQ(kTestAccessCode, *value);

        std::optional<int> access_code_lifetime =
            response->FindInt(kAccessCodeLifetime);
        ASSERT_TRUE(access_code_lifetime);
        EXPECT_EQ(kTestAccessCodeLifetime.InSeconds(), *access_code_lifetime);
      } else if (*state ==
                 It2MeHostStateToString(It2MeHostState::kConnecting)) {
        EXPECT_FALSE(connecting_received);
        connecting_received = true;
      } else if (*state == It2MeHostStateToString(It2MeHostState::kConnected)) {
        EXPECT_FALSE(connected_received);
        connected_received = true;

        const std::string* value = response->FindString(kClient);
        ASSERT_TRUE(value);
        EXPECT_EQ(kTestClientUsername, *value);
      } else {
        ADD_FAILURE() << "Unexpected host state: " << state;
      }
    } else {
      ADD_FAILURE() << "Unexpected message type: " << type;
    }
  }
}

void It2MeNativeMessagingHostTest::VerifyDisconnectResponses(int request_id) {
  bool disconnect_response_received = false;
  bool disconnected_received = false;

  // We expect a total of 2 messages: disconnectResponse and hostStateChanged.
  for (int i = 0; i < 2; i++) {
    std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
    ASSERT_TRUE(response);

    const std::string* type = response->FindString(kMessageType);
    ASSERT_TRUE(type);

    if (*type == kDisconnectResponse) {
      EXPECT_FALSE(disconnect_response_received);
      disconnect_response_received = true;
      VerifyId(*response, request_id);
    } else if (*type == kHostStateChangedMessage) {
      const std::string* state = response->FindString(kState);
      ASSERT_TRUE(state);
      if (*state == It2MeHostStateToString(It2MeHostState::kDisconnected)) {
        EXPECT_FALSE(disconnected_received);
        disconnected_received = true;
        const std::string* error_code = response->FindString(kDisconnectReason);
        ASSERT_TRUE(error_code);
        EXPECT_EQ(ErrorCodeToString(protocol::ErrorCode::OK), *error_code);
      } else {
        ADD_FAILURE() << "Unexpected host state: " << state;
      }
    } else {
      ADD_FAILURE() << "Unexpected message type: " << type;
    }
  }
}

void It2MeNativeMessagingHostTest::VerifyPolicyErrorResponse() {
  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  const std::string* type = response->FindString(kMessageType);
  ASSERT_TRUE(type);
  ASSERT_EQ(kPolicyErrorMessage, *type);
}

void It2MeNativeMessagingHostTest::TestBadRequest(
    const base::Value::Dict& message,
    bool expect_error_response) {
  base::Value::Dict good_message;
  good_message.Set(kMessageType, kHelloMessage);
  good_message.Set(kMessageId, 1);

  WriteMessageToInputPipe(good_message);
  WriteMessageToInputPipe(message);
  WriteMessageToInputPipe(good_message);

  VerifyHelloResponse(1);

  if (expect_error_response) {
    VerifyErrorResponse();
  }

  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  EXPECT_FALSE(response);
}

void It2MeNativeMessagingHostTest::StartHost() {
  DCHECK(host_task_runner_->RunsTasksInCurrentSequence());

  base::File input_read_file;
  base::File output_write_file;

  ASSERT_TRUE(MakePipe(&input_read_file, &input_write_file_));
  ASSERT_TRUE(MakePipe(&output_read_file_, &output_write_file));

  pipe_ = std::make_unique<NativeMessagingPipe>();

  std::unique_ptr<extensions::NativeMessagingChannel> channel(
      new PipeMessagingChannel(std::move(input_read_file),
                               std::move(output_write_file)));

  // Creating a native messaging host with a mock It2MeHostFactory and policy
  // loader.
  std::unique_ptr<ChromotingHostContext> context =
      ChromotingHostContext::CreateForTesting(host_task_runner_,
                                              test_url_loader_factory_);
  auto policy_loader =
      std::make_unique<policy::FakeAsyncPolicyLoader>(host_task_runner_);
  policy_loader_ = policy_loader.get();
  std::unique_ptr<PolicyWatcher> policy_watcher =
      PolicyWatcher::CreateFromPolicyLoaderForTesting(std::move(policy_loader));
  auto factory = std::make_unique<MockIt2MeHostFactory>();
  factory_raw_ptr_ = factory.get();
  std::unique_ptr<It2MeNativeMessagingHost> it2me_host(
      new It2MeNativeMessagingHost(
          /*needs_elevation=*/false, std::move(policy_watcher),
          std::move(context), std::move(factory)));
  it2me_host->SetPolicyErrorClosureForTesting(base::BindOnce(
      base::IgnoreResult(&base::TaskRunner::PostTask),
      task_environment_->GetMainThreadTaskRunner(), FROM_HERE,
      base::BindOnce(&It2MeNativeMessagingHostTest::ExitPolicyRunLoop,
                     base::Unretained(this))));
  it2me_host->Start(pipe_.get());

  pipe_->Start(std::move(it2me_host), std::move(channel));

  // Notify the test that the host has finished starting up.
  test_run_loop_->Quit();
}

void It2MeNativeMessagingHostTest::ExitTest() {
  if (!task_environment_->GetMainThreadTaskRunner()
           ->RunsTasksInCurrentSequence()) {
    task_environment_->GetMainThreadTaskRunner()->PostTask(
        FROM_HERE, base::BindOnce(&It2MeNativeMessagingHostTest::ExitTest,
                                  base::Unretained(this)));
    return;
  }
  test_run_loop_->Quit();
}

void It2MeNativeMessagingHostTest::ExitPolicyRunLoop() {
  DCHECK(task_environment_->GetMainThreadTaskRunner()
             ->RunsTasksInCurrentSequence());
  if (policy_run_loop_) {
    policy_run_loop_->Quit();
  }
}

void It2MeNativeMessagingHostTest::TestConnect() {
  int next_id = 1;
  WriteMessageToInputPipe(CreateConnectMessage(next_id));
  VerifyConnectResponses(next_id);
  ++next_id;
  WriteMessageToInputPipe(CreateDisconnectMessage(next_id));
  VerifyDisconnectResponses(next_id);
}

// Test hello request.
TEST_F(It2MeNativeMessagingHostTest, Hello) {
  int next_id = 0;
  base::Value::Dict message;
  message.Set(kMessageId, ++next_id);
  message.Set(kMessageType, kHelloMessage);
  WriteMessageToInputPipe(message);

  VerifyHelloResponse(next_id);
}

// Verify that response ID matches request ID.
TEST_F(It2MeNativeMessagingHostTest, Id) {
  base::Value::Dict message;
  message.Set(kMessageType, kHelloMessage);
  WriteMessageToInputPipe(message);
  message.Set(kMessageId, "42");
  WriteMessageToInputPipe(message);

  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  const std::string* value = response->FindString(kMessageId);
  EXPECT_FALSE(value);

  response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  value = response->FindString(kMessageId);
  ASSERT_TRUE(value);
  EXPECT_EQ("42", *value);
}

TEST_F(It2MeNativeMessagingHostTest, ConnectMultiple) {
  // A new It2MeHost instance is created for every it2me session. The native
  // messaging host, on the other hand, is long lived. This test verifies
  // multiple It2Me host startup and shutdowns.
  for (int i = 0; i < 3; ++i) {
    TestConnect();
  }
}

TEST_F(It2MeNativeMessagingHostTest,
       ConnectRespectsEnterpriseOptionsParameterOnChromeOsOnly) {
  int next_id = 1;
  base::Value::Dict connect_message = CreateConnectMessage(next_id);
  connect_message.Set(kIsEnterpriseAdminUser, true);
  ChromeOsEnterpriseParams params;
  params.suppress_user_dialogs = true;
  params.suppress_notifications = true;
  params.terminate_upon_input = true;
  params.curtain_local_user_session = true;
  params.allow_remote_input = false;
  params.allow_clipboard_sync = false;
  params.connection_auto_accept_timeout = base::Hours(8);
  params.request_origin = ChromeOsEnterpriseRequestOrigin::kEnterpriseAdmin;
  connect_message.Merge(params.ToDict());
  WriteMessageToInputPipe(connect_message);
  VerifyConnectResponses(next_id);
#if BUILDFLAG(IS_CHROMEOS) || !defined(NDEBUG)
  ASSERT_TRUE(get_chrome_os_enterprise_params().has_value());
  ASSERT_TRUE(get_chrome_os_enterprise_params()->suppress_user_dialogs);
  ASSERT_TRUE(get_chrome_os_enterprise_params()->suppress_notifications);
  ASSERT_TRUE(get_chrome_os_enterprise_params()->terminate_upon_input);
  ASSERT_TRUE(get_chrome_os_enterprise_params()->curtain_local_user_session);
  ASSERT_FALSE(get_chrome_os_enterprise_params()->allow_remote_input);
  ASSERT_FALSE(get_chrome_os_enterprise_params()->allow_clipboard_sync);
  ASSERT_EQ(get_chrome_os_enterprise_params()->connection_auto_accept_timeout,
            base::Hours(8));
  ASSERT_EQ(get_chrome_os_enterprise_params()->request_origin,
            ChromeOsEnterpriseRequestOrigin::kEnterpriseAdmin);
#else
  ASSERT_FALSE(get_chrome_os_enterprise_params().has_value());
#endif
  ++next_id;
  WriteMessageToInputPipe(CreateDisconnectMessage(next_id));
  VerifyDisconnectResponses(next_id);
}

TEST_F(It2MeNativeMessagingHostTest,
       ConnectRespectsIsEnterpriseAdminUserParameterOnChromeOsOnly) {
  int next_id = 1;
  base::Value::Dict connect_message = CreateConnectMessage(next_id);
  connect_message.Set(kIsEnterpriseAdminUser, true);
  WriteMessageToInputPipe(connect_message);
  VerifyConnectResponses(next_id);
#if BUILDFLAG(IS_CHROMEOS) || !defined(NDEBUG)
  EXPECT_TRUE(factory_raw_ptr_->host->is_enterprise_session());
#else
  EXPECT_FALSE(factory_raw_ptr_->host->is_enterprise_session());
#endif
  ++next_id;
  WriteMessageToInputPipe(CreateDisconnectMessage(next_id));
  VerifyDisconnectResponses(next_id);
}

// Verify requests with no type are rejected.
TEST_F(It2MeNativeMessagingHostTest, MissingType) {
  base::Value::Dict message;
  TestBadRequest(message, true);
}

// Verify rejection if type is unrecognized.
TEST_F(It2MeNativeMessagingHostTest, InvalidType) {
  base::Value::Dict message;
  message.Set(kMessageType, "xxx");
  TestBadRequest(message, true);
}

// Verify rejection if type is unrecognized.
TEST_F(It2MeNativeMessagingHostTest, BadPoliciesBeforeConnect) {
  base::Value::Dict bad_policy;
  bad_policy.Set(policy::key::kRemoteAccessHostFirewallTraversal, 1);
  SetPolicies(std::move(bad_policy));
  WriteMessageToInputPipe(CreateConnectMessage(1));
  VerifyPolicyErrorResponse();
}

// Verify rejection if type is unrecognized.
TEST_F(It2MeNativeMessagingHostTest, BadPoliciesAfterConnect) {
  base::Value::Dict bad_policy;
  bad_policy.Set(policy::key::kRemoteAccessHostFirewallTraversal, 1);
  WriteMessageToInputPipe(CreateConnectMessage(1));
  VerifyConnectResponses(1);
  SetPolicies(std::move(bad_policy));
  VerifyPolicyErrorResponse();
}

TEST_F(It2MeNativeMessagingHostTest, PlumbsAccessTokensFromConnectMessage) {
  WriteMessageToInputPipe(CreateConnectMessage(1));
  VerifyConnectResponses(1);

  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->signaling_token_getter()),
            kTestSignalingAccessToken);
  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->api_token_getter()),
            kTestApiAccessToken);
}

TEST_F(It2MeNativeMessagingHostTest,
       PlumbsLegacyAccessTokenFromConnectMessage) {
  base::Value::Dict connect_message = CreateConnectMessage(1);
  connect_message.Remove(kSignalingAccessToken);
  connect_message.Remove(kApiAccessToken);
  connect_message.Set(kAccessToken, "legacy_access_token");
  WriteMessageToInputPipe(connect_message);
  VerifyConnectResponses(1);

  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->signaling_token_getter()),
            "legacy_access_token");
  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->api_token_getter()),
            "legacy_access_token");
}

TEST_F(It2MeNativeMessagingHostTest,
       PlumbsAccessTokensFromUpdateAccessTokensMessage) {
  WriteMessageToInputPipe(CreateConnectMessage(1));
  VerifyConnectResponses(1);

  base::Value::Dict update_access_tokens_message;
  update_access_tokens_message.Set(kMessageType, kUpdateAccessTokensMessage);
  update_access_tokens_message.Set(kSignalingAccessToken,
                                   "new_signaling_token");
  update_access_tokens_message.Set(kApiAccessToken, "new_api_access_token");
  WriteMessageToInputPipe(update_access_tokens_message);

  std::optional<base::Value::Dict> response = ReadMessageFromOutputPipe();
  ASSERT_TRUE(response);
  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->signaling_token_getter()),
            "new_signaling_token");
  ASSERT_EQ(GetOAuthAccessToken(*mock_it2me_host()->api_token_getter()),
            "new_api_access_token");
}

}  // namespace remoting