Add ICU message format support
[chromium-blink-merge.git] / ipc / attachment_broker_privileged_win_unittest.cc
blobc4110bd3082301a85e660abc6d3ddf9c109d3407
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
7 #include <windows.h>
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "ipc/attachment_broker_privileged_win.h"
14 #include "ipc/attachment_broker_unprivileged_win.h"
15 #include "ipc/handle_attachment_win.h"
16 #include "ipc/ipc_listener.h"
17 #include "ipc/ipc_message.h"
18 #include "ipc/ipc_test_base.h"
20 namespace {
22 const char kDataBuffer[] = "This is some test data to write to the file.";
24 // Returns the contents of the file represented by |h| as a std::string.
25 std::string ReadFromFile(HANDLE h) {
26 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
27 char buffer[100];
28 DWORD bytes_read;
29 BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
30 &bytes_read, nullptr);
31 return success ? std::string(buffer, bytes_read) : std::string();
34 HANDLE GetHandleFromBrokeredAttachment(
35 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
36 if (attachment->GetType() !=
37 IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT)
38 return nullptr;
39 if (attachment->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE)
40 return nullptr;
41 IPC::internal::HandleAttachmentWin* received_handle_attachment =
42 static_cast<IPC::internal::HandleAttachmentWin*>(attachment.get());
43 return received_handle_attachment->get_handle();
46 // Returns true if |attachment| is a file HANDLE whose contents is
47 // |kDataBuffer|.
48 bool CheckContentsOfBrokeredAttachment(
49 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
50 HANDLE h = GetHandleFromBrokeredAttachment(attachment);
51 if (h == nullptr)
52 return false;
54 std::string contents = ReadFromFile(h);
55 return contents == std::string(kDataBuffer);
58 enum TestResult {
59 RESULT_UNKNOWN,
60 RESULT_SUCCESS,
61 RESULT_FAILURE,
64 // Once the test is finished, send a control message to the parent process with
65 // the result. The message may require the runloop to be run before its
66 // dispatched.
67 void SendControlMessage(IPC::Sender* sender, bool success) {
68 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
69 TestResult result = success ? RESULT_SUCCESS : RESULT_FAILURE;
70 message->WriteInt(result);
71 sender->Send(message);
74 class MockObserver : public IPC::AttachmentBroker::Observer {
75 public:
76 void ReceivedBrokerableAttachmentWithId(
77 const IPC::BrokerableAttachment::AttachmentId& id) override {
78 id_ = id;
80 IPC::BrokerableAttachment::AttachmentId* get_id() { return &id_; }
82 private:
83 IPC::BrokerableAttachment::AttachmentId id_;
86 // Forwards all messages to |listener_|. Quits the message loop after a
87 // message is received, or the channel has an error.
88 class ProxyListener : public IPC::Listener {
89 public:
90 ProxyListener() : reason_(MESSAGE_RECEIVED) {}
91 ~ProxyListener() override {}
93 // The reason for exiting the message loop.
94 enum Reason { MESSAGE_RECEIVED, CHANNEL_ERROR };
96 bool OnMessageReceived(const IPC::Message& message) override {
97 bool result = listener_->OnMessageReceived(message);
98 reason_ = MESSAGE_RECEIVED;
99 base::MessageLoop::current()->Quit();
100 return result;
103 void OnChannelError() override {
104 reason_ = CHANNEL_ERROR;
105 base::MessageLoop::current()->Quit();
108 void set_listener(IPC::Listener* listener) { listener_ = listener; }
109 Reason get_reason() { return reason_; }
111 private:
112 IPC::Listener* listener_;
113 Reason reason_;
116 // Waits for a result to be sent over the channel. Quits the message loop
117 // after a message is received, or the channel has an error.
118 class ResultListener : public IPC::Listener {
119 public:
120 ResultListener() : result_(RESULT_UNKNOWN) {}
121 ~ResultListener() override {}
123 bool OnMessageReceived(const IPC::Message& message) override {
124 base::PickleIterator iter(message);
126 int result;
127 EXPECT_TRUE(iter.ReadInt(&result));
128 result_ = static_cast<TestResult>(result);
129 return true;
132 TestResult get_result() { return result_; }
134 private:
135 TestResult result_;
138 // The parent process acts as an unprivileged process. The forked process acts
139 // as the privileged process.
140 class IPCAttachmentBrokerPrivilegedWinTest : public IPCTestBase {
141 public:
142 IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {}
143 ~IPCAttachmentBrokerPrivilegedWinTest() override {}
145 void SetUp() override {
146 IPCTestBase::SetUp();
147 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
148 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &temp_path_));
151 void TearDown() override { IPCTestBase::TearDown(); }
153 // Takes ownership of |broker|. Has no effect if called after CommonSetUp().
154 void set_broker(IPC::AttachmentBrokerUnprivilegedWin* broker) {
155 broker_.reset(broker);
158 void CommonSetUp() {
159 if (!broker_.get())
160 set_broker(new IPC::AttachmentBrokerUnprivilegedWin);
161 broker_->AddObserver(&observer_);
162 set_attachment_broker(broker_.get());
163 CreateChannel(&proxy_listener_);
164 broker_->DesignateBrokerCommunicationChannel(channel());
165 ASSERT_TRUE(ConnectChannel());
166 ASSERT_TRUE(StartClient());
169 void CommonTearDown() {
170 // Close the channel so the client's OnChannelError() gets fired.
171 channel()->Close();
173 EXPECT_TRUE(WaitForClientShutdown());
174 DestroyChannel();
175 broker_.reset();
178 HANDLE CreateTempFile() {
179 EXPECT_NE(-1, WriteFile(temp_path_, kDataBuffer,
180 static_cast<int>(strlen(kDataBuffer))));
182 HANDLE h =
183 CreateFile(temp_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0,
184 nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
185 EXPECT_NE(h, INVALID_HANDLE_VALUE);
186 return h;
189 void SendMessageWithAttachment(HANDLE h) {
190 IPC::Message* message =
191 new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
192 message->WriteInt(message_index_++);
193 scoped_refptr<IPC::internal::HandleAttachmentWin> attachment(
194 new IPC::internal::HandleAttachmentWin(h));
195 ASSERT_TRUE(message->WriteAttachment(attachment));
196 sender()->Send(message);
199 ProxyListener* get_proxy_listener() { return &proxy_listener_; }
200 IPC::AttachmentBrokerUnprivilegedWin* get_broker() { return broker_.get(); }
201 MockObserver* get_observer() { return &observer_; }
203 private:
204 base::ScopedTempDir temp_dir_;
205 base::FilePath temp_path_;
206 int message_index_;
207 ProxyListener proxy_listener_;
208 scoped_ptr<IPC::AttachmentBrokerUnprivilegedWin> broker_;
209 MockObserver observer_;
212 // A broker which always sets the current process as the destination process
213 // for attachments.
214 class MockBroker : public IPC::AttachmentBrokerUnprivilegedWin {
215 public:
216 MockBroker() {}
217 ~MockBroker() override {}
218 bool SendAttachmentToProcess(const IPC::BrokerableAttachment* attachment,
219 base::ProcessId destination_process) override {
220 return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess(
221 attachment, base::Process::Current().Pid());
225 // An unprivileged process makes a file HANDLE, and writes a string to it. The
226 // file HANDLE is sent to the privileged process using the attachment broker.
227 // The privileged process dups the HANDLE into its own HANDLE table. This test
228 // checks that the file has the same contents in the privileged process.
229 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandle) {
230 Init("SendHandle");
232 CommonSetUp();
233 ResultListener result_listener;
234 get_proxy_listener()->set_listener(&result_listener);
236 HANDLE h = CreateTempFile();
237 SendMessageWithAttachment(h);
238 base::MessageLoop::current()->Run();
240 // Check the result.
241 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
242 get_proxy_listener()->get_reason());
243 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
245 CommonTearDown();
248 // Similar to SendHandle, except the file HANDLE attached to the message has
249 // neither read nor write permissions.
250 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleWithoutPermissions) {
251 Init("SendHandleWithoutPermissions");
253 CommonSetUp();
254 ResultListener result_listener;
255 get_proxy_listener()->set_listener(&result_listener);
257 HANDLE h = CreateTempFile();
258 HANDLE h2;
259 BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(),
260 &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
261 ASSERT_TRUE(result);
262 SendMessageWithAttachment(h2);
263 base::MessageLoop::current()->Run();
265 // Check the result.
266 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
267 get_proxy_listener()->get_reason());
268 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
270 CommonTearDown();
273 // Similar to SendHandle, except the attachment's destination process is this
274 // process. This is an unrealistic scenario, but simulates an unprivileged
275 // process sending an attachment to another unprivileged process.
276 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleToSelf) {
277 Init("SendHandleToSelf");
279 set_broker(new MockBroker);
280 CommonSetUp();
281 // Technically, the channel is an endpoint, but we need the proxy listener to
282 // receive the messages so that it can quit the message loop.
283 channel()->set_attachment_broker_endpoint(false);
284 get_proxy_listener()->set_listener(get_broker());
286 HANDLE h = CreateTempFile();
287 SendMessageWithAttachment(h);
288 base::MessageLoop::current()->Run();
290 // Get the received attachment.
291 IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id();
292 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
293 get_broker()->GetAttachmentWithId(*id, &received_attachment);
294 ASSERT_NE(received_attachment.get(), nullptr);
296 // Check that it's a new entry in the HANDLE table.
297 HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment);
298 EXPECT_NE(h2, h);
299 EXPECT_NE(h2, nullptr);
301 // But it still points to the same file.
302 std::string contents = ReadFromFile(h);
303 EXPECT_EQ(contents, std::string(kDataBuffer));
305 CommonTearDown();
308 using OnMessageReceivedCallback =
309 void (*)(MockObserver* observer,
310 IPC::AttachmentBrokerPrivilegedWin* broker,
311 IPC::Sender* sender);
313 int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback,
314 const char* channel_name) {
315 base::MessageLoopForIO main_message_loop;
316 ProxyListener listener;
318 // Set up IPC channel.
319 IPC::AttachmentBrokerPrivilegedWin broker;
320 listener.set_listener(&broker);
321 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
322 IPCTestBase::GetChannelName(channel_name), &listener, &broker));
323 broker.RegisterCommunicationChannel(channel.get());
324 CHECK(channel->Connect());
326 MockObserver observer;
327 broker.AddObserver(&observer);
329 while (true) {
330 base::MessageLoop::current()->Run();
331 ProxyListener::Reason reason = listener.get_reason();
332 if (reason == ProxyListener::CHANNEL_ERROR)
333 break;
335 callback(&observer, &broker, channel.get());
338 return 0;
341 void SendHandleCallback(MockObserver* observer,
342 IPC::AttachmentBrokerPrivilegedWin* broker,
343 IPC::Sender* sender) {
344 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
345 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
346 broker->GetAttachmentWithId(*id, &received_attachment);
348 // Check that it's the expected handle.
349 bool success = CheckContentsOfBrokeredAttachment(received_attachment);
351 SendControlMessage(sender, success);
354 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) {
355 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle");
358 void SendHandleWithoutPermissionsCallback(
359 MockObserver* observer,
360 IPC::AttachmentBrokerPrivilegedWin* broker,
361 IPC::Sender* sender) {
362 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
363 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
364 broker->GetAttachmentWithId(*id, &received_attachment);
366 // Check that it's the expected handle.
367 HANDLE h = GetHandleFromBrokeredAttachment(received_attachment);
368 if (h != nullptr) {
369 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
371 char buffer[100];
372 DWORD bytes_read;
373 BOOL success =
374 ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
375 &bytes_read, nullptr);
376 if (!success && GetLastError() == ERROR_ACCESS_DENIED) {
377 SendControlMessage(sender, true);
378 return;
382 SendControlMessage(sender, false);
385 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) {
386 return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback,
387 "SendHandleWithoutPermissions");
390 void SendHandleToSelfCallback(MockObserver* observer,
391 IPC::AttachmentBrokerPrivilegedWin* broker,
392 IPC::Sender* sender) {
393 // Do nothing special. The default behavior already runs the
394 // AttachmentBrokerPrivilegedWin.
397 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) {
398 return CommonPrivilegedProcessMain(&SendHandleToSelfCallback,
399 "SendHandleToSelf");
402 } // namespace