Charm with unit tests

Working charm with unit tests. Various features:

Change the install ownership for token store

It turns out that the 'user' that creates the token store, is the only one that
can access it, apart from root.  As Barbican uses a 'barbican' user for the
barbican-worker process, we need to create the token store with 1777 perms (see
https://github.com/opendnssec/SoftHSMv2/issues/185) and also create the initial
token using the barbican user.

Add an initial README.md: This describes the charm, where to get help
and how to use it.
This commit is contained in:
Alex Kavanagh 2016-07-01 17:22:13 +00:00
parent cbe7232aac
commit 45e370b142
11 changed files with 923 additions and 38 deletions

8
.testr.conf Normal file
View File

@ -0,0 +1,8 @@
[DEFAULT]
test_command=OS_STDOUT_CAPTURE=${OS_STDOUT_CAPTURE:-1} \
OS_STDERR_CAPTURE=${OS_STDERR_CAPTURE:-1} \
OS_TEST_TIMEOUT=${OS_TEST_TIMEOUT:-60} \
${PYTHON:-python} -m subunit.run discover -t ./ ./unit_tests $LISTOPT $IDOPTION
test_id_option=--load-list $IDFILE
test_list_option=--list

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

60
README.md Normal file
View File

@ -0,0 +1,60 @@
# Barbican SoftHSM2 Plugin
Barbican is a REST API designed for the secure storage, provisioning and
management of secrets. It is aimed at being useful for all environments,
including large ephemeral Clouds. (see [Barbican
Charm](https://github.com/openstack/barbican) for details on Barbican)
The Barbican SoftHSM2 Plugin is EXPERIMENTAL and not for use in Production
Systems. It is intended to provide a example on how to plug an HSM into
Barbican.
In particular, the SoftHSM2 plugin charm (as a subordinate) implements the
barbican-hsm-plugin interface which transfers the credentials to the Barbican
charm to be able to access the the HSM.
From [the GitHub page](https://github.com/opendnssec/SoftHSMv2):
OpenDNSSEC handles and stores its cryptographic keys via the PKCS#11 interface.
This interface specifies how to communicate with cryptographic devices such as
HSM:s (Hardware Security Modules) and smart cards. The purpose of these devices
is, among others, to generate cryptographic keys and sign information without
revealing private-key material to the outside world. They are often designed to
perform well on these specific tasks compared to ordinary processes in a normal
computer.
A potential problem with the use of the PKCS#11 interface is that it might
limit the wide spread use of OpenDNSSEC, since a potential user might not be
willing to invest in a new hardware device. To counter this effect, OpenDNSSEC
is providing a software implementation of a generic cryptographic device with a
PKCS#11 interface, the SoftHSM. SoftHSM is designed to meet the requirements of
OpenDNSSEC, but can also work together with other cryptographic products
because of the PKCS#11 interface.
If you have a technical question about this Charm, you can send an email to the
[OpenStack General mailing list](
http://lists.openstack.org/pipermail/openstack/) at
`openstack@lists.openstack.org` with the prefix `[barbican]` in the subject, or
ask in the `#openstack-charms` on Freenode..
To file a bug, use our bug tracker on [Launchpad](
http://bugs.launchpad.net/charms/+source/barbican/).
## How it works
Barbican communicates with HSM devices via a local (to Barbican) PKCS11
library. Thus an HSM plugin needs to be local to the unit that a Barbican is
installed on, and so a plugin charm is subordinate to the Barbican charm. A
plugin provides the barbican-hsm-plugin interface that provides sufficient
details to the Barbican charm to be able to configure barbican to access the
HSM's PKCS11 libary.
The barbican-hsm-plugin interface transfers `login`, `slot_id` and
`library_path` parameters to the Barbican charm, which uses them to configure
Barbican to access the PKCS11 compliant library of the HSM.
Barbican assumes that the slot & token are configured and that with the `login`
(or pin) that Barbican will be able to access the token to store keys, etc. In
this case of softhsm2, this charm initialises the token, creates the login and
provides those details across the relation.

View File

@ -1,13 +0,0 @@
Copyright 2016 Canonical Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,5 +1,37 @@
import charms_openstack.charm
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import os.path
import shutil
import subprocess
import charmhelpers.core.hookenv as hookenv
import charmhelpers.core.host as ch_core_host
import charms_openstack.adapters
import charms_openstack.charm
SOFTHSM2_UTIL_CMD = "/usr/bin/softhsm2-util"
TOKEN_STORE = "/var/lib/softhsm/tokens/"
SOFTHSM2_CONF = "/etc/softhsm/softhsm2.conf"
SOFTHSM2_LIB_PATH = "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so"
PIN_LENGTH = 32
BARBICAN_TOKEN_LABEL = "barbican_token"
STORED_PINS_FILE = "/var/lib/softhsm/stored_pins.txt"
def install():
@ -9,6 +41,10 @@ def install():
BarbicanSoftHSMCharm.singleton.install()
def on_hsm_connected(hsm):
BarbicanSoftHSMCharm.singleton.on_hsm_connected(hsm)
class BarbicanSoftHSMCharm(charms_openstack.charm.OpenStackCharm):
service_name = 'barbican-softhsm'
@ -16,22 +52,200 @@ class BarbicanSoftHSMCharm(charms_openstack.charm.OpenStackCharm):
release = 'mitaka'
# Packages that the service needs installed
packages = []
# Init services the charm manages
services = []
packages = ['softhsm2']
# Standard interface adapters class to use.
adapters_class = charms_openstack.adapters.OpenStackRelationAdapters
# Ports that need exposing
default_service = ''
api_ports = {}
def install(self):
"""Perform the normal charm install, and then kick off setting up the
barbican_token in the softhsm2 token store.
"""
super(BarbicanSoftHSMCharm, self).install()
# now add the barbican user to the softhsm group so that the
# barbican-worker can access the softhsm2.conf file.
ch_core_host.add_user_to_group('barbican', 'softhsm')
self.setup_token_store()
hookenv.status_set(
'waiting', 'Charm installed and token store configured')
# Database sync command (if needed)
sync_cmd = []
def setup_token_store(self):
"""Set up the token store for barbican to use, create a pin and
user_pin and store those details locally so that they can be used when
Barbican connects.
# The restart map defines which services should be restarted when a given
# file changes
restart_map = {
Performs as needed:
softhsm2-util --init-token --free --label "barbican_token" --pin <pin>
--so-pin <so-pin>
The <pin> and <so-pin> are generated randomly and saved to a
configuration file.
If the <pin> and <so-pin> configuration file don't exist, then the
token directory is deleted and re-initialised.
Thus if we are upgrading a charm, the charm checks to see if it has
already been run on this host, and if so, doesn't re-initialise the
token store, otherwise the token store is re-initialised.
The configuration file for the softhsm2 library is also written.
"""
# see if the <pin> and <so_pin> exist?
pin, so_pin = read_pins_from_store()
if pin is not None:
# return as the token store is already set up
return
# see if the token directory exists - if so, delete it.
if os.path.exists(TOKEN_STORE):
if os.path.isdir(TOKEN_STORE):
shutil.rmtree(TOKEN_STORE)
else:
os.remove(TOKEN_STORE)
os.makedirs(TOKEN_STORE)
# We need the token store to be 1777 so that whoever creates a token
# can also gain access to it - the token will be created by the
# barbican user.
os.chmod(TOKEN_STORE, 0o1777)
# now create the token store
pin = ch_core_host.pwgen(PIN_LENGTH)
so_pin = ch_core_host.pwgen(PIN_LENGTH)
write_pins_to_store(pin, so_pin)
cmd = [
'sudo', '-u', 'barbican',
SOFTHSM2_UTIL_CMD,
'--init-token', '--free',
'--label', BARBICAN_TOKEN_LABEL,
'--pin', pin,
'--so-pin', so_pin]
subprocess.check_call(cmd)
hookenv.log("Initialised token store.")
def on_hsm_connected(self, hsm):
"""Called when the hsm interface becomes connected. This means the
plugin has connected to the principal Barbican charm.
In order for the Barbican charm to use this plugin (softhsm2) the
plugin needs to provide a PKCS#11 libary for barbican to access, a
password to access the token and a slot_id for the token.
This sets the plugin_data on the hsm relation for the Barbican charm to
pick up.
:param hsm: a BarbicanProvides instance for the relation.
:raises RuntimeError: if the token_store can't be setup - which is
FATAL.
"""
hookenv.log("Setting plugin name to softhsm2", level=hookenv.DEBUG)
hsm.set_name('softhsm2')
pin, so_pin = read_pins_from_store()
if pin is None:
self.setup_token_store()
pin, so_pin = read_pins_from_store()
if pin is None:
hookenv.status_set('error', "Couldn't set up the token store?")
raise RuntimeError(
"BarbicanSoftHSMCharm.setup_token_store() failed?")
slot_id = read_slot_id(BARBICAN_TOKEN_LABEL)
if slot_id is None:
raise RuntimeError("No {} slot in token store?"
.format(BARBICAN_TOKEN_LABEL))
plugin_data = {
"library_path": SOFTHSM2_LIB_PATH,
"login": pin,
"slot_id": slot_id
}
hsm.set_plugin_data(plugin_data)
def read_pins_from_store():
"""Read the pin and so_pin from the STORED_PINS_FILE file so that they can
be retrieved later.
The pins are stored in the file with 600 permissions, with the following
JSON format:
{
'pin': <pin string>,
'so_pin': <so_pin string>
}
:returns (pin, so_pin): the pins from the store or None, None
"""
try:
with open(STORED_PINS_FILE, 'r') as f:
o = json.load(f)
pin = o['pin']
so_pin = o['so_pin']
return pin, so_pin
except:
return None, None
def write_pins_to_store(pin, so_pin):
"""Write the pin and so_pin to the STORED_PINS_FILE file so that they can
be retrieved later.
The pins are stored in the file with 600 permissions, with the following
JSON format:
{
'pin': <pin string>,
'so_pin': <so_pin string>
}
:param pin: string to store
:param so_pin: string to store
:raises OSError: If the file couldn't be written.
:returns None:
"""
try:
with os.fdopen(os.open(STORED_PINS_FILE,
os.O_WRONLY | os.O_CREAT,
0o600), 'w') as f:
json.dump({'pin': pin, 'so_pin': so_pin}, f)
except OSError as e:
hookenv.log("Couldn't write pins file: {}".format(str(e)))
def read_slot_id(label):
"""Read the slot id for the `label` slot.
The format of the slot from 'softhsm2-util --show-slots' is:
Available slots:
Slot 0
Slot info:
Description: SoftHSM slot 0
Manufacturer ID: SoftHSM project
Hardware version: 2.0
Firmware version: 2.0
Token present: yes
Token info:
Manufacturer ID: SoftHSM project
Model: SoftHSM v2
Hardware version: 2.0
Firmware version: 2.0
Serial number: 02ae3171143498e7
Initialized: yes
User PIN init.: yes
Label: barbican_token
The function reads the text and then looks for the 'Label:' field, to
recover the Slot number.
:param label: string representing the slot to look for
:returns: slot number as String.
"""
cmd = [SOFTHSM2_UTIL_CMD, '--show-slots']
results = subprocess.check_output(cmd)
lines = results.decode().split("\n")
slot = None
for line in lines:
if line.startswith("Slot "):
slot = line[5:]
if (line.find('Label:') >= 0 and
line.find(label) >= 0 and
slot is not None):
return slot
return None

View File

@ -1,8 +1,19 @@
import charms.reactive as reactive
import charmhelpers.core.hookenv as hookenv
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import charms.reactive as reactive
# This charm's library contains all of the handler code associated with
# congress
import charm.openstack.softhsm_plugin as softhsm_plugin
@ -13,7 +24,8 @@ def install_packages():
softhsm_plugin.install()
reactive.set_state('charm.installed')
@reactive.when('hsm.connected')
def hsm_connected(hsm):
hookenv.log("Setting my name to softhsm")
hsm.set_name('softhsm')
softhsm_plugin.on_hsm_connected(hsm)
reactive.set_state('hsm.available')

View File

@ -3,4 +3,4 @@ os-testr>=0.4.1
charms.reactive
mock>=1.2
coverage>=3.6
git+https://github.com/ajkavanagh/charm.openstack#egg=charms-openstack
git+https://github.com/ajkavanagh/charms.openstack.git#egg=charms-openstack

10
tox.ini
View File

@ -22,10 +22,10 @@ basepython = python2.7
commands =
charm-build --log-level DEBUG -o {toxinidir}/build src {posargs}
[testenv:py27]
basepython = python2.7
deps = -r{toxinidir}/test-requirements.txt
commands = ostestr {posargs}
;[testenv:py27]
;basepython = python2.7
;deps = -r{toxinidir}/test-requirements.txt
;commands = ostestr {posargs}
[testenv:py34]
basepython = python3.4
@ -40,7 +40,7 @@ commands = ostestr {posargs}
[testenv:lint]
basepython = python2.7
deps = -r{toxinidir}/test-requirements.txt
commands = flake8 {posargs} src unit_tests
commands = flake8 {posargs} src
[testenv:venv]
commands = {posargs}

43
unit_tests/__init__.py Normal file
View File

@ -0,0 +1,43 @@
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import mock
sys.path.append('src')
sys.path.append('src/lib')
# Mock out charmhelpers so that we can test without it.
# also stops sideeffects from occuring.
charmhelpers = mock.MagicMock()
sys.modules['charmhelpers'] = charmhelpers
sys.modules['charmhelpers.core'] = charmhelpers.core
sys.modules['charmhelpers.core.hookenv'] = charmhelpers.core.hookenv
sys.modules['charmhelpers.core.host'] = charmhelpers.core.host
sys.modules['charmhelpers.core.unitdata'] = charmhelpers.core.unitdata
sys.modules['charmhelpers.core.templating'] = charmhelpers.core.templating
sys.modules['charmhelpers.contrib'] = charmhelpers.contrib
sys.modules['charmhelpers.contrib.openstack'] = charmhelpers.contrib.openstack
sys.modules['charmhelpers.contrib.openstack.utils'] = (
charmhelpers.contrib.openstack.utils)
sys.modules['charmhelpers.contrib.openstack.templating'] = (
charmhelpers.contrib.openstack.templating)
sys.modules['charmhelpers.contrib.network'] = charmhelpers.contrib.network
sys.modules['charmhelpers.contrib.network.ip'] = (
charmhelpers.contrib.network.ip)
sys.modules['charmhelpers.fetch'] = charmhelpers.fetch
sys.modules['charmhelpers.cli'] = charmhelpers.cli
sys.modules['charmhelpers.contrib.hahelpers'] = charmhelpers.contrib.hahelpers
sys.modules['charmhelpers.contrib.hahelpers.cluster'] = (
charmhelpers.contrib.hahelpers.cluster)

132
unit_tests/test_handlers.py Normal file
View File

@ -0,0 +1,132 @@
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import print_function
import unittest
import mock
import reactive.handlers as handlers
_when_args = {}
_when_not_args = {}
def mock_hook_factory(d):
def mock_hook(*args, **kwargs):
def inner(f):
# remember what we were passed. Note that we can't actually
# determine the class we're attached to, as the decorator only gets
# the function.
try:
d[f.__name__].append(dict(args=args, kwargs=kwargs))
except KeyError:
d[f.__name__] = [dict(args=args, kwargs=kwargs)]
return f
return inner
return mock_hook
class TestBarbicanHandlers(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._patched_when = mock.patch('charms.reactive.when',
mock_hook_factory(_when_args))
cls._patched_when_started = cls._patched_when.start()
cls._patched_when_not = mock.patch('charms.reactive.when_not',
mock_hook_factory(_when_not_args))
cls._patched_when_not_started = cls._patched_when_not.start()
# force requires to rerun the mock_hook decorator:
# try except is Python2/Python3 compatibility as Python3 has moved
# reload to importlib.
try:
reload(handlers)
except NameError:
import importlib
importlib.reload(handlers)
@classmethod
def tearDownClass(cls):
cls._patched_when.stop()
cls._patched_when_started = None
cls._patched_when = None
cls._patched_when_not.stop()
cls._patched_when_not_started = None
cls._patched_when_not = None
# and fix any breakage we did to the module
try:
reload(handlers)
except NameError:
import importlib
importlib.reload(handlers)
def setUp(self):
self._patches = {}
self._patches_start = {}
def tearDown(self):
for k, v in self._patches.items():
v.stop()
setattr(self, k, None)
self._patches = None
self._patches_start = None
def patch(self, obj, attr, return_value=None):
mocked = mock.patch.object(obj, attr)
self._patches[attr] = mocked
started = mocked.start()
started.return_value = return_value
self._patches_start[attr] = started
setattr(self, attr, started)
def test_registered_hooks(self):
# test that the hooks actually registered the relation expressions that
# are meaningful for this interface: this is to handle regressions.
# The keys are the function names that the hook attaches to.
when_patterns = {
'hsm_connected': ('hsm.connected', ),
}
when_not_patterns = {
'install_packages': ('charm.installed', ),
}
# check the when hooks are attached to the expected functions
for t, p in [(_when_args, when_patterns),
(_when_not_args, when_not_patterns)]:
for f, args in t.items():
# check that function is in patterns
# print("f: {}, args: {}".format(f, args))
self.assertTrue(f in p.keys())
# check that the lists are equal
l = [a['args'][0] for a in args]
self.assertEqual(l, sorted(p[f]))
def test_install_packages(self):
self.patch(handlers.softhsm_plugin, 'install')
self.patch(handlers.reactive, 'set_state')
handlers.install_packages()
self.install.assert_called_once_with()
self.set_state.assert_called_once_with('charm.installed')
def test_hsm_connected(self):
self.patch(handlers.softhsm_plugin, 'on_hsm_connected')
self.patch(handlers.reactive, 'set_state')
handlers.hsm_connected('hsm-thing')
self.on_hsm_connected.assert_called_once_with('hsm-thing')
self.set_state.assert_called_once_with('hsm.available')

View File

@ -0,0 +1,227 @@
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import print_function
import textwrap
import unittest
import mock
import charm.openstack.softhsm_plugin as softhsm_plugin
class Helper(unittest.TestCase):
def setUp(self):
self._patches = {}
self._patches_start = {}
# patch out the select_release to always return 'mitaka'
# self.patch(softhsm_plugin.unitdata, 'kv')
# _getter = mock.MagicMock()
# _getter.get.return_value = softhsm_plugin.BarbicanSoftHSMCharm.release
# self.kv.return_value = _getter
def tearDown(self):
for k, v in self._patches.items():
v.stop()
setattr(self, k, None)
self._patches = None
self._patches_start = None
def patch(self, obj, attr, return_value=None, **kwargs):
mocked = mock.patch.object(obj, attr, **kwargs)
self._patches[attr] = mocked
started = mocked.start()
started.return_value = return_value
self._patches_start[attr] = started
setattr(self, attr, started)
class TestSoftHSM(Helper):
def test_install(self):
self.patch(softhsm_plugin.BarbicanSoftHSMCharm.singleton, 'install')
softhsm_plugin.install()
self.install.assert_called_once_with()
def test_on_hsm_connected(self):
self.patch(softhsm_plugin.BarbicanSoftHSMCharm.singleton,
'on_hsm_connected')
softhsm_plugin.on_hsm_connected('hsm-thing')
self.on_hsm_connected.assert_called_once_with('hsm-thing')
def test_read_pins_from_store(self):
# test with no file (patch open so that it raises an error)
mock_open = mock.MagicMock(return_value=mock.sentinel.file_handle)
with mock.patch('builtins.open', mock_open):
def raise_exception():
raise Exception("Supposed to break")
mock_open.side_effect = raise_exception
pin, so_pin = softhsm_plugin.read_pins_from_store()
self.assertEqual(pin, None)
self.assertEqual(so_pin, None)
# now provide the pin and so pin as a json object
d = '{"pin": "1234", "so_pin": "5678"}'
with mock.patch('builtins.open',
mock.mock_open(read_data=d),
create=True):
pin, so_pin = softhsm_plugin.read_pins_from_store()
self.assertEqual(pin, '1234')
self.assertEqual(so_pin, '5678')
def test_write_pins_to_store(self):
f = mock.MagicMock()
self.patch(softhsm_plugin.os, 'fdopen', return_value=f)
self.patch(softhsm_plugin.os, 'open', return_value='opener')
self.patch(softhsm_plugin.json, 'dump')
softhsm_plugin.write_pins_to_store('1234', '5678')
self.open.assert_called_once_with(
softhsm_plugin.STORED_PINS_FILE,
softhsm_plugin.os.O_WRONLY | softhsm_plugin.os.O_CREAT,
0o600)
self.fdopen.assert_called_once_with('opener', 'w')
self.dump.assert_called_once_with(
{'pin': '1234', 'so_pin': '5678'}, f.__enter__())
def test_read_slot_id(self):
result = textwrap.dedent("""
Slot 5
Slot info:
Description: SoftHSM slot 0
Manufacturer ID: SoftHSM project
Hardware version: 2.0
Firmware version: 2.0
Token present: yes
Token info:
Manufacturer ID: SoftHSM project
Model: SoftHSM v2
Hardware version: 2.0
Firmware version: 2.0
Serial number: 02ae3171143498e7
Initialized: yes
User PIN init.: yes
Label: barbican_token
""")
self.patch(softhsm_plugin.subprocess, 'check_output',
return_value=result.encode())
self.assertEqual(softhsm_plugin.read_slot_id('barbican_token'), '5')
self.check_output.assert_called_once_with(
[softhsm_plugin.SOFTHSM2_UTIL_CMD, '--show-slots'])
self.assertEqual(softhsm_plugin.read_slot_id('not_found'), None)
class TestBarbicanSoftHSMCharm(Helper):
def test_install(self):
self.patch(softhsm_plugin.charms_openstack.charm.OpenStackCharm,
'install')
self.patch(softhsm_plugin.ch_core_host, 'add_user_to_group')
c = softhsm_plugin.BarbicanSoftHSMCharm()
self.patch(c, 'setup_token_store')
self.patch(softhsm_plugin.hookenv, 'status_set')
c.install()
self.install.assert_called_once_with()
self.add_user_to_group.assert_called_once_with('barbican', 'softhsm')
self.setup_token_store.assert_called_once_with()
self.status_set.assert_called_once_with(
'waiting', 'Charm installed and token store configured')
def test_setup_token_store(self):
self.patch(softhsm_plugin, 'read_pins_from_store')
self.patch(softhsm_plugin.os.path, 'exists')
self.patch(softhsm_plugin.os.path, 'isdir')
self.patch(softhsm_plugin.shutil, 'rmtree')
self.patch(softhsm_plugin.os, 'remove')
self.patch(softhsm_plugin.os, 'makedirs')
self.patch(softhsm_plugin.os, 'chmod')
self.patch(softhsm_plugin.ch_core_host, 'pwgen')
self.patch(softhsm_plugin, 'write_pins_to_store')
self.patch(softhsm_plugin.subprocess, 'check_call')
self.patch(softhsm_plugin.hookenv, 'log')
# first, pretend that the token store is already setup.
self.read_pins_from_store.return_value = ('1234', '5678', )
c = softhsm_plugin.BarbicanSoftHSMCharm()
c.setup_token_store()
self.assertEqual(self.log.call_count, 0)
# now pretend the token store isn't set up
self.read_pins_from_store.return_value = None, None
# assume that the token store exists and is a dir first:
self.exists.return_value = True
self.isdir.return_value = True
# return two values, for each of the two pwgen calls.
self.pwgen.side_effect = ['abcd', 'efgh']
c.setup_token_store()
# now validate it did everything we expected.
self.exists.assert_called_once_with(softhsm_plugin.TOKEN_STORE)
self.isdir.assert_called_once_with(softhsm_plugin.TOKEN_STORE)
self.rmtree.assert_called_once_with(softhsm_plugin.TOKEN_STORE)
self.makedirs.assert_called_once_with(softhsm_plugin.TOKEN_STORE)
self.chmod.assert_called_once_with(softhsm_plugin.TOKEN_STORE, 0o1777)
self.assertEqual(self.pwgen.call_count, 2)
self.write_pins_to_store.assert_called_once_with('abcd', 'efgh')
self.check_call.called_once_with([
'sudo', '-u', 'barbican',
softhsm_plugin.SOFTHSM2_UTIL_CMD,
'--init-token', '--free',
'--label', softhsm_plugin.BARBICAN_TOKEN_LABEL,
'--pin', 'abcd',
'--so-pin', 'efgh'])
self.log.assert_called_once_with("Initialised token store.")
def test_on_hsm_connected(self):
hsm = mock.MagicMock()
self.patch(softhsm_plugin, 'read_pins_from_store')
self.patch(softhsm_plugin, 'read_slot_id')
self.patch(softhsm_plugin.hookenv, 'status_set')
self.patch(softhsm_plugin.hookenv, 'log')
c = softhsm_plugin.BarbicanSoftHSMCharm()
self.patch(c, 'setup_token_store')
# simulate not being able to set up the token store
self.read_pins_from_store.return_value = None, None
with self.assertRaises(RuntimeError):
c.on_hsm_connected(hsm)
self.status_set.assert_called_once_with(
'error', "Couldn't set up the token store?")
self.setup_token_store.assert_called_once_with()
self.log.assert_called_once_with(
"Setting plugin name to softhsm2",
level=softhsm_plugin.hookenv.DEBUG)
# now assume that the pins can be read, but no slot is set up.
self.read_pins_from_store.return_value = '1234', '5678'
self.read_slot_id.return_value = None
with self.assertRaises(RuntimeError):
c.on_hsm_connected(hsm)
# now assume that the slot is also set up.
self.read_slot_id.return_value = '10'
c.on_hsm_connected(hsm)
hsm.set_plugin_data.assert_called_once_with({
"library_path": softhsm_plugin.SOFTHSM2_LIB_PATH,
"login": '1234',
"slot_id": '10'
})
# finally test corner case where token store isn't set up already
self.read_pins_from_store.side_effect = [
[None, None], ['abcd', 'efgh']]
hsm.reset_mock()
self.setup_token_store.reset_mock()
c.on_hsm_connected(hsm)
self.setup_token_store.assert_called_once_with()
hsm.set_plugin_data.assert_called_once_with({
"library_path": softhsm_plugin.SOFTHSM2_LIB_PATH,
"login": 'abcd',
"slot_id": '10'
})