~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
# -*- 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/>.
"""
Provides a twisted interface to access the system keyring via DBus.
Implements the Secrets Service API Draft:
 * http://code.confuego.org/secrets-xdg-specs/
"""

import gobject
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import dbus.mainloop.glib
from twisted.internet.defer import Deferred

gobject.threads_init()
dbus.mainloop.glib.threads_init()
DBusGMainLoop(set_as_default=True)

BUS_NAME = "org.gnome.keyring"
SERVICE_IFACE = "org.freedesktop.Secret.Service"
PROMPT_IFACE = "org.freedesktop.Secret.Prompt"
SESSION_IFACE = "org.freedesktop.Secret.Session"
COLLECTION_IFACE = "org.freedesktop.Secret.Collection"
ITEM_IFACE = "org.freedesktop.Secret.Item"
SECRETS_SERVICE = "/org/freedesktop/secrets"
DEFAULT_COLLECTION = "/org/freedesktop/secrets/aliases/default"
ALGORITHM = "plain"
ALGORITHM_PARAMS = ""
LABEL_PROPERTY = "Label"
ATTRIBUTES_PROPERTY = "Attributes"


class UserCancelled(Exception):
    """The user cancelled a prompt."""


def no_op(*args):
    """Do nothing."""


class SecretService(object):
    """The Secret Service manages all the sessions and collections."""
    service = None
    session = None
    bus = None
    window_id = None

    def open_session(self, window_id=0):
        """Open a unique session for the caller application."""
        d = Deferred()
        try:
            self.window_id = str(window_id)
            self.bus = dbus.SessionBus()
            service_object = self.bus.get_object(BUS_NAME, SECRETS_SERVICE)
            self.service = dbus.Interface(service_object,
                                          dbus_interface=SERVICE_IFACE)

            def session_opened(result, session):
                """The session was successfully opened."""
                self.session = self.bus.get_object(BUS_NAME, session)
                d.callback(self)

            parameters = dbus.String(ALGORITHM_PARAMS, variant_level=1)
            self.service.OpenSession(ALGORITHM, parameters,
                                     reply_handler=session_opened,
                                     error_handler=d.errback)
        except dbus.exceptions.DBusException, e:
            d.errback(e)
        return d

    def do_prompt(self, prompt_path):
        """Show a prompt given its path."""
        d = Deferred()
        prompt_object = self.bus.get_object(BUS_NAME, prompt_path)
        prompt = dbus.Interface(prompt_object, dbus_interface=PROMPT_IFACE)

        def prompt_completed(dismissed, result):
            """The prompt was either completed or dismissed."""
            sigcompleted.remove()
            if dismissed:
                d.errback(UserCancelled())
            else:
                d.callback(result)

        sigcompleted = prompt.connect_to_signal("Completed", prompt_completed)
        prompt.Prompt(self.window_id,
                      reply_handler=no_op,
                      error_handler=d.errback)
        return d

    def make_item_list(self, object_path_list):
        """Make a list of items given their paths."""
        return [Item(self, o) for o in object_path_list]

    def search_items(self, attributes):
        """Find items in any collection."""
        # TODO: check if the lists of unlocked items found should be merged
        d = Deferred()

        def unlock_handler(unlocked, prompt):
            """The items were unlocked, or a prompt should be shown first."""
            if prompt != "/":
                self.do_prompt(prompt).chainDeferred(d)
            else:
                d.callback(unlocked)

        def items_found(unlocked, locked):
            """Called with two lists of found items."""
            if len(locked) > 0:
                self.service.Unlock(locked,
                                    reply_handler=unlock_handler,
                                    error_handler=d.errback)
            else:
                d.callback(unlocked)

        self.service.SearchItems(attributes,
                                 reply_handler=items_found,
                                 error_handler=d.errback)
        d.addCallback(self.make_item_list)
        return d

    def create_collection(self, label):
        """Create a new collection with the specified properties."""
        d = Deferred()

        def createcollection_handler(collection, prompt):
            """A collection was created, or a prompt should be shown first."""
            if prompt != "/":
                self.do_prompt(prompt).chainDeferred(d)
            else:
                d.callback(collection)

        properties = {LABEL_PROPERTY: dbus.String(label, variant_level=1)}
        self.service.CreateCollection(properties,
                                      reply_handler=createcollection_handler,
                                      error_handler=d.errback)

        d.addCallback(lambda p: Collection(self, p))
        return d

    def get_default_collection(self):
        """The collection were default items should be created."""
        return Collection(self, DEFAULT_COLLECTION)


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

    def __init__(self, service, object_path):
        """Initialize a new collection."""
        self.service = service
        collection_object = service.bus.get_object(BUS_NAME, object_path)
        self.collection_iface = dbus.Interface(collection_object,
                                               dbus_interface=COLLECTION_IFACE)

    def create_item(self, label, attr, value, replace=True):
        """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.
        """
        d = Deferred()

        def createitem_handler(item, prompt):
            """An item was created, or a prompt should be shown first."""
            if prompt != "/":
                self.service.do_prompt(prompt).chainDeferred(d)
            else:
                d.callback(item)

        properties = dbus.Dictionary(signature="sv")
        properties[LABEL_PROPERTY] = label
        attributes = dbus.Dictionary(attr, signature="ss")
        properties[ATTRIBUTES_PROPERTY] = attributes
        parameters = dbus.ByteArray(ALGORITHM_PARAMS)
        value_bytes = dbus.ByteArray(value)
        secret = (self.service.session, parameters, value_bytes)
        self.collection_iface.CreateItem(properties, secret, replace,
                                         reply_handler=createitem_handler,
                                         error_handler=d.errback)
        return d


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

    def __init__(self, service, object_path):
        """Initialize this new Item."""
        self.service = service
        item_object = service.bus.get_object(BUS_NAME, object_path)
        self.item_iface = dbus.Interface(item_object,
                                         dbus_interface=ITEM_IFACE)

    def get_value(self):
        """Retrieve the secret for this item."""
        d = Deferred()

        def getsecret_handler(secret):
            """The secret for this item was found."""
            # pylint: disable=W0612
            session, parameters, value = secret
            d.callback(value)

        self.item_iface.GetSecret(self.service.session, byte_arrays=True,
                                  reply_handler=getsecret_handler,
                                  error_handler=d.errback)
        return d

    def delete(self):
        """Delete this item."""
        d = Deferred()

        def delete_handler(prompt):
            """The item was deleted, or a prompt should be shown first."""
            if prompt != "/":
                self.service.do_prompt(prompt).chainDeferred(d)
            else:
                d.callback(True)

        self.item_iface.Delete(reply_handler=delete_handler,
                               error_handler=d.errback)
        return d