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
|
# -*- coding: utf-8 -*-
# Author: Alejandro J. Cura <alecu@canonical.com>
#
# Copyright 2010 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
"""Tests for txkeyring."""
import uuid
import dbus.service
from ubuntuone.devtools.testcase import DBusTestCase
from twisted.internet.defer import inlineCallbacks, returnValue
from ubuntu_sso.utils import txsecrets
# DBus exported objects have different naming conventions than vanilla python
# pylint: disable=C0103
# pylint, my clock says... 2010. Do you need a tutorial on decorators?
# pylint: disable=C0322
# pylint complains when things are a little too dynamic
# pylint: disable=E1101
class SampleMiscException(Exception):
"""An exception that will be turned into a DBus Exception."""
class ItemMock(dbus.service.Object):
"""An item contains a secret, lookup attributes and has a label."""
get_secret_fail = False
delete_fail = False
delete_prompt = False
dismissed = False
def __init__(self, collection, label, attributes, value, *args, **kwargs):
"""Initialize this instance."""
super(ItemMock, self).__init__(*args, **kwargs)
self.collection = collection
self.label = label
self.attributes = attributes
self.value = value
@dbus.service.method(dbus_interface=txsecrets.ITEM_IFACE,
out_signature="o")
def Delete(self):
"""Delete this item."""
if self.delete_fail:
raise SampleMiscException()
self.collection.items.remove(self)
if self.delete_prompt:
prompt_path = create_object_path("/org/freedesktop/secrets/prompt")
prompt = self.dbus_publish(prompt_path, PromptMock,
result="",
dismissed=self.dismissed)
return prompt
else:
return "/"
@dbus.service.method(dbus_interface=txsecrets.ITEM_IFACE,
in_signature="o", out_signature="(oayay)")
def GetSecret(self, session):
"""Retrieve the secret for this item."""
if self.get_secret_fail:
raise SampleMiscException()
return (session, "", self.value)
class PromptMock(dbus.service.Object):
"""A prompt necessary to complete an operation."""
def __init__(self, dismissed=True,
result=dbus.String("", variant_level=1), *args, **kwargs):
"""Initialize this instance."""
super(PromptMock, self).__init__(*args, **kwargs)
self.dismissed = dismissed
self.result = result
@dbus.service.method(dbus_interface=txsecrets.PROMPT_IFACE,
in_signature="s")
def Prompt(self, window_id):
"""Perform the prompt."""
self.Completed(self.dismissed, self.result)
@dbus.service.signal(dbus_interface=txsecrets.PROMPT_IFACE,
signature="bv")
def Completed(self, dismissed, result):
"""The prompt and operation completed."""
class CollectionMock(dbus.service.Object):
"""A collection of items containing secrets."""
SUPPORTS_MULTIPLE_OBJECT_PATHS = True
SUPPORTS_MULTIPLE_CONNECTIONS = True
create_item_prompt = False
dismissed = False
create_item_fail = False
locked = False
def __init__(self, label, *args, **kwargs):
"""Initialize this instance."""
super(CollectionMock, self).__init__(*args, **kwargs)
self.items = []
self.label = label
@dbus.service.method(dbus_interface=txsecrets.COLLECTION_IFACE,
in_signature="a{sv}(oayay)b", out_signature="oo",
byte_arrays=True)
def CreateItem(self, properties, secret, replace):
"""Create an item with the given attributes, secret and label.
If replace is set, then it replaces an item already present with the
same values for the attributes.
"""
if self.create_item_fail:
raise SampleMiscException()
attributes = properties[txsecrets.ATTRIBUTES_PROPERTY]
item_label = properties[txsecrets.LABEL_PROPERTY]
session, parameters, value = secret
item_path = create_object_path("/org/freedesktop/secrets/collection/" +
self.label)
item = self.dbus_publish(item_path, ItemMock, self, item_label,
attributes, value)
self.items.append(item)
if self.create_item_prompt:
prompt_path = create_object_path("/org/freedesktop/secrets/prompt")
prompt = self.dbus_publish(prompt_path, PromptMock,
result=item,
dismissed=self.dismissed)
return "/", prompt
else:
return item, "/"
class SessionMock(dbus.service.Object):
"""A session tracks state between the service and a client application."""
@dbus.service.method(dbus_interface=txsecrets.SESSION_IFACE)
def Close(self):
"""Close this session."""
class SecretServiceMock(dbus.service.Object):
"""The Secret Service manages all the sessions and collections."""
create_collection_prompt = False
create_collection_fail = False
open_session_fail = False
unlock_prompts = False
dismissed = False
def __init__(self, *args, **kwargs):
"""Initialize this instance."""
super(SecretServiceMock, self).__init__(*args, **kwargs)
self.sessions = {}
self.collections = {}
@dbus.service.method(dbus_interface=txsecrets.SERVICE_IFACE,
in_signature="sv", out_signature="vo")
def OpenSession(self, algorithm, algorithm_parameters):
"""Open a unique session for the caller application."""
if self.open_session_fail:
raise SampleMiscException()
session_path = create_object_path("/org/freedesktop/secrets/session")
session = self.dbus_publish(session_path, SessionMock)
self.sessions[session_path] = session
return True, session
@dbus.service.method(dbus_interface=txsecrets.SERVICE_IFACE,
in_signature="a{sv}", out_signature="oo")
def CreateCollection(self, properties):
"""Create a new collection with the specified properties."""
if self.create_collection_fail:
raise SampleMiscException()
label = str(properties[txsecrets.LABEL_PROPERTY])
if len(self.collections):
coll_path = "/org/freedesktop/secrets/collection/" + label
else:
coll_path = txsecrets.DEFAULT_COLLECTION
collection = self.dbus_publish(coll_path, CollectionMock, label)
self.collections[label] = collection
if self.create_collection_prompt:
prompt_path = create_object_path("/org/freedesktop/secrets/prompt")
prompt = self.dbus_publish(prompt_path, PromptMock,
result=collection,
dismissed=self.dismissed)
return "/", prompt
else:
return collection, "/"
@dbus.service.method(dbus_interface=txsecrets.SERVICE_IFACE,
in_signature="a{ss}", out_signature="aoao")
def SearchItems(self, attributes):
"""Find items in any collection."""
unlocked_items = []
locked_items = []
for c in self.collections.values():
if c.locked:
append_item = locked_items.append
else:
append_item = unlocked_items.append
for i in c.items:
# TODO: check if attrs match (not needed for now)
append_item(i)
return unlocked_items, locked_items
def unlock_objects(self, objects):
"""Unlock the objects or its containers."""
for c in self.collections.values():
if c.__dbus_object_path__ in objects:
c.locked = False
for i in c.items:
if i.__dbus_object_path__ in objects:
c.locked = False
@dbus.service.method(dbus_interface=txsecrets.SERVICE_IFACE,
in_signature="ao", out_signature="aoo")
def Unlock(self, objects):
"""Unlock the specified objects."""
if self.unlock_prompts:
prompt_path = create_object_path("/org/freedesktop/secrets/prompt")
self.unlock_objects(objects)
prompt = self.dbus_publish(prompt_path, PromptMock,
result=objects,
dismissed=self.dismissed)
return "/", prompt
else:
self.unlock_objects(objects)
return objects, "/"
def create_object_path(base):
"""Create a random object path given a base path."""
random = uuid.uuid4().hex
return base + "/" + random
class BaseTestCase(DBusTestCase):
"""Base class for DBus tests."""
timeout = 10
def setUp(self):
super(BaseTestCase, self).setUp()
self.session_bus = dbus.SessionBus()
self.mock_service = self.dbus_publish(txsecrets.SECRETS_SERVICE,
SecretServiceMock)
self.secretservice = txsecrets.SecretService()
def dbus_publish(self, object_path, object_class, *args, **kwargs):
"""Create an object and publish it on the bus."""
name = self.session_bus.request_name(txsecrets.BUS_NAME,
dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
self.assertNotEqual(name, dbus.bus.REQUEST_NAME_REPLY_EXISTS)
mock_object = object_class(*args, object_path=object_path,
conn=self.session_bus, **kwargs)
self.addCleanup(mock_object.remove_from_connection)
mock_object.dbus_publish = self.dbus_publish
return mock_object
@inlineCallbacks
def create_sample_collection(self, label):
"""Create a collection with a given label."""
coll = yield self.secretservice.create_collection(label)
returnValue(coll)
class SecretServiceTestCase(BaseTestCase):
"""Test the Secret Service class."""
@inlineCallbacks
def test_open_session(self):
"""The secret service session is opened."""
result = yield self.secretservice.open_session()
self.assertEqual(result, self.secretservice)
@inlineCallbacks
def test_open_session_throws_dbus_error_as_failure(self):
"""The secret service open session throws a dbus error as a failure."""
d = self.secretservice.open_session()
self.mock_service.open_session_fail = True
yield self.assertFailure(d, dbus.exceptions.DBusException)
@inlineCallbacks
def test_open_session_fails_before_opening_as_failure(self):
"""A dbus error before opening the session is thrown as a failure."""
def fail(*args, **kwargs):
"""Throw a DBus exception."""
raise dbus.exceptions.DBusException()
self.patch(txsecrets.dbus, "SessionBus", fail)
d = self.secretservice.open_session()
self.mock_service.open_session_fail = True
yield self.assertFailure(d, dbus.exceptions.DBusException)
@inlineCallbacks
def test_create_collection(self):
"""The secret service creates a collection."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
self.assertIn(collection_label, self.mock_service.collections)
@inlineCallbacks
def test_create_collection_prompt(self):
"""The secret service creates a collection after a prompt."""
yield self.secretservice.open_session()
self.mock_service.create_collection_prompt = True
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
self.assertIn(collection_label, self.mock_service.collections)
@inlineCallbacks
def test_create_collection_prompt_dismissed(self):
"""The service fails to create collection when prompt dismissed."""
yield self.secretservice.open_session()
self.mock_service.create_collection_prompt = True
self.mock_service.dismissed = True
collection_label = "sample_keyring"
yield self.assertFailure(
self.create_sample_collection(collection_label),
txsecrets.UserCancelled)
@inlineCallbacks
def test_create_collection_throws_dbus_error(self):
"""The service fails to create collection on a DBus error."""
yield self.secretservice.open_session()
self.mock_service.create_collection_fail = True
collection_label = "sample_keyring"
yield self.assertFailure(
self.create_sample_collection(collection_label),
dbus.exceptions.DBusException)
@inlineCallbacks
def test_prompt_accepted(self):
"""A prompt is accepted."""
yield self.secretservice.open_session()
expected_result = "hello world"
prompt_path = "/prompt"
self.dbus_publish(prompt_path, PromptMock, result=expected_result,
dismissed=False)
result = yield self.secretservice.do_prompt(prompt_path)
self.assertEqual(result, expected_result)
@inlineCallbacks
def test_prompt_dismissed(self):
"""A prompt is dismissed with a UserCancelled failure."""
yield self.secretservice.open_session()
expected_result = "hello world2"
prompt_path = "/prompt"
self.dbus_publish(prompt_path, PromptMock, result=expected_result,
dismissed=True)
d = self.secretservice.do_prompt(prompt_path)
self.assertFailure(d, txsecrets.UserCancelled)
@inlineCallbacks
def test_search_unlocked_items(self):
"""The secret service searchs for unlocked items."""
yield self.secretservice.open_session()
coll = yield self.create_sample_collection("sample_keyring")
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
value = yield items[0].get_value()
self.assertEqual(value, sample_secret)
@inlineCallbacks
def test_search_locked_items(self):
"""The secret service searchs for locked items."""
yield self.secretservice.open_session()
collection_name = "sample_keyring"
coll = yield self.create_sample_collection(collection_name)
mock_collection = self.mock_service.collections[collection_name]
mock_collection.locked = True
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret99!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
value = yield items[0].get_value()
self.assertEqual(value, sample_secret)
@inlineCallbacks
def test_search_locked_items_prompts(self):
"""The secret service searchs for locked items after a prompt."""
yield self.secretservice.open_session()
collection_name = "sample_keyring"
coll = yield self.create_sample_collection(collection_name)
mock_collection = self.mock_service.collections[collection_name]
mock_collection.locked = True
self.mock_service.unlock_prompts = True
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret99!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
value = yield items[0].get_value()
self.assertEqual(value, sample_secret)
@inlineCallbacks
def test_search_locked_items_prompts_dismissed(self):
"""Service fails search for locked items after dismissed prompt."""
yield self.secretservice.open_session()
collection_name = "sample_keyring"
coll = yield self.create_sample_collection(collection_name)
mock_collection = self.mock_service.collections[collection_name]
mock_collection.locked = True
self.mock_service.unlock_prompts = True
self.mock_service.dismissed = True
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret99!"
yield coll.create_item("Cucaracha", attr, sample_secret)
d = self.secretservice.search_items(attr)
yield self.assertFailure(d, txsecrets.UserCancelled)
class CollectionTestCase(BaseTestCase):
"""Test the Collection class."""
@inlineCallbacks
def test_create_item(self):
"""The collection creates an item."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
coll = self.secretservice.get_default_collection()
mock_collection = self.mock_service.collections[collection_label]
attr = {"key-type": "Ubuntu 242 credentials"}
sample_secret = "secret!"
yield coll.create_item("Cucaracha", attr, sample_secret)
self.assertEqual(len(mock_collection.items), 1)
self.assertEqual(mock_collection.items[0].value, sample_secret)
@inlineCallbacks
def test_create_item_prompt(self):
"""The collection creates an item after a prompt."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
coll = self.secretservice.get_default_collection()
mock_collection = self.mock_service.collections[collection_label]
mock_collection.create_item_prompt = True
attr = {"key-type": "Ubuntu 242 credentials"}
sample_secret = "secret2!"
yield coll.create_item("Cucaracha", attr, sample_secret)
self.assertEqual(len(mock_collection.items), 1)
self.assertEqual(mock_collection.items[0].value, sample_secret)
@inlineCallbacks
def test_create_item_prompt_dismissed(self):
"""The collection fails to create an item when prompt is dismissed."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
coll = self.secretservice.get_default_collection()
mock_collection = self.mock_service.collections[collection_label]
mock_collection.create_item_prompt = True
mock_collection.dismissed = True
attr = {"key-type": "Ubuntu 242 credentials"}
sample_secret = "secret3!"
yield self.assertFailure(coll.create_item("Cuca", attr, sample_secret),
txsecrets.UserCancelled)
@inlineCallbacks
def test_create_item_throws_dbus_error(self):
"""The collection fails to create an item when DBus fails."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
yield self.create_sample_collection(collection_label)
coll = self.secretservice.get_default_collection()
mock_collection = self.mock_service.collections[collection_label]
mock_collection.create_item_fail = True
attr = {"key-type": "Ubuntu 242 credentials"}
sample_secret = "secret4!"
yield self.assertFailure(coll.create_item("Cuca", attr, sample_secret),
dbus.exceptions.DBusException)
class ItemTestCase(BaseTestCase):
"""Test the Item class."""
@inlineCallbacks
def test_get_value(self):
"""The secret value is retrieved from the item."""
yield self.secretservice.open_session()
coll = yield self.create_sample_collection("sample_keyring")
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
value = yield items[0].get_value()
self.assertEqual(value, sample_secret)
@inlineCallbacks
def test_get_value_throws_dbus_error(self):
"""The secret value is not retrieved if DBus fails."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
coll = yield self.create_sample_collection(collection_label)
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
mock = self.mock_service.collections[collection_label].items[0]
mock.get_secret_fail = True
yield self.assertFailure(items[0].get_value(),
dbus.exceptions.DBusException)
@inlineCallbacks
def test_delete(self):
"""The item is deleted."""
yield self.secretservice.open_session()
coll = yield self.create_sample_collection("sample_keyring")
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
yield items[0].delete()
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 0)
@inlineCallbacks
def test_delete_prompt(self):
"""The item is deleted after a prompt."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
coll = yield self.create_sample_collection(collection_label)
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
mock_item = self.mock_service.collections[collection_label].items[0]
mock_item.delete_prompt = True
yield items[0].delete()
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 0)
@inlineCallbacks
def test_delete_prompt_dismissed(self):
"""The item is not deleted after a dismissed prompt."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
coll = yield self.create_sample_collection(collection_label)
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
mock_item = self.mock_service.collections[collection_label].items[0]
mock_item.delete_prompt = True
mock_item.dismissed = True
yield self.assertFailure(items[0].delete(), txsecrets.UserCancelled)
@inlineCallbacks
def test_delete_throws_dbus_error(self):
"""The item is not deleted when a DBus error happens."""
yield self.secretservice.open_session()
collection_label = "sample_keyring"
coll = yield self.create_sample_collection(collection_label)
attr = {"key-type": "Ubuntu SSO credentials"}
sample_secret = "secret83!"
yield coll.create_item("Cucaracha", attr, sample_secret)
items = yield self.secretservice.search_items(attr)
self.assertEqual(len(items), 1)
mock_item = self.mock_service.collections[collection_label].items[0]
mock_item.delete_fail = True
yield self.assertFailure(items[0].delete(),
dbus.exceptions.DBusException)
|