BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / ipc / attachment_broker_privileged_win_unittest.cc
blob480a2b4bfa7109a59c5b12d9eb6a68e71091f65b
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/handle_win.h"
17 #include "ipc/ipc_listener.h"
18 #include "ipc/ipc_message.h"
19 #include "ipc/ipc_test_base.h"
21 namespace {
23 const char kDataBuffer[] = "This is some test data to write to the file.";
25 // Returns the contents of the file represented by |h| as a std::string.
26 std::string ReadFromFile(HANDLE h) {
27 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
28 char buffer[100];
29 DWORD bytes_read;
30 BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
31 &bytes_read, nullptr);
32 return success ? std::string(buffer, bytes_read) : std::string();
35 HANDLE GetHandleFromBrokeredAttachment(
36 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
37 if (attachment->GetType() !=
38 IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT)
39 return nullptr;
40 if (attachment->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE)
41 return nullptr;
42 IPC::internal::HandleAttachmentWin* received_handle_attachment =
43 static_cast<IPC::internal::HandleAttachmentWin*>(attachment.get());
44 return received_handle_attachment->get_handle();
47 // Returns true if |attachment| is a file HANDLE whose contents is
48 // |kDataBuffer|.
49 bool CheckContentsOfBrokeredAttachment(
50 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
51 HANDLE h = GetHandleFromBrokeredAttachment(attachment);
52 if (h == nullptr)
53 return false;
55 std::string contents = ReadFromFile(h);
56 return contents == std::string(kDataBuffer);
59 enum TestResult {
60 RESULT_UNKNOWN,
61 RESULT_SUCCESS,
62 RESULT_FAILURE,
65 // Once the test is finished, send a control message to the parent process with
66 // the result. The message may require the runloop to be run before its
67 // dispatched.
68 void SendControlMessage(IPC::Sender* sender, bool success) {
69 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
70 TestResult result = success ? RESULT_SUCCESS : RESULT_FAILURE;
71 message->WriteInt(result);
72 sender->Send(message);
75 class MockObserver : public IPC::AttachmentBroker::Observer {
76 public:
77 void ReceivedBrokerableAttachmentWithId(
78 const IPC::BrokerableAttachment::AttachmentId& id) override {
79 id_ = id;
81 IPC::BrokerableAttachment::AttachmentId* get_id() { return &id_; }
83 private:
84 IPC::BrokerableAttachment::AttachmentId id_;
87 // Forwards all messages to |listener_|. Quits the message loop after a
88 // message is received, or the channel has an error.
89 class ProxyListener : public IPC::Listener {
90 public:
91 ProxyListener() : reason_(MESSAGE_RECEIVED) {}
92 ~ProxyListener() override {}
94 // The reason for exiting the message loop.
95 enum Reason { MESSAGE_RECEIVED, CHANNEL_ERROR };
97 bool OnMessageReceived(const IPC::Message& message) override {
98 bool result = listener_->OnMessageReceived(message);
99 reason_ = MESSAGE_RECEIVED;
100 base::MessageLoop::current()->Quit();
101 return result;
104 void OnChannelError() override {
105 reason_ = CHANNEL_ERROR;
106 base::MessageLoop::current()->Quit();
109 void set_listener(IPC::Listener* listener) { listener_ = listener; }
110 Reason get_reason() { return reason_; }
112 private:
113 IPC::Listener* listener_;
114 Reason reason_;
117 // Waits for a result to be sent over the channel. Quits the message loop
118 // after a message is received, or the channel has an error.
119 class ResultListener : public IPC::Listener {
120 public:
121 ResultListener() : result_(RESULT_UNKNOWN) {}
122 ~ResultListener() override {}
124 bool OnMessageReceived(const IPC::Message& message) override {
125 base::PickleIterator iter(message);
127 int result;
128 EXPECT_TRUE(iter.ReadInt(&result));
129 result_ = static_cast<TestResult>(result);
130 return true;
133 TestResult get_result() { return result_; }
135 private:
136 TestResult result_;
139 // The parent process acts as an unprivileged process. The forked process acts
140 // as the privileged process.
141 class IPCAttachmentBrokerPrivilegedWinTest : public IPCTestBase {
142 public:
143 IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {}
144 ~IPCAttachmentBrokerPrivilegedWinTest() override {}
146 void SetUp() override {
147 IPCTestBase::SetUp();
148 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
149 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &temp_path_));
152 void TearDown() override { IPCTestBase::TearDown(); }
154 // Takes ownership of |broker|. Has no effect if called after CommonSetUp().
155 void set_broker(IPC::AttachmentBrokerUnprivilegedWin* broker) {
156 broker_.reset(broker);
157 IPC::AttachmentBroker::SetGlobal(broker);
160 void CommonSetUp() {
161 if (!broker_.get())
162 set_broker(new IPC::AttachmentBrokerUnprivilegedWin);
163 broker_->AddObserver(&observer_);
164 set_attachment_broker(broker_.get());
165 CreateChannel(&proxy_listener_);
166 broker_->DesignateBrokerCommunicationChannel(channel());
167 ASSERT_TRUE(ConnectChannel());
168 ASSERT_TRUE(StartClient());
171 void CommonTearDown() {
172 // Close the channel so the client's OnChannelError() gets fired.
173 channel()->Close();
175 EXPECT_TRUE(WaitForClientShutdown());
176 DestroyChannel();
177 broker_.reset();
180 HANDLE CreateTempFile() {
181 EXPECT_NE(-1, WriteFile(temp_path_, kDataBuffer,
182 static_cast<int>(strlen(kDataBuffer))));
184 HANDLE h =
185 CreateFile(temp_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0,
186 nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
187 EXPECT_NE(h, INVALID_HANDLE_VALUE);
188 return h;
191 void SendMessageWithAttachment(HANDLE h) {
192 IPC::Message* message =
193 new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
194 message->WriteInt(message_index_++);
195 scoped_refptr<IPC::internal::HandleAttachmentWin> attachment(
196 new IPC::internal::HandleAttachmentWin(h, IPC::HandleWin::DUPLICATE));
197 ASSERT_TRUE(message->WriteAttachment(attachment));
198 sender()->Send(message);
201 ProxyListener* get_proxy_listener() { return &proxy_listener_; }
202 IPC::AttachmentBrokerUnprivilegedWin* get_broker() { return broker_.get(); }
203 MockObserver* get_observer() { return &observer_; }
205 private:
206 base::ScopedTempDir temp_dir_;
207 base::FilePath temp_path_;
208 int message_index_;
209 ProxyListener proxy_listener_;
210 scoped_ptr<IPC::AttachmentBrokerUnprivilegedWin> broker_;
211 MockObserver observer_;
214 // A broker which always sets the current process as the destination process
215 // for attachments.
216 class MockBroker : public IPC::AttachmentBrokerUnprivilegedWin {
217 public:
218 MockBroker() {}
219 ~MockBroker() override {}
220 bool SendAttachmentToProcess(const IPC::BrokerableAttachment* attachment,
221 base::ProcessId destination_process) override {
222 return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess(
223 attachment, base::Process::Current().Pid());
227 // An unprivileged process makes a file HANDLE, and writes a string to it. The
228 // file HANDLE is sent to the privileged process using the attachment broker.
229 // The privileged process dups the HANDLE into its own HANDLE table. This test
230 // checks that the file has the same contents in the privileged process.
231 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandle) {
232 Init("SendHandle");
234 CommonSetUp();
235 ResultListener result_listener;
236 get_proxy_listener()->set_listener(&result_listener);
238 HANDLE h = CreateTempFile();
239 SendMessageWithAttachment(h);
240 base::MessageLoop::current()->Run();
242 // Check the result.
243 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
244 get_proxy_listener()->get_reason());
245 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
247 CommonTearDown();
250 // Similar to SendHandle, except the file HANDLE attached to the message has
251 // neither read nor write permissions.
252 TEST_F(IPCAttachmentBrokerPrivilegedWinTest,
253 DISABLED_SendHandleWithoutPermissions) {
254 Init("SendHandleWithoutPermissions");
256 CommonSetUp();
257 ResultListener result_listener;
258 get_proxy_listener()->set_listener(&result_listener);
260 HANDLE h = CreateTempFile();
261 HANDLE h2;
262 BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(),
263 &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
264 ASSERT_TRUE(result);
265 SendMessageWithAttachment(h2);
266 base::MessageLoop::current()->Run();
268 // Check the result.
269 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
270 get_proxy_listener()->get_reason());
271 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
273 CommonTearDown();
276 // Similar to SendHandle, except the attachment's destination process is this
277 // process. This is an unrealistic scenario, but simulates an unprivileged
278 // process sending an attachment to another unprivileged process.
279 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleToSelf) {
280 Init("SendHandleToSelf");
282 set_broker(new MockBroker);
283 CommonSetUp();
284 // Technically, the channel is an endpoint, but we need the proxy listener to
285 // receive the messages so that it can quit the message loop.
286 channel()->SetAttachmentBrokerEndpoint(false);
287 get_proxy_listener()->set_listener(get_broker());
289 HANDLE h = CreateTempFile();
290 SendMessageWithAttachment(h);
291 base::MessageLoop::current()->Run();
293 // Get the received attachment.
294 IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id();
295 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
296 get_broker()->GetAttachmentWithId(*id, &received_attachment);
297 ASSERT_NE(received_attachment.get(), nullptr);
299 // Check that it's a new entry in the HANDLE table.
300 HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment);
301 EXPECT_NE(h2, h);
302 EXPECT_NE(h2, nullptr);
304 // But it still points to the same file.
305 std::string contents = ReadFromFile(h);
306 EXPECT_EQ(contents, std::string(kDataBuffer));
308 CommonTearDown();
311 // Similar to SendHandle, except this test uses the HandleWin class.
312 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleWin) {
313 Init("SendHandleWin");
315 CommonSetUp();
316 ResultListener result_listener;
317 get_proxy_listener()->set_listener(&result_listener);
319 HANDLE h = CreateTempFile();
320 IPC::HandleWin handle_win(h, IPC::HandleWin::FILE_READ_WRITE);
321 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
322 message->WriteInt(0);
323 IPC::ParamTraits<IPC::HandleWin>::Write(message, handle_win);
324 sender()->Send(message);
325 base::MessageLoop::current()->Run();
327 // Check the result.
328 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
329 get_proxy_listener()->get_reason());
330 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
332 CommonTearDown();
335 using OnMessageReceivedCallback =
336 void (*)(MockObserver* observer,
337 IPC::AttachmentBrokerPrivilegedWin* broker,
338 IPC::Sender* sender);
340 int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback,
341 const char* channel_name) {
342 base::MessageLoopForIO main_message_loop;
343 ProxyListener listener;
345 // Set up IPC channel.
346 IPC::AttachmentBrokerPrivilegedWin broker;
347 IPC::AttachmentBroker::SetGlobal(&broker);
348 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
349 IPCTestBase::GetChannelName(channel_name), &listener, &broker));
350 broker.RegisterCommunicationChannel(channel.get());
351 CHECK(channel->Connect());
353 MockObserver observer;
354 broker.AddObserver(&observer);
356 while (true) {
357 base::MessageLoop::current()->Run();
358 ProxyListener::Reason reason = listener.get_reason();
359 if (reason == ProxyListener::CHANNEL_ERROR)
360 break;
362 callback(&observer, &broker, channel.get());
365 return 0;
368 void SendHandleCallback(MockObserver* observer,
369 IPC::AttachmentBrokerPrivilegedWin* broker,
370 IPC::Sender* sender) {
371 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
372 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
373 broker->GetAttachmentWithId(*id, &received_attachment);
375 // Check that it's the expected handle.
376 bool success = CheckContentsOfBrokeredAttachment(received_attachment);
378 SendControlMessage(sender, success);
381 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) {
382 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle");
385 void SendHandleWithoutPermissionsCallback(
386 MockObserver* observer,
387 IPC::AttachmentBrokerPrivilegedWin* broker,
388 IPC::Sender* sender) {
389 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
390 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
391 broker->GetAttachmentWithId(*id, &received_attachment);
393 // Check that it's the expected handle.
394 HANDLE h = GetHandleFromBrokeredAttachment(received_attachment);
395 if (h != nullptr) {
396 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
398 char buffer[100];
399 DWORD bytes_read;
400 BOOL success =
401 ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
402 &bytes_read, nullptr);
403 if (!success && GetLastError() == ERROR_ACCESS_DENIED) {
404 SendControlMessage(sender, true);
405 return;
409 SendControlMessage(sender, false);
412 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) {
413 return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback,
414 "SendHandleWithoutPermissions");
417 void SendHandleToSelfCallback(MockObserver* observer,
418 IPC::AttachmentBrokerPrivilegedWin* broker,
419 IPC::Sender* sender) {
420 // Do nothing special. The default behavior already runs the
421 // AttachmentBrokerPrivilegedWin.
424 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) {
425 return CommonPrivilegedProcessMain(&SendHandleToSelfCallback,
426 "SendHandleToSelf");
429 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWin) {
430 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandleWin");
433 } // namespace