~mvo/ubuntu-sso-client/strawman-lp711413

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
# -*- coding: utf-8 -*-
#
# test_keyring - tests for ubuntu_sso.keyring
#
# Author: Alejandro J. Cura <alecu@canonical.com>
# Author: Natalia B. Bidart <natalia.bidart@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 the keyring.py module."""

import socket

from twisted.internet import defer
from twisted.internet.defer import inlineCallbacks
from twisted.trial.unittest import TestCase

from ubuntu_sso import keyring as common_keyring
from ubuntu_sso.keyring import linux as keyring
from ubuntu_sso.tests import APP_NAME


def build_fake_gethostname(fake_hostname):
    """Return a fake hostname getter."""
    return lambda *a: fake_hostname


class MockItem(object):
    """An item contains a secret, lookup attributes and has a label."""

    def __init__(self, label, collection, attr, value):
        """Initialize a new Item."""
        self.label = label
        self.collection = collection
        self.attributes = attr
        self.value = value

    def get_value(self):
        """Retrieve the secret for this item."""
        return defer.succeed(self.value)

    def delete(self):
        """Delete this item."""
        self.collection.items.remove(self)
        return defer.succeed(None)

    def matches(self, search_attr):
        """See if this item matches a given search."""
        for k, val in search_attr.items():
            if k not in self.attributes:
                return False
            if self.attributes[k] != val:
                return False
        return True


class MockCollection(object):
    """A collection of items containing secrets."""

    def __init__(self, label, service):
        """Initialize a new collection."""
        self.label = label
        self.service = service
        self.items = []

    def create_item(self, label, attr, value, replace=True):
        """Create an item with the given attributes, secret and label."""
        item = MockItem(label, self, attr, value)
        self.items.append(item)
        return defer.succeed(item)


class MockSecretService(object):
    """A class that mocks txsecrets.SecretService."""

    def __init__(self, *args, **kwargs):
        super(MockSecretService, self).__init__(*args, **kwargs)
        self.collections = {}

    def open_session(self, window_id=0):
        """Open a unique session for the caller application."""
        return defer.succeed(self)

    def search_items(self, attributes):
        """Find items in any collection."""
        results = []
        for collection in self.collections.values():
            for item in collection.items:
                if item.matches(attributes):
                    results.append(item)
        return defer.succeed(results)

    def create_collection(self, label):
        """Create a new collection with the specified properties."""
        collection = MockCollection(label, self)
        self.collections[label] = collection
        if "default" not in self.collections:
            self.collections["default"] = collection
        return defer.succeed(collection)

    def get_default_collection(self):
        """The collection were default items should be created."""
        if len(self.collections) == 0:
            self.create_collection("default")
        return defer.succeed(self.collections["default"])


class TestTokenNameBuilder(TestCase):
    """Test the method that builds the token name."""

    def test_get_simple_token_name(self):
        """A simple token name is built right."""
        sample_app_name = "UbuntuTwo"
        sample_hostname = "Darkstar"
        expected_result = "UbuntuTwo @ Darkstar"

        fake_gethostname = build_fake_gethostname(sample_hostname)
        self.patch(socket, "gethostname", fake_gethostname)
        result = keyring.get_token_name(sample_app_name)
        self.assertEqual(result, expected_result)

    def test_get_complex_token_name_for_app_name(self):
        """A complex token name is built right too."""
        sample_app_name = "Ubuntu @ Eleven"
        sample_hostname = "Mate+Cocido"
        expected_result = "Ubuntu @ Eleven @ Mate+Cocido"

        fake_gethostname = build_fake_gethostname(sample_hostname)
        self.patch(socket, "gethostname", fake_gethostname)
        result = keyring.get_token_name(sample_app_name)
        self.assertEqual(result, expected_result)

    def test_get_complex_token_name_for_hostname(self):
        """A complex token name is built right too."""
        sample_app_name = "Ubuntu Eleven"
        sample_hostname = "Mate @ Cocido"
        expected_result = "Ubuntu Eleven @ Mate AT Cocido"

        fake_gethostname = build_fake_gethostname(sample_hostname)
        self.patch(socket, "gethostname", fake_gethostname)
        result = keyring.get_token_name(sample_app_name)
        self.assertEqual(result, expected_result)


class TestKeyring(TestCase):
    """Test the keyring related functions."""

    timeout = 5

    def setUp(self):
        """Initialize the mock used in these tests."""
        self.mock_service = None
        self.service = self.patch(keyring, "SecretService",
                                  self.get_mock_service)
        fake_gethostname = build_fake_gethostname("darkstar")
        self.patch(socket, "gethostname", fake_gethostname)

    def get_mock_service(self):
        """Create only one instance of the mock service per test."""
        if self.mock_service == None:
            self.mock_service = MockSecretService()
        return self.mock_service

    @inlineCallbacks
    def test_set_credentials(self):
        """Test that the set method does not erase previous keys."""
        sample_creds = {"name": "sample creds name"}
        sample_creds2 = {"name": "sample creds name 2"}
        kr = keyring.Keyring()
        yield kr.set_credentials("appname", sample_creds)
        yield kr.set_credentials("appname", sample_creds2)

        # pylint: disable=E1101
        self.assertEqual(len(kr.service.collections["default"].items), 2)

    @inlineCallbacks
    def test_delete_credentials(self):
        """Test that a given key is deleted."""
        sample_creds = {"name": "sample creds name"}
        kr = keyring.Keyring()
        yield kr.set_credentials("appname", sample_creds)
        yield kr.delete_credentials("appname")

        # pylint: disable=E1101
        self.assertEqual(len(kr.service.collections["default"].items), 1)

    @inlineCallbacks
    def test_get_credentials(self):
        """Test that credentials are properly retrieved."""
        sample_creds = {"name": "sample creds name"}
        kr = keyring.Keyring()
        yield kr.set_credentials("appname", sample_creds)

        result = yield kr.get_credentials("appname")
        self.assertEqual(result, sample_creds)

    @inlineCallbacks
    def test_get_credentials_migrating_token(self):
        """Test that credentials are properly retrieved and migrated."""
        sample_creds = {"name": "sample creds name"}
        kr = keyring.Keyring()
        self.patch(keyring, "get_token_name", keyring.get_old_token_name)
        yield kr.set_credentials(APP_NAME, sample_creds)

        result = yield kr.get_credentials(APP_NAME)
        self.assertEqual(result, sample_creds)

    @inlineCallbacks
    def test_get_old_cred_found(self):
        """The method returns a new set of creds if old creds are found."""
        sample_oauth_token = "sample oauth token"
        sample_oauth_secret = "sample oauth secret"
        old_creds = {
            "oauth_token": sample_oauth_token,
            "oauth_token_secret": sample_oauth_secret,
        }
        u1kr = common_keyring.UbuntuOneOAuthKeyring()
        yield u1kr.set_credentials(keyring.U1_APP_NAME, old_creds)

        kr = keyring.Keyring()
        result = yield kr.get_credentials(keyring.U1_APP_NAME)
        self.assertIn("token", result)
        self.assertEqual(result["token"], sample_oauth_token)
        self.assertIn("token_secret", result)
        self.assertEqual(result["token_secret"], sample_oauth_secret)

    @inlineCallbacks
    def test_get_old_cred_found_but_not_asked_for(self):
        """Returns None if old creds are present but the appname is not U1"""
        sample_oauth_token = "sample oauth token"
        sample_oauth_secret = "sample oauth secret"
        old_creds = {
            "oauth_token": sample_oauth_token,
            "oauth_token_secret": sample_oauth_secret,
        }
        u1kr = common_keyring.UbuntuOneOAuthKeyring()
        yield u1kr.set_credentials(keyring.U1_APP_NAME, old_creds)

        kr = keyring.Keyring()
        result = yield kr.get_credentials("Software Center")
        self.assertEqual(result, None)

    @inlineCallbacks
    def test_get_old_cred_not_found(self):
        """The method returns None if no old nor new credentials found."""
        kr = keyring.Keyring()
        result = yield kr.get_credentials(keyring.U1_APP_NAME)
        self.assertEqual(result, None)