[libgnome-keyring] Better testing, and build tweaks
- From: Stefan Walter <stefw src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [libgnome-keyring] Better testing, and build tweaks
- Date: Tue, 31 Jan 2012 12:50:09 +0000 (UTC)
commit 612830913ba26f9f54395636a23beee3ea3f33c9
Author: Stef Walter <stefw gnome org>
Date: Tue Jan 31 11:05:21 2012 +0100
Better testing, and build tweaks
* Use python mock service to test against
* Fix up some compatibility issues
* Add debug messages for some operations
* Add --enable-strict to build with strict rules
* Build debug stuff by default, --enable-debug to disable optimizations
* Run tests with GNOME_KEYRING_TEST_SERVICE=org.freedesktop.secrets
to run against a running daemon
configure.ac | 58 ++--
egg/Makefile.am | 8 +-
library/Makefile.am | 16 +-
library/gkr-debug.c | 1 +
library/gkr-debug.h | 1 +
library/gkr-misc.c | 53 +++-
library/gkr-misc.h | 6 +-
library/gkr-operation.c | 30 +-
library/gkr-operation.h | 2 +
library/gkr-session.c | 4 +-
library/gnome-keyring.c | 160 ++++++---
library/tests/Makefile.am | 21 +-
library/tests/mock-service-normal.py | 59 +++
library/tests/mock-service.c | 93 +++++
library/tests/mock-service.h | 27 ++
library/tests/mock/__init__.py | 1 +
library/tests/mock/aes.py | 656 ++++++++++++++++++++++++++++++++
library/tests/mock/dh.py | 81 ++++
library/tests/mock/hkdf.py | 86 +++++
library/tests/mock/service.py | 679 ++++++++++++++++++++++++++++++++++
library/tests/test-keyrings.c | 107 ++----
21 files changed, 1944 insertions(+), 205 deletions(-)
---
diff --git a/configure.ac b/configure.ac
index 0addf28..fa7418d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -134,26 +134,29 @@ AC_SUBST([LIBGCRYPT_LIBS])
# Debug mode
#
+AC_MSG_CHECKING([for debug mode])
AC_ARG_ENABLE(debug,
- AC_HELP_STRING([--enable-debug=no/yes/full],
+ AC_HELP_STRING([--enable-debug=no/default/yes],
[Turn on or off debugging]))
if test "$enable_debug" != "no"; then
AC_DEFINE_UNQUOTED(WITH_DEBUG, 1, [Print debug output])
+ AC_DEFINE_UNQUOTED(_DEBUG, 1, [In debug mode])
+ CFLAGS="$CFLAGS -g"
fi
-if test "$enable_debug" = "full"; then
- debug_status="full"
- CFLAGS="$CFLAGS -g -O0 -Werror"
- CFLAGS="$CFLAGS -DG_DISABLE_DEPRECATED -DGDK_PIXBUF_DISABLE_DEPRECATED"
- CFLAGS="$CFLAGS -DGDK_DISABLE_DEPRECATED -DGTK_DISABLE_DEPRECATED"
+if test "$enable_debug" = "yes"; then
+ debug_status="yes (-g, -O0, debug output, testable)"
+ CFLAGS="$CFLAGS -O0"
elif test "$enable_debug" = "no"; then
- debug_status="no"
+ debug_status="no (no debug output, not testable, G_DISABLE_ASSERT)"
AC_DEFINE_UNQUOTED(G_DISABLE_ASSERT, 1, [Disable glib assertions])
else
- debug_status="yes"
+ debug_status="default (-g, debug output, testable)"
fi
+AC_MSG_RESULT($debug_status)
+
AC_MSG_CHECKING(for more warnings)
if test "$enale_debug" != "no" -a "$GCC" = "yes"; then
AC_MSG_RESULT(yes)
@@ -183,33 +186,32 @@ else
AC_MSG_RESULT(no)
fi
-# --------------------------------------------------------------------
-# Tests and Unit Tests
-
-AC_ARG_ENABLE(tests,
- AC_HELP_STRING([--enable-tests=yes/no/full],
- [Build tests and testing tools. default: yes]))
+AC_ARG_ENABLE(strict, [
+ AS_HELP_STRING([--enable-strict], [Strict code compilation])
+ ])
-AC_MSG_CHECKING([build test tools, unit tests, and -Werror])
+AC_MSG_CHECKING([build strict])
-if test "$enable_tests" = "full"; then
- tests_status="full"
- CFLAGS="$CFLAGS -Werror"
+if test "$enable_strict" = "yes"; then
+ CFLAGS="$CFLAGS -Werror \
+ -DGTK_DISABLE_DEPRECATED \
+ -DGDK_DISABLE_DEPRECATED \
+ -DG_DISABLE_DEPRECATED \
+ -DGDK_PIXBUF_DISABLE_DEPRECATED"
TEST_MODE="thorough"
- AC_DEFINE_UNQUOTED(WITH_TESTABLE, 1, [Build extra hooks for more testable code])
-elif test "$enable_tests" = "no"; then
- tests_status="no"
+ INTROSPECTION_FLAGS="--warn-error"
+ AC_DEFINE_UNQUOTED(WITH_STRICT, 1, [More strict checks])
+ strict_status="yes (-Werror, thorough tests, fatals, no deprecations)"
else
TEST_MODE="quick"
- tests_status="yes"
+ INTROSPECTION_FLAGS=""
+ strict_status="no (quick tests, non-fatal warnings)"
fi
-AC_MSG_RESULT($tests_status)
-AC_SUBST(TEST_MODE)
-AM_CONDITIONAL(WITH_TESTS, test "$enable_tests" != "no")
+AC_MSG_RESULT($strict_status)
-AC_PATH_PROG(GNOME_KEYRING_DAEMON_PATH, gnome-keyring-daemon, "gnome-keyring-daemon")
-AC_DEFINE_UNQUOTED(GNOME_KEYRING_DAEMON_PATH, "$GNOME_KEYRING_DAEMON_PATH", [Path to gnome-keyring-daemon])
+AC_SUBST(INTROSPECTION_FLAGS)
+AC_SUBST(TEST_MODE)
# ----------------------------------------------------------------------
# Status
@@ -241,5 +243,5 @@ echo
echo "OPTIONS:"
echo " Introspection: $found_introspection"
echo " Debug Build: $debug_status"
-echo " Tests: $tests_status"
+echo " Strict Build: $strict_status"
echo
diff --git a/egg/Makefile.am b/egg/Makefile.am
index ee0c111..1d26530 100644
--- a/egg/Makefile.am
+++ b/egg/Makefile.am
@@ -21,10 +21,4 @@ libegg_la_SOURCES = \
# -------------------------------------------------------------------
-if WITH_TESTS
-TESTS_DIR = tests
-else
-TESTS_DIR =
-endif
-
-SUBDIRS = . $(TESTS_DIR)
+SUBDIRS = . tests
diff --git a/library/Makefile.am b/library/Makefile.am
index a8fd0ee..04049ca 100644
--- a/library/Makefile.am
+++ b/library/Makefile.am
@@ -41,6 +41,13 @@ libgnome_keyring_la_LDFLAGS = \
-version-info $(LIB_GNOME_KEYRING_LT_VERSION) \
-no-undefined -export-symbols-regex 'gnome_keyring_|GNOME_KEYRING_'
+noinst_LTLIBRARIES = libgnome-keyring-testable.la
+libgnome_keyring_testable_la_SOURCES =
+libgnome_keyring_testable_la_LIBADD = \
+ $(libgnome_keyring_la_OBJECTS) \
+ $(libgnome_keyring_la_LIBADD)
+libgnome_keyring_testable_la_DEPENDENCIES = $(libgnome_keyring_la_OBJECTS)
+
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = gnome-keyring-1.pc
@@ -75,11 +82,4 @@ typelib_DATA = $(INTROSPECTION_GIRS:.gir=.typelib)
CLEANFILES += $(gir_DATA) $(typelib_DATA)
endif
-if WITH_TESTS
-TESTS_DIR = tests
-else
-TESTS_DIR =
-endif
-
-SUBDIRS = . \
- $(TESTS_DIR)
+SUBDIRS = . tests
diff --git a/library/gkr-debug.c b/library/gkr-debug.c
index 68123e6..0b36dbc 100644
--- a/library/gkr-debug.c
+++ b/library/gkr-debug.c
@@ -41,6 +41,7 @@ static GkrDebugFlags current_flags = 0;
static GDebugKey keys[] = {
{ "operation", GKR_DEBUG_OPERATION },
+ { "methods", GKR_DEBUG_METHODS },
{ 0, }
};
diff --git a/library/gkr-debug.h b/library/gkr-debug.h
index 757b5cb..60e4f88 100644
--- a/library/gkr-debug.h
+++ b/library/gkr-debug.h
@@ -29,6 +29,7 @@ G_BEGIN_DECLS
/* Please keep this enum in sync with #keys in gkr-debug.c */
typedef enum {
GKR_DEBUG_OPERATION = 1 << 1,
+ GKR_DEBUG_METHODS = 1 << 2,
} GkrDebugFlags;
gboolean gkr_debug_flag_is_set (GkrDebugFlags flag);
diff --git a/library/gkr-misc.c b/library/gkr-misc.c
index 5f20bcd..9cb50ec 100644
--- a/library/gkr-misc.c
+++ b/library/gkr-misc.c
@@ -45,16 +45,8 @@
* The type of item info to retrieve with gnome_keyring_item_get_info_full().
*/
-const gchar*
-gkr_service_name (void)
-{
-#ifdef WITH_TESTABLE
- const gchar *service = g_getenv ("GNOME_KEYRING_TEST_SERVICE");
- if (service && service[0])
- return service;
-#endif
- return SECRETS_SERVICE;
-}
+/* Exposed via gkr-misc.h */
+const gchar *gkr_service_name = SECRETS_SERVICE;
static void
encode_object_identifier (GString *string, const gchar* name, gssize length)
@@ -235,3 +227,44 @@ gkr_decode_keyring_item_id (const char *path, guint32* id)
return result;
}
+
+gchar *
+gkr_attributes_print (GnomeKeyringAttributeList *attrs)
+{
+ GnomeKeyringAttribute *attr;
+ GString *string;
+ guint i;
+
+ if (attrs == NULL)
+ return g_strdup ("(null)");
+
+ string = g_string_new ("{ ");
+
+ for (i = 0; attrs && i < attrs->len; ++i) {
+ if (i > 0)
+ g_string_append (string, ", ");
+
+ attr = &gnome_keyring_attribute_list_index (attrs, i);
+
+ /* Add in the attribute type */
+ g_string_append (string, attr->name ? attr->name : "(null)");
+ g_string_append (string, ": ");
+
+ /* String values */
+ if (attr->type == GNOME_KEYRING_ATTRIBUTE_TYPE_STRING) {
+ g_string_append_c (string, '"');
+ g_string_append (string, attr->value.string ? attr->value.string : "");
+ g_string_append_c (string, '"');
+
+ /* Integer values */
+ } else if (attr->type == GNOME_KEYRING_ATTRIBUTE_TYPE_UINT32) {
+ g_string_append_printf (string, "%u", (guint)attr->value.integer);
+
+ } else {
+ g_string_append (string, "???");
+ }
+ }
+
+ g_string_append (string, " }");
+ return g_string_free (string, FALSE);
+}
diff --git a/library/gkr-misc.h b/library/gkr-misc.h
index 195c0d4..0a9f629 100644
--- a/library/gkr-misc.h
+++ b/library/gkr-misc.h
@@ -24,9 +24,11 @@
#ifndef GKR_MISC_H
#define GKR_MISC_H
+#include "gnome-keyring.h"
+
#include <glib.h>
-const gchar* gkr_service_name (void);
+extern const gchar * gkr_service_name;
gchar* gkr_encode_keyring_name (const gchar *keyring);
@@ -43,4 +45,6 @@ gchar* gkr_decode_keyring_item_id (const char *path,
gboolean gkr_decode_is_keyring (const char *path);
+gchar * gkr_attributes_print (GnomeKeyringAttributeList *attrs);
+
#endif /* GKR_MISC_H */
diff --git a/library/gkr-operation.c b/library/gkr-operation.c
index 85385c1..d3792b3 100644
--- a/library/gkr-operation.c
+++ b/library/gkr-operation.c
@@ -38,6 +38,7 @@
/* Exposed in gkr-operation.h */
gboolean gkr_inited = FALSE;
+int gkr_timeout = -1;
static DBusConnection *dbus_connection = NULL;
G_LOCK_DEFINE_STATIC(dbus_connection);
@@ -293,7 +294,7 @@ on_connection_filter (DBusConnection *connection,
DBUS_TYPE_INVALID)) {
/* See if it's the secret service going away */
- if (object_name && g_str_equal (gkr_service_name (), object_name) &&
+ if (object_name && g_str_equal (gkr_service_name, object_name) &&
new_owner && g_str_equal ("", new_owner)) {
/* Clear any session, when the service goes away */
@@ -406,23 +407,17 @@ on_pending_call_notify (DBusPendingCall *pending, void *user_data)
static void
send_with_pending (GkrOperation *op)
{
- int timeout = -1;
-
g_assert (op);
g_assert (op->request);
g_assert (!op->pending);
-#if WITH_TESTABLE
- timeout = INT_MAX;
-#endif
-
if (!op->conn)
op->conn = connect_to_service ();
if (op->conn) {
gkr_debug ("%p: sending request", op);
if (!dbus_connection_send_with_reply (op->conn, op->request,
- &op->pending, timeout))
+ &op->pending, gkr_timeout))
g_return_if_reached ();
dbus_message_unref (op->request);
op->request = NULL;
@@ -516,14 +511,9 @@ GnomeKeyringResult
gkr_operation_block_and_unref (GkrOperation *op)
{
DBusMessage *reply = NULL;
- int timeout = -1;
g_return_val_if_fail (op, BROKEN);
-#if WITH_TESTABLE
- timeout = INT_MAX;
-#endif
-
gkr_debug ("%p: processing", op);
g_assert (!op->pending);
@@ -540,7 +530,7 @@ gkr_operation_block_and_unref (GkrOperation *op)
/* A dbus request, then send and wait for reply */
} else if (op->request) {
gkr_debug ("%p: blocking request", op);
- reply = send_with_reply_and_block (op->conn, op->request, timeout);
+ reply = send_with_reply_and_block (op->conn, op->request, gkr_timeout);
dbus_message_unref (op->request);
op->request = NULL;
@@ -587,6 +577,8 @@ gkr_operation_handle_errors (GkrOperation *op, DBusMessage *reply)
DBusError derr = DBUS_ERROR_INIT;
GnomeKeyringResult res;
gboolean was_keyring;
+ gboolean no_such_object;
+ gboolean unknown_method;
g_assert (op);
g_assert (reply);
@@ -595,8 +587,12 @@ gkr_operation_handle_errors (GkrOperation *op, DBusMessage *reply)
op->was_keyring = FALSE;
if (dbus_set_error_from_message (&derr, reply)) {
- if (dbus_error_has_name (&derr, ERROR_NO_SUCH_OBJECT)) {
+ no_such_object = dbus_error_has_name (&derr, ERROR_NO_SUCH_OBJECT);
+ unknown_method = dbus_error_has_name (&derr, DBUS_ERROR_UNKNOWN_METHOD);
+ if (no_such_object || (was_keyring && unknown_method)) {
gkr_debug ("%p: no-such-object", op);
+ if (unknown_method)
+ gkr_debug ("unknown method: %s", derr.message);
if (was_keyring)
res = GNOME_KEYRING_RESULT_NO_SUCH_KEYRING;
else
@@ -686,7 +682,7 @@ on_prompt_signal (DBusConnection *connection, DBusMessage *message, void *user_d
DBUS_TYPE_INVALID)) {
/* See if it's the secret service going away */
- if (object_name && g_str_equal (gkr_service_name (), object_name) &&
+ if (object_name && g_str_equal (gkr_service_name, object_name) &&
new_owner && g_str_equal ("", new_owner)) {
g_message ("secret service disappeared while waiting for prompt");
@@ -746,7 +742,7 @@ gkr_operation_prompt (GkrOperation *op, const gchar *prompt)
dbus_connection_add_filter (op->conn, on_prompt_signal, args,
on_prompt_completed);
- req = dbus_message_new_method_call (gkr_service_name (), prompt,
+ req = dbus_message_new_method_call (gkr_service_name, prompt,
PROMPT_INTERFACE, "Prompt");
window_id = "";
diff --git a/library/gkr-operation.h b/library/gkr-operation.h
index 3cf4030..c541320 100644
--- a/library/gkr-operation.h
+++ b/library/gkr-operation.h
@@ -81,6 +81,8 @@ void gkr_operation_prompt (GkrOperation *op,
extern gboolean gkr_inited;
+extern int gkr_timeout;
+
#define gkr_init() do { if (!gkr_inited) gkr_operation_init (); } while (0)
void gkr_operation_init (void);
diff --git a/library/gkr-session.c b/library/gkr-session.c
index 60041b2..38cce46 100644
--- a/library/gkr-session.c
+++ b/library/gkr-session.c
@@ -207,7 +207,7 @@ session_negotiate_plain (GkrOperation *op)
g_assert (op);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "OpenSession");
dbus_message_iter_init_append (req, &iter);
dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &algorithm);
@@ -349,7 +349,7 @@ session_negotiate_aes (GkrOperation *op)
gcry_mpi_release (base);
if (ret == TRUE) {
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "OpenSession");
dbus_message_iter_init_append (req, &iter);
diff --git a/library/gnome-keyring.c b/library/gnome-keyring.c
index 6dc6b4b..ccd7019 100644
--- a/library/gnome-keyring.c
+++ b/library/gnome-keyring.c
@@ -25,7 +25,9 @@
#include "config.h"
+#define DEBUG_FLAG GKR_DEBUG_OPERATION
#include "gkr-callback.h"
+#include "gkr-debug.h"
#include "gkr-misc.h"
#include "gkr-operation.h"
#include "gkr-session.h"
@@ -72,7 +74,7 @@ prepare_property_get (const gchar *path, const gchar *interface, const gchar *na
if (!interface)
interface = "";
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
DBUS_INTERFACE_PROPERTIES, "Get");
dbus_message_append_args (req, DBUS_TYPE_STRING, &interface,
DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
@@ -90,7 +92,7 @@ prepare_property_getall (const gchar *path, const gchar *interface)
if (!interface)
interface = "";
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
DBUS_INTERFACE_PROPERTIES, "GetAll");
dbus_message_append_args (req, DBUS_TYPE_STRING, &interface, DBUS_TYPE_INVALID);
@@ -106,7 +108,7 @@ prepare_get_secret (GkrSession *session, const char *path)
g_assert (session);
g_assert (path);
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
ITEM_INTERFACE, "GetSecret");
spath = gkr_session_get_path (session);
@@ -123,7 +125,7 @@ prepare_get_secrets (GkrSession *session, char **paths, int n_paths)
g_assert (session);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "GetSecrets");
spath = gkr_session_get_path (session);
@@ -138,7 +140,7 @@ prepare_xlock (const char *action, char **objects, int n_objects)
{
DBusMessage *req;
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, action);
dbus_message_append_args (req, DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH, &objects, n_objects,
@@ -492,7 +494,7 @@ gnome_keyring_is_available (void)
gkr_init ();
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
DBUS_INTERFACE_PEER, "Ping");
op = gkr_operation_new (gkr_callback_empty, GKR_CALLBACK_RES, NULL, NULL);
@@ -550,7 +552,7 @@ set_default_keyring_start (const gchar *keyring, GnomeKeyringOperationDoneCallba
g_return_val_if_fail (callback, NULL);
path = gkr_encode_keyring_name (keyring);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "SetAlias");
string = "default";
@@ -668,7 +670,7 @@ get_default_keyring_start (GnomeKeyringOperationGetStringCallback callback,
g_return_val_if_fail (callback, NULL);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "ReadAlias");
string = "default";
@@ -872,7 +874,7 @@ lock_all_start (GnomeKeyringOperationDoneCallback callback,
g_return_val_if_fail (callback, NULL);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "LockService");
op = gkr_operation_new (callback, GKR_CALLBACK_RES, data, destroy_data);
@@ -969,7 +971,7 @@ create_keyring_password_reply (GkrOperation *op, GkrSession *session, gpointer u
DBusMessageIter iter;
DBusMessage *req;
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
"org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface",
"CreateWithMasterPassword");
@@ -1021,7 +1023,8 @@ create_keyring_check_reply (GkrOperation *op, DBusMessage *reply, gpointer user_
const gchar *alias = "";
/* If no such object, then no such keyring exists and we're good to go. */
- if (!dbus_message_is_error (reply, ERROR_NO_SUCH_OBJECT)) {
+ if (!dbus_message_is_error (reply, ERROR_NO_SUCH_OBJECT) &&
+ !dbus_message_is_error (reply, DBUS_ERROR_UNKNOWN_METHOD)) {
/* Success means 'already exists' */
if (!gkr_operation_handle_errors (op, reply))
gkr_operation_complete (op, GNOME_KEYRING_RESULT_ALREADY_EXISTS);
@@ -1035,7 +1038,7 @@ create_keyring_check_reply (GkrOperation *op, DBusMessage *reply, gpointer user_
/* Otherwiswe just create the collection */
} else {
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "CreateCollection");
dbus_message_iter_init_append (req, &iter);
create_keyring_encode_properties (&iter, args->keyring_name);
@@ -1173,10 +1176,13 @@ xlock_2_reply (GkrOperation *op, DBusMessage *reply, gpointer user_data)
return;
}
- if (dismissed || !args.matched)
+ if (dismissed || !args.matched) {
+ gkr_debug ("xlock prompt dismissed");
gkr_operation_complete (op, GNOME_KEYRING_RESULT_DENIED);
- else
+ } else {
+ gkr_debug ("xlock prompt completed");
gkr_operation_complete (op, GNOME_KEYRING_RESULT_OK);
+ }
}
static void
@@ -1189,22 +1195,26 @@ xlock_1_reply (GkrOperation *op, DBusMessage *reply, gpointer user_data)
return;
if (!decode_xlock_reply (reply, &prompt, xlock_check_path, &args)) {
+ gkr_debug ("invalid response to xlock");
gkr_operation_complete (op, decode_invalid_response (reply));
return;
}
if (args.matched) {
+ gkr_debug ("xlocked without prompt");
gkr_callback_invoke_res (gkr_operation_pop (op), GNOME_KEYRING_RESULT_OK);
return;
}
/* Is there a prompt needed? */
if (!g_str_equal (prompt, "/")) {
+ gkr_debug ("prompting for xlock");
gkr_operation_push (op, xlock_2_reply, GKR_CALLBACK_OP_MSG, user_data, NULL);
gkr_operation_prompt (op, prompt);
/* No prompt, and no opportunity to */
} else {
+ gkr_debug ("couldn't unlock the keyring, and no prompt");
gkr_callback_invoke_res (gkr_operation_pop (op), GNOME_KEYRING_RESULT_NO_SUCH_KEYRING);
}
}
@@ -1219,6 +1229,8 @@ xlock_async (const gchar *method, const gchar *keyring,
gchar *path;
path = gkr_encode_keyring_name (keyring);
+
+ gkr_debug ("xlock operation without password, probable prompt %s", path);
req = prepare_xlock (method, &path, 1);
op = gkr_operation_new (callback, GKR_CALLBACK_RES, data, destroy_data);
@@ -1251,7 +1263,9 @@ unlock_password_reply (GkrOperation *op, GkrSession *session, gpointer user_data
DBusMessage *req;
gchar *path;
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ gkr_debug ("have session, unlocking with password");
+
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
"org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface",
"UnlockWithMasterPassword");
@@ -1284,6 +1298,7 @@ unlock_keyring_start (const char *keyring, const char *password,
return xlock_async ("Unlock", keyring, callback, data, destroy_data);
g_return_val_if_fail (callback, NULL);
+ gkr_debug ("unlocking with password");
op = gkr_operation_new (callback, GKR_CALLBACK_RES, data, destroy_data);
@@ -1447,7 +1462,7 @@ delete_keyring_start (const char *keyring, GnomeKeyringOperationDoneCallback cal
g_return_val_if_fail (callback, NULL);
path = gkr_encode_keyring_name (keyring);
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
COLLECTION_INTERFACE, "Delete");
op = gkr_operation_new (callback, GKR_CALLBACK_RES, data, destroy_data);
@@ -1535,7 +1550,7 @@ change_password_reply (GkrOperation *op, GkrSession *session, gpointer user_data
DBusMessage *req;
gchar *path;
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
"org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface",
"ChangeWithMasterPassword");
@@ -1629,7 +1644,7 @@ change_password_start (const char *keyring, const char *original, const char *pa
gkr_session_negotiate (op);
} else {
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "ChangeLock");
path = gkr_encode_keyring_name (keyring);
dbus_message_append_args (req, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID);
@@ -1709,11 +1724,30 @@ gnome_keyring_change_password_sync (const char *keyring_name,
}
static gboolean
+decode_time_from_iter (DBusMessageIter *iter,
+ time_t *tval)
+{
+ dbus_int64_t i64val;
+ dbus_uint64_t ui64val;
+
+ if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_INT64) {
+ dbus_message_iter_get_basic (iter, &i64val);
+ *tval = (time_t)i64val;
+ } else if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UINT64) {
+ dbus_message_iter_get_basic (iter, &ui64val);
+ *tval = (time_t)ui64val;
+ } else {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+static gboolean
get_keyring_info_foreach (const gchar *property, DBusMessageIter *iter, gpointer user_data)
{
GnomeKeyringInfo *info = user_data;
dbus_bool_t bval;
- dbus_int64_t i64val;
if (g_str_equal (property, "Locked")) {
if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_BOOLEAN)
@@ -1722,16 +1756,18 @@ get_keyring_info_foreach (const gchar *property, DBusMessageIter *iter, gpointer
info->is_locked = (bval == TRUE);
} else if (g_str_equal (property, "Created")) {
- if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT64)
+ if (!decode_time_from_iter (iter, &info->ctime)) {
+ gkr_debug ("invalid Created property type: %s",
+ dbus_message_iter_get_signature (iter));
return FALSE;
- dbus_message_iter_get_basic (iter, &i64val);
- info->ctime = (time_t)i64val;
+ }
} else if (g_str_equal (property, "Modified")) {
- if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT64)
+ if (!decode_time_from_iter (iter, &info->mtime)) {
+ gkr_debug ("invalid Modified property type: %s",
+ dbus_message_iter_get_signature (iter));
return FALSE;
- dbus_message_iter_get_basic (iter, &i64val);
- info->ctime = (time_t)i64val;
+ }
}
return TRUE;
@@ -1779,6 +1815,8 @@ get_keyring_info_start (const char *keyring, GnomeKeyringOperationGetKeyringInfo
g_return_val_if_fail (callback, NULL);
path = gkr_encode_keyring_name (keyring);
+
+ gkr_debug ("getting info for keyring: %s", path);
req = prepare_property_getall (path, COLLECTION_INTERFACE);
op = gkr_operation_new (callback, GKR_CALLBACK_RES_KEYRING_INFO, data, destroy_data);
@@ -2452,7 +2490,7 @@ find_items_start (GnomeKeyringItemType type, GnomeKeyringAttributeList *attribut
g_return_val_if_fail (attributes, NULL);
g_return_val_if_fail (callback, NULL);
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "SearchItems");
/* Encode the attribute list */
@@ -2750,7 +2788,7 @@ item_create_prepare (const gchar *path, GnomeKeyringItemType type, const gchar *
const char *string;
const gchar *type_string;
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
COLLECTION_INTERFACE, "CreateItem");
dbus_message_iter_init_append (req, iter);
@@ -2807,10 +2845,12 @@ item_create_3_created_reply (GkrOperation *op, DBusMessage *reply, gpointer data
}
if (!gkr_decode_item_id (path, &id)) {
+ gkr_debug ("couldn't decode item item path %s", path);
gkr_operation_complete (op, GNOME_KEYRING_RESULT_IO_ERROR);
return;
}
+ gkr_debug ("new item id %u for path %s", (guint)id, path);
gkr_callback_invoke_ok_uint (gkr_operation_pop (op), id);
}
@@ -2822,6 +2862,8 @@ item_create_2_session_reply (GkrOperation *op, GkrSession *session, gpointer dat
item_create_args *args = data;
dbus_bool_t replace;
+ gkr_debug ("have session, encoding secret");
+
if (!gkr_session_encode_secret (session, &args->iter, args->secret)) {
gkr_operation_complete (op, BROKEN);
g_return_if_reached ();
@@ -2830,6 +2872,8 @@ item_create_2_session_reply (GkrOperation *op, GkrSession *session, gpointer dat
replace = args->update_if_exists;
dbus_message_iter_append_basic (&args->iter, DBUS_TYPE_BOOLEAN, &replace);
+ gkr_debug ("creating item");
+
gkr_operation_push (op, item_create_3_created_reply, GKR_CALLBACK_OP_MSG, NULL, NULL);
gkr_operation_set_keyring_hint (op);
gkr_operation_request (op, args->request);
@@ -2840,6 +2884,8 @@ item_create_2_session_request (GkrOperation *op, gpointer data)
{
/* Called to get us a valid session */
+ gkr_debug ("requesting session");
+
gkr_operation_push (op, item_create_2_session_reply, GKR_CALLBACK_OP_SESSION, data, NULL);
gkr_session_negotiate (op);
}
@@ -2881,6 +2927,8 @@ item_create_1_create_prompt_reply (GkrOperation *op, DBusMessage *reply, gpointe
g_return_if_fail (dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_OBJECT_PATH);
dbus_message_iter_get_basic (&variant, &path);
+ gkr_debug ("created default keyring: %s", path);
+
/* Start the session */
item_create_2_session_request (op, data);
}
@@ -2907,10 +2955,12 @@ item_create_1_collection_reply (GkrOperation *op, DBusMessage *reply, gpointer d
/* No prompt, set keyring as default */
g_return_if_fail (prompt);
if (g_str_equal (prompt, "/")) {
+ gkr_debug ("created default keyring: %s", collection);
item_create_2_session_request (op, data);
/* A prompt, display it get the response */
} else {
+ gkr_debug ("prompting to create default keyring: %s", prompt);
gkr_operation_push (op, item_create_1_create_prompt_reply, GKR_CALLBACK_OP_MSG, data, NULL);
gkr_operation_prompt (op, prompt);
}
@@ -2937,10 +2987,13 @@ item_create_1_unlock_prompt_reply (GkrOperation *op, DBusMessage *reply, gpointe
}
if (dismissed || !unlocked) {
+ gkr_debug ("unlock prompt dismissed or not unlocked");
gkr_operation_complete (op, GNOME_KEYRING_RESULT_DENIED);
return;
}
+ gkr_debug ("keyring unlocked");
+
/* Now that its unlocked, we need a session to transfer the secret */
item_create_2_session_request (op, data);
}
@@ -2967,6 +3020,7 @@ item_create_1_unlock_reply (GkrOperation *op, DBusMessage *reply, gpointer data)
/* Prompt to unlock the collection */
if (!g_str_equal (prompt, "/")) {
+ gkr_debug ("prompting to unlock the keyring: %s", prompt);
gkr_operation_push (op, item_create_1_unlock_prompt_reply, GKR_CALLBACK_OP_MSG, args, NULL);
gkr_operation_prompt (op, prompt);
@@ -2975,7 +3029,8 @@ item_create_1_unlock_reply (GkrOperation *op, DBusMessage *reply, gpointer data)
/* Caller asked for default keyring, and there is no such keyring. Create */
if (args->is_default) {
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ gkr_debug ("no such default keyring, creating");
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "CreateCollection");
dbus_message_iter_init_append (req, &iter);
/* TRANSLATORS: This is the name of an automatically created default keyring. */
@@ -2987,11 +3042,13 @@ item_create_1_unlock_reply (GkrOperation *op, DBusMessage *reply, gpointer data)
/* No such keyring, error */
} else {
+ gkr_debug ("no such keyring");
gkr_operation_complete (op, GNOME_KEYRING_RESULT_NO_SUCH_KEYRING);
}
/* Successfully unlocked, or not locked. We need a session to transfer the secret */
} else {
+ gkr_debug ("unlocked keyring");
item_create_2_session_request (op, args);
}
}
@@ -3007,8 +3064,10 @@ item_create_start (const char *keyring, GnomeKeyringItemType type, const char *d
GkrOperation *op;
gchar *path;
- if (!display_name)
+ if (!display_name) {
+ gkr_debug ("creating item with blank label");
display_name = "";
+ }
args = g_slice_new0 (item_create_args);
args->update_if_exists = update_if_exists;
@@ -3020,6 +3079,7 @@ item_create_start (const char *keyring, GnomeKeyringItemType type, const char *d
g_return_val_if_fail (args->request, NULL);
/* First unlock the keyring */
+ gkr_debug ("unlocking the keyring: %s", path);
req = prepare_xlock ("Unlock", &path, 1);
g_free (path);
@@ -3143,7 +3203,7 @@ item_delete_start (const char *keyring, guint32 id, GnomeKeyringOperationDoneCal
gchar *path;
path = gkr_encode_keyring_item_id (keyring, id);
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
ITEM_INTERFACE, "Delete");
op = gkr_operation_new (callback, GKR_CALLBACK_RES, data, destroy_data);
@@ -3285,7 +3345,6 @@ item_get_info_foreach (const gchar *property, DBusMessageIter *iter, gpointer us
{
GnomeKeyringItemInfo *info = user_data;
const char *sval;
- dbus_int64_t i64val;
if (g_str_equal (property, "Label")) {
if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_STRING)
@@ -3294,17 +3353,17 @@ item_get_info_foreach (const gchar *property, DBusMessageIter *iter, gpointer us
info->display_name = g_strdup (sval);
} else if (g_str_equal (property, "Created")) {
- if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT64)
+ if (!decode_time_from_iter (iter, &info->ctime)) {
+ gkr_debug ("invalid Created property type: %s",
+ dbus_message_iter_get_signature (iter));
return FALSE;
- dbus_message_iter_get_basic (iter, &i64val);
- info->ctime = (time_t)i64val;
-
+ }
} else if (g_str_equal (property, "Modified")) {
- if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_INT64)
+ if (!decode_time_from_iter (iter, &info->mtime)) {
+ gkr_debug ("invalid Modified property type: %s",
+ dbus_message_iter_get_signature (iter));
return FALSE;
- dbus_message_iter_get_basic (iter, &i64val);
- info->mtime = (time_t)i64val;
-
+ }
} else if (g_str_equal (property, "Type")) {
if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_STRING)
return FALSE;
@@ -3392,7 +3451,7 @@ item_get_info_2_reply (GkrOperation *op, GkrSession *session, gpointer data)
g_assert (!args->session);
args->session = gkr_session_ref (session);
- req = dbus_message_new_method_call (gkr_service_name (), args->path, ITEM_INTERFACE, "GetSecret");
+ req = dbus_message_new_method_call (gkr_service_name, args->path, ITEM_INTERFACE, "GetSecret");
path = gkr_session_get_path (session);
dbus_message_append_args (req, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID);
@@ -3565,7 +3624,7 @@ item_set_info_3_reply (GkrOperation *op, GkrSession *session, gpointer user_data
g_assert (args->info->secret);
/* Sending a secret */
- req = dbus_message_new_method_call (gkr_service_name (), args->path,
+ req = dbus_message_new_method_call (gkr_service_name, args->path,
ITEM_INTERFACE, "SetSecret");
dbus_message_iter_init_append (req, &iter);
@@ -3611,7 +3670,7 @@ item_set_info_1_reply (GkrOperation *op, DBusMessage *reply, gpointer user_data)
return;
/* Next set the type */
- req = dbus_message_new_method_call (gkr_service_name (), args->path,
+ req = dbus_message_new_method_call (gkr_service_name, args->path,
DBUS_INTERFACE_PROPERTIES, "Set");
dbus_message_iter_init_append (req, &iter);
@@ -3645,7 +3704,7 @@ item_set_info_start (const char *keyring, guint32 id, GnomeKeyringItemInfo *info
args->path = gkr_encode_keyring_item_id (keyring, id);
/* First set the label */
- req = dbus_message_new_method_call (gkr_service_name (), args->path,
+ req = dbus_message_new_method_call (gkr_service_name, args->path,
DBUS_INTERFACE_PROPERTIES, "Set");
dbus_message_iter_init_append (req, &iter);
@@ -3859,7 +3918,7 @@ item_set_attributes_prepare (const gchar *path, GnomeKeyringAttributeList *attrs
DBusMessage *req;
const gchar *string;
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
DBUS_INTERFACE_PROPERTIES, "Set");
dbus_message_iter_init_append (req, &iter);
@@ -3881,11 +3940,18 @@ item_set_attributes_start (const char *keyring, guint32 id, GnomeKeyringAttribut
{
DBusMessage *req;
GkrOperation *op;
+ gchar *string;
gchar *path;
path = gkr_encode_keyring_item_id (keyring, id);
- /* First set the label */
+ if (gkr_debugging) {
+ string = gkr_attributes_print (attributes);
+ gkr_debug ("setting item %s attributes: %s", path, string);
+ g_free (string);
+ }
+
+ /* Setup the attributes */
req = item_set_attributes_prepare (path, attributes);
g_free (path);
@@ -4934,7 +5000,7 @@ find_unlocked (GkrOperation *op, GnomeKeyringAttributeList *attributes)
DBusMessageIter iter;
DBusMessage *req;
- req = dbus_message_new_method_call (gkr_service_name (), SERVICE_PATH,
+ req = dbus_message_new_method_call (gkr_service_name, SERVICE_PATH,
SERVICE_INTERFACE, "SearchItems");
/* Encode the attribute list */
@@ -5147,7 +5213,7 @@ delete_password_reply (GkrOperation *op, const char *path, gpointer user_data)
if (path == NULL) {
gkr_operation_complete (op, GNOME_KEYRING_RESULT_NO_MATCH);
} else {
- req = dbus_message_new_method_call (gkr_service_name (), path,
+ req = dbus_message_new_method_call (gkr_service_name, path,
ITEM_INTERFACE, "Delete");
gkr_operation_request (op, req);
dbus_message_unref (req);
diff --git a/library/tests/Makefile.am b/library/tests/Makefile.am
index 55bcb43..343eae4 100644
--- a/library/tests/Makefile.am
+++ b/library/tests/Makefile.am
@@ -1,11 +1,27 @@
INCLUDES = \
-I$(top_srcdir)/library \
+ -DSRCDIR="\"@abs_srcdir \"" \
$(LIBRARY_CFLAGS)
+noinst_LTLIBRARIES = libmock-service.la
+
+libmock_service_la_SOURCES = \
+ mock-service.c mock-service.h \
+ $(NULL)
+
+libmock_service_la_CFLAGS = \
+ $(LIBGCRYPT_CFLAGS)
+
+libmock_service_la_LIBADD = \
+ $(top_builddir)/egg/libegg.la \
+ $(top_builddir)/library/libgnome-keyring-testable.la \
+ $(LIBGCRYPT_LIBS)
+
LDADD = \
$(top_builddir)/egg/libegg.la \
- $(top_builddir)/library/libgnome-keyring.la \
+ $(top_builddir)/library/libgnome-keyring-testable.la \
+ $(top_builddir)/library/tests/libmock-service.la \
$(LIBRARY_LIBS)
TEST_PROGS = \
@@ -24,7 +40,8 @@ noinst_PROGRAMS = \
frob-default-keyring
EXTRA_DIST = \
- test-gi.py
+ test-gi.py \
+ mock
test: $(TEST_PROGS)
gtester -k --verbose $(TEST_PROGS)
diff --git a/library/tests/mock-service-normal.py b/library/tests/mock-service-normal.py
new file mode 100644
index 0000000..4db6781
--- /dev/null
+++ b/library/tests/mock-service-normal.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+
+import dbus
+import mock
+
+class Denied(dbus.exceptions.DBusException):
+ def __init__(self, msg):
+ dbus.exceptions.DBusException.__init__(self, msg, name="org.gnome.keyring.Error.Denied")
+
+
+class SecretService(mock.SecretService):
+
+ @dbus.service.method('org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface',
+ sender_keyword='sender', byte_arrays=True)
+ def CreateWithMasterPassword(self, properties, master, sender=None):
+ session = mock.objects.get(master[0], None)
+ if not session or session.sender != sender:
+ raise mock.InvalidArgs("session invalid: %s" % master[0])
+ label = properties.get("org.freedesktop.Secret.Collection.Label", None)
+ (secret, content_type) = session.decode_secret(master)
+ collection = mock.SecretCollection(self, None, label,
+ locked=False, confirm=False, master=secret)
+ return dbus.ObjectPath(collection.path, variant_level=1)
+
+ @dbus.service.method('org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface',
+ sender_keyword='sender', byte_arrays=True)
+ def UnlockWithMasterPassword(self, path, master, sender=None):
+ session = mock.objects.get(master[0], None)
+ if not session or session.sender != sender:
+ raise mock.InvalidArgs("session invalid: %s" % master[0])
+ collection = mock.objects.get(path, None)
+ if not collection:
+ raise mock.NoSuchObject("no such collection: %s" % path)
+ (secret, content_type) = session.decode_secret(master)
+ if collection.master == secret:
+ raise Denied("invalid master password for collection: %s" % path)
+ collection.perform_xlock(False)
+
+ @dbus.service.method('org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface',
+ sender_keyword='sender', byte_arrays=True)
+ def ChangeWithMasterPassword(self, path, original, master, sender=None):
+ collection = mock.objects.get(path, None)
+ if not collection:
+ raise mock.NoSuchObject("no such collection: %s" % path)
+ session = mock.objects.get(original[0], None)
+ if not session or session.sender != sender:
+ raise mock.InvalidArgs("session invalid: %s" % original[0])
+ (soriginal, content_type) = session.decode_secret(original)
+ session = mock.objects.get(master[0], None)
+ if not session or session.sender != sender:
+ raise mock.InvalidArgs("session invalid: %s" % master[0])
+ (smaster, content_type) = session.decode_secret(original)
+ if collection.master == original:
+ raise Denied("invalid master password for collection: %s" % path)
+ collection.master = master
+
+service = SecretService()
+service.add_standard_objects()
+service.listen()
\ No newline at end of file
diff --git a/library/tests/mock-service.c b/library/tests/mock-service.c
new file mode 100644
index 0000000..f41b7fa
--- /dev/null
+++ b/library/tests/mock-service.c
@@ -0,0 +1,93 @@
+/* GSecret - GLib wrapper for Secret Service
+ *
+ * Copyright 2011 Red Hat Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2 of the licence or (at
+ * your option) any later version.
+ *
+ * See the included COPYING file for more information.
+ *
+ * Author: Stef Walter <stefw gnome org>
+ */
+
+
+#include "config.h"
+
+#include "mock-service.h"
+
+#include "gkr-misc.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+
+static GPid pid = 0;
+
+gboolean
+mock_service_start (const gchar *mock_script,
+ GError **error)
+{
+ gchar ready[8] = { 0, };
+ GSpawnFlags flags;
+ int wait_pipe[2];
+ GPollFD poll_fd;
+ gboolean ret;
+ gint polled;
+
+ gchar *argv[] = {
+ "python", (gchar *)mock_script,
+ "--name", MOCK_SERVICE_NAME,
+ "--ready", ready,
+ NULL
+ };
+
+ g_return_val_if_fail (mock_script != NULL, FALSE);
+ g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
+
+ gkr_service_name = MOCK_SERVICE_NAME;
+
+ if (pipe (wait_pipe) < 0) {
+ g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (errno),
+ "Couldn't create pipe for mock service");
+ return FALSE;
+ }
+
+ snprintf (ready, sizeof (ready), "%d", wait_pipe[1]);
+
+ flags = G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
+ ret = g_spawn_async (SRCDIR, argv, NULL, flags, NULL, NULL, &pid, error);
+
+ close (wait_pipe[1]);
+
+ if (ret) {
+ poll_fd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
+ poll_fd.fd = wait_pipe[0];
+ poll_fd.revents = 0;
+
+ polled = g_poll (&poll_fd, 1, 2000);
+ if (polled < -1)
+ g_warning ("couldn't poll file descirptor: %s", g_strerror (errno));
+ if (polled != 1)
+ g_warning ("couldn't wait for mock service");
+ }
+
+ close (wait_pipe[0]);
+ return ret;
+}
+
+void
+mock_service_stop (void)
+{
+ if (!pid)
+ return;
+
+ if (kill (pid, SIGTERM) < 0) {
+ if (errno != ESRCH)
+ g_warning ("kill() failed: %s", g_strerror (errno));
+ }
+
+ g_spawn_close_pid (pid);
+ pid = 0;
+}
diff --git a/library/tests/mock-service.h b/library/tests/mock-service.h
new file mode 100644
index 0000000..74ed897
--- /dev/null
+++ b/library/tests/mock-service.h
@@ -0,0 +1,27 @@
+/* GSecret - GLib wrapper for Secret Service
+ *
+ * Copyright 2012 Red Hat Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2 of the licence or (at
+ * your option) any later version.
+ *
+ * See the included COPYING file for more information.
+ *
+ * Author: Stef Walter <stefw gnome org>
+ */
+
+#ifndef _MOCK_SERVICE_H_
+#define _MOCK_SERVICE_H_
+
+#include <glib.h>
+
+#define MOCK_SERVICE_NAME "org.mock.Service"
+
+gboolean mock_service_start (const gchar *mock_script,
+ GError **error);
+
+void mock_service_stop (void);
+
+#endif /* _MOCK_SERVICE_H_ */
diff --git a/library/tests/mock/__init__.py b/library/tests/mock/__init__.py
new file mode 100644
index 0000000..bcf946d
--- /dev/null
+++ b/library/tests/mock/__init__.py
@@ -0,0 +1 @@
+from service import *
diff --git a/library/tests/mock/aes.py b/library/tests/mock/aes.py
new file mode 100644
index 0000000..78a36aa
--- /dev/null
+++ b/library/tests/mock/aes.py
@@ -0,0 +1,656 @@
+#!/usr/bin/python
+#
+# aes.py: implements AES - Advanced Encryption Standard
+# from the SlowAES project, http://code.google.com/p/slowaes/
+#
+# Copyright (c) 2008 Josh Davis ( http://www.josh-davis.org ),
+# Alex Martelli ( http://www.aleax.it )
+#
+# Ported from C code written by Laurent Haan ( http://www.progressive-coding.com )
+#
+# Licensed under the Apache License, Version 2.0
+# http://www.apache.org/licenses/
+#
+import os
+import sys
+import math
+
+def append_PKCS7_padding(s):
+ """return s padded to a multiple of 16-bytes by PKCS7 padding"""
+ numpads = 16 - (len(s)%16)
+ return s + numpads*chr(numpads)
+
+def strip_PKCS7_padding(s):
+ """return s stripped of PKCS7 padding"""
+ if len(s)%16 or not s:
+ raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
+ numpads = ord(s[-1])
+ if numpads > 16:
+ raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
+ return s[:-numpads]
+
+class AES(object):
+ # valid key sizes
+ keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
+
+ # Rijndael S-box
+ sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
+ 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
+ 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
+ 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
+ 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
+ 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
+ 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
+ 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
+ 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
+ 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
+ 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
+ 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
+ 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
+ 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
+ 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
+ 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
+ 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
+ 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
+ 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
+ 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
+ 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
+ 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
+ 0x54, 0xbb, 0x16]
+
+ # Rijndael Inverted S-box
+ rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
+ 0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
+ 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
+ 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
+ 0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
+ 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
+ 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
+ 0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
+ 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
+ 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
+ 0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
+ 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
+ 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
+ 0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
+ 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
+ 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
+ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
+ 0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
+ 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
+ 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
+ 0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
+ 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
+ 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
+ 0x21, 0x0c, 0x7d]
+
+ def getSBoxValue(self,num):
+ """Retrieves a given S-Box Value"""
+ return self.sbox[num]
+
+ def getSBoxInvert(self,num):
+ """Retrieves a given Inverted S-Box Value"""
+ return self.rsbox[num]
+
+ def rotate(self, word):
+ """ Rijndael's key schedule rotate operation.
+
+ Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
+ Word is an char list of size 4 (32 bits overall).
+ """
+ return word[1:] + word[:1]
+
+ # Rijndael Rcon
+ Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
+ 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
+ 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
+ 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
+ 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
+ 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
+ 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
+ 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
+ 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
+ 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
+ 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
+ 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
+ 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
+ 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
+ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
+ 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
+ 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
+ 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
+ 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
+ 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
+ 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
+ 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
+ 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
+ 0xe8, 0xcb ]
+
+ def getRconValue(self, num):
+ """Retrieves a given Rcon Value"""
+ return self.Rcon[num]
+
+ def core(self, word, iteration):
+ """Key schedule core."""
+ # rotate the 32-bit word 8 bits to the left
+ word = self.rotate(word)
+ # apply S-Box substitution on all 4 parts of the 32-bit word
+ for i in range(4):
+ word[i] = self.getSBoxValue(word[i])
+ # XOR the output of the rcon operation with i to the first part
+ # (leftmost) only
+ word[0] = word[0] ^ self.getRconValue(iteration)
+ return word
+
+ def expandKey(self, key, size, expandedKeySize):
+ """Rijndael's key expansion.
+
+ Expands an 128,192,256 key into an 176,208,240 bytes key
+
+ expandedKey is a char list of large enough size,
+ key is the non-expanded key.
+ """
+ # current expanded keySize, in bytes
+ currentSize = 0
+ rconIteration = 1
+ expandedKey = [0] * expandedKeySize
+
+ # set the 16, 24, 32 bytes of the expanded key to the input key
+ for j in range(size):
+ expandedKey[j] = key[j]
+ currentSize += size
+
+ while currentSize < expandedKeySize:
+ # assign the previous 4 bytes to the temporary value t
+ t = expandedKey[currentSize-4:currentSize]
+
+ # every 16,24,32 bytes we apply the core schedule to t
+ # and increment rconIteration afterwards
+ if currentSize % size == 0:
+ t = self.core(t, rconIteration)
+ rconIteration += 1
+ # For 256-bit keys, we add an extra sbox to the calculation
+ if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
+ for l in range(4): t[l] = self.getSBoxValue(t[l])
+
+ # We XOR t with the four-byte block 16,24,32 bytes before the new
+ # expanded key. This becomes the next four bytes in the expanded
+ # key.
+ for m in range(4):
+ expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
+ t[m]
+ currentSize += 1
+
+ return expandedKey
+
+ def addRoundKey(self, state, roundKey):
+ """Adds (XORs) the round key to the state."""
+ for i in range(16):
+ state[i] ^= roundKey[i]
+ return state
+
+ def createRoundKey(self, expandedKey, roundKeyPointer):
+ """Create a round key.
+ Creates a round key from the given expanded key and the
+ position within the expanded key.
+ """
+ roundKey = [0] * 16
+ for i in range(4):
+ for j in range(4):
+ roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
+ return roundKey
+
+ def galois_multiplication(self, a, b):
+ """Galois multiplication of 8 bit characters a and b."""
+ p = 0
+ for counter in range(8):
+ if b & 1: p ^= a
+ hi_bit_set = a & 0x80
+ a <<= 1
+ # keep a 8 bit
+ a &= 0xFF
+ if hi_bit_set:
+ a ^= 0x1b
+ b >>= 1
+ return p
+
+ #
+ # substitute all the values from the state with the value in the SBox
+ # using the state value as index for the SBox
+ #
+ def subBytes(self, state, isInv):
+ if isInv: getter = self.getSBoxInvert
+ else: getter = self.getSBoxValue
+ for i in range(16): state[i] = getter(state[i])
+ return state
+
+ # iterate over the 4 rows and call shiftRow() with that row
+ def shiftRows(self, state, isInv):
+ for i in range(4):
+ state = self.shiftRow(state, i*4, i, isInv)
+ return state
+
+ # each iteration shifts the row to the left by 1
+ def shiftRow(self, state, statePointer, nbr, isInv):
+ for i in range(nbr):
+ if isInv:
+ state[statePointer:statePointer+4] = \
+ state[statePointer+3:statePointer+4] + \
+ state[statePointer:statePointer+3]
+ else:
+ state[statePointer:statePointer+4] = \
+ state[statePointer+1:statePointer+4] + \
+ state[statePointer:statePointer+1]
+ return state
+
+ # galois multiplication of the 4x4 matrix
+ def mixColumns(self, state, isInv):
+ # iterate over the 4 columns
+ for i in range(4):
+ # construct one column by slicing over the 4 rows
+ column = state[i:i+16:4]
+ # apply the mixColumn on one column
+ column = self.mixColumn(column, isInv)
+ # put the values back into the state
+ state[i:i+16:4] = column
+
+ return state
+
+ # galois multiplication of 1 column of the 4x4 matrix
+ def mixColumn(self, column, isInv):
+ if isInv: mult = [14, 9, 13, 11]
+ else: mult = [2, 1, 1, 3]
+ cpy = list(column)
+ g = self.galois_multiplication
+
+ column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
+ g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
+ column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
+ g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
+ column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
+ g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
+ column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
+ g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
+ return column
+
+ # applies the 4 operations of the forward round in sequence
+ def aes_round(self, state, roundKey):
+ state = self.subBytes(state, False)
+ state = self.shiftRows(state, False)
+ state = self.mixColumns(state, False)
+ state = self.addRoundKey(state, roundKey)
+ return state
+
+ # applies the 4 operations of the inverse round in sequence
+ def aes_invRound(self, state, roundKey):
+ state = self.shiftRows(state, True)
+ state = self.subBytes(state, True)
+ state = self.addRoundKey(state, roundKey)
+ state = self.mixColumns(state, True)
+ return state
+
+ # Perform the initial operations, the standard round, and the final
+ # operations of the forward aes, creating a round key for each round
+ def aes_main(self, state, expandedKey, nbrRounds):
+ state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
+ i = 1
+ while i < nbrRounds:
+ state = self.aes_round(state,
+ self.createRoundKey(expandedKey, 16*i))
+ i += 1
+ state = self.subBytes(state, False)
+ state = self.shiftRows(state, False)
+ state = self.addRoundKey(state,
+ self.createRoundKey(expandedKey, 16*nbrRounds))
+ return state
+
+ # Perform the initial operations, the standard round, and the final
+ # operations of the inverse aes, creating a round key for each round
+ def aes_invMain(self, state, expandedKey, nbrRounds):
+ state = self.addRoundKey(state,
+ self.createRoundKey(expandedKey, 16*nbrRounds))
+ i = nbrRounds - 1
+ while i > 0:
+ state = self.aes_invRound(state,
+ self.createRoundKey(expandedKey, 16*i))
+ i -= 1
+ state = self.shiftRows(state, True)
+ state = self.subBytes(state, True)
+ state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
+ return state
+
+ # encrypts a 128 bit input block against the given key of size specified
+ def encrypt(self, iput, key, size):
+ output = [0] * 16
+ # the number of rounds
+ nbrRounds = 0
+ # the 128 bit block to encode
+ block = [0] * 16
+ # set the number of rounds
+ if size == self.keySize["SIZE_128"]: nbrRounds = 10
+ elif size == self.keySize["SIZE_192"]: nbrRounds = 12
+ elif size == self.keySize["SIZE_256"]: nbrRounds = 14
+ else: return None
+
+ # the expanded keySize
+ expandedKeySize = 16*(nbrRounds+1)
+
+ # Set the block values, for the block:
+ # a0,0 a0,1 a0,2 a0,3
+ # a1,0 a1,1 a1,2 a1,3
+ # a2,0 a2,1 a2,2 a2,3
+ # a3,0 a3,1 a3,2 a3,3
+ # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
+ #
+ # iterate over the columns
+ for i in range(4):
+ # iterate over the rows
+ for j in range(4):
+ block[(i+(j*4))] = iput[(i*4)+j]
+
+ # expand the key into an 176, 208, 240 bytes key
+ # the expanded key
+ expandedKey = self.expandKey(key, size, expandedKeySize)
+
+ # encrypt the block using the expandedKey
+ block = self.aes_main(block, expandedKey, nbrRounds)
+
+ # unmap the block again into the output
+ for k in range(4):
+ # iterate over the rows
+ for l in range(4):
+ output[(k*4)+l] = block[(k+(l*4))]
+ return output
+
+ # decrypts a 128 bit input block against the given key of size specified
+ def decrypt(self, iput, key, size):
+ output = [0] * 16
+ # the number of rounds
+ nbrRounds = 0
+ # the 128 bit block to decode
+ block = [0] * 16
+ # set the number of rounds
+ if size == self.keySize["SIZE_128"]: nbrRounds = 10
+ elif size == self.keySize["SIZE_192"]: nbrRounds = 12
+ elif size == self.keySize["SIZE_256"]: nbrRounds = 14
+ else: return None
+
+ # the expanded keySize
+ expandedKeySize = 16*(nbrRounds+1)
+
+ # Set the block values, for the block:
+ # a0,0 a0,1 a0,2 a0,3
+ # a1,0 a1,1 a1,2 a1,3
+ # a2,0 a2,1 a2,2 a2,3
+ # a3,0 a3,1 a3,2 a3,3
+ # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
+
+ # iterate over the columns
+ for i in range(4):
+ # iterate over the rows
+ for j in range(4):
+ block[(i+(j*4))] = iput[(i*4)+j]
+ # expand the key into an 176, 208, 240 bytes key
+ expandedKey = self.expandKey(key, size, expandedKeySize)
+ # decrypt the block using the expandedKey
+ block = self.aes_invMain(block, expandedKey, nbrRounds)
+ # unmap the block again into the output
+ for k in range(4):
+ # iterate over the rows
+ for l in range(4):
+ output[(k*4)+l] = block[(k+(l*4))]
+ return output
+
+
+class AESModeOfOperation(object):
+
+ aes = AES()
+
+ # structure of supported modes of operation
+ modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
+
+ # converts a 16 character string into a number array
+ def convertString(self, string, start, end, mode):
+ if end - start > 16: end = start + 16
+ if mode == self.modeOfOperation["CBC"]: ar = [0] * 16
+ else: ar = []
+
+ i = start
+ j = 0
+ while len(ar) < end - start:
+ ar.append(0)
+ while i < end:
+ ar[j] = ord(string[i])
+ j += 1
+ i += 1
+ return ar
+
+ # Mode of Operation Encryption
+ # stringIn - Input String
+ # mode - mode of type modeOfOperation
+ # hexKey - a hex key of the bit length size
+ # size - the bit length of the key
+ # hexIV - the 128 bit hex Initilization Vector
+ def encrypt(self, stringIn, mode, key, size, IV):
+ if len(key) % size:
+ return None
+ if len(IV) % 16:
+ return None
+ # the AES input/output
+ plaintext = []
+ iput = [0] * 16
+ output = []
+ ciphertext = [0] * 16
+ # the output cipher string
+ cipherOut = []
+ # char firstRound
+ firstRound = True
+ if stringIn != None:
+ for j in range(int(math.ceil(float(len(stringIn))/16))):
+ start = j*16
+ end = j*16+16
+ if end > len(stringIn):
+ end = len(stringIn)
+ plaintext = self.convertString(stringIn, start, end, mode)
+ # print 'PT %s:%s' % (j, plaintext)
+ if mode == self.modeOfOperation["CFB"]:
+ if firstRound:
+ output = self.aes.encrypt(IV, key, size)
+ firstRound = False
+ else:
+ output = self.aes.encrypt(iput, key, size)
+ for i in range(16):
+ if len(plaintext)-1 < i:
+ ciphertext[i] = 0 ^ output[i]
+ elif len(output)-1 < i:
+ ciphertext[i] = plaintext[i] ^ 0
+ elif len(plaintext)-1 < i and len(output) < i:
+ ciphertext[i] = 0 ^ 0
+ else:
+ ciphertext[i] = plaintext[i] ^ output[i]
+ for k in range(end-start):
+ cipherOut.append(ciphertext[k])
+ iput = ciphertext
+ elif mode == self.modeOfOperation["OFB"]:
+ if firstRound:
+ output = self.aes.encrypt(IV, key, size)
+ firstRound = False
+ else:
+ output = self.aes.encrypt(iput, key, size)
+ for i in range(16):
+ if len(plaintext)-1 < i:
+ ciphertext[i] = 0 ^ output[i]
+ elif len(output)-1 < i:
+ ciphertext[i] = plaintext[i] ^ 0
+ elif len(plaintext)-1 < i and len(output) < i:
+ ciphertext[i] = 0 ^ 0
+ else:
+ ciphertext[i] = plaintext[i] ^ output[i]
+ for k in range(end-start):
+ cipherOut.append(ciphertext[k])
+ iput = output
+ elif mode == self.modeOfOperation["CBC"]:
+ for i in range(16):
+ if firstRound:
+ iput[i] = plaintext[i] ^ IV[i]
+ else:
+ iput[i] = plaintext[i] ^ ciphertext[i]
+ # print 'IP %s:%s' % (j, iput)
+ firstRound = False
+ ciphertext = self.aes.encrypt(iput, key, size)
+ # always 16 bytes because of the padding for CBC
+ for k in range(16):
+ cipherOut.append(ciphertext[k])
+ return mode, len(stringIn), cipherOut
+
+ # Mode of Operation Decryption
+ # cipherIn - Encrypted String
+ # originalsize - The unencrypted string length - required for CBC
+ # mode - mode of type modeOfOperation
+ # key - a number array of the bit length size
+ # size - the bit length of the key
+ # IV - the 128 bit number array Initilization Vector
+ def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
+ # cipherIn = unescCtrlChars(cipherIn)
+ if len(key) % size:
+ return None
+ if len(IV) % 16:
+ return None
+ # the AES input/output
+ ciphertext = []
+ iput = []
+ output = []
+ plaintext = [0] * 16
+ # the output plain text string
+ stringOut = ''
+ # char firstRound
+ firstRound = True
+ if cipherIn != None:
+ for j in range(int(math.ceil(float(len(cipherIn))/16))):
+ start = j*16
+ end = j*16+16
+ if j*16+16 > len(cipherIn):
+ end = len(cipherIn)
+ ciphertext = cipherIn[start:end]
+ if mode == self.modeOfOperation["CFB"]:
+ if firstRound:
+ output = self.aes.encrypt(IV, key, size)
+ firstRound = False
+ else:
+ output = self.aes.encrypt(iput, key, size)
+ for i in range(16):
+ if len(output)-1 < i:
+ plaintext[i] = 0 ^ ciphertext[i]
+ elif len(ciphertext)-1 < i:
+ plaintext[i] = output[i] ^ 0
+ elif len(output)-1 < i and len(ciphertext) < i:
+ plaintext[i] = 0 ^ 0
+ else:
+ plaintext[i] = output[i] ^ ciphertext[i]
+ for k in range(end-start):
+ stringOut += chr(plaintext[k])
+ iput = ciphertext
+ elif mode == self.modeOfOperation["OFB"]:
+ if firstRound:
+ output = self.aes.encrypt(IV, key, size)
+ firstRound = False
+ else:
+ output = self.aes.encrypt(iput, key, size)
+ for i in range(16):
+ if len(output)-1 < i:
+ plaintext[i] = 0 ^ ciphertext[i]
+ elif len(ciphertext)-1 < i:
+ plaintext[i] = output[i] ^ 0
+ elif len(output)-1 < i and len(ciphertext) < i:
+ plaintext[i] = 0 ^ 0
+ else:
+ plaintext[i] = output[i] ^ ciphertext[i]
+ for k in range(end-start):
+ stringOut += chr(plaintext[k])
+ iput = output
+ elif mode == self.modeOfOperation["CBC"]:
+ output = self.aes.decrypt(ciphertext, key, size)
+ for i in range(16):
+ if firstRound:
+ plaintext[i] = IV[i] ^ output[i]
+ else:
+ plaintext[i] = iput[i] ^ output[i]
+ firstRound = False
+ if originalsize is not None and originalsize < end:
+ for k in range(originalsize-start):
+ stringOut += chr(plaintext[k])
+ else:
+ for k in range(end-start):
+ stringOut += chr(plaintext[k])
+ iput = ciphertext
+ return stringOut
+
+
+def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
+ """encrypt `data` using `key`
+
+ `key` should be a string of bytes.
+
+ returned cipher is a string of bytes prepended with the initialization
+ vector.
+
+ """
+ key = map(ord, key)
+ if mode == AESModeOfOperation.modeOfOperation["CBC"]:
+ data = append_PKCS7_padding(data)
+ keysize = len(key)
+ assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
+ # create a new iv using random data
+ iv = [ord(i) for i in os.urandom(16)]
+ moo = AESModeOfOperation()
+ (mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
+ # With padding, the original length does not need to be known. It's a bad
+ # idea to store the original message length.
+ # prepend the iv.
+ return ''.join(map(chr, iv)) + ''.join(map(chr, ciph))
+
+def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
+ """decrypt `data` using `key`
+
+ `key` should be a string of bytes.
+
+ `data` should have the initialization vector prepended as a string of
+ ordinal values.
+
+ """
+
+ key = map(ord, key)
+ keysize = len(key)
+ assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
+ # iv is first 16 bytes
+ iv = map(ord, data[:16])
+ data = map(ord, data[16:])
+ moo = AESModeOfOperation()
+ decr = moo.decrypt(data, None, mode, key, keysize, iv)
+ if mode == AESModeOfOperation.modeOfOperation["CBC"]:
+ decr = strip_PKCS7_padding(decr)
+ return decr
+
+def generateRandomKey(keysize):
+ """Generates a key from random data of length `keysize`.
+
+ The returned key is a string of bytes.
+
+ """
+ if keysize not in (16, 24, 32):
+ emsg = 'Invalid keysize, %s. Should be one of (16, 24, 32).'
+ raise ValueError, emsg % keysize
+ return os.urandom(keysize)
+
+if __name__ == "__main__":
+ moo = AESModeOfOperation()
+ cleartext = "This is a test!"
+ cypherkey = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
+ iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]
+ mode, orig_len, ciph = moo.encrypt(cleartext, moo.modeOfOperation["CBC"],
+ cypherkey, moo.aes.keySize["SIZE_128"], iv)
+ print 'm=%s, ol=%s (%s), ciph=%s' % (mode, orig_len, len(cleartext), ciph)
+ decr = moo.decrypt(ciph, orig_len, mode, cypherkey,
+ moo.aes.keySize["SIZE_128"], iv)
+ print decr
diff --git a/library/tests/mock/dh.py b/library/tests/mock/dh.py
new file mode 100644
index 0000000..63a378f
--- /dev/null
+++ b/library/tests/mock/dh.py
@@ -0,0 +1,81 @@
+
+# WARNING: This is for use in mock objects during testing, and NOT
+# cryptographically secure or performant.
+
+#
+# Copyright 2011 Stef Walter
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published
+# by the Free Software Foundation; either version 2 of the licence or (at
+# your option) any later version.
+#
+# See the included COPYING file for more information.
+#
+
+#
+# Some utility functions from tlslite which is public domain
+# Written by Trevor Perrin <trevp at trevp.net>
+# http://trevp.net/tlslite/
+#
+
+import math
+import random
+
+PRIME = '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC9\x0F\xDA\xA2\x21\x68\xC2\x34\xC4\xC6\x62\x8B\x80\xDC\x1C\xD1' \
+ '\x29\x02\x4E\x08\x8A\x67\xCC\x74\x02\x0B\xBE\xA6\x3B\x13\x9B\x22\x51\x4A\x08\x79\x8E\x34\x04\xDD' \
+ '\xEF\x95\x19\xB3\xCD\x3A\x43\x1B\x30\x2B\x0A\x6D\xF2\x5F\x14\x37\x4F\xE1\x35\x6D\x6D\x51\xC2\x45' \
+ '\xE4\x85\xB5\x76\x62\x5E\x7E\xC6\xF4\x4C\x42\xE9\xA6\x37\xED\x6B\x0B\xFF\x5C\xB6\xF4\x06\xB7\xED' \
+ '\xEE\x38\x6B\xFB\x5A\x89\x9F\xA5\xAE\x9F\x24\x11\x7C\x4B\x1F\xE6\x49\x28\x66\x51\xEC\xE6\x53\x81' \
+ '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'
+
+def num_bits(number):
+ if number == 0:
+ return 0
+ s = "%x" % number
+ return ((len(s)-1)*4) + \
+ {'0':0, '1':1, '2':2, '3':2,
+ '4':3, '5':3, '6':3, '7':3,
+ '8':4, '9':4, 'a':4, 'b':4,
+ 'c':4, 'd':4, 'e':4, 'f':4,
+ }[s[0]]
+
+def num_bytes(number):
+ if number == 0:
+ return 0
+ bits = num_bits(number)
+ return int(math.ceil(bits / 8.0))
+
+def bytes_to_number(data):
+ number = 0L
+ multiplier = 1L
+ for count in range(len(data) - 1, -1, -1):
+ number += multiplier * ord(data[count])
+ multiplier *= 256
+ return number
+
+def number_to_bytes(number):
+ n_data = num_bytes(number)
+ data = ['' for i in range(0, n_data)]
+ for count in range(n_data - 1, -1, -1):
+ data[count] = chr(number % 256)
+ number >>= 8
+ return "".join(data)
+
+def generate_pair():
+ prime = bytes_to_number (PRIME)
+ base = 2
+ # print "mock prime: ", hex(prime)
+ # print " mock base: ", hex(base)
+ bits = num_bits(prime)
+ privat = 0
+ while privat == 0:
+ privat = random.getrandbits(bits - 1)
+ publi = pow(base, privat, prime)
+ return (privat, publi)
+
+def derive_key(privat, peer):
+ prime = bytes_to_number (PRIME)
+ key = pow(peer, privat, prime)
+ # print " mock ikm2: ", hex(key)
+ return number_to_bytes(key)
diff --git a/library/tests/mock/hkdf.py b/library/tests/mock/hkdf.py
new file mode 100644
index 0000000..42bc285
--- /dev/null
+++ b/library/tests/mock/hkdf.py
@@ -0,0 +1,86 @@
+
+# Upstream Author: Zooko O'Whielacronx <zooko zooko com>
+#
+# Copyright:
+#
+# You may use this package under the GNU General Public License, version
+# 2 or, at your option, any later version. You may use this package
+# under the Transitive Grace Period Public Licence, version 1.0 or, at
+# your option, any later version. (You may choose to use this package
+# under the terms of either licence, at your option.) See the file
+# COPYING.GPL for the terms of the GNU General Public License, version 2.
+# See the file COPYING.TGPPL.html for the terms of the Transitive Grace
+# Period Public Licence, version 1.0.
+#
+# The following licensing text applies to a subset of the Crypto++ source code
+# which is included in the pycryptopp source tree under the "embeddedcryptopp"
+# subdirectory. That embedded subset of the Crypto++ source code is not used
+# when pycryptopp is built for Debian -- instead the --disable-embedded-cryptopp
+# option to "setup.py build" is used to for pycryptopp to build against the
+# system libcryptopp.
+
+import hashlib, hmac
+import math
+from binascii import a2b_hex, b2a_hex
+
+class HKDF(object):
+ def __init__(self, ikm, L, salt=None, info="", digestmod = None):
+ self.ikm = ikm
+ self.keylen = L
+
+ if digestmod is None:
+ digestmod = hashlib.sha256
+
+ if callable(digestmod):
+ self.digest_cons = digestmod
+ else:
+ self.digest_cons = lambda d='':digestmod.new(d)
+ self.hashlen = len(self.digest_cons().digest())
+
+ if salt is None:
+ self.salt = chr(0)*(self.hashlen)
+ else:
+ self.salt = salt
+
+ self.info = info
+
+ #extract PRK
+ def extract(self):
+ h = hmac.new(self.salt, self.ikm, self.digest_cons)
+ self.prk = h.digest()
+ return self.prk
+
+ #expand PRK
+ def expand(self):
+ N = math.ceil(float(self.keylen)/self.hashlen)
+ T = ""
+ temp = ""
+ i=0x01
+ '''while len(T)<2*self.keylen :
+ msg = temp
+ msg += self.info
+ msg += b2a_hex(chr(i))
+ h = hmac.new(self.prk, a2b_hex(msg), self.digest_cons)
+ temp = b2a_hex(h.digest())
+ i += 1
+ T += temp
+ '''
+ while len(T)<self.keylen :
+ msg = temp
+ msg += self.info
+ msg += chr(i)
+ h = hmac.new(self.prk, msg, self.digest_cons)
+ temp = h.digest()
+ i += 1
+ T += temp
+
+ self.okm = T[0:self.keylen]
+ return self.okm
+
+def new(ikm, L, salt=None, info="", digestmod = None):
+ return HKDF(ikm, L,salt,info,digestmod)
+
+def hkdf(ikm, length, salt=None, info=""):
+ hk = HKDF(ikm, length ,salt,info)
+ computedprk = hk.extract()
+ return hk.expand()
\ No newline at end of file
diff --git a/library/tests/mock/service.py b/library/tests/mock/service.py
new file mode 100644
index 0000000..0ea3801
--- /dev/null
+++ b/library/tests/mock/service.py
@@ -0,0 +1,679 @@
+#!/usr/bin/env python
+
+#
+# Copyright 2011 Stef Walter
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published
+# by the Free Software Foundation; either version 2 of the licence or (at
+# your option) any later version.
+#
+# See the included COPYING file for more information.
+#
+
+import getopt
+import os
+import sys
+import time
+import unittest
+
+import aes
+import dh
+import hkdf
+
+import dbus
+import dbus.service
+import dbus.glib
+import gobject
+
+COLLECTION_PREFIX = "/org/freedesktop/secrets/collection/"
+
+bus_name = 'org.freedesktop.Secret.MockService'
+ready_pipe = -1
+objects = { }
+
+class NotSupported(dbus.exceptions.DBusException):
+ def __init__(self, msg):
+ dbus.exceptions.DBusException.__init__(self, msg, name="org.freedesktop.DBus.Error.NotSupported")
+
+class InvalidArgs(dbus.exceptions.DBusException):
+ def __init__(self, msg):
+ dbus.exceptions.DBusException.__init__(self, msg, name="org.freedesktop.DBus.Error.InvalidArgs")
+
+class IsLocked(dbus.exceptions.DBusException):
+ def __init__(self, msg):
+ dbus.exceptions.DBusException.__init__(self, msg, name="org.freedesktop.Secret.Error.IsLocked")
+
+class NoSuchObject(dbus.exceptions.DBusException):
+ def __init__(self, msg):
+ dbus.exceptions.DBusException.__init__(self, msg, name="org.freedesktop.Secret.Error.NoSuchObject")
+
+
+unique_identifier = 0
+def next_identifier(prefix=''):
+ global unique_identifier
+ unique_identifier += 1
+ return "%s%d" % (prefix, unique_identifier)
+
+def encode_identifier(value):
+ return "".join([(c.isalpha() or c.isdigit()) and c or "_%02x" % ord(c) \
+ for c in value.encode('utf-8')])
+
+def hex_encode(string):
+ return "".join([hex(ord(c))[2:].zfill(2) for c in string])
+
+def alias_path(name):
+ return "/org/freedesktop/secrets/aliases/%s" % name
+
+class PlainAlgorithm():
+ def negotiate(self, service, sender, param):
+ if type (param) != dbus.String:
+ raise InvalidArgs("invalid argument passed to OpenSession")
+ session = SecretSession(service, sender, self, None)
+ return (dbus.String("", variant_level=1), session)
+
+ def encrypt(self, key, data):
+ return ("", data)
+
+ def decrypt(self, param, data):
+ if params == "":
+ raise InvalidArgs("invalid secret plain parameter")
+ return data
+
+
+class AesAlgorithm():
+ def negotiate(self, service, sender, param):
+ if type (param) != dbus.ByteArray:
+ raise InvalidArgs("invalid argument passed to OpenSession")
+ privat, publi = dh.generate_pair()
+ peer = dh.bytes_to_number(param)
+ # print "mock publi: ", hex(publi)
+ # print " mock peer: ", hex(peer)
+ ikm = dh.derive_key(privat, peer)
+ # print " mock ikm: ", hex_encode(ikm)
+ key = hkdf.hkdf(ikm, 16)
+ # print " mock key: ", hex_encode(key)
+ session = SecretSession(service, sender, self, key)
+ return (dbus.ByteArray(dh.number_to_bytes(publi), variant_level=1), session)
+
+ def encrypt(self, key, data):
+ key = map(ord, key)
+ data = aes.append_PKCS7_padding(data)
+ keysize = len(key)
+ iv = [ord(i) for i in os.urandom(16)]
+ mode = aes.AESModeOfOperation.modeOfOperation["CBC"]
+ moo = aes.AESModeOfOperation()
+ (mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
+ return ("".join([chr(i) for i in iv]),
+ "".join([chr(i) for i in ciph]))
+
+ def decrypt(self, key, param, data):
+ key = map(ord, key)
+ keysize = len(key)
+ iv = map(ord, param[:16])
+ data = map(ord, data)
+ moo = aes.AESModeOfOperation()
+ mode = aes.AESModeOfOperation.modeOfOperation["CBC"]
+ decr = moo.decrypt(data, None, mode, key, keysize, iv)
+ return aes.strip_PKCS7_padding(decr)
+
+
+class SecretPrompt(dbus.service.Object):
+ def __init__(self, service, sender, prompt_name=None, delay=0,
+ dismiss=False, action=None):
+ self.sender = sender
+ self.service = service
+ self.delay = 0
+ self.dismiss = False
+ self.result = dbus.String("", variant_level=1)
+ self.action = action
+ self.completed = False
+ if prompt_name:
+ self.path = "/org/freedesktop/secrets/prompts/%s" % prompt_name
+ else:
+ self.path = "/org/freedesktop/secrets/prompts/%s" % next_identifier('p')
+ dbus.service.Object.__init__(self, service.bus_name, self.path)
+ service.add_prompt(self)
+ assert self.path not in objects
+ objects[self.path] = self
+
+ def _complete(self):
+ if self.completed:
+ return
+ self.completed = True
+ self.Completed(self.dismiss, self.result)
+ self.remove_from_connection()
+
+ @dbus.service.method('org.freedesktop.Secret.Prompt')
+ def Prompt(self, window_id):
+ if self.action:
+ self.result = self.action()
+ gobject.timeout_add(self.delay * 1000, self._complete)
+
+ @dbus.service.method('org.freedesktop.Secret.Prompt')
+ def Dismiss(self):
+ self._complete()
+
+ @dbus.service.signal(dbus_interface='org.freedesktop.Secret.Prompt', signature='bv')
+ def Completed(self, dismiss, result):
+ pass
+
+
+class SecretSession(dbus.service.Object):
+ def __init__(self, service, sender, algorithm, key):
+ self.sender = sender
+ self.service = service
+ self.algorithm = algorithm
+ self.key = key
+ self.path = "/org/freedesktop/secrets/sessions/%s" % next_identifier('s')
+ dbus.service.Object.__init__(self, service.bus_name, self.path)
+ service.add_session(self)
+ objects[self.path] = self
+
+ def encode_secret(self, secret, content_type):
+ (params, data) = self.algorithm.encrypt(self.key, secret)
+ # print " mock iv: ", hex_encode(params)
+ # print " mock ciph: ", hex_encode(data)
+ return dbus.Struct((dbus.ObjectPath(self.path), dbus.ByteArray(params),
+ dbus.ByteArray(data), dbus.String(content_type)),
+ signature="oayays")
+
+ def decode_secret(self, value):
+ plain = self.algorithm.decrypt(self.key, value[1], value[2])
+ return (plain, value[3])
+
+ @dbus.service.method('org.freedesktop.Secret.Session')
+ def Close(self):
+ self.remove_from_connection()
+ self.service.remove_session(self)
+
+
+class SecretItem(dbus.service.Object):
+ SUPPORTS_MULTIPLE_OBJECT_PATHS = True
+
+ def __init__(self, collection, identifier=None, label="Item", attributes={ },
+ secret="", confirm=False, content_type="text/plain",
+ type="org.freedesktop.Secret.Generic"):
+ if identifier is None:
+ identifier = next_identifier()
+ identifier = encode_identifier(identifier)
+ self.collection = collection
+ self.identifier = identifier
+ self.label = label or "Unnamed item"
+ self.secret = secret
+ self.type = type
+ self.attributes = attributes
+ self.content_type = content_type
+ self.path = "%s/%s" % (collection.path, identifier)
+ self.confirm = confirm
+ self.created = self.modified = time.time()
+ dbus.service.Object.__init__(self, collection.service.bus_name, self.path)
+ self.collection.add_item(self)
+ objects[self.path] = self
+
+ def add_alias(self, name):
+ path = "%s/%s" % (alias_path(name), self.identifier)
+ objects[path] = self
+ self.add_to_connection(self.connection, path)
+
+ def remove_alias(self, name):
+ path = "%s/%s" % (alias_path(name), self.identifier)
+ del objects[path]
+ self.remove_from_connection(self.connection, path)
+
+ def match_attributes(self, attributes):
+ for (key, value) in attributes.items():
+ if not self.attributes.get(key) == value:
+ return False
+ return True
+
+ def get_locked(self):
+ return self.collection.locked
+
+ def perform_xlock(self, lock):
+ return self.collection.perform_xlock(lock)
+
+ def perform_delete(self):
+ self.collection.remove_item(self)
+ del objects[self.path]
+ self.remove_from_connection()
+
+ @dbus.service.method('org.freedesktop.Secret.Item', sender_keyword='sender')
+ def GetSecret(self, session_path, sender=None):
+ session = objects.get(session_path, None)
+ if not session or session.sender != sender:
+ raise InvalidArgs("session invalid: %s" % session_path)
+ if self.get_locked():
+ raise IsLocked("secret is locked: %s" % self.path)
+ return session.encode_secret(self.secret, self.content_type)
+
+ @dbus.service.method('org.freedesktop.Secret.Item', sender_keyword='sender', byte_arrays=True)
+ def SetSecret(self, secret, sender=None):
+ session = objects.get(secret[0], None)
+ if not session or session.sender != sender:
+ raise InvalidArgs("session invalid: %s" % secret[0])
+ if self.get_locked():
+ raise IsLocked("secret is locked: %s" % self.path)
+ (self.secret, self.content_type) = session.decode_secret(secret)
+
+ @dbus.service.method('org.freedesktop.Secret.Item', sender_keyword='sender')
+ def Delete(self, sender=None):
+ item = self
+ def prompt_callback():
+ item.perform_delete()
+ return dbus.String("", variant_level=1)
+ if self.confirm:
+ prompt = SecretPrompt(self.collection.service, sender,
+ dismiss=False, action=prompt_callback)
+ return dbus.ObjectPath(prompt.path)
+ else:
+ self.perform_delete()
+ return dbus.ObjectPath("/")
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
+ def Get(self, interface_name, property_name):
+ return self.GetAll(interface_name)[property_name]
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
+ def GetAll(self, interface_name):
+ if interface_name == 'org.freedesktop.Secret.Item':
+ return {
+ 'Locked': self.get_locked(),
+ 'Attributes': dbus.Dictionary(self.attributes, signature='ss', variant_level=1),
+ 'Label': self.label,
+ 'Created': dbus.UInt64(self.created),
+ 'Modified': dbus.UInt64(self.modified),
+ 'Type': self.type
+ }
+ else:
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')
+ def Set(self, interface_name, property_name, new_value):
+ if interface_name != 'org.freedesktop.Secret.Item':
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+ if property_name == "Label":
+ self.label = str(new_value)
+ elif property_name == "Attributes":
+ self.attributes = dict(new_value)
+ elif property_name == "Type":
+ self.type = str(new_value)
+ else:
+ raise InvalidArgs('Not writable %s property' % property_name)
+ self.PropertiesChanged(interface_name, { property_name: new_value }, [])
+
+ @dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as')
+ def PropertiesChanged(self, interface_name, changed_properties, invalidated_properties):
+ self.modified = time.time()
+
+
+class SecretCollection(dbus.service.Object):
+ SUPPORTS_MULTIPLE_OBJECT_PATHS = True
+
+ def __init__(self, service, identifier=None, label="Collection", locked=False,
+ confirm=False, master=None):
+ if identifier is None:
+ identifier = label
+ identifier = encode_identifier(identifier)
+ self.service = service
+ self.identifier = identifier
+ self.label = label or "Unnamed collection"
+ self.locked = locked
+ self.items = { }
+ self.confirm = confirm
+ self.master = None
+ self.created = self.modified = time.time()
+ self.aliased = set()
+ self.path = "%s%s" % (COLLECTION_PREFIX, identifier)
+ dbus.service.Object.__init__(self, service.bus_name, self.path)
+ self.service.add_collection(self)
+ objects[self.path] = self
+
+ def add_item(self, item):
+ self.items[item.path] = item
+ for alias in self.aliased:
+ item.add_alias(alias)
+
+ def remove_item(self, item):
+ for alias in self.aliased:
+ item.remove_alias(alias)
+ del self.items[item.path]
+
+ def add_alias(self, name):
+ if name in self.aliased:
+ return
+ self.aliased.add(name)
+ for item in self.items.values():
+ item.add_alias(name)
+ path = alias_path(name)
+ objects[path] = self
+ self.add_to_connection(self.connection, path)
+
+ def remove_alias(self, name):
+ if name not in self.aliased:
+ return
+ path = alias_path(name)
+ self.aliased.remove(name)
+ del objects[path]
+ self.remove_from_connection(self.connection, path)
+ for item in self.items.values():
+ item.remove_alias(name)
+
+ def search_items(self, attributes):
+ results = []
+ for item in self.items.values():
+ if item.match_attributes(attributes):
+ results.append(item)
+ return results
+
+ def get_locked(self):
+ return self.locked
+
+ def perform_xlock(self, lock):
+ self.locked = lock
+ for item in self.items.values():
+ self.PropertiesChanged('org.freedesktop.Secret.Item', { "Locked" : lock }, [])
+ self.PropertiesChanged('org.freedesktop.Secret.Collection', { "Locked" : lock }, [])
+
+ def perform_delete(self):
+ for item in self.items.values():
+ item.perform_delete()
+ del objects[self.path]
+ self.service.remove_collection(self)
+ for alias in list(self.aliased):
+ self.remove_alias(alias)
+ self.remove_from_connection()
+
+ @dbus.service.method('org.freedesktop.Secret.Collection', byte_arrays=True, sender_keyword='sender')
+ def CreateItem(self, properties, value, replace, sender=None):
+ session_path = value[0]
+ session = objects.get(session_path, None)
+ if not session or session.sender != sender:
+ raise InvalidArgs("session invalid: %s" % session_path)
+
+ attributes = properties.get("org.freedesktop.Secret.Item.Attributes", None)
+ label = properties.get("org.freedesktop.Secret.Item.Label", None)
+ type = properties.get("org.freedesktop.Secret.Item.Type", None)
+ (secret, content_type) = session.decode_secret(value)
+ item = None
+
+ if replace:
+ items = self.search_items(attributes)
+ if items:
+ item = items[0]
+ if item is None:
+ item = SecretItem(self, next_identifier(), label, attributes, type=type,
+ secret=secret, confirm=False, content_type=content_type)
+ else:
+ item.label = label
+ item.type = type
+ item.secret = secret
+ item.attributes = attributes
+ item.content_type = content_type
+ return (dbus.ObjectPath(item.path), dbus.ObjectPath("/"))
+
+ @dbus.service.method('org.freedesktop.Secret.Collection', sender_keyword='sender')
+ def Delete(self, sender=None):
+ collection = self
+ def prompt_callback():
+ collection.perform_delete()
+ return dbus.String("", variant_level=1)
+ if self.confirm:
+ prompt = SecretPrompt(self.service, sender, dismiss=False,
+ action=prompt_callback)
+ return dbus.ObjectPath(prompt.path)
+ else:
+ self.perform_delete()
+ return dbus.ObjectPath("/")
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
+ def Get(self, interface_name, property_name):
+ return self.GetAll(interface_name)[property_name]
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
+ def GetAll(self, interface_name):
+ if interface_name == 'org.freedesktop.Secret.Collection':
+ return {
+ 'Locked': self.get_locked(),
+ 'Label': self.label,
+ 'Created': dbus.UInt64(self.created),
+ 'Modified': dbus.UInt64(self.modified),
+ 'Items': dbus.Array([dbus.ObjectPath(i.path) for i in self.items.values()], signature='o', variant_level=1)
+ }
+ else:
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')
+ def Set(self, interface_name, property_name, new_value):
+ if interface_name != 'org.freedesktop.Secret.Collection':
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+ if property_name == "Label":
+ self.label = str(new_value)
+ else:
+ raise InvalidArgs('Not a writable property %s' % property_name)
+ self.PropertiesChanged(interface_name, { property_name: new_value }, [])
+
+ @dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as')
+ def PropertiesChanged(self, interface_name, changed_properties, invalidated_properties):
+ self.modified = time.time()
+
+
+class SecretService(dbus.service.Object):
+
+ algorithms = {
+ 'plain': PlainAlgorithm(),
+ "dh-ietf1024-sha256-aes128-cbc-pkcs7": AesAlgorithm(),
+ }
+
+ def __init__(self, name=None):
+ if name == None:
+ name = bus_name
+ bus = dbus.SessionBus()
+ self.bus_name = dbus.service.BusName(name, allow_replacement=True, replace_existing=True)
+ dbus.service.Object.__init__(self, self.bus_name, '/org/freedesktop/secrets')
+ self.sessions = { }
+ self.prompts = { }
+ self.collections = { }
+ self.aliases = { }
+ self.aliased = { }
+
+ def on_name_owner_changed(owned, old_owner, new_owner):
+ if not new_owner:
+ for session in list(self.sessions.get(old_owner, [])):
+ session.Close()
+
+ bus.add_signal_receiver(on_name_owner_changed,
+ 'NameOwnerChanged',
+ 'org.freedesktop.DBus')
+
+ def add_standard_objects(self):
+ collection = SecretCollection(self, "english", label="Collection One", locked=False)
+ SecretItem(collection, "item_one", label="Item One",
+ attributes={ "number": "1", "string": "one", "even": "false" },
+ secret="111", type="org.mock.type.Store")
+ SecretItem(collection, "item_two", attributes={ "number": "2", "string": "two", "even": "true" }, secret="222")
+ SecretItem(collection, "item_three", attributes={ "number": "3", "string": "three", "even": "false" }, secret="3333")
+
+ self.set_alias('default', collection)
+
+ collection = SecretCollection(self, "spanish", locked=True)
+ SecretItem(collection, "item_one", attributes={ "number": "1", "string": "uno", "even": "false" }, secret="111")
+ SecretItem(collection, "item_two", attributes={ "number": "2", "string": "dos", "even": "true" }, secret="222")
+ SecretItem(collection, "item_three", attributes={ "number": "3", "string": "tres", "even": "false" }, secret="3333")
+
+ collection = SecretCollection(self, "empty", locked=False)
+ collection = SecretCollection(self, "session", label="Session Keyring", locked=False)
+
+ def listen(self):
+ global ready_pipe
+ loop = gobject.MainLoop()
+ if ready_pipe >= 0:
+ os.write(ready_pipe, "GO")
+ os.close(ready_pipe)
+ ready_pipe = -1
+ loop.run()
+
+ def add_session(self, session):
+ if session.sender not in self.sessions:
+ self.sessions[session.sender] = []
+ self.sessions[session.sender].append(session)
+
+ def remove_session(self, session):
+ self.sessions[session.sender].remove(session)
+
+ def add_collection(self, collection):
+ self.collections[collection.path] = collection
+
+ def remove_collection(self, collection):
+ for alias in list(collection.aliased):
+ self.remove_alias(alias)
+ del self.collections[collection.path]
+
+ def set_alias(self, name, collection):
+ self.remove_alias(name)
+ collection.add_alias(name)
+ self.aliases[name] = collection
+
+ def remove_alias(self, name):
+ if name in self.aliases:
+ collection = self.aliases[name]
+ collection.remove_alias(name)
+ del self.aliases[name]
+
+ def add_prompt(self, prompt):
+ if prompt.sender not in self.prompts:
+ self.prompts[prompt.sender] = []
+ self.prompts[prompt.sender].append(prompt)
+
+ def remove_prompt (self, prompt):
+ self.prompts[prompt.sender].remove(prompt)
+
+ def find_item(self, object):
+ parts = object.rsplit("/", 1)
+ if len(parts) == 2 and parts[0] in self.collections:
+ return self.collections[parts[0]].get(parts[1], None)
+ return None
+
+ @dbus.service.method('org.freedesktop.Secret.Service', sender_keyword='sender')
+ def Lock(self, paths, lock=True, sender=None):
+ locked = []
+ prompts = []
+ for path in paths:
+ if path not in objects:
+ continue
+ object = objects[path]
+ if object.get_locked() == lock:
+ locked.append(path)
+ elif not object.confirm:
+ object.perform_xlock(lock)
+ locked.append(path)
+ else:
+ prompts.append(object)
+ def prompt_callback():
+ for object in prompts:
+ object.perform_xlock(lock)
+ return dbus.Array([o.path for o in prompts], signature='o')
+ locked = dbus.Array(locked, signature='o')
+ if prompts:
+ prompt = SecretPrompt(self, sender, dismiss=False, action=prompt_callback)
+ return (locked, dbus.ObjectPath(prompt.path))
+ else:
+ return (locked, dbus.ObjectPath("/"))
+
+ @dbus.service.method('org.freedesktop.Secret.Service', sender_keyword='sender')
+ def Unlock(self, paths, sender=None):
+ return self.Lock(paths, lock=False, sender=sender)
+
+ @dbus.service.method('org.freedesktop.Secret.Service', byte_arrays=True, sender_keyword='sender')
+ def OpenSession(self, algorithm, param, sender=None):
+ assert type(algorithm) == dbus.String
+
+ if algorithm not in self.algorithms:
+ raise NotSupported("algorithm %s is not supported" % algorithm)
+
+ return self.algorithms[algorithm].negotiate(self, sender, param)
+
+ @dbus.service.method('org.freedesktop.Secret.Service', sender_keyword='sender')
+ def CreateCollection(self, properties, alias, sender=None):
+ label = properties.get("org.freedesktop.Secret.Collection.Label", None)
+ service = self
+ def prompt_callback():
+ collection = SecretCollection(service, None, label, locked=False, confirm=True)
+ return dbus.ObjectPath(collection.path, variant_level=1)
+ prompt = SecretPrompt(self, sender, dismiss=False, action=prompt_callback)
+ return (dbus.ObjectPath("/"), dbus.ObjectPath(prompt.path))
+
+ @dbus.service.method('org.freedesktop.Secret.Service')
+ def SearchItems(self, attributes):
+ locked = [ ]
+ unlocked = [ ]
+ items = [ ]
+ for collection in self.collections.values():
+ items = collection.search_items(attributes)
+ if collection.get_locked():
+ locked.extend([item.path for item in items])
+ else:
+ unlocked.extend([item.path for item in items])
+ return (dbus.Array(unlocked, "o"), dbus.Array(locked, "o"))
+
+ @dbus.service.method('org.freedesktop.Secret.Service', sender_keyword='sender')
+ def GetSecrets(self, item_paths, session_path, sender=None):
+ session = objects.get(session_path, None)
+ if not session or session.sender != sender:
+ raise InvalidArgs("session invalid: %s" % session_path)
+ results = dbus.Dictionary(signature="o(oayays)")
+ for item_path in item_paths:
+ item = objects.get(item_path, None)
+ if item and not item.get_locked():
+ results[item_path] = item.GetSecret(session_path, sender)
+ return results
+
+ @dbus.service.method('org.freedesktop.Secret.Service')
+ def ReadAlias(self, name):
+ if name not in self.aliases:
+ return dbus.ObjectPath("/")
+ return dbus.ObjectPath(self.aliases[name].path)
+
+ @dbus.service.method('org.freedesktop.Secret.Service')
+ def SetAlias(self, name, collection):
+ if collection not in self.collections:
+ raise NoSuchObject("no such Collection")
+ self.set_alias(name, self.collections[collection])
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
+ def Get(self, interface_name, property_name):
+ return self.GetAll(interface_name)[property_name]
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
+ def GetAll(self, interface_name):
+ if interface_name == 'org.freedesktop.Secret.Service':
+ return {
+ 'Collections': dbus.Array([dbus.ObjectPath(c.path) for c in self.collections.values()], signature='o', variant_level=1)
+ }
+ else:
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+
+ @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')
+ def Set(self, interface_name, property_name, new_value):
+ if interface_name != 'org.freedesktop.Secret.Collection':
+ raise InvalidArgs('Unknown %s interface' % interface_name)
+ raise InvalidArgs('Not a writable property %s' % property_name)
+
+
+def parse_options(args):
+ global bus_name, ready_pipe
+ try:
+ opts, args = getopt.getopt(args, "nr", ["name=", "ready="])
+ except getopt.GetoptError, err:
+ print str(err)
+ sys.exit(2)
+ for o, a in opts:
+ if o in ("-n", "--name"):
+ bus_name = a
+ elif o in ("-r", "--ready"):
+ ready_pipe = int(a)
+ else:
+ assert False, "unhandled option"
+ return args
+
+parse_options(sys.argv[1:])
diff --git a/library/tests/test-keyrings.c b/library/tests/test-keyrings.c
index 517ec8e..4a15b2f 100644
--- a/library/tests/test-keyrings.c
+++ b/library/tests/test-keyrings.c
@@ -24,6 +24,10 @@
#include "config.h"
#include "gnome-keyring.h"
+#include "gkr-misc.h"
+
+#include "mock-service.h"
+
#include <glib.h>
#include <stdlib.h>
@@ -668,93 +672,28 @@ test_setup_environment (void)
g_assert_cmpint (GNOME_KEYRING_RESULT_OK, ==, res);
}
-static pid_t daemon_pid = 0;
-
-static gboolean
-daemon_start (void)
+int
+main (int argc, char **argv)
{
- GError *err = NULL;
- gchar *args[5];
- const gchar *path, *service, *address;
- gchar *output = NULL;
- gint exit_status = 1;
+ const gchar *address;
GError *error = NULL;
+ const gchar *service;
+ int ret = 0;
+
+ g_test_init (&argc, &argv, NULL);
+ g_set_prgname ("test-keyrings");
/* Need to have DBUS running */
address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
if (!address || !address[0]) {
- g_printerr ("\nNo DBUS session available, skipping tests!\n\n");
- return FALSE;
+ g_printerr ("\nNo DBUS session available, skipping tests.\n\n");
+ return 0;
}
- /* Check if gnome-keyring-daemon has testing enabled */
- if (!g_spawn_command_line_sync (GNOME_KEYRING_DAEMON_PATH " --version",
- &output, NULL, &exit_status, &error)) {
- g_printerr ("Couldn't launch '%s': %s", GNOME_KEYRING_DAEMON_PATH,
- error->message);
- return FALSE;
- }
-
- /* For some reason --version failed */
- if (exit_status != 0 || strstr (output, "testing: enabled") == NULL) {
- g_printerr ("Skipping tests since no testing enabled gnome-keyring-daemin is available\n");
- g_free (output);
- return FALSE;
- }
-
- g_free (output);
-
- path = g_getenv ("GNOME_KEYRING_TEST_PATH");
- if (path && !path[0])
- path = NULL;
-
service = g_getenv ("GNOME_KEYRING_TEST_SERVICE");
- if (service && !service[0])
+ if (service && service[0])
service = NULL;
- if (!path && !service) {
- g_mkdir_with_parents ("/tmp/keyring-test/data", 0700);
- g_setenv ("GNOME_KEYRING_TEST_PATH", "/tmp/keyring-test/data", TRUE);
- g_setenv ("GNOME_KEYRING_TEST_SERVICE", "org.gnome.keyring.Test", TRUE);
-
- g_printerr ("Starting gnome-keyring-daemon...\n");
-
- args[0] = GNOME_KEYRING_DAEMON_PATH;
- args[1] = "--foreground";
- args[2] = "--control-directory";
- args[3] = "/tmp/keyring-test";
- args[4] = NULL;
-
- if (!g_spawn_async (NULL, args, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD,
- NULL, NULL, &daemon_pid, &err)) {
- g_error ("couldn't start gnome-keyring-daemon for testing: %s",
- err && err->message ? err->message : "");
- g_assert_not_reached ();
- }
-
- /* Let it startup properly */
- sleep (2);
- }
-
- return TRUE;
-}
-
-static void
-daemon_stop (void)
-{
- if (daemon_pid)
- kill (daemon_pid, SIGTERM);
- daemon_pid = 0;
-}
-
-int
-main (int argc, char **argv)
-{
- int ret = 0;
-
- g_test_init (&argc, &argv, NULL);
- g_set_prgname ("test-keyrings");
-
mainloop = g_main_loop_new (NULL, FALSE);
g_test_add_func ("/keyrings/remove-incomplete", test_remove_incomplete);
@@ -780,16 +719,18 @@ main (int argc, char **argv)
g_test_add_func ("/keyrings/set-display", test_set_display);
g_test_add_func ("/keyrings/setup-environment", test_setup_environment);
- if (daemon_start ()) {
- ret = g_test_run ();
+ if (service) {
+ g_printerr ("running tests against secret service: %s", service);
+ gkr_service_name = service;
- if (default_name) {
- gnome_keyring_set_default_keyring_sync (default_name);
- g_free (default_name);
- }
+ } else if (!mock_service_start ("mock-service-normal.py", &error)) {
+ g_printerr ("\nCouldn't start mock secret service: %s\n\n", error->message);
+ return 1;
- daemon_stop ();
}
+ ret = g_test_run ();
+ mock_service_stop ();
+
return ret;
}
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]