summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.rst131
-rw-r--r--examples/pki/certs/cacert.pem18
-rw-r--r--examples/pki/certs/middleware.pem33
-rw-r--r--examples/pki/certs/signing_cert.pem17
-rw-r--r--examples/pki/certs/ssl_cert.pem17
-rw-r--r--examples/pki/cms/auth_token_revoked.json1
-rw-r--r--examples/pki/cms/auth_token_revoked.pem42
-rw-r--r--examples/pki/cms/auth_token_scoped.json1
-rw-r--r--examples/pki/cms/auth_token_scoped.pem41
-rw-r--r--examples/pki/cms/auth_token_unscoped.json1
-rw-r--r--examples/pki/cms/auth_token_unscoped.pem17
-rw-r--r--examples/pki/cms/revocation_list.json1
-rw-r--r--examples/pki/cms/revocation_list.pem12
-rwxr-xr-xexamples/pki/gen_pki.sh222
-rw-r--r--examples/pki/private/cakey.pem16
-rw-r--r--examples/pki/private/signing_key.pem16
-rw-r--r--examples/pki/private/ssl_key.pem16
-rw-r--r--keystoneclient/access.py144
-rw-r--r--keystoneclient/client.py86
-rw-r--r--keystoneclient/common/__init__.py0
-rw-r--r--keystoneclient/common/cms.py169
-rw-r--r--keystoneclient/middleware/__init__.py0
-rw-r--r--keystoneclient/middleware/auth_token.py864
-rw-r--r--keystoneclient/middleware/test.py67
-rw-r--r--keystoneclient/openstack/common/cfg.py1653
-rw-r--r--keystoneclient/openstack/common/iniparser.py130
-rw-r--r--keystoneclient/openstack/common/jsonutils.py148
-rw-r--r--keystoneclient/openstack/common/setup.py94
-rw-r--r--keystoneclient/openstack/common/timeutils.py137
-rw-r--r--keystoneclient/service_catalog.py2
-rw-r--r--keystoneclient/shell.py60
-rw-r--r--keystoneclient/utils.py7
-rw-r--r--keystoneclient/v2_0/client.py166
-rwxr-xr-xkeystoneclient/v2_0/shell.py8
-rw-r--r--keystoneclient/v2_0/tenants.py11
-rw-r--r--keystoneclient/v2_0/tokens.py10
-rw-r--r--openstack-common.conf2
-rwxr-xr-xrun_tests.sh7
-rw-r--r--tests/client_fixtures.py72
-rw-r--r--tests/test_access.py56
-rw-r--r--tests/test_auth_token_middleware.py670
-rw-r--r--tests/test_client.py37
-rw-r--r--tests/test_http.py7
-rw-r--r--tests/v2_0/test_auth.py6
-rw-r--r--tools/test-requires2
45 files changed, 5016 insertions, 201 deletions
diff --git a/README.rst b/README.rst
index 6106b48..b6eb7cb 100644
--- a/README.rst
+++ b/README.rst
@@ -5,15 +5,15 @@ This is a client for the OpenStack Identity API, implemented by Keystone.
There's a Python API (the ``keystoneclient`` module), and a command-line script
(``keystone``).
-Development takes place via the usual OpenStack processes as outlined in
-the `OpenStack wiki`_. The master repository is on GitHub__.
+Development takes place via the usual OpenStack processes as outlined in the
+`OpenStack wiki`_. The master repository is on GitHub__.
__ http://wiki.openstack.org/HowToContribute
__ http://github.com/openstack/python-keystoneclient
-This code a fork of `Rackspace's python-novaclient`__ which is in turn a fork of
-`Jacobian's python-cloudservers`__. The python-keystoneclient is licensed under
-the Apache License like the rest of OpenStack.
+This code a fork of `Rackspace's python-novaclient`__ which is in turn a fork
+of `Jacobian's python-cloudservers`__. The python-keystoneclient is licensed
+under the Apache License like the rest of OpenStack.
__ http://github.com/rackspace/python-novaclient
__ http://github.com/jacobian/python-cloudservers
@@ -37,40 +37,45 @@ By way of a quick-start::
Command-line API
----------------
-Installing this package gets you a shell command, ``keystone``, that you
-can use to interact with OpenStack's Identity API.
+Installing this package gets you a shell command, ``keystone``, that you can
+use to interact with OpenStack's Identity API.
-You'll need to provide your OpenStack tenant, username and password. You can
-do this with the ``--os-tenant-name``, ``--os-username`` and ``--os-password``
+You'll need to provide your OpenStack tenant, username and password. You can do
+this with the ``--os-tenant-name``, ``--os-username`` and ``--os-password``
params, but it's easier to just set them as environment variables::
export OS_TENANT_NAME=project
export OS_USERNAME=user
export OS_PASSWORD=pass
-You will also need to define the authentication url with ``--os-auth-url`` and the
-version of the API with ``--os-identity-api-version``. Or set them as an environment
-variables as well::
+You will also need to define the authentication url with ``--os-auth-url`` and
+the version of the API with ``--os-identity-api-version``. Or set them as an
+environment variables as well::
export OS_AUTH_URL=http://example.com:5000/v2.0
export OS_IDENTITY_API_VERSION=2.0
-Alternatively, to authenticate to Keystone without a username/password,
-such as when there are no users in the database yet, use the service
-token and endpoint arguemnts. The service token is set in keystone.conf as
-``admin_token``; set it with ``service_token``. Note: keep the service token
-secret as it allows total access to Keystone's database. The admin endpoint is set
-with ``--endpoint`` or ``SERVICE_ENDPOINT``::
+Alternatively, to bypass username/password authentication, you can provide a
+pre-established token. In Keystone, this approach is necessary to bootstrap the
+service with an administrative user, tenant & role (to do so, provide the
+client with the value of your ``admin_token`` defined in ``keystone.conf`` in
+addition to the URL of your admin API deployment, typically on port 35357)::
- export SERVICE_TOKEN=thequickbrownfox-jumpsover-thelazydog
- export SERVICE_ENDPOINT=http://example.com:35357/v2.0
+ export OS_SERVICE_TOKEN=thequickbrownfox-jumpsover-thelazydog
+ export OS_SERVICE_ENDPOINT=http://example.com:35357/v2.0
-Since Keystone can return multiple regions in the Service Catalog, you
-can specify the one you want with ``--region_name`` (or
-``export OS_REGION_NAME``). It defaults to the first in the list returned.
+Since the Identity service can return multiple regions in the service catalog,
+you can specify the one you want with ``--os-region-name`` (or ``export
+OS_REGION_NAME``)::
-You'll find complete documentation on the shell by running
-``keystone help``::
+ export OS_REGION_NAME=north
+
+.. WARNING::
+
+ If a region is not specified and multiple regions are returned by the
+ Identity service, the client may not access the same region consistently.
+
+You'll find complete documentation on the shell by running ``keystone help``::
usage: keystone [--os-username <auth-user-name>]
[--os-password <auth-password>]
@@ -78,14 +83,17 @@ You'll find complete documentation on the shell by running
[--os-tenant-id <tenant-id>] [--os-auth-url <auth-url>]
[--os-region-name <region-name>]
[--os-identity-api-version <identity-api-version>]
- [--token <service-token>] [--endpoint <service-endpoint>]
+ [--os-token <service-token>]
+ [--os-endpoint <service-endpoint>]
+ [--os-cacert <ca-certificate>] [--os-cert <certificate>]
+ [--os-key <key>] [--insecure]
<subcommand> ...
Command-line interface to the OpenStack Identity API.
Positional arguments:
- <subcommand>
- catalog List service catalog, possibly filtered by service.
+ <subcommand>
+ catalog
ec2-credentials-create
Create EC2-compatibile credentials for user per tenant
ec2-credentials-delete
@@ -96,13 +104,12 @@ You'll find complete documentation on the shell by running
List EC2-compatibile credentials for a user
endpoint-create Create a new endpoint associated with a service
endpoint-delete Delete a service endpoint
- endpoint-get Find endpoint filtered by a specific attribute or
- service type
+ endpoint-get
endpoint-list List configured service endpoints
role-create Create new role
role-delete Delete role
role-get Display role details
- role-list List all available roles
+ role-list List all roles
service-create Add service to Service Catalog
service-delete Delete service from Service Catalog
service-get Display service from Service Catalog
@@ -112,39 +119,61 @@ You'll find complete documentation on the shell by running
tenant-get Display tenant details
tenant-list List all tenants
tenant-update Update tenant name, description, enabled status
- token-get Display the current user token
+ token-get
user-create Create new user
user-delete Delete user
+ user-get Display user details.
user-list List users
user-password-update
Update user password
user-role-add Add role to user
+ user-role-list List roles granted to a user
user-role-remove Remove role from user
- user-role-list List roles for user
user-update Update user's name, email, and enabled status
discover Discover Keystone servers and show authentication
protocols and
+ bootstrap Grants a new role to a new user on a new tenant, after
+ creating each.
+ bash-completion Prints all of the commands and options to stdout.
help Display help about this program or one of its
subcommands.
Optional arguments:
- --os-username <auth-user-name>
- Defaults to env[OS_USERNAME]
- --os-password <auth-password>
- Defaults to env[OS_PASSWORD]
- --os-tenant-name <auth-tenant-name>
- Defaults to env[OS_TENANT_NAME]
- --os-tenant-id <tenant-id>
- Defaults to env[OS_TENANT_ID]
- --os-auth-url <auth-url>
- Defaults to env[OS_AUTH_URL]
- --os-region-name <region-name>
+ --os-username <auth-user-name>
+ Name used for authentication with the OpenStack
+ Identity service. Defaults to env[OS_USERNAME]
+ --os-password <auth-password>
+ Password used for authentication with the OpenStack
+ Identity service. Defaults to env[OS_PASSWORD]
+ --os-tenant-name <auth-tenant-name>
+ Tenant to request authorization on. Defaults to
+ env[OS_TENANT_NAME]
+ --os-tenant-id <tenant-id>
+ Tenant to request authorization on. Defaults to
+ env[OS_TENANT_ID]
+ --os-auth-url <auth-url>
+ Specify the Identity endpoint to use for
+ authentication. Defaults to env[OS_AUTH_URL]
+ --os-region-name <region-name>
Defaults to env[OS_REGION_NAME]
- --os-identity-api-version <identity-api-version>
+ --os-identity-api-version <identity-api-version>
Defaults to env[OS_IDENTITY_API_VERSION] or 2.0
- --token <service-token>
- Defaults to env[SERVICE_TOKEN]
- --endpoint <service-endpoint>
- Defaults to env[SERVICE_ENDPOINT]
-
-See "keystone help COMMAND" for help on a specific command.
+ --os-token <service-token>
+ Specify an existing token to use instead of retrieving
+ one via authentication (e.g. with username &
+ password). Defaults to env[OS_SERVICE_TOKEN]
+ --os-endpoint <service-endpoint>
+ Specify an endpoint to use instead of retrieving one
+ from the service catalog (via authentication).
+ Defaults to env[OS_SERVICE_ENDPOINT]
+ --os-cacert <ca-certificate>
+ Defaults to env[OS_CACERT]
+ --os-cert <certificate>
+ Defaults to env[OS_CERT]
+ --os-key <key> Defaults to env[OS_KEY]
+ --insecure Explicitly allow keystoneclient to perform "insecure"
+ SSL (https) requests. The server's certificate will
+ not be verified against any certificate authorities.
+ This option should be used with caution.
+
+ See "keystone help COMMAND" for help on a specific command.
diff --git a/examples/pki/certs/cacert.pem b/examples/pki/certs/cacert.pem
new file mode 100644
index 0000000..8cf663c
--- /dev/null
+++ b/examples/pki/certs/cacert.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC0TCCAjqgAwIBAgIJAP2TNFqmE1KUMA0GCSqGSIb3DQEBBQUAMIGeMQowCAYD
+VQQFEwE1MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVN1bm55
+dmFsZTESMBAGA1UEChMJT3BlblN0YWNrMREwDwYDVQQLEwhLZXlzdG9uZTElMCMG
+CSqGSIb3DQEJARYWa2V5c3RvbmVAb3BlbnN0YWNrLm9yZzEUMBIGA1UEAxMLU2Vs
+ZiBTaWduZWQwIBcNMTIxMTExMTA1NDA2WhgPMjA3MTA1MDYxMDU0MDZaMIGeMQow
+CAYDVQQFEwE1MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVN1
+bm55dmFsZTESMBAGA1UEChMJT3BlblN0YWNrMREwDwYDVQQLEwhLZXlzdG9uZTEl
+MCMGCSqGSIb3DQEJARYWa2V5c3RvbmVAb3BlbnN0YWNrLm9yZzEUMBIGA1UEAxML
+U2VsZiBTaWduZWQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMXgnd5wlHAp
+GxZ58LrpEkHU995lT9PxtMgkp0tpFhg7R5HQw9K7TfQk5NHB28hNzf8UE/c0z2pJ
+XggPnAzvdx27NQeJGX5CWsi6fITZ8vH/+SxgfxxC+CE/6BkDpzw21MgBtq11vWL7
+XVaxNeU12Ax889U66i3CrObuCYt2mbpzAgMBAAGjEzARMA8GA1UdEwEB/wQFMAMB
+Af8wDQYJKoZIhvcNAQEFBQADgYEAkFIbnr2/0/XWp+f80Gl6GAC7tdmZFlT9udVF
+q794rXyMlYY64pq34SzfQAn+4DztT4B9yzrTx03tLNr6Uf+5TS+ubcwG41UBBMs/
+Icf9zBMRqr+IXhijS49gQ7dPjqNTCqX+6ILbRWjdXP15ZWymI3ayQL/CMwFt/E+0
+kT6MLes=
+-----END CERTIFICATE-----
diff --git a/examples/pki/certs/middleware.pem b/examples/pki/certs/middleware.pem
new file mode 100644
index 0000000..ae5b8db
--- /dev/null
+++ b/examples/pki/certs/middleware.pem
@@ -0,0 +1,33 @@
+-----BEGIN CERTIFICATE-----
+MIICoTCCAgoCARAwDQYJKoZIhvcNAQEFBQAwgZ4xCjAIBgNVBAUTATUxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQK
+EwlPcGVuU3RhY2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZr
+ZXlzdG9uZUBvcGVuc3RhY2sub3JnMRQwEgYDVQQDEwtTZWxmIFNpZ25lZDAgFw0x
+MjExMTExMDU0MDZaGA8yMDcxMDUwNjEwNTQwNlowgZAxCzAJBgNVBAYTAlVTMQsw
+CQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQKEwlPcGVuU3Rh
+Y2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZrZXlzdG9uZUBv
+cGVuc3RhY2sub3JnMRIwEAYDVQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEB
+BQADgY0AMIGJAoGBALVu4bjaOH33yAx0WdpEqj4UDVsLxVjWxEpIbOlDlc6IfJd+
+cUriQtxf6ahjxtzLPERS81SnwZmrICWZngbOn733pULMTZktTJH+o7C74NdKwUSN
+xjlCeWUy+FqIQoje4ygoJRPpMdkp1wHNO0ZERwRN9e8M5TIlx/LRtk+q8bT5AgMB
+AAEwDQYJKoZIhvcNAQEFBQADgYEAcp9ancue9Oq+MkaPucCrIqFhiUsdUThulJlB
+etPpUDGgStBSHgze/oxG2+flIjRoI6gG9Chfw//vWHOwDT7N32AHSgaI4b8/k/+s
+hAV2khYkV4PW2oS1TfeU/vxQzXbgApqhLBNqfFmJVW48aGAr/aqsJi3MYWN3269+
+6vChaVw=
+-----END CERTIFICATE-----
+-----BEGIN PRIVATE KEY-----
+MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALVu4bjaOH33yAx0
+WdpEqj4UDVsLxVjWxEpIbOlDlc6IfJd+cUriQtxf6ahjxtzLPERS81SnwZmrICWZ
+ngbOn733pULMTZktTJH+o7C74NdKwUSNxjlCeWUy+FqIQoje4ygoJRPpMdkp1wHN
+O0ZERwRN9e8M5TIlx/LRtk+q8bT5AgMBAAECgYAmwq6EYFJrTvE0//JmN/8qzfvg
+dI5PoWpD+F8UInUxr2T2tHOdrOLd07vGVrKYXu7cJeCIOGKa4r02azAggioL/nE9
+FgPpqEC+QROvLuhFsk1gLZ2pGQ06sveKZVMH22h59BKZkYlhjh5qd4vlmhPqkmPp
+gdXj7ZjDCJhhQdFVkQJBANp18k2mVksn8q29LMieVTSIZNN3ucDA1QHbim+3fp/O
+GxCzU7Mv1Xfnu1zoRFu5/sF3YG0Zy3TGPDrEljBC3rUCQQDUnBjVFXL35OkBZqXW
+taJPzGbsPoqAO+Ls2juS97zNzeGxUNhvcKuEvHO63PXqDxp1535DpvJEBN1rT2FF
+iaO1AkEAt/QTWWFUTqrPxY6DNFdm5fpn9E1fg7icZJkKBDJeFJCH59MpCryfovzl
+n0ERtq9ynlQ4RQYwdR8rvkylLvRP9QJAOiXHFOAc5XeR0nREfwiGL9TzgUFJl/DJ
+C4ZULMnctVzNkTVPPItQHal87WppR26CCiUZ/161e6zo8eRv8hjG0QJABWqfYQuK
+dWH8nxlXS+NFUDbsCdL+XpOVE7iEH7hvSw/A/kz40mLx8sDp/Fz1ysrogR/L+NGC
+Vrlwm4q/WYJO0Q==
+-----END PRIVATE KEY-----
diff --git a/examples/pki/certs/signing_cert.pem b/examples/pki/certs/signing_cert.pem
new file mode 100644
index 0000000..1491b55
--- /dev/null
+++ b/examples/pki/certs/signing_cert.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICoDCCAgkCAREwDQYJKoZIhvcNAQEFBQAwgZ4xCjAIBgNVBAUTATUxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQK
+EwlPcGVuU3RhY2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZr
+ZXlzdG9uZUBvcGVuc3RhY2sub3JnMRQwEgYDVQQDEwtTZWxmIFNpZ25lZDAgFw0x
+MjExMTExMDU0MDZaGA8yMDcxMDUwNjEwNTQwNlowgY8xCzAJBgNVBAYTAlVTMQsw
+CQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQKEwlPcGVuU3Rh
+Y2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZrZXlzdG9uZUBv
+cGVuc3RhY2sub3JnMREwDwYDVQQDEwhLZXlzdG9uZTCBnzANBgkqhkiG9w0BAQEF
+AAOBjQAwgYkCgYEAuoQC6IBqMxC5845c/ZkLsdcQbTHqIpYJHEkwEoxyeEjwiGFf
+iZmiZ91pSFNc9MfjdJnN+be/ndVS19w1nrrJvV/udVsf6JZWkTPX5HyxnllwznCH
+pP7gfvMZzGsqzWlSdiD6mcRbCYRX9hCCauG3jhCtISINCVYMYQGH6QSib9sCAwEA
+ATANBgkqhkiG9w0BAQUFAAOBgQBCssELi+1RSjEmzeqSnpgUqmtpvB9oxbcwl+xH
+rIrYvqMU6pV2aSxgLDqpGjjusLHUau9Bmu3Myc/fm9/mlPUQHNj0AWl8vvfSlq1b
+vsWMUa1h4UFlPWoF2DIUFd+noBxe5CbcLUV6K0oyJAcPO433OyuGl5oQkhxmoy1J
+w59KRg==
+-----END CERTIFICATE-----
diff --git a/examples/pki/certs/ssl_cert.pem b/examples/pki/certs/ssl_cert.pem
new file mode 100644
index 0000000..0a0bc21
--- /dev/null
+++ b/examples/pki/certs/ssl_cert.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICoTCCAgoCARAwDQYJKoZIhvcNAQEFBQAwgZ4xCjAIBgNVBAUTATUxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQK
+EwlPcGVuU3RhY2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZr
+ZXlzdG9uZUBvcGVuc3RhY2sub3JnMRQwEgYDVQQDEwtTZWxmIFNpZ25lZDAgFw0x
+MjExMTExMDU0MDZaGA8yMDcxMDUwNjEwNTQwNlowgZAxCzAJBgNVBAYTAlVTMQsw
+CQYDVQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQKEwlPcGVuU3Rh
+Y2sxETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZrZXlzdG9uZUBv
+cGVuc3RhY2sub3JnMRIwEAYDVQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEB
+BQADgY0AMIGJAoGBALVu4bjaOH33yAx0WdpEqj4UDVsLxVjWxEpIbOlDlc6IfJd+
+cUriQtxf6ahjxtzLPERS81SnwZmrICWZngbOn733pULMTZktTJH+o7C74NdKwUSN
+xjlCeWUy+FqIQoje4ygoJRPpMdkp1wHNO0ZERwRN9e8M5TIlx/LRtk+q8bT5AgMB
+AAEwDQYJKoZIhvcNAQEFBQADgYEAcp9ancue9Oq+MkaPucCrIqFhiUsdUThulJlB
+etPpUDGgStBSHgze/oxG2+flIjRoI6gG9Chfw//vWHOwDT7N32AHSgaI4b8/k/+s
+hAV2khYkV4PW2oS1TfeU/vxQzXbgApqhLBNqfFmJVW48aGAr/aqsJi3MYWN3269+
+6vChaVw=
+-----END CERTIFICATE-----
diff --git a/examples/pki/cms/auth_token_revoked.json b/examples/pki/cms/auth_token_revoked.json
new file mode 100644
index 0000000..92c6922
--- /dev/null
+++ b/examples/pki/cms/auth_token_revoked.json
@@ -0,0 +1 @@
+{"access": {"serviceCatalog": [{"endpoints": [{"adminURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a", "region": "regionOne", "internalURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a", "publicURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a"}], "endpoints_links": [], "type": "volume", "name": "volume"}, {"endpoints": [{"adminURL": "http://127.0.0.1:9292/v1", "region": "regionOne", "internalURL": "http://127.0.0.1:9292/v1", "publicURL": "http://127.0.0.1:9292/v1"}], "endpoints_links": [], "type": "image", "name": "glance"}, {"endpoints": [{"adminURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a", "region": "regionOne", "internalURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a", "publicURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a"}], "endpoints_links": [], "type": "compute", "name": "nova"}, {"endpoints": [{"adminURL": "http://127.0.0.1:35357/v2.0", "region": "RegionOne", "internalURL": "http://127.0.0.1:35357/v2.0", "publicURL": "http://127.0.0.1:5000/v2.0"}], "endpoints_links": [], "type": "identity", "name": "keystone"}],"token": {"expires": "2012-06-02T14:47:34Z", "id": "placeholder", "tenant": {"enabled": true, "description": null, "name": "tenant_name1", "id": "tenant_id1"}}, "user": {"username": "revoked_username1", "roles_links": ["role1","role2"], "id": "revoked_user_id1", "roles": [{"name": "role1"}, {"name": "role2"}], "name": "revoked_username1"}}}
diff --git a/examples/pki/cms/auth_token_revoked.pem b/examples/pki/cms/auth_token_revoked.pem
new file mode 100644
index 0000000..0bd7a70
--- /dev/null
+++ b/examples/pki/cms/auth_token_revoked.pem
@@ -0,0 +1,42 @@
+-----BEGIN CMS-----
+MIIHVgYJKoZIhvcNAQcCoIIHRzCCB0MCAQExCTAHBgUrDgMCGjCCBeQGCSqGSIb3
+DQEHAaCCBdUEggXReyJhY2Nlc3MiOiB7InNlcnZpY2VDYXRhbG9nIjogW3siZW5k
+cG9pbnRzIjogW3siYWRtaW5VUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo4Nzc2L3Yx
+LzY0YjZmM2ZiY2M1MzQzNWU4YTYwZmNmODliYjY2MTdhIiwgInJlZ2lvbiI6ICJy
+ZWdpb25PbmUiLCAiaW50ZXJuYWxVUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo4Nzc2
+L3YxLzY0YjZmM2ZiY2M1MzQzNWU4YTYwZmNmODliYjY2MTdhIiwgInB1YmxpY1VS
+TCI6ICJodHRwOi8vMTI3LjAuMC4xOjg3NzYvdjEvNjRiNmYzZmJjYzUzNDM1ZThh
+NjBmY2Y4OWJiNjYxN2EifV0sICJlbmRwb2ludHNfbGlua3MiOiBbXSwgInR5cGUi
+OiAidm9sdW1lIiwgIm5hbWUiOiAidm9sdW1lIn0sIHsiZW5kcG9pbnRzIjogW3si
+YWRtaW5VUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo5MjkyL3YxIiwgInJlZ2lvbiI6
+ICJyZWdpb25PbmUiLCAiaW50ZXJuYWxVUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo5
+MjkyL3YxIiwgInB1YmxpY1VSTCI6ICJodHRwOi8vMTI3LjAuMC4xOjkyOTIvdjEi
+fV0sICJlbmRwb2ludHNfbGlua3MiOiBbXSwgInR5cGUiOiAiaW1hZ2UiLCAibmFt
+ZSI6ICJnbGFuY2UifSwgeyJlbmRwb2ludHMiOiBbeyJhZG1pblVSTCI6ICJodHRw
+Oi8vMTI3LjAuMC4xOjg3NzQvdjEuMS82NGI2ZjNmYmNjNTM0MzVlOGE2MGZjZjg5
+YmI2NjE3YSIsICJyZWdpb24iOiAicmVnaW9uT25lIiwgImludGVybmFsVVJMIjog
+Imh0dHA6Ly8xMjcuMC4wLjE6ODc3NC92MS4xLzY0YjZmM2ZiY2M1MzQzNWU4YTYw
+ZmNmODliYjY2MTdhIiwgInB1YmxpY1VSTCI6ICJodHRwOi8vMTI3LjAuMC4xOjg3
+NzQvdjEuMS82NGI2ZjNmYmNjNTM0MzVlOGE2MGZjZjg5YmI2NjE3YSJ9XSwgImVu
+ZHBvaW50c19saW5rcyI6IFtdLCAidHlwZSI6ICJjb21wdXRlIiwgIm5hbWUiOiAi
+bm92YSJ9LCB7ImVuZHBvaW50cyI6IFt7ImFkbWluVVJMIjogImh0dHA6Ly8xMjcu
+MC4wLjE6MzUzNTcvdjIuMCIsICJyZWdpb24iOiAiUmVnaW9uT25lIiwgImludGVy
+bmFsVVJMIjogImh0dHA6Ly8xMjcuMC4wLjE6MzUzNTcvdjIuMCIsICJwdWJsaWNV
+UkwiOiAiaHR0cDovLzEyNy4wLjAuMTo1MDAwL3YyLjAifV0sICJlbmRwb2ludHNf
+bGlua3MiOiBbXSwgInR5cGUiOiAiaWRlbnRpdHkiLCAibmFtZSI6ICJrZXlzdG9u
+ZSJ9XSwidG9rZW4iOiB7ImV4cGlyZXMiOiAiMjAxMi0wNi0wMlQxNDo0NzozNFoi
+LCAiaWQiOiAicGxhY2Vob2xkZXIiLCAidGVuYW50IjogeyJlbmFibGVkIjogdHJ1
+ZSwgImRlc2NyaXB0aW9uIjogbnVsbCwgIm5hbWUiOiAidGVuYW50X25hbWUxIiwg
+ImlkIjogInRlbmFudF9pZDEifX0sICJ1c2VyIjogeyJ1c2VybmFtZSI6ICJyZXZv
+a2VkX3VzZXJuYW1lMSIsICJyb2xlc19saW5rcyI6IFsicm9sZTEiLCJyb2xlMiJd
+LCAiaWQiOiAicmV2b2tlZF91c2VyX2lkMSIsICJyb2xlcyI6IFt7Im5hbWUiOiAi
+cm9sZTEifSwgeyJuYW1lIjogInJvbGUyIn1dLCAibmFtZSI6ICJyZXZva2VkX3Vz
+ZXJuYW1lMSJ9fX0NCjGCAUkwggFFAgEBMIGkMIGeMQowCAYDVQQFEwE1MQswCQYD
+VQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVN1bm55dmFsZTESMBAGA1UE
+ChMJT3BlblN0YWNrMREwDwYDVQQLEwhLZXlzdG9uZTElMCMGCSqGSIb3DQEJARYW
+a2V5c3RvbmVAb3BlbnN0YWNrLm9yZzEUMBIGA1UEAxMLU2VsZiBTaWduZWQCAREw
+BwYFKw4DAhowDQYJKoZIhvcNAQEBBQAEgYBhV5KrVjcdACPUNafkPY+lgCSlh6uc
+N55SATBcQmg1/argEUFg/cx2GcF7ftQV384iGepLEgsq+6om2wPw6DWA0RknpVLJ
+vMsHbWdGoXIZ5jRuAQTPtkXcJQOR677baDHvGJ+5zwBBDT2CmN2Tcv348+Xpjp7D
+hF/cmAXnYYo00g==
+-----END CMS-----
diff --git a/examples/pki/cms/auth_token_scoped.json b/examples/pki/cms/auth_token_scoped.json
new file mode 100644
index 0000000..16eb644
--- /dev/null
+++ b/examples/pki/cms/auth_token_scoped.json
@@ -0,0 +1 @@
+{"access": {"serviceCatalog": [{"endpoints": [{"adminURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a", "region": "regionOne", "internalURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a", "publicURL": "http://127.0.0.1:8776/v1/64b6f3fbcc53435e8a60fcf89bb6617a"}], "endpoints_links": [], "type": "volume", "name": "volume"}, {"endpoints": [{"adminURL": "http://127.0.0.1:9292/v1", "region": "regionOne", "internalURL": "http://127.0.0.1:9292/v1", "publicURL": "http://127.0.0.1:9292/v1"}], "endpoints_links": [], "type": "image", "name": "glance"}, {"endpoints": [{"adminURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a", "region": "regionOne", "internalURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a", "publicURL": "http://127.0.0.1:8774/v1.1/64b6f3fbcc53435e8a60fcf89bb6617a"}], "endpoints_links": [], "type": "compute", "name": "nova"}, {"endpoints": [{"adminURL": "http://127.0.0.1:35357/v2.0", "region": "RegionOne", "internalURL": "http://127.0.0.1:35357/v2.0", "publicURL": "http://127.0.0.1:5000/v2.0"}], "endpoints_links": [], "type": "identity", "name": "keystone"}],"token": {"expires": "2012-06-02T14:47:34Z", "id": "placeholder", "tenant": {"enabled": true, "description": null, "name": "tenant_name1", "id": "tenant_id1"}}, "user": {"username": "user_name1", "roles_links": ["role1","role2"], "id": "user_id1", "roles": [{"name": "role1"}, {"name": "role2"}], "name": "user_name1"}}}
diff --git a/examples/pki/cms/auth_token_scoped.pem b/examples/pki/cms/auth_token_scoped.pem
new file mode 100644
index 0000000..529d7f8
--- /dev/null
+++ b/examples/pki/cms/auth_token_scoped.pem
@@ -0,0 +1,41 @@
+-----BEGIN CMS-----
+MIIHQAYJKoZIhvcNAQcCoIIHMTCCBy0CAQExCTAHBgUrDgMCGjCCBc4GCSqGSIb3
+DQEHAaCCBb8EggW7eyJhY2Nlc3MiOiB7InNlcnZpY2VDYXRhbG9nIjogW3siZW5k
+cG9pbnRzIjogW3siYWRtaW5VUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo4Nzc2L3Yx
+LzY0YjZmM2ZiY2M1MzQzNWU4YTYwZmNmODliYjY2MTdhIiwgInJlZ2lvbiI6ICJy
+ZWdpb25PbmUiLCAiaW50ZXJuYWxVUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo4Nzc2
+L3YxLzY0YjZmM2ZiY2M1MzQzNWU4YTYwZmNmODliYjY2MTdhIiwgInB1YmxpY1VS
+TCI6ICJodHRwOi8vMTI3LjAuMC4xOjg3NzYvdjEvNjRiNmYzZmJjYzUzNDM1ZThh
+NjBmY2Y4OWJiNjYxN2EifV0sICJlbmRwb2ludHNfbGlua3MiOiBbXSwgInR5cGUi
+OiAidm9sdW1lIiwgIm5hbWUiOiAidm9sdW1lIn0sIHsiZW5kcG9pbnRzIjogW3si
+YWRtaW5VUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo5MjkyL3YxIiwgInJlZ2lvbiI6
+ICJyZWdpb25PbmUiLCAiaW50ZXJuYWxVUkwiOiAiaHR0cDovLzEyNy4wLjAuMTo5
+MjkyL3YxIiwgInB1YmxpY1VSTCI6ICJodHRwOi8vMTI3LjAuMC4xOjkyOTIvdjEi
+fV0sICJlbmRwb2ludHNfbGlua3MiOiBbXSwgInR5cGUiOiAiaW1hZ2UiLCAibmFt
+ZSI6ICJnbGFuY2UifSwgeyJlbmRwb2ludHMiOiBbeyJhZG1pblVSTCI6ICJodHRw
+Oi8vMTI3LjAuMC4xOjg3NzQvdjEuMS82NGI2ZjNmYmNjNTM0MzVlOGE2MGZjZjg5
+YmI2NjE3YSIsICJyZWdpb24iOiAicmVnaW9uT25lIiwgImludGVybmFsVVJMIjog
+Imh0dHA6Ly8xMjcuMC4wLjE6ODc3NC92MS4xLzY0YjZmM2ZiY2M1MzQzNWU4YTYw
+ZmNmODliYjY2MTdhIiwgInB1YmxpY1VSTCI6ICJodHRwOi8vMTI3LjAuMC4xOjg3
+NzQvdjEuMS82NGI2ZjNmYmNjNTM0MzVlOGE2MGZjZjg5YmI2NjE3YSJ9XSwgImVu
+ZHBvaW50c19saW5rcyI6IFtdLCAidHlwZSI6ICJjb21wdXRlIiwgIm5hbWUiOiAi
+bm92YSJ9LCB7ImVuZHBvaW50cyI6IFt7ImFkbWluVVJMIjogImh0dHA6Ly8xMjcu
+MC4wLjE6MzUzNTcvdjIuMCIsICJyZWdpb24iOiAiUmVnaW9uT25lIiwgImludGVy
+bmFsVVJMIjogImh0dHA6Ly8xMjcuMC4wLjE6MzUzNTcvdjIuMCIsICJwdWJsaWNV
+UkwiOiAiaHR0cDovLzEyNy4wLjAuMTo1MDAwL3YyLjAifV0sICJlbmRwb2ludHNf
+bGlua3MiOiBbXSwgInR5cGUiOiAiaWRlbnRpdHkiLCAibmFtZSI6ICJrZXlzdG9u
+ZSJ9XSwidG9rZW4iOiB7ImV4cGlyZXMiOiAiMjAxMi0wNi0wMlQxNDo0NzozNFoi
+LCAiaWQiOiAicGxhY2Vob2xkZXIiLCAidGVuYW50IjogeyJlbmFibGVkIjogdHJ1
+ZSwgImRlc2NyaXB0aW9uIjogbnVsbCwgIm5hbWUiOiAidGVuYW50X25hbWUxIiwg
+ImlkIjogInRlbmFudF9pZDEifX0sICJ1c2VyIjogeyJ1c2VybmFtZSI6ICJ1c2Vy
+X25hbWUxIiwgInJvbGVzX2xpbmtzIjogWyJyb2xlMSIsInJvbGUyIl0sICJpZCI6
+ICJ1c2VyX2lkMSIsICJyb2xlcyI6IFt7Im5hbWUiOiAicm9sZTEifSwgeyJuYW1l
+IjogInJvbGUyIn1dLCAibmFtZSI6ICJ1c2VyX25hbWUxIn19fQ0KMYIBSTCCAUUC
+AQEwgaQwgZ4xCjAIBgNVBAUTATUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTES
+MBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQKEwlPcGVuU3RhY2sxETAPBgNVBAsT
+CEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZrZXlzdG9uZUBvcGVuc3RhY2sub3Jn
+MRQwEgYDVQQDEwtTZWxmIFNpZ25lZAIBETAHBgUrDgMCGjANBgkqhkiG9w0BAQEF
+AASBgFizBVs3dCvlHx04nUHgXHpaA9RL+e3uaaNszK9UwCBpBlv8c6+74sz6i3+G
+eYDIpL9bc6QgNJ6cKhmW5yLmS8/+mmAMAcm06bdWc7p/mqC3Ild+xmQ+OHDYyyJg
+DvtRUgtidFUCvxne/nwKK0WHJlpY+iwWqel5F+Xqmb8vheb1
+-----END CMS-----
diff --git a/examples/pki/cms/auth_token_unscoped.json b/examples/pki/cms/auth_token_unscoped.json
new file mode 100644
index 0000000..b2340a7
--- /dev/null
+++ b/examples/pki/cms/auth_token_unscoped.json
@@ -0,0 +1 @@
+{"access": {"token": {"expires": "2012-08-17T15:35:34Z", "id": "01e032c996ef4406b144335915a41e79"}, "serviceCatalog": {}, "user": {"username": "user_name1", "roles_links": [], "id": "c9c89e3be3ee453fbf00c7966f6d3fbd", "roles": [{'name': 'role1'},{'name': 'role2'},], "name": "user_name1"}}} \ No newline at end of file
diff --git a/examples/pki/cms/auth_token_unscoped.pem b/examples/pki/cms/auth_token_unscoped.pem
new file mode 100644
index 0000000..d42d1f1
--- /dev/null
+++ b/examples/pki/cms/auth_token_unscoped.pem
@@ -0,0 +1,17 @@
+-----BEGIN CMS-----
+MIICpwYJKoZIhvcNAQcCoIICmDCCApQCAQExCTAHBgUrDgMCGjCCATUGCSqGSIb3
+DQEHAaCCASYEggEieyJhY2Nlc3MiOiB7InRva2VuIjogeyJleHBpcmVzIjogIjIw
+MTItMDgtMTdUMTU6MzU6MzRaIiwgImlkIjogIjAxZTAzMmM5OTZlZjQ0MDZiMTQ0
+MzM1OTE1YTQxZTc5In0sICJzZXJ2aWNlQ2F0YWxvZyI6IHt9LCAidXNlciI6IHsi
+dXNlcm5hbWUiOiAidXNlcl9uYW1lMSIsICJyb2xlc19saW5rcyI6IFtdLCAiaWQi
+OiAiYzljODllM2JlM2VlNDUzZmJmMDBjNzk2NmY2ZDNmYmQiLCAicm9sZXMiOiBb
+eyduYW1lJzogJ3JvbGUxJ30seyduYW1lJzogJ3JvbGUyJ30sXSwgIm5hbWUiOiAi
+dXNlcl9uYW1lMSJ9fX0xggFJMIIBRQIBATCBpDCBnjEKMAgGA1UEBRMBNTELMAkG
+A1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlTdW5ueXZhbGUxEjAQBgNV
+BAoTCU9wZW5TdGFjazERMA8GA1UECxMIS2V5c3RvbmUxJTAjBgkqhkiG9w0BCQEW
+FmtleXN0b25lQG9wZW5zdGFjay5vcmcxFDASBgNVBAMTC1NlbGYgU2lnbmVkAgER
+MAcGBSsOAwIaMA0GCSqGSIb3DQEBAQUABIGAITCwkW7cAbcWbCBD5GfGMGHB9hP/
+UagaCZ8HFhlzjdQoJjvC+Mtu+3lWlwqPGR8ztY9kBc1401S2qJxD4FGo+M3CkNpF
+s0mtaT2PUJfFkDCzHqeBQNFHyZeqLjkPYnokPcw4s3i60DBGTFfAiUT3xumn8a4h
+C+zEAee35C/A+Iw=
+-----END CMS-----
diff --git a/examples/pki/cms/revocation_list.json b/examples/pki/cms/revocation_list.json
new file mode 100644
index 0000000..c3401b0
--- /dev/null
+++ b/examples/pki/cms/revocation_list.json
@@ -0,0 +1 @@
+{"revoked":[{"id":"7acfcfdaf6a14aebe97c61c5947bc4d3","expires":"2012-08-14T17:58:48Z"}]}
diff --git a/examples/pki/cms/revocation_list.pem b/examples/pki/cms/revocation_list.pem
new file mode 100644
index 0000000..969d10d
--- /dev/null
+++ b/examples/pki/cms/revocation_list.pem
@@ -0,0 +1,12 @@
+-----BEGIN CMS-----
+MIIB2QYJKoZIhvcNAQcCoIIByjCCAcYCAQExCTAHBgUrDgMCGjBpBgkqhkiG9w0B
+BwGgXARaeyJyZXZva2VkIjpbeyJpZCI6IjdhY2ZjZmRhZjZhMTRhZWJlOTdjNjFj
+NTk0N2JjNGQzIiwiZXhwaXJlcyI6IjIwMTItMDgtMTRUMTc6NTg6NDhaIn1dfQ0K
+MYIBSTCCAUUCAQEwgaQwgZ4xCjAIBgNVBAUTATUxCzAJBgNVBAYTAlVTMQswCQYD
+VQQIEwJDQTESMBAGA1UEBxMJU3Vubnl2YWxlMRIwEAYDVQQKEwlPcGVuU3RhY2sx
+ETAPBgNVBAsTCEtleXN0b25lMSUwIwYJKoZIhvcNAQkBFhZrZXlzdG9uZUBvcGVu
+c3RhY2sub3JnMRQwEgYDVQQDEwtTZWxmIFNpZ25lZAIBETAHBgUrDgMCGjANBgkq
+hkiG9w0BAQEFAASBgDNDhvViAo8EqTVVvZ00pWUWjajTwoV1w1os1XDJ1XacBUo+
+rsh7gljIIVuvHL2F9C660I5jxhb7QVsTge3CwSiDmexxBAPOs4lNR5hFH7FdT47b
+OK2qd0XnRjo5F7odUxIkozuQ/UISaNTPeWxGEMNVhpTXo2Dwn8wN1wrs/Z2E
+-----END CMS-----
diff --git a/examples/pki/gen_pki.sh b/examples/pki/gen_pki.sh
new file mode 100755
index 0000000..9bf6c32
--- /dev/null
+++ b/examples/pki/gen_pki.sh
@@ -0,0 +1,222 @@
+#!/bin/bash
+
+# Copyright 2012 OpenStack LLC
+#
+# 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.
+
+# This script generates the crypto necessary for the SSL tests.
+
+DIR=`dirname "$0"`
+CURRENT_DIR=`cd "$DIR" && pwd`
+CERTS_DIR=$CURRENT_DIR/certs
+PRIVATE_DIR=$CURRENT_DIR/private
+CMS_DIR=$CURRENT_DIR/cms
+
+
+function rm_old {
+ rm -rf $CERTS_DIR/*.pem
+ rm -rf $PRIVATE_DIR/*.pem
+}
+
+function cleanup {
+ rm -rf *.conf > /dev/null 2>&1
+ rm -rf index* > /dev/null 2>&1
+ rm -rf *.crt > /dev/null 2>&1
+ rm -rf newcerts > /dev/null 2>&1
+ rm -rf *.pem > /dev/null 2>&1
+ rm -rf serial* > /dev/null 2>&1
+}
+
+function generate_ca_conf {
+ echo '
+[ req ]
+default_bits = 1024
+default_keyfile = cakey.pem
+default_md = sha1
+
+prompt = no
+distinguished_name = ca_distinguished_name
+
+x509_extensions = ca_extensions
+
+[ ca_distinguished_name ]
+serialNumber = 5
+countryName = US
+stateOrProvinceName = CA
+localityName = Sunnyvale
+organizationName = OpenStack
+organizationalUnitName = Keystone
+emailAddress = keystone@openstack.org
+commonName = Self Signed
+
+[ ca_extensions ]
+basicConstraints = critical,CA:true
+' > ca.conf
+}
+
+function generate_ssl_req_conf {
+ echo '
+[ req ]
+default_bits = 1024
+default_keyfile = keystonekey.pem
+default_md = sha1
+
+prompt = no
+distinguished_name = distinguished_name
+
+[ distinguished_name ]
+countryName = US
+stateOrProvinceName = CA
+localityName = Sunnyvale
+organizationName = OpenStack
+organizationalUnitName = Keystone
+commonName = localhost
+emailAddress = keystone@openstack.org
+' > ssl_req.conf
+}
+
+function generate_cms_signing_req_conf {
+ echo '
+[ req ]
+default_bits = 1024
+default_keyfile = keystonekey.pem
+default_md = sha1
+
+prompt = no
+distinguished_name = distinguished_name
+
+[ distinguished_name ]
+countryName = US
+stateOrProvinceName = CA
+localityName = Sunnyvale
+organizationName = OpenStack
+organizationalUnitName = Keystone
+commonName = Keystone
+emailAddress = keystone@openstack.org
+' > cms_signing_req.conf
+}
+
+function generate_signing_conf {
+ echo '
+[ ca ]
+default_ca = signing_ca
+
+[ signing_ca ]
+dir = .
+database = $dir/index.txt
+new_certs_dir = $dir/newcerts
+
+certificate = $dir/certs/cacert.pem
+serial = $dir/serial
+private_key = $dir/private/cakey.pem
+
+default_days = 21360
+default_crl_days = 30
+default_md = sha1
+
+policy = policy_any
+
+[ policy_any ]
+countryName = supplied
+stateOrProvinceName = supplied
+localityName = optional
+organizationName = supplied
+organizationalUnitName = supplied
+emailAddress = supplied
+commonName = supplied
+' > signing.conf
+}
+
+function setup {
+ touch index.txt
+ echo '10' > serial
+ generate_ca_conf
+ mkdir newcerts
+}
+
+function check_error {
+ if [ $1 != 0 ] ; then
+ echo "Failed! rc=${1}"
+ echo 'Bailing ...'
+ cleanup
+ exit $1
+ else
+ echo 'Done'
+ fi
+}
+
+function generate_ca {
+ echo 'Generating New CA Certificate ...'
+ openssl req -x509 -newkey rsa:1024 -days 21360 -out $CERTS_DIR/cacert.pem -keyout $PRIVATE_DIR/cakey.pem -outform PEM -config ca.conf -nodes
+ check_error $?
+}
+
+function ssl_cert_req {
+ echo 'Generating SSL Certificate Request ...'
+ generate_ssl_req_conf
+ openssl req -newkey rsa:1024 -keyout $PRIVATE_DIR/ssl_key.pem -keyform PEM -out ssl_req.pem -outform PEM -config ssl_req.conf -nodes
+ check_error $?
+ #openssl req -in req.pem -text -noout
+}
+
+function cms_signing_cert_req {
+ echo 'Generating CMS Signing Certificate Request ...'
+ generate_cms_signing_req_conf
+ openssl req -newkey rsa:1024 -keyout $PRIVATE_DIR/signing_key.pem -keyform PEM -out cms_signing_req.pem -outform PEM -config cms_signing_req.conf -nodes
+ check_error $?
+ #openssl req -in req.pem -text -noout
+}
+
+function issue_certs {
+ generate_signing_conf
+ echo 'Issuing SSL Certificate ...'
+ openssl ca -in ssl_req.pem -config signing.conf -batch
+ check_error $?
+ openssl x509 -in $CURRENT_DIR/newcerts/10.pem -out $CERTS_DIR/ssl_cert.pem
+ check_error $?
+ echo 'Issuing CMS Signing Certificate ...'
+ openssl ca -in cms_signing_req.pem -config signing.conf -batch
+ check_error $?
+ openssl x509 -in $CURRENT_DIR/newcerts/11.pem -out $CERTS_DIR/signing_cert.pem
+ check_error $?
+}
+
+function create_middleware_cert {
+ cp $CERTS_DIR/ssl_cert.pem $CERTS_DIR/middleware.pem
+ cat $PRIVATE_DIR/ssl_key.pem >> $CERTS_DIR/middleware.pem
+}
+
+function check_openssl {
+ echo 'Checking openssl availability ...'
+ which openssl
+ check_error $?
+}
+
+function gen_sample_cms {
+ for json_file in "${CMS_DIR}/auth_token_revoked.json" "${CMS_DIR}/auth_token_unscoped.json" "${CMS_DIR}/auth_token_scoped.json" "${CMS_DIR}/revocation_list.json"
+ do
+ openssl cms -sign -in $json_file -nosmimecap -signer $CERTS_DIR/signing_cert.pem -inkey $PRIVATE_DIR/signing_key.pem -outform PEM -nodetach -nocerts -noattr -out ${json_file/.json/.pem}
+ done
+}
+
+check_openssl
+rm_old
+cleanup
+setup
+generate_ca
+ssl_cert_req
+cms_signing_cert_req
+issue_certs
+create_middleware_cert
+gen_sample_cms
+cleanup
diff --git a/examples/pki/private/cakey.pem b/examples/pki/private/cakey.pem
new file mode 100644
index 0000000..3db9c22
--- /dev/null
+++ b/examples/pki/private/cakey.pem
@@ -0,0 +1,16 @@
+-----BEGIN PRIVATE KEY-----
+MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMXgnd5wlHApGxZ5
+8LrpEkHU995lT9PxtMgkp0tpFhg7R5HQw9K7TfQk5NHB28hNzf8UE/c0z2pJXggP
+nAzvdx27NQeJGX5CWsi6fITZ8vH/+SxgfxxC+CE/6BkDpzw21MgBtq11vWL7XVax
+NeU12Ax889U66i3CrObuCYt2mbpzAgMBAAECgYEAligxJE9CFSrcR14Zc3zSQeqe
+fcFbpnXQveAyo2MHRTQWx2wobY19RjuI+DOn2IRSQbK2w+zrSLiMBonx3U8Kj8nx
+A4EQ75GLJEEr81TvBoIZSJAqrowNrkXNq8W++qwjlGXRjKiBAYlKMrFvR4lij4XN
+6cdB7kGdSIUmhvC20sECQQD4ebCGfsgFWnrqOrco6T9eQRTvP3+gJuqYXYLuVSTC
+R4gHxT5QVXSZt/Hv3UWJ0BLDbyLzLGHf30w1AqgwsUP5AkEAy96qXq6j2+IRa5w7
+2G+KZHF5N/MK/Hyy27Jw67GBVeGQj1Dwq2ZGAJBZrfXjTtQQAGdQ7EfOTCAOzHgX
+2Bx0ywJAYqfGbBBIkL+VEA0SDh9WNrE2g6u9m7P371kplEGgH7dRDmzFShYz/pin
+aep8IrTHzmsBAHY9wiqh0mZkqzim2QJADTYdxkr89WfeByI1wp3f0wiDeXu3j4sp
+MBGNPcjf/8fBTXhKUGEtUiYImbxggaA+dTg8x0MT/FzreJajvO6DJwJARMc6rhzv
+aTlm4IgApcDPBeuz6SKex9TfvDUJpqACoFM4lMgyHADi9NrJBslxFHPP5eTiM2Ag
+vI7EuW837e6raQ==
+-----END PRIVATE KEY-----
diff --git a/examples/pki/private/signing_key.pem b/examples/pki/private/signing_key.pem
new file mode 100644
index 0000000..b6ad710
--- /dev/null
+++ b/examples/pki/private/signing_key.pem
@@ -0,0 +1,16 @@
+-----BEGIN PRIVATE KEY-----
+MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALqEAuiAajMQufOO
+XP2ZC7HXEG0x6iKWCRxJMBKMcnhI8IhhX4mZomfdaUhTXPTH43SZzfm3v53VUtfc
+NZ66yb1f7nVbH+iWVpEz1+R8sZ5ZcM5wh6T+4H7zGcxrKs1pUnYg+pnEWwmEV/YQ
+gmrht44QrSEiDQlWDGEBh+kEom/bAgMBAAECgYBywfSUHya4gqsW2toGQps6cauu
+s85uN0glujY0w2tO7Pnpv5errvaI12cG1BvWlAIz5MohwlfIgc919wyavCyRJgQN
+xQo5v5MEMYKKc8ppmXpRr03HLwoPLOHVs6UHRJQT9dhOBfmLzMZIP7P/lJlt2/1X
+Okwxft/PWorczKX1aQJBAORlVqP+Cj4r5kz1A77agnCvINioV1VM5n9PvzPVzYLH
+5r1I53RWFooy1Hx2RUCmtSRQMZMeI9iGMg9c8d3LJ4UCQQDRDuIAd3AoNBcwXKC4
+BPNkbI9BSqnpIdZo87BzpY8rJ/ra3VHMHuq4w+gQsmmEy3pp01AZd1uBqv3s1wHy
+muffAkEAn2ZmiH+lUGy9B5q8qXfBL7naF7utb/gCqnnSvO+LxamUTSjTeKsYgg0l
+pVO503xF0fkyEDYp2FUYHQbGOwAtLQJAHkJ3N/YRx9/yU0+0+63LxQdpnNu/yDzb
+mglbywF1vZtl1fQe+NqowuGoX3JTj6McLuElQOpj1lr3siZU49bEJQJBANRazUzj
+Xfoja7wGuZ3PwHdxxoNDlJ2u0rYjcfK9VZuPGSz/25iCOkaar3OralJ3lfCWbFKA
+vvRp8Hl2Yk4hdKM=
+-----END PRIVATE KEY-----
diff --git a/examples/pki/private/ssl_key.pem b/examples/pki/private/ssl_key.pem
new file mode 100644
index 0000000..2e4667f
--- /dev/null
+++ b/examples/pki/private/ssl_key.pem
@@ -0,0 +1,16 @@
+-----BEGIN PRIVATE KEY-----
+MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALVu4bjaOH33yAx0
+WdpEqj4UDVsLxVjWxEpIbOlDlc6IfJd+cUriQtxf6ahjxtzLPERS81SnwZmrICWZ
+ngbOn733pULMTZktTJH+o7C74NdKwUSNxjlCeWUy+FqIQoje4ygoJRPpMdkp1wHN
+O0ZERwRN9e8M5TIlx/LRtk+q8bT5AgMBAAECgYAmwq6EYFJrTvE0//JmN/8qzfvg
+dI5PoWpD+F8UInUxr2T2tHOdrOLd07vGVrKYXu7cJeCIOGKa4r02azAggioL/nE9
+FgPpqEC+QROvLuhFsk1gLZ2pGQ06sveKZVMH22h59BKZkYlhjh5qd4vlmhPqkmPp
+gdXj7ZjDCJhhQdFVkQJBANp18k2mVksn8q29LMieVTSIZNN3ucDA1QHbim+3fp/O
+GxCzU7Mv1Xfnu1zoRFu5/sF3YG0Zy3TGPDrEljBC3rUCQQDUnBjVFXL35OkBZqXW
+taJPzGbsPoqAO+Ls2juS97zNzeGxUNhvcKuEvHO63PXqDxp1535DpvJEBN1rT2FF
+iaO1AkEAt/QTWWFUTqrPxY6DNFdm5fpn9E1fg7icZJkKBDJeFJCH59MpCryfovzl
+n0ERtq9ynlQ4RQYwdR8rvkylLvRP9QJAOiXHFOAc5XeR0nREfwiGL9TzgUFJl/DJ
+C4ZULMnctVzNkTVPPItQHal87WppR26CCiUZ/161e6zo8eRv8hjG0QJABWqfYQuK
+dWH8nxlXS+NFUDbsCdL+XpOVE7iEH7hvSw/A/kz40mLx8sDp/Fz1ysrogR/L+NGC
+Vrlwm4q/WYJO0Q==
+-----END PRIVATE KEY-----
diff --git a/keystoneclient/access.py b/keystoneclient/access.py
new file mode 100644
index 0000000..6d0e9fa
--- /dev/null
+++ b/keystoneclient/access.py
@@ -0,0 +1,144 @@
+# Copyright 2012 Nebula, Inc.
+#
+# All Rights Reserved.
+#
+# 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.
+
+
+class AccessInfo(dict):
+ """An object for encapsulating a raw authentication token from keystone
+ and helper methods for extracting useful values from that token."""
+
+ def __init__(self, *args, **kwargs):
+ dict.__init__(self, *args, **kwargs)
+
+ @property
+ def auth_token(self):
+ """ Returns the token_id associated with the auth request, to be used
+ in headers for authenticating OpenStack API requests.
+
+ :returns: str
+ """
+ return self['token'].get('id', None)
+
+ @property
+ def username(self):
+ """ Returns the username associated with the authentication request.
+ Follows the pattern defined in the V2 API of first looking for 'name',
+ returning that if available, and falling back to 'username' if name
+ is unavailable.
+
+ :returns: str
+ """
+ name = self['user'].get('name', None)
+ if name:
+ return name
+ else:
+ return self['user'].get('username', None)
+
+ @property
+ def user_id(self):
+ """ Returns the user id associated with the authentication request.
+
+ :returns: str
+ """
+ return self['user'].get('id', None)
+
+ @property
+ def tenant_name(self):
+ """ Returns the tenant (project) name associated with the
+ authentication request.
+
+ :returns: str
+ """
+ tenant_dict = self['token'].get('tenant', None)
+ if tenant_dict:
+ return tenant_dict.get('name', None)
+ return None
+
+ @property
+ def project_name(self):
+ """ Synonym for tenant_name """
+ return self.tenant_name
+
+ @property
+ def scoped(self):
+ """ Returns true if the authorization token was scoped to a tenant
+ (project), and contains a populated service catalog.
+
+ :returns: bool
+ """
+ if ('serviceCatalog' in self
+ and self['serviceCatalog']
+ and 'tenant' in self['token']):
+ return True
+ return False
+
+ @property
+ def tenant_id(self):
+ """ Returns the tenant (project) id associated with the authentication
+ request, or None if the authentication request wasn't scoped to a
+ tenant (project).
+
+ :returns: str
+ """
+ tenant_dict = self['token'].get('tenant', None)
+ if tenant_dict:
+ return tenant_dict.get('id', None)
+ return None
+
+ @property
+ def project_id(self):
+ """ Synonym for project_id """
+ return self.tenant_id
+
+ @property
+ def auth_url(self):
+ """ Returns a tuple of URLs from publicURL and adminURL for the service
+ 'identity' from the service catalog associated with the authorization
+ request. If the authentication request wasn't scoped to a tenant
+ (project), this property will return None.
+
+ :returns: tuple of urls
+ """
+ return_list = []
+ if 'serviceCatalog' in self and self['serviceCatalog']:
+ identity_services = [x for x in self['serviceCatalog']
+ if x['type'] == 'identity']
+ for svc in identity_services:
+ for endpoint in svc['endpoints']:
+ if 'publicURL' in endpoint:
+ return_list.append(endpoint['publicURL'])
+ if len(return_list) > 0:
+ return tuple(return_list)
+ return None
+
+ @property
+ def management_url(self):
+ """ Returns the first adminURL for 'identity' from the service catalog
+ associated with the authorization request, or None if the
+ authentication request wasn't scoped to a tenant (project).
+
+ :returns: tuple of urls
+ """
+ return_list = []
+ if 'serviceCatalog' in self and self['serviceCatalog']:
+ identity_services = [x for x in self['serviceCatalog']
+ if x['type'] == 'identity']
+ for svc in identity_services:
+ for endpoint in svc['endpoints']:
+ if 'adminURL' in endpoint:
+ return_list.append(endpoint['adminURL'])
+ if len(return_list) > 0:
+ return tuple(return_list)
+ return None
diff --git a/keystoneclient/client.py b/keystoneclient/client.py
index d5b5ac3..c15cdc1 100644
--- a/keystoneclient/client.py
+++ b/keystoneclient/client.py
@@ -10,7 +10,6 @@ OpenStack Client interface. Handles the REST calls and responses.
import copy
import logging
-import os
import urlparse
import httplib2
@@ -26,6 +25,7 @@ if not hasattr(urlparse, 'parse_qsl'):
urlparse.parse_qsl = cgi.parse_qsl
+from keystoneclient import access
from keystoneclient import exceptions
@@ -39,31 +39,57 @@ class HTTPClient(httplib2.Http):
def __init__(self, username=None, tenant_id=None, tenant_name=None,
password=None, auth_url=None, region_name=None, timeout=None,
endpoint=None, token=None, cacert=None, key=None,
- cert=None, insecure=False, original_ip=None):
+ cert=None, insecure=False, original_ip=None, debug=False,
+ auth_ref=None):
super(HTTPClient, self).__init__(timeout=timeout, ca_certs=cacert)
if cert:
if key:
self.add_certificate(key=key, cert=cert, domain='')
else:
self.add_certificate(key=cert, cert=cert, domain='')
- self.username = username
- self.tenant_id = tenant_id
- self.tenant_name = tenant_name
- self.password = password
- self.auth_url = auth_url.rstrip('/') if auth_url else None
self.version = 'v2.0'
- self.region_name = region_name
- self.auth_token = token
+ # set baseline defaults
+ self.username = None
+ self.tenant_id = None
+ self.tenant_name = None
+ self.auth_url = None
+ self.token = None
+ self.auth_token = None
+ self.management_url = None
+ # if loading from a dictionary passed in via auth_ref,
+ # load values from AccessInfo parsing that dictionary
+ self.auth_ref = access.AccessInfo(**auth_ref) if auth_ref else None
+ if self.auth_ref:
+ self.username = self.auth_ref.username
+ self.tenant_id = self.auth_ref.tenant_id
+ self.tenant_name = self.auth_ref.tenant_name
+ self.auth_url = self.auth_ref.auth_url[0]
+ self.management_url = self.auth_ref.management_url[0]
+ self.auth_token = self.auth_ref.auth_token
+ # allow override of the auth_ref defaults from explicit
+ # values provided to the client
+ if username:
+ self.username = username
+ if tenant_id:
+ self.tenant_id = tenant_id
+ if tenant_name:
+ self.tenant_name = tenant_name
+ if auth_url:
+ self.auth_url = auth_url.rstrip('/')
+ if token:
+ self.auth_token = token
+ if endpoint:
+ self.management_url = endpoint.rstrip('/')
+ self.password = password
self.original_ip = original_ip
-
- self.management_url = endpoint
+ self.region_name = region_name
# httplib2 overrides
self.force_exception_to_status_code = True
self.disable_ssl_certificate_validation = insecure
# logging setup
- self.debug_log = os.environ.get('KEYSTONECLIENT_DEBUG', False)
+ self.debug_log = debug
if self.debug_log:
ch = logging.StreamHandler()
_logger.setLevel(logging.DEBUG)
@@ -74,6 +100,10 @@ class HTTPClient(httplib2.Http):
Not implemented here because auth protocols should be API
version-specific.
+
+ Expected to authenticate or validate an existing authentication
+ reference already associated with the client. Invoking this call
+ *always* makes a call to the Keystone.
"""
raise NotImplementedError
@@ -135,7 +165,7 @@ class HTTPClient(httplib2.Http):
self.http_log_resp(resp, body)
if resp.status in (400, 401, 403, 404, 408, 409, 413, 500, 501):
- _logger.debug("Request returned failure status.")
+ _logger.debug("Request returned failure status: %s", resp.status)
raise exceptions.from_response(resp, body)
elif resp.status in (301, 302, 305):
# Redirected. Reissue the request to the new location.
@@ -153,32 +183,20 @@ class HTTPClient(httplib2.Http):
return resp, body
def _cs_request(self, url, method, **kwargs):
- if not self.management_url:
- self.authenticate()
+ """ Makes an authenticated request to keystone endpoint by
+ concatenating self.management_url and url and passing in method and
+ any associated kwargs. """
+ if self.management_url is None:
+ raise exceptions.AuthorizationFailure(
+ 'Current authorization does not have a known management url')
kwargs.setdefault('headers', {})
if self.auth_token:
kwargs['headers']['X-Auth-Token'] = self.auth_token
- # Perform the request once. If we get a 401 back then it
- # might be because the auth token expired, so try to
- # re-authenticate and try again. If it still fails, bail.
- try:
- resp, body = self.request(self.management_url + url, method,
- **kwargs)
- return resp, body
- except exceptions.Unauthorized:
- try:
- if getattr(self, '_failures', 0) < 1:
- self._failures = getattr(self, '_failures', 0) + 1
- self.authenticate()
- resp, body = self.request(self.management_url + url,
- method, **kwargs)
- return resp, body
- else:
- raise
- except exceptions.Unauthorized:
- raise
+ resp, body = self.request(self.management_url + url, method,
+ **kwargs)
+ return resp, body
def get(self, url, **kwargs):
return self._cs_request(url, 'GET', **kwargs)
diff --git a/keystoneclient/common/__init__.py b/keystoneclient/common/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/keystoneclient/common/__init__.py
diff --git a/keystoneclient/common/cms.py b/keystoneclient/common/cms.py
new file mode 100644
index 0000000..93c0505
--- /dev/null
+++ b/keystoneclient/common/cms.py
@@ -0,0 +1,169 @@
+import hashlib
+
+import logging
+
+
+subprocess = None
+LOG = logging.getLogger(__name__)
+PKI_ANS1_PREFIX = 'MII'
+
+
+def _ensure_subprocess():
+ # NOTE(vish): late loading subprocess so we can
+ # use the green version if we are in
+ # eventlet.
+ global subprocess
+ if not subprocess:
+ try:
+ from eventlet import patcher
+ if patcher.already_patched.get('os'):
+ from eventlet.green import subprocess
+ else:
+ import subprocess
+ except ImportError:
+ import subprocess
+
+
+def cms_verify(formatted, signing_cert_file_name, ca_file_name):
+ """
+ verifies the signature of the contents IAW CMS syntax
+ """
+ _ensure_subprocess()
+ process = subprocess.Popen(["openssl", "cms", "-verify",
+ "-certfile", signing_cert_file_name,
+ "-CAfile", ca_file_name,
+ "-inform", "PEM",
+ "-nosmimecap", "-nodetach",
+ "-nocerts", "-noattr"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ output, err = process.communicate(formatted)
+ retcode = process.poll()
+ if retcode:
+ LOG.error('Verify error: %s' % err)
+ raise subprocess.CalledProcessError(retcode, "openssl", output=err)
+ return output
+
+
+def token_to_cms(signed_text):
+ copy_of_text = signed_text.replace('-', '/')
+
+ formatted = "-----BEGIN CMS-----\n"
+ line_length = 64
+ while len(copy_of_text) > 0:
+ if (len(copy_of_text) > line_length):
+ formatted += copy_of_text[:line_length]
+ copy_of_text = copy_of_text[line_length:]
+ else:
+ formatted += copy_of_text
+ copy_of_text = ""
+ formatted += "\n"
+
+ formatted += "-----END CMS-----\n"
+
+ return formatted
+
+
+def verify_token(token, signing_cert_file_name, ca_file_name):
+ return cms_verify(token_to_cms(token),
+ signing_cert_file_name,
+ ca_file_name)
+
+
+def is_ans1_token(token):
+ '''
+ thx to ayoung for sorting this out.
+
+ base64 decoded hex representation of MII is 3082
+ In [3]: binascii.hexlify(base64.b64decode('MII='))
+ Out[3]: '3082'
+
+ re: http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
+
+ pg4: For tags from 0 to 30 the first octet is the identfier
+ pg10: Hex 30 means sequence, followed by the length of that sequence.
+ pg5: Second octet is the length octet
+ first bit indicates short or long form, next 7 bits encode the number
+ of subsequent octets that make up the content length octets as an
+ unsigned binary int
+
+ 82 = 10000010 (first bit indicates long form)
+ 0000010 = 2 octets of content length
+ so read the next 2 octets to get the length of the content.
+
+ In the case of a very large content length there could be a requirement to
+ have more than 2 octets to designate the content length, therefore
+ requiring us to check for MIM, MIQ, etc.
+ In [4]: base64.b64encode(binascii.a2b_hex('3083'))
+ Out[4]: 'MIM='
+ In [5]: base64.b64encode(binascii.a2b_hex('3084'))
+ Out[5]: 'MIQ='
+ Checking for MI would become invalid at 16 octets of content length
+ 10010000 = 90
+ In [6]: base64.b64encode(binascii.a2b_hex('3090'))
+ Out[6]: 'MJA='
+ Checking for just M is insufficient
+
+ But we will only check for MII:
+ Max length of the content using 2 octets is 7FFF or 32767
+ It's not practical to support a token of this length or greater in http
+ therefore, we will check for MII only and ignore the case of larger tokens
+ '''
+ return token[:3] == PKI_ANS1_PREFIX
+
+
+def cms_sign_text(text, signing_cert_file_name, signing_key_file_name):
+ """ Uses OpenSSL to sign a document
+ Produces a Base64 encoding of a DER formatted CMS Document
+ http://en.wikipedia.org/wiki/Cryptographic_Message_Syntax
+ """
+ _ensure_subprocess()
+ process = subprocess.Popen(["openssl", "cms", "-sign",
+ "-signer", signing_cert_file_name,
+ "-inkey", signing_key_file_name,
+ "-outform", "PEM",
+ "-nosmimecap", "-nodetach",
+ "-nocerts", "-noattr"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ output, err = process.communicate(text)
+ retcode = process.poll()
+ if retcode or "Error" in err:
+ LOG.error('Signing error: %s' % err)
+ raise subprocess.CalledProcessError(retcode, "openssl")
+ return output
+
+
+def cms_sign_token(text, signing_cert_file_name, signing_key_file_name):
+ output = cms_sign_text(text, signing_cert_file_name, signing_key_file_name)
+ return cms_to_token(output)
+
+
+def cms_to_token(cms_text):
+
+ start_delim = "-----BEGIN CMS-----"
+ end_delim = "-----END CMS-----"
+ signed_text = cms_text
+ signed_text = signed_text.replace('/', '-')
+ signed_text = signed_text.replace(start_delim, '')
+ signed_text = signed_text.replace(end_delim, '')
+ signed_text = signed_text.replace('\n', '')
+
+ return signed_text
+
+
+def cms_hash_token(token_id):
+ """
+ return: for ans1_token, returns the hash of the passed in token
+ otherwise, returns what it was passed in.
+ """
+ if token_id is None:
+ return None
+ if is_ans1_token(token_id):
+ hasher = hashlib.md5()
+ hasher.update(token_id)
+ return hasher.hexdigest()
+ else:
+ return token_id
diff --git a/keystoneclient/middleware/__init__.py b/keystoneclient/middleware/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/keystoneclient/middleware/__init__.py
diff --git a/keystoneclient/middleware/auth_token.py b/keystoneclient/middleware/auth_token.py
new file mode 100644
index 0000000..b6c2be0
--- /dev/null
+++ b/keystoneclient/middleware/auth_token.py
@@ -0,0 +1,864 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2010-2012 OpenStack LLC
+#
+# 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.
+
+"""
+TOKEN-BASED AUTH MIDDLEWARE
+
+This WSGI component:
+
+* Verifies that incoming client requests have valid tokens by validating
+ tokens with the auth service.
+* Rejects unauthenticated requests UNLESS it is in 'delay_auth_decision'
+ mode, which means the final decision is delegated to the downstream WSGI
+ component (usually the OpenStack service)
+* Collects and forwards identity information based on a valid token
+ such as user name, tenant, etc
+
+Refer to: http://keystone.openstack.org/middlewarearchitecture.html
+
+HEADERS
+-------
+
+* Headers starting with HTTP\_ is a standard http header
+* Headers starting with HTTP_X is an extended http header
+
+Coming in from initial call from client or customer
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+HTTP_X_AUTH_TOKEN
+ The client token being passed in.
+
+HTTP_X_STORAGE_TOKEN
+ The client token being passed in (legacy Rackspace use) to support
+ swift/cloud files
+
+Used for communication between components
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+WWW-Authenticate
+ HTTP header returned to a user indicating which endpoint to use
+ to retrieve a new token
+
+What we add to the request for use by the OpenStack service
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+HTTP_X_IDENTITY_STATUS
+ 'Confirmed' or 'Invalid'
+ The underlying service will only see a value of 'Invalid' if the Middleware
+ is configured to run in 'delay_auth_decision' mode
+
+HTTP_X_TENANT_ID
+ Identity service managed unique identifier, string
+
+HTTP_X_TENANT_NAME
+ Unique tenant identifier, string
+
+HTTP_X_USER_ID
+ Identity-service managed unique identifier, string
+
+HTTP_X_USER_NAME
+ Unique user identifier, string
+
+HTTP_X_ROLES
+ Comma delimited list of case-sensitive Roles
+
+HTTP_X_SERVICE_CATALOG
+ json encoded keystone service catalog (optional).
+
+HTTP_X_TENANT
+ *Deprecated* in favor of HTTP_X_TENANT_ID and HTTP_X_TENANT_NAME
+ Keystone-assigned unique identifier, deprecated
+
+HTTP_X_USER
+ *Deprecated* in favor of HTTP_X_USER_ID and HTTP_X_USER_NAME
+ Unique user name, string
+
+HTTP_X_ROLE
+ *Deprecated* in favor of HTTP_X_ROLES
+ This is being renamed, and the new header contains the same data.
+
+OTHER ENVIRONMENT VARIABLES
+---------------------------
+
+keystone.token_info
+ Information about the token discovered in the process of
+ validation. This may include extended information returned by the
+ Keystone token validation call, as well as basic information about
+ the tenant and user.
+
+"""
+
+import datetime
+import httplib
+import json
+import logging
+import os
+import stat
+import time
+import webob
+import webob.exc
+
+from keystoneclient.openstack.common import jsonutils
+from keystoneclient.common import cms
+from keystoneclient import utils
+from keystoneclient.openstack.common import timeutils
+
+CONF = None
+try:
+ from openstack.common import cfg
+ CONF = cfg.CONF
+except ImportError:
+ # cfg is not a library yet, try application copies
+ for app in 'nova', 'glance', 'quantum', 'cinder':
+ try:
+ cfg = __import__('%s.openstack.common.cfg' % app,
+ fromlist=['%s.openstack.common' % app])
+ # test which application middleware is running in
+ if hasattr(cfg, 'CONF') and 'config_file' in cfg.CONF:
+ CONF = cfg.CONF
+ break
+ except ImportError:
+ pass
+if not CONF:
+ from keystoneclient.openstack.common import cfg
+ CONF = cfg.CONF
+LOG = logging.getLogger(__name__)
+
+# alternative middleware configuration in the main application's
+# configuration file e.g. in nova.conf
+# [keystone_authtoken]
+# auth_host = 127.0.0.1
+# auth_port = 35357
+# auth_protocol = http
+# admin_tenant_name = admin
+# admin_user = admin
+# admin_password = badpassword
+opts = [
+ cfg.StrOpt('auth_admin_prefix', default=''),
+ cfg.StrOpt('auth_host', default='127.0.0.1'),
+ cfg.IntOpt('auth_port', default=35357),
+ cfg.StrOpt('auth_protocol', default='https'),
+ cfg.StrOpt('auth_uri', default=None),
+ cfg.BoolOpt('delay_auth_decision', default=False),
+ cfg.StrOpt('admin_token'),
+ cfg.StrOpt('admin_user'),
+ cfg.StrOpt('admin_password'),
+ cfg.StrOpt('admin_tenant_name', default='admin'),
+ cfg.StrOpt('certfile'),
+ cfg.StrOpt('keyfile'),
+ cfg.StrOpt('signing_dir'),
+ cfg.ListOpt('memcache_servers'),
+ cfg.IntOpt('token_cache_time', default=300),
+]
+CONF.register_opts(opts, group='keystone_authtoken')
+
+
+def will_expire_soon(expiry):
+ """ Determines if expiration is about to occur.
+
+ :param expiry: a datetime of the expected expiration
+ :returns: boolean : true if expiration is within 30 seconds
+ """
+ soon = (timeutils.utcnow() + datetime.timedelta(seconds=30))
+ return expiry < soon
+
+
+class InvalidUserToken(Exception):
+ pass
+
+
+class ServiceError(Exception):
+ pass
+
+
+class ConfigurationError(Exception):
+ pass
+
+
+class AuthProtocol(object):
+ """Auth Middleware that handles authenticating client calls."""
+
+ def __init__(self, app, conf):
+ LOG.info('Starting keystone auth_token middleware')
+ self.conf = conf
+ self.app = app
+
+ # delay_auth_decision means we still allow unauthenticated requests
+ # through and we let the downstream service make the final decision
+ self.delay_auth_decision = (self._conf_get('delay_auth_decision') in
+ (True, 'true', 't', '1', 'on', 'yes', 'y'))
+
+ # where to find the auth service (we use this to validate tokens)
+ self.auth_host = self._conf_get('auth_host')
+ self.auth_port = int(self._conf_get('auth_port'))
+ self.auth_protocol = self._conf_get('auth_protocol')
+ if self.auth_protocol == 'http':
+ self.http_client_class = httplib.HTTPConnection
+ else:
+ self.http_client_class = httplib.HTTPSConnection
+
+ self.auth_admin_prefix = self._conf_get('auth_admin_prefix')
+ self.auth_uri = self._conf_get('auth_uri')
+ if self.auth_uri is None:
+ self.auth_uri = '%s://%s:%s' % (self.auth_protocol,
+ self.auth_host,
+ self.auth_port)
+
+ # SSL
+ self.cert_file = self._conf_get('certfile')
+ self.key_file = self._conf_get('keyfile')
+
+ #signing
+ self.signing_dirname = self._conf_get('signing_dir')
+ if self.signing_dirname is None:
+ self.signing_dirname = '%s/keystone-signing' % os.environ['HOME']
+ LOG.info('Using %s as cache directory for signing certificate' %
+ self.signing_dirname)
+ if (os.path.exists(self.signing_dirname) and
+ not os.access(self.signing_dirname, os.W_OK)):
+ raise ConfigurationError("unable to access signing dir %s" %
+ self.signing_dirname)
+
+ if not os.path.exists(self.signing_dirname):
+ os.makedirs(self.signing_dirname)
+ #will throw IOError if it cannot change permissions
+ os.chmod(self.signing_dirname, stat.S_IRWXU)
+
+ val = '%s/signing_cert.pem' % self.signing_dirname
+ self.signing_cert_file_name = val
+ val = '%s/cacert.pem' % self.signing_dirname
+ self.ca_file_name = val
+ val = '%s/revoked.pem' % self.signing_dirname
+ self.revoked_file_name = val
+
+ # Credentials used to verify this component with the Auth service since
+ # validating tokens is a privileged call
+ self.admin_token = self._conf_get('admin_token')
+ self.admin_token_expiry = None
+ self.admin_user = self._conf_get('admin_user')
+ self.admin_password = self._conf_get('admin_password')
+ self.admin_tenant_name = self._conf_get('admin_tenant_name')
+
+ # Token caching via memcache
+ self._cache = None
+ self._iso8601 = None
+ memcache_servers = self._conf_get('memcache_servers')
+ # By default the token will be cached for 5 minutes
+ self.token_cache_time = int(self._conf_get('token_cache_time'))
+ self._token_revocation_list = None
+ self._token_revocation_list_fetched_time = None
+ cache_timeout = datetime.timedelta(seconds=0)
+ self.token_revocation_list_cache_timeout = cache_timeout
+ if memcache_servers:
+ try:
+ import memcache
+ import iso8601
+ LOG.info('Using memcache for caching token')
+ self._cache = memcache.Client(memcache_servers.split(','))
+ self._iso8601 = iso8601
+ except ImportError as e:
+ LOG.warn('disabled caching due to missing libraries %s', e)
+
+ def _conf_get(self, name):
+ # try config from paste-deploy first
+ if name in self.conf:
+ return self.conf[name]
+ else:
+ return CONF.keystone_authtoken[name]
+
+ def __call__(self, env, start_response):
+ """Handle incoming request.
+
+ Authenticate send downstream on success. Reject request if
+ we can't authenticate.
+
+ """
+ LOG.debug('Authenticating user token')
+ try:
+ self._remove_auth_headers(env)
+ user_token = self._get_user_token_from_header(env)
+ token_info = self._validate_user_token(user_token)
+ env['keystone.token_info'] = token_info
+ user_headers = self._build_user_headers(token_info)
+ self._add_headers(env, user_headers)
+ return self.app(env, start_response)
+
+ except InvalidUserToken:
+ if self.delay_auth_decision:
+ LOG.info('Invalid user token - deferring reject downstream')
+ self._add_headers(env, {'X-Identity-Status': 'Invalid'})
+ return self.app(env, start_response)
+ else:
+ LOG.info('Invalid user token - rejecting request')
+ return self._reject_request(env, start_response)
+
+ except ServiceError as e:
+ LOG.critical('Unable to obtain admin token: %s' % e)
+ resp = webob.exc.HTTPServiceUnavailable()
+ return resp(env, start_response)
+
+ def _remove_auth_headers(self, env):
+ """Remove headers so a user can't fake authentication.
+
+ :param env: wsgi request environment
+
+ """
+ auth_headers = (
+ 'X-Identity-Status',
+ 'X-Tenant-Id',
+ 'X-Tenant-Name',
+ 'X-User-Id',
+ 'X-User-Name',
+ 'X-Roles',
+ 'X-Service-Catalog',
+ # Deprecated
+ 'X-User',
+ 'X-Tenant',
+ 'X-Role',
+ )
+ LOG.debug('Removing headers from request environment: %s' %
+ ','.join(auth_headers))
+ self._remove_headers(env, auth_headers)
+
+ def _get_user_token_from_header(self, env):
+ """Get token id from request.
+
+ :param env: wsgi request environment
+ :return token id
+ :raises InvalidUserToken if no token is provided in request
+
+ """
+ token = self._get_header(env, 'X-Auth-Token',
+ self._get_header(env, 'X-Storage-Token'))
+ if token:
+ return token
+ else:
+ LOG.warn("Unable to find authentication token in headers: %s", env)
+ raise InvalidUserToken('Unable to find token in headers')
+
+ def _reject_request(self, env, start_response):
+ """Redirect client to auth server.
+
+ :param env: wsgi request environment
+ :param start_response: wsgi response callback
+ :returns HTTPUnauthorized http response
+
+ """
+ headers = [('WWW-Authenticate', 'Keystone uri=\'%s\'' % self.auth_uri)]
+ resp = webob.exc.HTTPUnauthorized('Authentication required', headers)
+ return resp(env, start_response)
+
+ def get_admin_token(self):
+ """Return admin token, possibly fetching a new one.
+
+ if self.admin_token_expiry is set from fetching an admin token, check
+ it for expiration, and request a new token is the existing token
+ is about to expire.
+
+ :return admin token id
+ :raise ServiceError when unable to retrieve token from keystone
+
+ """
+ if self.admin_token_expiry:
+ if will_expire_soon(self.admin_token_expiry):
+ self.admin_token = None
+
+ if not self.admin_token:
+ (self.admin_token,
+ self.admin_token_expiry) = self._request_admin_token()
+
+ return self.admin_token
+
+ def _get_http_connection(self):
+ if self.auth_protocol == 'http':
+ return self.http_client_class(self.auth_host, self.auth_port)
+ else:
+ return self.http_client_class(self.auth_host,
+ self.auth_port,
+ self.key_file,
+ self.cert_file)
+
+ def _http_request(self, method, path):
+ """HTTP request helper used to make unspecified content type requests.
+
+ :param method: http method
+ :param path: relative request url
+ :return (http response object)
+ :raise ServerError when unable to communicate with keystone
+
+ """
+ conn = self._get_http_connection()
+
+ try:
+ conn.request(method, path)
+ response = conn.getresponse()
+ body = response.read()
+ except Exception as e:
+ LOG.error('HTTP connection exception: %s' % e)
+ raise ServiceError('Unable to communicate with keystone')
+ finally:
+ conn.close()
+
+ return response, body
+
+ def _json_request(self, method, path, body=None, additional_headers=None):
+ """HTTP request helper used to make json requests.
+
+ :param method: http method
+ :param path: relative request url
+ :param body: dict to encode to json as request body. Optional.
+ :param additional_headers: dict of additional headers to send with
+ http request. Optional.
+ :return (http response object, response body parsed as json)
+ :raise ServerError when unable to communicate with keystone
+
+ """
+ conn = self._get_http_connection()
+
+ kwargs = {
+ 'headers': {
+ 'Content-type': 'application/json',
+ 'Accept': 'application/json',
+ },
+ }
+
+ if additional_headers:
+ kwargs['headers'].update(additional_headers)
+
+ if body:
+ kwargs['body'] = jsonutils.dumps(body)
+
+ full_path = self.auth_admin_prefix + path
+ try:
+ conn.request(method, full_path, **kwargs)
+ response = conn.getresponse()
+ body = response.read()
+ except Exception as e:
+ LOG.error('HTTP connection exception: %s' % e)
+ raise ServiceError('Unable to communicate with keystone')
+ finally:
+ conn.close()
+
+ try:
+ data = jsonutils.loads(body)
+ except ValueError:
+ LOG.debug('Keystone did not return json-encoded body')
+ data = {}
+
+ return response, data
+
+ def _request_admin_token(self):
+ """Retrieve new token as admin user from keystone.
+
+ :return token id upon success
+ :raises ServerError when unable to communicate with keystone
+
+ """
+ params = {
+ 'auth': {
+ 'passwordCredentials': {
+ 'username': self.admin_user,
+ 'password': self.admin_password,
+ },
+ 'tenantName': self.admin_tenant_name,
+ }
+ }
+
+ response, data = self._json_request('POST',
+ '/v2.0/tokens',
+ body=params)
+
+ try:
+ token = data['access']['token']['id']
+ expiry = data['access']['token']['expires']
+ assert token
+ assert expiry
+ datetime_expiry = timeutils.parse_isotime(expiry)
+ return (token, timeutils.normalize_time(datetime_expiry))
+ except (AssertionError, KeyError):
+ LOG.warn("Unexpected response from keystone service: %s", data)
+ raise ServiceError('invalid json response')
+ except (ValueError):
+ LOG.warn("Unable to parse expiration time from token: %s", data)
+ raise ServiceError('invalid json response')
+
+ def _validate_user_token(self, user_token, retry=True):
+ """Authenticate user using PKI
+
+ :param user_token: user's token id
+ :param retry: Ignored, as it is not longer relevant
+ :return uncrypted body of the token if the token is valid
+ :raise InvalidUserToken if token is rejected
+ :no longer raises ServiceError since it no longer makes RPC
+
+ """
+ try:
+ token_id = cms.cms_hash_token(user_token)
+ cached = self._cache_get(token_id)
+ if cached:
+ return cached
+ if cms.is_ans1_token(user_token):
+ verified = self.verify_signed_token(user_token)
+ data = json.loads(verified)
+ else:
+ data = self.verify_uuid_token(user_token, retry)
+ self._cache_put(token_id, data)
+ return data
+ except Exception as e:
+ LOG.debug('Token validation failure.', exc_info=True)
+ self._cache_store_invalid(user_token)
+ LOG.warn("Authorization failed for token %s", user_token)
+ raise InvalidUserToken('Token authorization failed')
+
+ def _build_user_headers(self, token_info):
+ """Convert token object into headers.
+
+ Build headers that represent authenticated user:
+ * X_IDENTITY_STATUS: Confirmed or Invalid
+ * X_TENANT_ID: id of tenant if tenant is present
+ * X_TENANT_NAME: name of tenant if tenant is present
+ * X_USER_ID: id of user
+ * X_USER_NAME: name of user
+ * X_ROLES: list of roles
+ * X_SERVICE_CATALOG: service catalog
+
+ Additional (deprecated) headers include:
+ * X_USER: name of user
+ * X_TENANT: For legacy compatibility before we had ID and Name
+ * X_ROLE: list of roles
+
+ :param token_info: token object returned by keystone on authentication
+ :raise InvalidUserToken when unable to parse token object
+
+ """
+ user = token_info['access']['user']
+ token = token_info['access']['token']
+ roles = ','.join([role['name'] for role in user.get('roles', [])])
+
+ def get_tenant_info():
+ """Returns a (tenant_id, tenant_name) tuple from context."""
+ def essex():
+ """Essex puts the tenant ID and name on the token."""
+ return (token['tenant']['id'], token['tenant']['name'])
+
+ def pre_diablo():
+ """Pre-diablo, Keystone only provided tenantId."""
+ return (token['tenantId'], token['tenantId'])
+
+ def default_tenant():
+ """Assume the user's default tenant."""
+ return (user['tenantId'], user['tenantName'])
+
+ for method in [essex, pre_diablo, default_tenant]:
+ try:
+ return method()
+ except KeyError:
+ pass
+
+ raise InvalidUserToken('Unable to determine tenancy.')
+
+ tenant_id, tenant_name = get_tenant_info()
+
+ user_id = user['id']
+ user_name = user['name']
+
+ rval = {
+ 'X-Identity-Status': 'Confirmed',
+ 'X-Tenant-Id': tenant_id,
+ 'X-Tenant-Name': tenant_name,
+ 'X-User-Id': user_id,
+ 'X-User-Name': user_name,
+ 'X-Roles': roles,
+ # Deprecated
+ 'X-User': user_name,
+ 'X-Tenant': tenant_name,
+ 'X-Role': roles,
+ }
+
+ try:
+ catalog = token_info['access']['serviceCatalog']
+ rval['X-Service-Catalog'] = jsonutils.dumps(catalog)
+ except KeyError:
+ pass
+
+ return rval
+
+ def _header_to_env_var(self, key):
+ """Convert header to wsgi env variable.
+
+ :param key: http header name (ex. 'X-Auth-Token')
+ :return wsgi env variable name (ex. 'HTTP_X_AUTH_TOKEN')
+
+ """
+ return 'HTTP_%s' % key.replace('-', '_').upper()
+
+ def _add_headers(self, env, headers):
+ """Add http headers to environment."""
+ for (k, v) in headers.iteritems():
+ env_key = self._header_to_env_var(k)
+ env[env_key] = v
+
+ def _remove_headers(self, env, keys):
+ """Remove http headers from environment."""
+ for k in keys:
+ env_key = self._header_to_env_var(k)
+ try:
+ del env[env_key]
+ except KeyError:
+ pass
+
+ def _get_header(self, env, key, default=None):
+ """Get http header from environment."""
+ env_key = self._header_to_env_var(key)
+ return env.get(env_key, default)
+
+ def _cache_get(self, token):
+ """Return token information from cache.
+
+ If token is invalid raise InvalidUserToken
+ return token only if fresh (not expired).
+ """
+ if self._cache and token:
+ key = 'tokens/%s' % token
+ cached = self._cache.get(key)
+ if cached == 'invalid':
+ LOG.debug('Cached Token %s is marked unauthorized', token)
+ raise InvalidUserToken('Token authorization failed')
+ if cached:
+ data, expires = cached
+ if time.time() < float(expires):
+ LOG.debug('Returning cached token %s', token)
+ return data
+ else:
+ LOG.debug('Cached Token %s seems expired', token)
+
+ def _cache_put(self, token, data):
+ """Put token data into the cache.
+
+ Stores the parsed expire date in cache allowing
+ quick check of token freshness on retrieval.
+ """
+ if self._cache and data:
+ key = 'tokens/%s' % token
+ if 'token' in data.get('access', {}):
+ timestamp = data['access']['token']['expires']
+ expires = self._iso8601.parse_date(timestamp).strftime('%s')
+ else:
+ LOG.error('invalid token format')
+ return
+ LOG.debug('Storing %s token in memcache', token)
+ self._cache.set(key,
+ (data, expires),
+ time=self.token_cache_time)
+
+ def _cache_store_invalid(self, token):
+ """Store invalid token in cache."""
+ if self._cache:
+ key = 'tokens/%s' % token
+ LOG.debug('Marking token %s as unauthorized in memcache', token)
+ self._cache.set(key,
+ 'invalid',
+ time=self.token_cache_time)
+
+ def cert_file_missing(self, called_proc_err, file_name):
+ return (called_proc_err.output.find(file_name)
+ and not os.path.exists(file_name))
+
+ def verify_uuid_token(self, user_token, retry=True):
+ """Authenticate user token with keystone.
+
+ :param user_token: user's token id
+ :param retry: flag that forces the middleware to retry
+ user authentication when an indeterminate
+ response is received. Optional.
+ :return token object received from keystone on success
+ :raise InvalidUserToken if token is rejected
+ :raise ServiceError if unable to authenticate token
+
+ """
+
+ headers = {'X-Auth-Token': self.get_admin_token()}
+ response, data = self._json_request('GET',
+ '/v2.0/tokens/%s' % user_token,
+ additional_headers=headers)
+
+ if response.status == 200:
+ self._cache_put(user_token, data)
+ return data
+ if response.status == 404:
+ # FIXME(ja): I'm assuming the 404 status means that user_token is
+ # invalid - not that the admin_token is invalid
+ self._cache_store_invalid(user_token)
+ LOG.warn("Authorization failed for token %s", user_token)
+ raise InvalidUserToken('Token authorization failed')
+ if response.status == 401:
+ LOG.info('Keystone rejected admin token %s, resetting', headers)
+ self.admin_token = None
+ else:
+ LOG.error('Bad response code while validating token: %s' %
+ response.status)
+ if retry:
+ LOG.info('Retrying validation')
+ return self._validate_user_token(user_token, False)
+ else:
+ LOG.warn("Invalid user token: %s. Keystone response: %s.",
+ user_token, data)
+
+ raise InvalidUserToken()
+
+ def is_signed_token_revoked(self, signed_text):
+ """Indicate whether the token appears in the revocation list."""
+ revocation_list = self.token_revocation_list
+ revoked_tokens = revocation_list.get('revoked', [])
+ if not revoked_tokens:
+ return
+ revoked_ids = (x['id'] for x in revoked_tokens)
+ token_id = utils.hash_signed_token(signed_text)
+ for revoked_id in revoked_ids:
+ if token_id == revoked_id:
+ LOG.debug('Token %s is marked as having been revoked',
+ token_id)
+ return True
+ return False
+
+ def cms_verify(self, data):
+ """Verifies the signature of the provided data's IAW CMS syntax.
+
+ If either of the certificate files are missing, fetch them and
+ retry.
+ """
+ while True:
+ try:
+ output = cms.cms_verify(data, self.signing_cert_file_name,
+ self.ca_file_name)
+ except cms.subprocess.CalledProcessError as err:
+ if self.cert_file_missing(err, self.signing_cert_file_name):
+ self.fetch_signing_cert()
+ continue
+ if self.cert_file_missing(err, self.ca_file_name):
+ self.fetch_ca_cert()
+ continue
+ raise err
+ return output
+
+ def verify_signed_token(self, signed_text):
+ """Check that the token is unrevoked and has a valid signature."""
+ if self.is_signed_token_revoked(signed_text):
+ raise InvalidUserToken('Token has been revoked')
+
+ formatted = cms.token_to_cms(signed_text)
+ return self.cms_verify(formatted)
+
+ @property
+ def token_revocation_list_fetched_time(self):
+ if not self._token_revocation_list_fetched_time:
+ # If the fetched list has been written to disk, use its
+ # modification time.
+ if os.path.exists(self.revoked_file_name):
+ mtime = os.path.getmtime(self.revoked_file_name)
+ fetched_time = datetime.datetime.fromtimestamp(mtime)
+ # Otherwise the list will need to be fetched.
+ else:
+ fetched_time = datetime.datetime.min
+ self._token_revocation_list_fetched_time = fetched_time
+ return self._token_revocation_list_fetched_time
+
+ @token_revocation_list_fetched_time.setter
+ def token_revocation_list_fetched_time(self, value):
+ self._token_revocation_list_fetched_time = value
+
+ @property
+ def token_revocation_list(self):
+ timeout = (self.token_revocation_list_fetched_time +
+ self.token_revocation_list_cache_timeout)
+ list_is_current = timeutils.utcnow() < timeout
+ if list_is_current:
+ # Load the list from disk if required
+ if not self._token_revocation_list:
+ with open(self.revoked_file_name, 'r') as f:
+ self._token_revocation_list = jsonutils.loads(f.read())
+ else:
+ self.token_revocation_list = self.fetch_revocation_list()
+ return self._token_revocation_list
+
+ @token_revocation_list.setter
+ def token_revocation_list(self, value):
+ """Save a revocation list to memory and to disk.
+
+ :param value: A json-encoded revocation list
+
+ """
+ self._token_revocation_list = jsonutils.loads(value)
+ self.token_revocation_list_fetched_time = timeutils.utcnow()
+ with open(self.revoked_file_name, 'w') as f:
+ f.write(value)
+
+ def fetch_revocation_list(self, retry=True):
+ headers = {'X-Auth-Token': self.get_admin_token()}
+ response, data = self._json_request('GET', '/v2.0/tokens/revoked',
+ additional_headers=headers)
+ if response.status == 401:
+ if retry:
+ LOG.info('Keystone rejected admin token %s, resetting admin '
+ 'token', headers)
+ self.admin_token = None
+ return self.fetch_revocation_list(retry=False)
+ if response.status != 200:
+ raise ServiceError('Unable to fetch token revocation list.')
+ if (not 'signed' in data):
+ raise ServiceError('Revocation list inmproperly formatted.')
+ return self.cms_verify(data['signed'])
+
+ def fetch_signing_cert(self):
+ response, data = self._http_request('GET',
+ '/v2.0/certificates/signing')
+ try:
+ #todo check response
+ certfile = open(self.signing_cert_file_name, 'w')
+ certfile.write(data)
+ certfile.close()
+ except (AssertionError, KeyError):
+ LOG.warn("Unexpected response from keystone service: %s", data)
+ raise ServiceError('invalid json response')
+
+ def fetch_ca_cert(self):
+ response, data = self._http_request('GET',
+ '/v2.0/certificates/ca')
+ try:
+ #todo check response
+ certfile = open(self.ca_file_name, 'w')
+ certfile.write(data)
+ certfile.close()
+ except (AssertionError, KeyError):
+ LOG.warn("Unexpected response from keystone service: %s", data)
+ raise ServiceError('invalid json response')
+
+
+def filter_factory(global_conf, **local_conf):
+ """Returns a WSGI filter app for use with paste.deploy."""
+ conf = global_conf.copy()
+ conf.update(local_conf)
+
+ def auth_filter(app):
+ return AuthProtocol(app, conf)
+ return auth_filter
+
+
+def app_factory(global_conf, **local_conf):
+ conf = global_conf.copy()
+ conf.update(local_conf)
+ return AuthProtocol(None, conf)
diff --git a/keystoneclient/middleware/test.py b/keystoneclient/middleware/test.py
new file mode 100644
index 0000000..e5c1171
--- /dev/null
+++ b/keystoneclient/middleware/test.py
@@ -0,0 +1,67 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2012 OpenStack LLC
+#
+# 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.
+
+#
+# Test support for middleware authentication
+#
+
+import os
+import sys
+
+
+ROOTDIR = os.path.dirname(os.path.abspath(os.curdir))
+
+
+def rootdir(*p):
+ return os.path.join(ROOTDIR, *p)
+
+
+class NoModule(object):
+ """A mixin class to provide support for unloading/disabling modules."""
+
+ def __init__(self, *args, **kw):
+ super(NoModule, self).__init__(*args, **kw)
+ self._finders = []
+ self._cleared_modules = {}
+
+ def tearDown(self):
+ super(NoModule, self).tearDown()
+ for finder in self._finders:
+ sys.meta_path.remove(finder)
+ sys.modules.update(self._cleared_modules)
+
+ def clear_module(self, module):
+ cleared_modules = {}
+ for fullname in sys.modules.keys():
+ if fullname == module or fullname.startswith(module + '.'):
+ cleared_modules[fullname] = sys.modules.pop(fullname)
+ return cleared_modules
+
+ def disable_module(self, module):
+ """Ensure ImportError for the specified module."""
+
+ # Clear 'module' references in sys.modules
+ self._cleared_modules.update(self.clear_module(module))
+
+ # Disallow further imports of 'module'
+ class NoModule(object):
+ def find_module(self, fullname, path):
+ if fullname == module or fullname.startswith(module + '.'):
+ raise ImportError
+
+ finder = NoModule()
+ self._finders.append(finder)
+ sys.meta_path.insert(0, finder)
diff --git a/keystoneclient/openstack/common/cfg.py b/keystoneclient/openstack/common/cfg.py
new file mode 100644
index 0000000..d48eb86
--- /dev/null
+++ b/keystoneclient/openstack/common/cfg.py
@@ -0,0 +1,1653 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2012 Red Hat, Inc.
+#
+# 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.
+
+r"""
+Configuration options which may be set on the command line or in config files.
+
+The schema for each option is defined using the Opt sub-classes, e.g.:
+
+::
+
+ common_opts = [
+ cfg.StrOpt('bind_host',
+ default='0.0.0.0',
+ help='IP address to listen on'),
+ cfg.IntOpt('bind_port',
+ default=9292,
+ help='Port number to listen on')
+ ]
+
+Options can be strings, integers, floats, booleans, lists or 'multi strings'::
+
+ enabled_apis_opt = cfg.ListOpt('enabled_apis',
+ default=['ec2', 'osapi_compute'],
+ help='List of APIs to enable by default')
+
+ DEFAULT_EXTENSIONS = [
+ 'nova.api.openstack.compute.contrib.standard_extensions'
+ ]
+ osapi_compute_extension_opt = cfg.MultiStrOpt('osapi_compute_extension',
+ default=DEFAULT_EXTENSIONS)
+
+Option schemas are registered with the config manager at runtime, but before
+the option is referenced::
+
+ class ExtensionManager(object):
+
+ enabled_apis_opt = cfg.ListOpt(...)
+
+ def __init__(self, conf):
+ self.conf = conf
+ self.conf.register_opt(enabled_apis_opt)
+ ...
+
+ def _load_extensions(self):
+ for ext_factory in self.conf.osapi_compute_extension:
+ ....
+
+A common usage pattern is for each option schema to be defined in the module or
+class which uses the option::
+
+ opts = ...
+
+ def add_common_opts(conf):
+ conf.register_opts(opts)
+
+ def get_bind_host(conf):
+ return conf.bind_host
+
+ def get_bind_port(conf):
+ return conf.bind_port
+
+An option may optionally be made available via the command line. Such options
+must registered with the config manager before the command line is parsed (for
+the purposes of --help and CLI arg validation)::
+
+ cli_opts = [
+ cfg.BoolOpt('verbose',
+ short='v',
+ default=False,
+ help='Print more verbose output'),
+ cfg.BoolOpt('debug',
+ short='d',
+ default=False,
+ help='Print debugging output'),
+ ]
+
+ def add_common_opts(conf):
+ conf.register_cli_opts(cli_opts)
+
+The config manager has two CLI options defined by default, --config-file
+and --config-dir::
+
+ class ConfigOpts(object):
+
+ def __call__(self, ...):
+
+ opts = [
+ MultiStrOpt('config-file',
+ ...),
+ StrOpt('config-dir',
+ ...),
+ ]
+
+ self.register_cli_opts(opts)
+
+Option values are parsed from any supplied config files using
+openstack.common.iniparser. If none are specified, a default set is used
+e.g. glance-api.conf and glance-common.conf::
+
+ glance-api.conf:
+ [DEFAULT]
+ bind_port = 9292
+
+ glance-common.conf:
+ [DEFAULT]
+ bind_host = 0.0.0.0
+
+Option values in config files override those on the command line. Config files
+are parsed in order, with values in later files overriding those in earlier
+files.
+
+The parsing of CLI args and config files is initiated by invoking the config
+manager e.g.::
+
+ conf = ConfigOpts()
+ conf.register_opt(BoolOpt('verbose', ...))
+ conf(sys.argv[1:])
+ if conf.verbose:
+ ...
+
+Options can be registered as belonging to a group::
+
+ rabbit_group = cfg.OptGroup(name='rabbit',
+ title='RabbitMQ options')
+
+ rabbit_host_opt = cfg.StrOpt('host',
+ default='localhost',
+ help='IP/hostname to listen on'),
+ rabbit_port_opt = cfg.IntOpt('port',
+ default=5672,
+ help='Port number to listen on')
+
+ def register_rabbit_opts(conf):
+ conf.register_group(rabbit_group)
+ # options can be registered under a group in either of these ways:
+ conf.register_opt(rabbit_host_opt, group=rabbit_group)
+ conf.register_opt(rabbit_port_opt, group='rabbit')
+
+If it no group attributes are required other than the group name, the group
+need not be explicitly registered e.g.
+
+ def register_rabbit_opts(conf):
+ # The group will automatically be created, equivalent calling::
+ # conf.register_group(OptGroup(name='rabbit'))
+ conf.register_opt(rabbit_port_opt, group='rabbit')
+
+If no group is specified, options belong to the 'DEFAULT' section of config
+files::
+
+ glance-api.conf:
+ [DEFAULT]
+ bind_port = 9292
+ ...
+
+ [rabbit]
+ host = localhost
+ port = 5672
+ use_ssl = False
+ userid = guest
+ password = guest
+ virtual_host = /
+
+Command-line options in a group are automatically prefixed with the
+group name::
+
+ --rabbit-host localhost --rabbit-port 9999
+
+Option values in the default group are referenced as attributes/properties on
+the config manager; groups are also attributes on the config manager, with
+attributes for each of the options associated with the group::
+
+ server.start(app, conf.bind_port, conf.bind_host, conf)
+
+ self.connection = kombu.connection.BrokerConnection(
+ hostname=conf.rabbit.host,
+ port=conf.rabbit.port,
+ ...)
+
+Option values may reference other values using PEP 292 string substitution::
+
+ opts = [
+ cfg.StrOpt('state_path',
+ default=os.path.join(os.path.dirname(__file__), '../'),
+ help='Top-level directory for maintaining nova state'),
+ cfg.StrOpt('sqlite_db',
+ default='nova.sqlite',
+ help='file name for sqlite'),
+ cfg.StrOpt('sql_connection',
+ default='sqlite:///$state_path/$sqlite_db',
+ help='connection string for sql database'),
+ ]
+
+Note that interpolation can be avoided by using '$$'.
+
+For command line utilities that dispatch to other command line utilities, the
+disable_interspersed_args() method is available. If this this method is called,
+then parsing e.g.::
+
+ script --verbose cmd --debug /tmp/mything
+
+will no longer return::
+
+ ['cmd', '/tmp/mything']
+
+as the leftover arguments, but will instead return::
+
+ ['cmd', '--debug', '/tmp/mything']
+
+i.e. argument parsing is stopped at the first non-option argument.
+
+Options may be declared as required so that an error is raised if the user
+does not supply a value for the option.
+
+Options may be declared as secret so that their values are not leaked into
+log files:
+
+ opts = [
+ cfg.StrOpt('s3_store_access_key', secret=True),
+ cfg.StrOpt('s3_store_secret_key', secret=True),
+ ...
+ ]
+
+This module also contains a global instance of the CommonConfigOpts class
+in order to support a common usage pattern in OpenStack:
+
+ from keystoneclient.openstack.common import cfg
+
+ opts = [
+ cfg.StrOpt('bind_host', default='0.0.0.0'),
+ cfg.IntOpt('bind_port', default=9292),
+ ]
+
+ CONF = cfg.CONF
+ CONF.register_opts(opts)
+
+ def start(server, app):
+ server.start(app, CONF.bind_port, CONF.bind_host)
+
+"""
+
+import collections
+import copy
+import functools
+import glob
+import optparse
+import os
+import string
+import sys
+
+from keystoneclient.openstack.common import iniparser
+
+
+class Error(Exception):
+ """Base class for cfg exceptions."""
+
+ def __init__(self, msg=None):
+ self.msg = msg
+
+ def __str__(self):
+ return self.msg
+
+
+class ArgsAlreadyParsedError(Error):
+ """Raised if a CLI opt is registered after parsing."""
+
+ def __str__(self):
+ ret = "arguments already parsed"
+ if self.msg:
+ ret += ": " + self.msg
+ return ret
+
+
+class NoSuchOptError(Error, AttributeError):
+ """Raised if an opt which doesn't exist is referenced."""
+
+ def __init__(self, opt_name, group=None):
+ self.opt_name = opt_name
+ self.group = group
+
+ def __str__(self):
+ if self.group is None:
+ return "no such option: %s" % self.opt_name
+ else:
+ return "no such option in group %s: %s" % (self.group.name,
+ self.opt_name)
+
+
+class NoSuchGroupError(Error):
+ """Raised if a group which doesn't exist is referenced."""
+
+ def __init__(self, group_name):
+ self.group_name = group_name
+
+ def __str__(self):
+ return "no such group: %s" % self.group_name
+
+
+class DuplicateOptError(Error):
+ """Raised if multiple opts with the same name are registered."""
+
+ def __init__(self, opt_name):
+ self.opt_name = opt_name
+
+ def __str__(self):
+ return "duplicate option: %s" % self.opt_name
+
+
+class RequiredOptError(Error):
+ """Raised if an option is required but no value is supplied by the user."""
+
+ def __init__(self, opt_name, group=None):
+ self.opt_name = opt_name
+ self.group = group
+
+ def __str__(self):
+ if self.group is None:
+ return "value required for option: %s" % self.opt_name
+ else:
+ return "value required for option: %s.%s" % (self.group.name,
+ self.opt_name)
+
+
+class TemplateSubstitutionError(Error):
+ """Raised if an error occurs substituting a variable in an opt value."""
+
+ def __str__(self):
+ return "template substitution error: %s" % self.msg
+
+
+class ConfigFilesNotFoundError(Error):
+ """Raised if one or more config files are not found."""
+
+ def __init__(self, config_files):
+ self.config_files = config_files
+
+ def __str__(self):
+ return ('Failed to read some config files: %s' %
+ string.join(self.config_files, ','))
+
+
+class ConfigFileParseError(Error):
+ """Raised if there is an error parsing a config file."""
+
+ def __init__(self, config_file, msg):
+ self.config_file = config_file
+ self.msg = msg
+
+ def __str__(self):
+ return 'Failed to parse %s: %s' % (self.config_file, self.msg)
+
+
+class ConfigFileValueError(Error):
+ """Raised if a config file value does not match its opt type."""
+ pass
+
+
+def _fixpath(p):
+ """Apply tilde expansion and absolutization to a path."""
+ return os.path.abspath(os.path.expanduser(p))
+
+
+def _get_config_dirs(project=None):
+ """Return a list of directors where config files may be located.
+
+ :param project: an optional project name
+
+ If a project is specified, following directories are returned::
+
+ ~/.${project}/
+ ~/
+ /etc/${project}/
+ /etc/
+
+ Otherwise, these directories::
+
+ ~/
+ /etc/
+ """
+ cfg_dirs = [
+ _fixpath(os.path.join('~', '.' + project)) if project else None,
+ _fixpath('~'),
+ os.path.join('/etc', project) if project else None,
+ '/etc'
+ ]
+
+ return filter(bool, cfg_dirs)
+
+
+def _search_dirs(dirs, basename, extension=""):
+ """Search a list of directories for a given filename.
+
+ Iterator over the supplied directories, returning the first file
+ found with the supplied name and extension.
+
+ :param dirs: a list of directories
+ :param basename: the filename, e.g. 'glance-api'
+ :param extension: the file extension, e.g. '.conf'
+ :returns: the path to a matching file, or None
+ """
+ for d in dirs:
+ path = os.path.join(d, '%s%s' % (basename, extension))
+ if os.path.exists(path):
+ return path
+
+
+def find_config_files(project=None, prog=None, extension='.conf'):
+ """Return a list of default configuration files.
+
+ :param project: an optional project name
+ :param prog: the program name, defaulting to the basename of sys.argv[0]
+ :param extension: the type of the config file
+
+ We default to two config files: [${project}.conf, ${prog}.conf]
+
+ And we look for those config files in the following directories::
+
+ ~/.${project}/
+ ~/
+ /etc/${project}/
+ /etc/
+
+ We return an absolute path for (at most) one of each the default config
+ files, for the topmost directory it exists in.
+
+ For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf
+ and ~/.foo/bar.conf all exist, then we return ['/etc/foo/foo.conf',
+ '~/.foo/bar.conf']
+
+ If no project name is supplied, we only look for ${prog.conf}.
+ """
+ if prog is None:
+ prog = os.path.basename(sys.argv[0])
+
+ cfg_dirs = _get_config_dirs(project)
+
+ config_files = []
+ if project:
+ config_files.append(_search_dirs(cfg_dirs, project, extension))
+ config_files.append(_search_dirs(cfg_dirs, prog, extension))
+
+ return filter(bool, config_files)
+
+
+def _is_opt_registered(opts, opt):
+ """Check whether an opt with the same name is already registered.
+
+ The same opt may be registered multiple times, with only the first
+ registration having any effect. However, it is an error to attempt
+ to register a different opt with the same name.
+
+ :param opts: the set of opts already registered
+ :param opt: the opt to be registered
+ :returns: True if the opt was previously registered, False otherwise
+ :raises: DuplicateOptError if a naming conflict is detected
+ """
+ if opt.dest in opts:
+ if opts[opt.dest]['opt'] != opt:
+ raise DuplicateOptError(opt.name)
+ return True
+ else:
+ return False
+
+
+class Opt(object):
+
+ """Base class for all configuration options.
+
+ An Opt object has no public methods, but has a number of public string
+ properties:
+
+ name:
+ the name of the option, which may include hyphens
+ dest:
+ the (hyphen-less) ConfigOpts property which contains the option value
+ short:
+ a single character CLI option name
+ default:
+ the default value of the option
+ metavar:
+ the name shown as the argument to a CLI option in --help output
+ help:
+ an string explaining how the options value is used
+ """
+ multi = False
+
+ def __init__(self, name, dest=None, short=None, default=None,
+ metavar=None, help=None, secret=False, required=False,
+ deprecated_name=None):
+ """Construct an Opt object.
+
+ The only required parameter is the option's name. However, it is
+ common to also supply a default and help string for all options.
+
+ :param name: the option's name
+ :param dest: the name of the corresponding ConfigOpts property
+ :param short: a single character CLI option name
+ :param default: the default value of the option
+ :param metavar: the option argument to show in --help
+ :param help: an explanation of how the option is used
+ :param secret: true iff the value should be obfuscated in log output
+ :param required: true iff a value must be supplied for this option
+ :param deprecated_name: deprecated name option. Acts like an alias
+ """
+ self.name = name
+ if dest is None:
+ self.dest = self.name.replace('-', '_')
+ else:
+ self.dest = dest
+ self.short = short
+ self.default = default
+ self.metavar = metavar
+ self.help = help
+ self.secret = secret
+ self.required = required
+ if deprecated_name is not None:
+ self.deprecated_name = deprecated_name.replace('-', '_')
+ else:
+ self.deprecated_name = None
+
+ def __ne__(self, another):
+ return vars(self) != vars(another)
+
+ def _get_from_config_parser(self, cparser, section):
+ """Retrieves the option value from a MultiConfigParser object.
+
+ This is the method ConfigOpts uses to look up the option value from
+ config files. Most opt types override this method in order to perform
+ type appropriate conversion of the returned value.
+
+ :param cparser: a ConfigParser object
+ :param section: a section name
+ """
+ return self._cparser_get_with_deprecated(cparser, section)
+
+ def _cparser_get_with_deprecated(self, cparser, section):
+ """If cannot find option as dest try deprecated_name alias."""
+ if self.deprecated_name is not None:
+ return cparser.get(section, [self.dest, self.deprecated_name])
+ return cparser.get(section, [self.dest])
+
+ def _add_to_cli(self, parser, group=None):
+ """Makes the option available in the command line interface.
+
+ This is the method ConfigOpts uses to add the opt to the CLI interface
+ as appropriate for the opt type. Some opt types may extend this method,
+ others may just extend the helper methods it uses.
+
+ :param parser: the CLI option parser
+ :param group: an optional OptGroup object
+ """
+ container = self._get_optparse_container(parser, group)
+ kwargs = self._get_optparse_kwargs(group)
+ prefix = self._get_optparse_prefix('', group)
+ self._add_to_optparse(container, self.name, self.short, kwargs, prefix,
+ self.deprecated_name)
+
+ def _add_to_optparse(self, container, name, short, kwargs, prefix='',
+ deprecated_name=None):
+ """Add an option to an optparse parser or group.
+
+ :param container: an optparse.OptionContainer object
+ :param name: the opt name
+ :param short: the short opt name
+ :param kwargs: the keyword arguments for add_option()
+ :param prefix: an optional prefix to prepend to the opt name
+ :raises: DuplicateOptError if a naming confict is detected
+ """
+ args = ['--' + prefix + name]
+ if short:
+ args += ['-' + short]
+ if deprecated_name:
+ args += ['--' + prefix + deprecated_name]
+ for a in args:
+ if container.has_option(a):
+ raise DuplicateOptError(a)
+ container.add_option(*args, **kwargs)
+
+ def _get_optparse_container(self, parser, group):
+ """Returns an optparse.OptionContainer.
+
+ :param parser: an optparse.OptionParser
+ :param group: an (optional) OptGroup object
+ :returns: an optparse.OptionGroup if a group is given, else the parser
+ """
+ if group is not None:
+ return group._get_optparse_group(parser)
+ else:
+ return parser
+
+ def _get_optparse_kwargs(self, group, **kwargs):
+ """Build a dict of keyword arguments for optparse's add_option().
+
+ Most opt types extend this method to customize the behaviour of the
+ options added to optparse.
+
+ :param group: an optional group
+ :param kwargs: optional keyword arguments to add to
+ :returns: a dict of keyword arguments
+ """
+ dest = self.dest
+ if group is not None:
+ dest = group.name + '_' + dest
+ kwargs.update({'dest': dest,
+ 'metavar': self.metavar,
+ 'help': self.help, })
+ return kwargs
+
+ def _get_optparse_prefix(self, prefix, group):
+ """Build a prefix for the CLI option name, if required.
+
+ CLI options in a group are prefixed with the group's name in order
+ to avoid conflicts between similarly named options in different
+ groups.
+
+ :param prefix: an existing prefix to append to (e.g. 'no' or '')
+ :param group: an optional OptGroup object
+ :returns: a CLI option prefix including the group name, if appropriate
+ """
+ if group is not None:
+ return group.name + '-' + prefix
+ else:
+ return prefix
+
+
+class StrOpt(Opt):
+ """
+ String opts do not have their values transformed and are returned as
+ str objects.
+ """
+ pass
+
+
+class BoolOpt(Opt):
+
+ """
+ Bool opts are set to True or False on the command line using --optname or
+ --noopttname respectively.
+
+ In config files, boolean values are case insensitive and can be set using
+ 1/0, yes/no, true/false or on/off.
+ """
+
+ _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
+ '0': False, 'no': False, 'false': False, 'off': False}
+
+ def _get_from_config_parser(self, cparser, section):
+ """Retrieve the opt value as a boolean from ConfigParser."""
+ def convert_bool(v):
+ value = self._boolean_states.get(v.lower())
+ if value is None:
+ raise ValueError('Unexpected boolean value %r' % v)
+
+ return value
+
+ return [convert_bool(v) for v in
+ self._cparser_get_with_deprecated(cparser, section)]
+
+ def _add_to_cli(self, parser, group=None):
+ """Extends the base class method to add the --nooptname option."""
+ super(BoolOpt, self)._add_to_cli(parser, group)
+ self._add_inverse_to_optparse(parser, group)
+
+ def _add_inverse_to_optparse(self, parser, group):
+ """Add the --nooptname option to the option parser."""
+ container = self._get_optparse_container(parser, group)
+ kwargs = self._get_optparse_kwargs(group, action='store_false')
+ prefix = self._get_optparse_prefix('no', group)
+ kwargs["help"] = "The inverse of --" + self.name
+ self._add_to_optparse(container, self.name, None, kwargs, prefix,
+ self.deprecated_name)
+
+ def _get_optparse_kwargs(self, group, action='store_true', **kwargs):
+ """Extends the base optparse keyword dict for boolean options."""
+ return super(BoolOpt,
+ self)._get_optparse_kwargs(group, action=action, **kwargs)
+
+
+class IntOpt(Opt):
+
+ """Int opt values are converted to integers using the int() builtin."""
+
+ def _get_from_config_parser(self, cparser, section):
+ """Retrieve the opt value as a integer from ConfigParser."""
+ return [int(v) for v in self._cparser_get_with_deprecated(cparser,
+ section)]
+
+ def _get_optparse_kwargs(self, group, **kwargs):
+ """Extends the base optparse keyword dict for integer options."""
+ return super(IntOpt,
+ self)._get_optparse_kwargs(group, type='int', **kwargs)
+
+
+class FloatOpt(Opt):
+
+ """Float opt values are converted to floats using the float() builtin."""
+
+ def _get_from_config_parser(self, cparser, section):
+ """Retrieve the opt value as a float from ConfigParser."""
+ return [float(v) for v in
+ self._cparser_get_with_deprecated(cparser, section)]
+
+ def _get_optparse_kwargs(self, group, **kwargs):
+ """Extends the base optparse keyword dict for float options."""
+ return super(FloatOpt,
+ self)._get_optparse_kwargs(group, type='float', **kwargs)
+
+
+class ListOpt(Opt):
+
+ """
+ List opt values are simple string values separated by commas. The opt value
+ is a list containing these strings.
+ """
+
+ def _get_from_config_parser(self, cparser, section):
+ """Retrieve the opt value as a list from ConfigParser."""
+ return [v.split(',') for v in
+ self._cparser_get_with_deprecated(cparser, section)]
+
+ def _get_optparse_kwargs(self, group, **kwargs):
+ """Extends the base optparse keyword dict for list options."""
+ return super(ListOpt,
+ self)._get_optparse_kwargs(group,
+ type='string',
+ action='callback',
+ callback=self._parse_list,
+ **kwargs)
+
+ def _parse_list(self, option, opt, value, parser):
+ """An optparse callback for parsing an option value into a list."""
+ setattr(parser.values, self.dest, value.split(','))
+
+
+class MultiStrOpt(Opt):
+
+ """
+ Multistr opt values are string opts which may be specified multiple times.
+ The opt value is a list containing all the string values specified.
+ """
+ multi = True
+
+ def _get_optparse_kwargs(self, group, **kwargs):
+ """Extends the base optparse keyword dict for multi str options."""
+ return super(MultiStrOpt,
+ self)._get_optparse_kwargs(group, action='append')
+
+ def _cparser_get_with_deprecated(self, cparser, section):
+ """If cannot find option as dest try deprecated_name alias."""
+ if self.deprecated_name is not None:
+ return cparser.get(section, [self.dest, self.deprecated_name],
+ multi=True)
+ return cparser.get(section, [self.dest], multi=True)
+
+
+class OptGroup(object):
+
+ """
+ Represents a group of opts.
+
+ CLI opts in the group are automatically prefixed with the group name.
+
+ Each group corresponds to a section in config files.
+
+ An OptGroup object has no public methods, but has a number of public string
+ properties:
+
+ name:
+ the name of the group
+ title:
+ the group title as displayed in --help
+ help:
+ the group description as displayed in --help
+ """
+
+ def __init__(self, name, title=None, help=None):
+ """Constructs an OptGroup object.
+
+ :param name: the group name
+ :param title: the group title for --help
+ :param help: the group description for --help
+ """
+ self.name = name
+ if title is None:
+ self.title = "%s options" % title
+ else:
+ self.title = title
+ self.help = help
+
+ self._opts = {} # dict of dicts of (opt:, override:, default:)
+ self._optparse_group = None
+
+ def _register_opt(self, opt):
+ """Add an opt to this group.
+
+ :param opt: an Opt object
+ :returns: False if previously registered, True otherwise
+ :raises: DuplicateOptError if a naming conflict is detected
+ """
+ if _is_opt_registered(self._opts, opt):
+ return False
+
+ self._opts[opt.dest] = {'opt': opt}
+
+ return True
+
+ def _unregister_opt(self, opt):
+ """Remove an opt from this group.
+
+ :param opt: an Opt object
+ """
+ if opt.dest in self._opts:
+ del self._opts[opt.dest]
+
+ def _get_optparse_group(self, parser):
+ """Build an optparse.OptionGroup for this group."""
+ if self._optparse_group is None:
+ self._optparse_group = optparse.OptionGroup(parser, self.title,
+ self.help)
+ return self._optparse_group
+
+ def _clear(self):
+ """Clear this group's option parsing state."""
+ self._optparse_group = None
+
+
+class ParseError(iniparser.ParseError):
+ def __init__(self, msg, lineno, line, filename):
+ super(ParseError, self).__init__(msg, lineno, line)
+ self.filename = filename
+
+ def __str__(self):
+ return 'at %s:%d, %s: %r' % (self.filename, self.lineno,
+ self.msg, self.line)
+
+
+class ConfigParser(iniparser.BaseParser):
+ def __init__(self, filename, sections):
+ super(ConfigParser, self).__init__()
+ self.filename = filename
+ self.sections = sections
+ self.section = None
+
+ def parse(self):
+ with open(self.filename) as f:
+ return super(ConfigParser, self).parse(f)
+
+ def new_section(self, section):
+ self.section = section
+ self.sections.setdefault(self.section, {})
+
+ def assignment(self, key, value):
+ if not self.section:
+ raise self.error_no_section()
+
+ self.sections[self.section].setdefault(key, [])
+ self.sections[self.section][key].append('\n'.join(value))
+
+ def parse_exc(self, msg, lineno, line=None):
+ return ParseError(msg, lineno, line, self.filename)
+
+ def error_no_section(self):
+ return self.parse_exc('Section must be started before assignment',
+ self.lineno)
+
+
+class MultiConfigParser(object):
+ def __init__(self):
+ self.parsed = []
+
+ def read(self, config_files):
+ read_ok = []
+
+ for filename in config_files:
+ sections = {}
+ parser = ConfigParser(filename, sections)
+
+ try:
+ parser.parse()
+ except IOError:
+ continue
+ self.parsed.insert(0, sections)
+ read_ok.append(filename)
+
+ return read_ok
+
+ def get(self, section, names, multi=False):
+ rvalue = []
+ for sections in self.parsed:
+ if section not in sections:
+ continue
+ for name in names:
+ if name in sections[section]:
+ if multi:
+ rvalue = sections[section][name] + rvalue
+ else:
+ return sections[section][name]
+ if multi and rvalue != []:
+ return rvalue
+ raise KeyError
+
+
+class ConfigOpts(collections.Mapping):
+
+ """
+ Config options which may be set on the command line or in config files.
+
+ ConfigOpts is a configuration option manager with APIs for registering
+ option schemas, grouping options, parsing option values and retrieving
+ the values of options.
+ """
+
+ def __init__(self):
+ """Construct a ConfigOpts object."""
+ self._opts = {} # dict of dicts of (opt:, override:, default:)
+ self._groups = {}
+
+ self._args = None
+ self._oparser = None
+ self._cparser = None
+ self._cli_values = {}
+ self.__cache = {}
+ self._config_opts = []
+ self._disable_interspersed_args = False
+
+ def _setup(self, project, prog, version, usage, default_config_files):
+ """Initialize a ConfigOpts object for option parsing."""
+ if prog is None:
+ prog = os.path.basename(sys.argv[0])
+
+ if default_config_files is None:
+ default_config_files = find_config_files(project, prog)
+
+ self._oparser = optparse.OptionParser(prog=prog,
+ version=version,
+ usage=usage)
+ if self._disable_interspersed_args:
+ self._oparser.disable_interspersed_args()
+
+ self._config_opts = [
+ MultiStrOpt('config-file',
+ default=default_config_files,
+ metavar='PATH',
+ help='Path to a config file to use. Multiple config '
+ 'files can be specified, with values in later '
+ 'files taking precedence. The default files '
+ ' used are: %s' % (default_config_files, )),
+ StrOpt('config-dir',
+ metavar='DIR',
+ help='Path to a config directory to pull *.conf '
+ 'files from. This file set is sorted, so as to '
+ 'provide a predictable parse order if individual '
+ 'options are over-ridden. The set is parsed after '
+ 'the file(s), if any, specified via --config-file, '
+ 'hence over-ridden options in the directory take '
+ 'precedence.'),
+ ]
+ self.register_cli_opts(self._config_opts)
+
+ self.project = project
+ self.prog = prog
+ self.version = version
+ self.usage = usage
+ self.default_config_files = default_config_files
+
+ def __clear_cache(f):
+ @functools.wraps(f)
+ def __inner(self, *args, **kwargs):
+ if kwargs.pop('clear_cache', True):
+ self.__cache.clear()
+ return f(self, *args, **kwargs)
+
+ return __inner
+
+ def __call__(self,
+ args=None,
+ project=None,
+ prog=None,
+ version=None,
+ usage=None,
+ default_config_files=None):
+ """Parse command line arguments and config files.
+
+ Calling a ConfigOpts object causes the supplied command line arguments
+ and config files to be parsed, causing opt values to be made available
+ as attributes of the object.
+
+ The object may be called multiple times, each time causing the previous
+ set of values to be overwritten.
+
+ Automatically registers the --config-file option with either a supplied
+ list of default config files, or a list from find_config_files().
+
+ If the --config-dir option is set, any *.conf files from this
+ directory are pulled in, after all the file(s) specified by the
+ --config-file option.
+
+ :param args: command line arguments (defaults to sys.argv[1:])
+ :param project: the toplevel project name, used to locate config files
+ :param prog: the name of the program (defaults to sys.argv[0] basename)
+ :param version: the program version (for --version)
+ :param usage: a usage string (%prog will be expanded)
+ :param default_config_files: config files to use by default
+ :returns: the list of arguments left over after parsing options
+ :raises: SystemExit, ConfigFilesNotFoundError, ConfigFileParseError,
+ RequiredOptError, DuplicateOptError
+ """
+ self.clear()
+
+ self._setup(project, prog, version, usage, default_config_files)
+
+ self._cli_values, leftovers = self._parse_cli_opts(args)
+
+ self._parse_config_files()
+
+ self._check_required_opts()
+
+ return leftovers
+
+ def __getattr__(self, name):
+ """Look up an option value and perform string substitution.
+
+ :param name: the opt name (or 'dest', more precisely)
+ :returns: the option value (after string subsititution) or a GroupAttr
+ :raises: NoSuchOptError,ConfigFileValueError,TemplateSubstitutionError
+ """
+ return self._get(name)
+
+ def __getitem__(self, key):
+ """Look up an option value and perform string substitution."""
+ return self.__getattr__(key)
+
+ def __contains__(self, key):
+ """Return True if key is the name of a registered opt or group."""
+ return key in self._opts or key in self._groups
+
+ def __iter__(self):
+ """Iterate over all registered opt and group names."""
+ for key in self._opts.keys() + self._groups.keys():
+ yield key
+
+ def __len__(self):
+ """Return the number of options and option groups."""
+ return len(self._opts) + len(self._groups)
+
+ def reset(self):
+ """Clear the object state and unset overrides and defaults."""
+ self._unset_defaults_and_overrides()
+ self.clear()
+
+ @__clear_cache
+ def clear(self):
+ """Clear the state of the object to before it was called."""
+ self._args = None
+ self._cli_values.clear()
+ self._oparser = None
+ self._cparser = None
+ self.unregister_opts(self._config_opts)
+ for group in self._groups.values():
+ group._clear()
+
+ @__clear_cache
+ def register_opt(self, opt, group=None):
+ """Register an option schema.
+
+ Registering an option schema makes any option value which is previously
+ or subsequently parsed from the command line or config files available
+ as an attribute of this object.
+
+ :param opt: an instance of an Opt sub-class
+ :param group: an optional OptGroup object or group name
+ :return: False if the opt was already register, True otherwise
+ :raises: DuplicateOptError
+ """
+ if group is not None:
+ return self._get_group(group, autocreate=True)._register_opt(opt)
+
+ if _is_opt_registered(self._opts, opt):
+ return False
+
+ self._opts[opt.dest] = {'opt': opt}
+
+ return True
+
+ @__clear_cache
+ def register_opts(self, opts, group=None):
+ """Register multiple option schemas at once."""
+ for opt in opts:
+ self.register_opt(opt, group, clear_cache=False)
+
+ @__clear_cache
+ def register_cli_opt(self, opt, group=None):
+ """Register a CLI option schema.
+
+ CLI option schemas must be registered before the command line and
+ config files are parsed. This is to ensure that all CLI options are
+ show in --help and option validation works as expected.
+
+ :param opt: an instance of an Opt sub-class
+ :param group: an optional OptGroup object or group name
+ :return: False if the opt was already register, True otherwise
+ :raises: DuplicateOptError, ArgsAlreadyParsedError
+ """
+ if self._args is not None:
+ raise ArgsAlreadyParsedError("cannot register CLI option")
+
+ return self.register_opt(opt, group, clear_cache=False)
+
+ @__clear_cache
+ def register_cli_opts(self, opts, group=None):
+ """Register multiple CLI option schemas at once."""
+ for opt in opts:
+ self.register_cli_opt(opt, group, clear_cache=False)
+
+ def register_group(self, group):
+ """Register an option group.
+
+ An option group must be registered before options can be registered
+ with the group.
+
+ :param group: an OptGroup object
+ """
+ if group.name in self._groups:
+ return
+
+ self._groups[group.name] = copy.copy(group)
+
+ @__clear_cache
+ def unregister_opt(self, opt, group=None):
+ """Unregister an option.
+
+ :param opt: an Opt object
+ :param group: an optional OptGroup object or group name
+ :raises: ArgsAlreadyParsedError, NoSuchGroupError
+ """
+ if self._args is not None:
+ raise ArgsAlreadyParsedError("reset before unregistering options")
+
+ if group is not None:
+ self._get_group(group)._unregister_opt(opt)
+ elif opt.dest in self._opts:
+ del self._opts[opt.dest]
+
+ @__clear_cache
+ def unregister_opts(self, opts, group=None):
+ """Unregister multiple CLI option schemas at once."""
+ for opt in opts:
+ self.unregister_opt(opt, group, clear_cache=False)
+
+ def import_opt(self, name, module_str, group=None):
+ """Import an option definition from a module.
+
+ Import a module and check that a given option is registered.
+
+ This is intended for use with global configuration objects
+ like cfg.CONF where modules commonly register options with
+ CONF at module load time. If one module requires an option
+ defined by another module it can use this method to explicitly
+ declare the dependency.
+
+ :param name: the name/dest of the opt
+ :param module_str: the name of a module to import
+ :param group: an option OptGroup object or group name
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ __import__(module_str)
+ self._get_opt_info(name, group)
+
+ @__clear_cache
+ def set_override(self, name, override, group=None):
+ """Override an opt value.
+
+ Override the command line, config file and default values of a
+ given option.
+
+ :param name: the name/dest of the opt
+ :param override: the override value
+ :param group: an option OptGroup object or group name
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ opt_info = self._get_opt_info(name, group)
+ opt_info['override'] = override
+
+ @__clear_cache
+ def set_default(self, name, default, group=None):
+ """Override an opt's default value.
+
+ Override the default value of given option. A command line or
+ config file value will still take precedence over this default.
+
+ :param name: the name/dest of the opt
+ :param default: the default value
+ :param group: an option OptGroup object or group name
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ opt_info = self._get_opt_info(name, group)
+ opt_info['default'] = default
+
+ @__clear_cache
+ def clear_override(self, name, group=None):
+ """Clear an override an opt value.
+
+ Clear a previously set override of the command line, config file
+ and default values of a given option.
+
+ :param name: the name/dest of the opt
+ :param group: an option OptGroup object or group name
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ opt_info = self._get_opt_info(name, group)
+ opt_info.pop('override', None)
+
+ @__clear_cache
+ def clear_default(self, name, group=None):
+ """Clear an override an opt's default value.
+
+ Clear a previously set override of the default value of given option.
+
+ :param name: the name/dest of the opt
+ :param group: an option OptGroup object or group name
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ opt_info = self._get_opt_info(name, group)
+ opt_info.pop('default', None)
+
+ def _all_opt_infos(self):
+ """A generator function for iteration opt infos."""
+ for info in self._opts.values():
+ yield info, None
+ for group in self._groups.values():
+ for info in group._opts.values():
+ yield info, group
+
+ def _all_opts(self):
+ """A generator function for iteration opts."""
+ for info, group in self._all_opt_infos():
+ yield info['opt'], group
+
+ def _unset_defaults_and_overrides(self):
+ """Unset any default or override on all options."""
+ for info, group in self._all_opt_infos():
+ info.pop('default', None)
+ info.pop('override', None)
+
+ def disable_interspersed_args(self):
+ """Set parsing to stop on the first non-option.
+
+ If this this method is called, then parsing e.g.
+
+ script --verbose cmd --debug /tmp/mything
+
+ will no longer return:
+
+ ['cmd', '/tmp/mything']
+
+ as the leftover arguments, but will instead return:
+
+ ['cmd', '--debug', '/tmp/mything']
+
+ i.e. argument parsing is stopped at the first non-option argument.
+ """
+ self._disable_interspersed_args = True
+
+ def enable_interspersed_args(self):
+ """Set parsing to not stop on the first non-option.
+
+ This it the default behaviour."""
+ self._disable_interspersed_args = False
+
+ def find_file(self, name):
+ """Locate a file located alongside the config files.
+
+ Search for a file with the supplied basename in the directories
+ which we have already loaded config files from and other known
+ configuration directories.
+
+ The directory, if any, supplied by the config_dir option is
+ searched first. Then the config_file option is iterated over
+ and each of the base directories of the config_files values
+ are searched. Failing both of these, the standard directories
+ searched by the module level find_config_files() function is
+ used. The first matching file is returned.
+
+ :param basename: the filename, e.g. 'policy.json'
+ :returns: the path to a matching file, or None
+ """
+ dirs = []
+ if self.config_dir:
+ dirs.append(_fixpath(self.config_dir))
+
+ for cf in reversed(self.config_file):
+ dirs.append(os.path.dirname(_fixpath(cf)))
+
+ dirs.extend(_get_config_dirs(self.project))
+
+ return _search_dirs(dirs, name)
+
+ def log_opt_values(self, logger, lvl):
+ """Log the value of all registered opts.
+
+ It's often useful for an app to log its configuration to a log file at
+ startup for debugging. This method dumps to the entire config state to
+ the supplied logger at a given log level.
+
+ :param logger: a logging.Logger object
+ :param lvl: the log level (e.g. logging.DEBUG) arg to logger.log()
+ """
+ logger.log(lvl, "*" * 80)
+ logger.log(lvl, "Configuration options gathered from:")
+ logger.log(lvl, "command line args: %s", self._args)
+ logger.log(lvl, "config files: %s", self.config_file)
+ logger.log(lvl, "=" * 80)
+
+ def _sanitize(opt, value):
+ """Obfuscate values of options declared secret"""
+ return value if not opt.secret else '*' * len(str(value))
+
+ for opt_name in sorted(self._opts):
+ opt = self._get_opt_info(opt_name)['opt']
+ logger.log(lvl, "%-30s = %s", opt_name,
+ _sanitize(opt, getattr(self, opt_name)))
+
+ for group_name in self._groups:
+ group_attr = self.GroupAttr(self, self._get_group(group_name))
+ for opt_name in sorted(self._groups[group_name]._opts):
+ opt = self._get_opt_info(opt_name, group_name)['opt']
+ logger.log(lvl, "%-30s = %s",
+ "%s.%s" % (group_name, opt_name),
+ _sanitize(opt, getattr(group_attr, opt_name)))
+
+ logger.log(lvl, "*" * 80)
+
+ def print_usage(self, file=None):
+ """Print the usage message for the current program."""
+ self._oparser.print_usage(file)
+
+ def print_help(self, file=None):
+ """Print the help message for the current program."""
+ self._oparser.print_help(file)
+
+ def _get(self, name, group=None):
+ if isinstance(group, OptGroup):
+ key = (group.name, name)
+ else:
+ key = (group, name)
+ try:
+ return self.__cache[key]
+ except KeyError:
+ value = self._substitute(self._do_get(name, group))
+ self.__cache[key] = value
+ return value
+
+ def _do_get(self, name, group=None):
+ """Look up an option value.
+
+ :param name: the opt name (or 'dest', more precisely)
+ :param group: an OptGroup
+ :returns: the option value, or a GroupAttr object
+ :raises: NoSuchOptError, NoSuchGroupError, ConfigFileValueError,
+ TemplateSubstitutionError
+ """
+ if group is None and name in self._groups:
+ return self.GroupAttr(self, self._get_group(name))
+
+ info = self._get_opt_info(name, group)
+ opt = info['opt']
+
+ if 'override' in info:
+ return info['override']
+
+ values = []
+ if self._cparser is not None:
+ section = group.name if group is not None else 'DEFAULT'
+ try:
+ value = opt._get_from_config_parser(self._cparser, section)
+ except KeyError:
+ pass
+ except ValueError as ve:
+ raise ConfigFileValueError(str(ve))
+ else:
+ if not opt.multi:
+ # No need to continue since the last value wins
+ return value[-1]
+ values.extend(value)
+
+ name = name if group is None else group.name + '_' + name
+ value = self._cli_values.get(name)
+ if value is not None:
+ if not opt.multi:
+ return value
+
+ return value + values
+
+ if values:
+ return values
+
+ if 'default' in info:
+ return info['default']
+
+ return opt.default
+
+ def _substitute(self, value):
+ """Perform string template substitution.
+
+ Substitute any template variables (e.g. $foo, ${bar}) in the supplied
+ string value(s) with opt values.
+
+ :param value: the string value, or list of string values
+ :returns: the substituted string(s)
+ """
+ if isinstance(value, list):
+ return [self._substitute(i) for i in value]
+ elif isinstance(value, str):
+ tmpl = string.Template(value)
+ return tmpl.safe_substitute(self.StrSubWrapper(self))
+ else:
+ return value
+
+ def _get_group(self, group_or_name, autocreate=False):
+ """Looks up a OptGroup object.
+
+ Helper function to return an OptGroup given a parameter which can
+ either be the group's name or an OptGroup object.
+
+ The OptGroup object returned is from the internal dict of OptGroup
+ objects, which will be a copy of any OptGroup object that users of
+ the API have access to.
+
+ :param group_or_name: the group's name or the OptGroup object itself
+ :param autocreate: whether to auto-create the group if it's not found
+ :raises: NoSuchGroupError
+ """
+ group = group_or_name if isinstance(group_or_name, OptGroup) else None
+ group_name = group.name if group else group_or_name
+
+ if not group_name in self._groups:
+ if not group is None or not autocreate:
+ raise NoSuchGroupError(group_name)
+
+ self.register_group(OptGroup(name=group_name))
+
+ return self._groups[group_name]
+
+ def _get_opt_info(self, opt_name, group=None):
+ """Return the (opt, override, default) dict for an opt.
+
+ :param opt_name: an opt name/dest
+ :param group: an optional group name or OptGroup object
+ :raises: NoSuchOptError, NoSuchGroupError
+ """
+ if group is None:
+ opts = self._opts
+ else:
+ group = self._get_group(group)
+ opts = group._opts
+
+ if not opt_name in opts:
+ raise NoSuchOptError(opt_name, group)
+
+ return opts[opt_name]
+
+ def _parse_config_files(self):
+ """Parse the config files from --config-file and --config-dir.
+
+ :raises: ConfigFilesNotFoundError, ConfigFileParseError
+ """
+ config_files = list(self.config_file)
+
+ if self.config_dir:
+ config_dir_glob = os.path.join(self.config_dir, '*.conf')
+ config_files += sorted(glob.glob(config_dir_glob))
+
+ config_files = [_fixpath(p) for p in config_files]
+
+ self._cparser = MultiConfigParser()
+
+ try:
+ read_ok = self._cparser.read(config_files)
+ except iniparser.ParseError as pe:
+ raise ConfigFileParseError(pe.filename, str(pe))
+
+ if read_ok != config_files:
+ not_read_ok = filter(lambda f: f not in read_ok, config_files)
+ raise ConfigFilesNotFoundError(not_read_ok)
+
+ def _check_required_opts(self):
+ """Check that all opts marked as required have values specified.
+
+ :raises: RequiredOptError
+ """
+ for info, group in self._all_opt_infos():
+ opt = info['opt']
+
+ if opt.required:
+ if ('default' in info or 'override' in info):
+ continue
+
+ if self._get(opt.dest, group) is None:
+ raise RequiredOptError(opt.name, group)
+
+ def _parse_cli_opts(self, args):
+ """Parse command line options.
+
+ Initializes the command line option parser and parses the supplied
+ command line arguments.
+
+ :param args: the command line arguments
+ :returns: a dict of parsed option values
+ :raises: SystemExit, DuplicateOptError
+
+ """
+ self._args = args
+
+ for opt, group in self._all_opts():
+ opt._add_to_cli(self._oparser, group)
+
+ values, leftovers = self._oparser.parse_args(args)
+
+ return vars(values), leftovers
+
+ class GroupAttr(collections.Mapping):
+
+ """
+ A helper class representing the option values of a group as a mapping
+ and attributes.
+ """
+
+ def __init__(self, conf, group):
+ """Construct a GroupAttr object.
+
+ :param conf: a ConfigOpts object
+ :param group: an OptGroup object
+ """
+ self.conf = conf
+ self.group = group
+
+ def __getattr__(self, name):
+ """Look up an option value and perform template substitution."""
+ return self.conf._get(name, self.group)
+
+ def __getitem__(self, key):
+ """Look up an option value and perform string substitution."""
+ return self.__getattr__(key)
+
+ def __contains__(self, key):
+ """Return True if key is the name of a registered opt or group."""
+ return key in self.group._opts
+
+ def __iter__(self):
+ """Iterate over all registered opt and group names."""
+ for key in self.group._opts.keys():
+ yield key
+
+ def __len__(self):
+ """Return the number of options and option groups."""
+ return len(self.group._opts)
+
+ class StrSubWrapper(object):
+
+ """
+ A helper class exposing opt values as a dict for string substitution.
+ """
+
+ def __init__(self, conf):
+ """Construct a StrSubWrapper object.
+
+ :param conf: a ConfigOpts object
+ """
+ self.conf = conf
+
+ def __getitem__(self, key):
+ """Look up an opt value from the ConfigOpts object.
+
+ :param key: an opt name
+ :returns: an opt value
+ :raises: TemplateSubstitutionError if attribute is a group
+ """
+ value = getattr(self.conf, key)
+ if isinstance(value, self.conf.GroupAttr):
+ raise TemplateSubstitutionError(
+ 'substituting group %s not supported' % key)
+ return value
+
+
+class CommonConfigOpts(ConfigOpts):
+
+ DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"
+ DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
+
+ common_cli_opts = [
+ BoolOpt('debug',
+ short='d',
+ default=False,
+ help='Print debugging output'),
+ BoolOpt('verbose',
+ short='v',
+ default=False,
+ help='Print more verbose output'),
+ ]
+
+ logging_cli_opts = [
+ StrOpt('log-config',
+ metavar='PATH',
+ help='If this option is specified, the logging configuration '
+ 'file specified is used and overrides any other logging '
+ 'options specified. Please see the Python logging module '
+ 'documentation for details on logging configuration '
+ 'files.'),
+ StrOpt('log-format',
+ default=DEFAULT_LOG_FORMAT,
+ metavar='FORMAT',
+ help='A logging.Formatter log message format string which may '
+ 'use any of the available logging.LogRecord attributes. '
+ 'Default: %default'),
+ StrOpt('log-date-format',
+ default=DEFAULT_LOG_DATE_FORMAT,
+ metavar='DATE_FORMAT',
+ help='Format string for %(asctime)s in log records. '
+ 'Default: %default'),
+ StrOpt('log-file',
+ metavar='PATH',
+ help='(Optional) Name of log file to output to. '
+ 'If not set, logging will go to stdout.'),
+ StrOpt('log-dir',
+ help='(Optional) The directory to keep log files in '
+ '(will be prepended to --logfile)'),
+ BoolOpt('use-syslog',
+ default=False,
+ help='Use syslog for logging.'),
+ StrOpt('syslog-log-facility',
+ default='LOG_USER',
+ help='syslog facility to receive log lines')
+ ]
+
+ def __init__(self):
+ super(CommonConfigOpts, self).__init__()
+ self.register_cli_opts(self.common_cli_opts)
+ self.register_cli_opts(self.logging_cli_opts)
+
+
+CONF = CommonConfigOpts()
diff --git a/keystoneclient/openstack/common/iniparser.py b/keystoneclient/openstack/common/iniparser.py
new file mode 100644
index 0000000..2412844
--- /dev/null
+++ b/keystoneclient/openstack/common/iniparser.py
@@ -0,0 +1,130 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2012 OpenStack LLC.
+#
+# 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.
+
+
+class ParseError(Exception):
+ def __init__(self, message, lineno, line):
+ self.msg = message
+ self.line = line
+ self.lineno = lineno
+
+ def __str__(self):
+ return 'at line %d, %s: %r' % (self.lineno, self.msg, self.line)
+
+
+class BaseParser(object):
+ lineno = 0
+ parse_exc = ParseError
+
+ def _assignment(self, key, value):
+ self.assignment(key, value)
+ return None, []
+
+ def _get_section(self, line):
+ if line[-1] != ']':
+ return self.error_no_section_end_bracket(line)
+ if len(line) <= 2:
+ return self.error_no_section_name(line)
+
+ return line[1:-1]
+
+ def _split_key_value(self, line):
+ colon = line.find(':')
+ equal = line.find('=')
+ if colon < 0 and equal < 0:
+ return self.error_invalid_assignment(line)
+
+ if colon < 0 or (equal >= 0 and equal < colon):
+ key, value = line[:equal], line[equal + 1:]
+ else:
+ key, value = line[:colon], line[colon + 1:]
+
+ value = value.strip()
+ if ((value and value[0] == value[-1]) and
+ (value[0] == "\"" or value[0] == "'")):
+ value = value[1:-1]
+ return key.strip(), [value]
+
+ def parse(self, lineiter):
+ key = None
+ value = []
+
+ for line in lineiter:
+ self.lineno += 1
+
+ line = line.rstrip()
+ if not line:
+ # Blank line, ends multi-line values
+ if key:
+ key, value = self._assignment(key, value)
+ continue
+ elif line[0] in (' ', '\t'):
+ # Continuation of previous assignment
+ if key is None:
+ self.error_unexpected_continuation(line)
+ else:
+ value.append(line.lstrip())
+ continue
+
+ if key:
+ # Flush previous assignment, if any
+ key, value = self._assignment(key, value)
+
+ if line[0] == '[':
+ # Section start
+ section = self._get_section(line)
+ if section:
+ self.new_section(section)
+ elif line[0] in '#;':
+ self.comment(line[1:].lstrip())
+ else:
+ key, value = self._split_key_value(line)
+ if not key:
+ return self.error_empty_key(line)
+
+ if key:
+ # Flush previous assignment, if any
+ self._assignment(key, value)
+
+ def assignment(self, key, value):
+ """Called when a full assignment is parsed"""
+ raise NotImplementedError()
+
+ def new_section(self, section):
+ """Called when a new section is started"""
+ raise NotImplementedError()
+
+ def comment(self, comment):
+ """Called when a comment is parsed"""
+ pass
+
+ def error_invalid_assignment(self, line):
+ raise self.parse_exc("No ':' or '=' found in assignment",
+ self.lineno, line)
+
+ def error_empty_key(self, line):
+ raise self.parse_exc('Key cannot be empty', self.lineno, line)
+
+ def error_unexpected_continuation(self, line):
+ raise self.parse_exc('Unexpected continuation line',
+ self.lineno, line)
+
+ def error_no_section_end_bracket(self, line):
+ raise self.parse_exc('Invalid section (must end with ])',
+ self.lineno, line)
+
+ def error_no_section_name(self, line):
+ raise self.parse_exc('Empty section name', self.lineno, line)
diff --git a/keystoneclient/openstack/common/jsonutils.py b/keystoneclient/openstack/common/jsonutils.py
new file mode 100644
index 0000000..d06ba59
--- /dev/null
+++ b/keystoneclient/openstack/common/jsonutils.py
@@ -0,0 +1,148 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2010 United States Government as represented by the
+# Administrator of the National Aeronautics and Space Administration.
+# Copyright 2011 Justin Santa Barbara
+# All Rights Reserved.
+#
+# 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.
+
+'''
+JSON related utilities.
+
+This module provides a few things:
+
+ 1) A handy function for getting an object down to something that can be
+ JSON serialized. See to_primitive().
+
+ 2) Wrappers around loads() and dumps(). The dumps() wrapper will
+ automatically use to_primitive() for you if needed.
+
+ 3) This sets up anyjson to use the loads() and dumps() wrappers if anyjson
+ is available.
+'''
+
+
+import datetime
+import inspect
+import itertools
+import json
+import xmlrpclib
+
+from keystoneclient.openstack.common import timeutils
+
+
+def to_primitive(value, convert_instances=False, level=0):
+ """Convert a complex object into primitives.
+
+ Handy for JSON serialization. We can optionally handle instances,
+ but since this is a recursive function, we could have cyclical
+ data structures.
+
+ To handle cyclical data structures we could track the actual objects
+ visited in a set, but not all objects are hashable. Instead we just
+ track the depth of the object inspections and don't go too deep.
+
+ Therefore, convert_instances=True is lossy ... be aware.
+
+ """
+ nasty = [inspect.ismodule, inspect.isclass, inspect.ismethod,
+ inspect.isfunction, inspect.isgeneratorfunction,
+ inspect.isgenerator, inspect.istraceback, inspect.isframe,
+ inspect.iscode, inspect.isbuiltin, inspect.isroutine,
+ inspect.isabstract]
+ for test in nasty:
+ if test(value):
+ return unicode(value)
+
+ # value of itertools.count doesn't get caught by inspects
+ # above and results in infinite loop when list(value) is called.
+ if type(value) == itertools.count:
+ return unicode(value)
+
+ # FIXME(vish): Workaround for LP bug 852095. Without this workaround,
+ # tests that raise an exception in a mocked method that
+ # has a @wrap_exception with a notifier will fail. If
+ # we up the dependency to 0.5.4 (when it is released) we
+ # can remove this workaround.
+ if getattr(value, '__module__', None) == 'mox':
+ return 'mock'
+
+ if level > 3:
+ return '?'
+
+ # The try block may not be necessary after the class check above,
+ # but just in case ...
+ try:
+ # It's not clear why xmlrpclib created their own DateTime type, but
+ # for our purposes, make it a datetime type which is explicitly
+ # handled
+ if isinstance(value, xmlrpclib.DateTime):
+ value = datetime.datetime(*tuple(value.timetuple())[:6])
+
+ if isinstance(value, (list, tuple)):
+ o = []
+ for v in value:
+ o.append(to_primitive(v, convert_instances=convert_instances,
+ level=level))
+ return o
+ elif isinstance(value, dict):
+ o = {}
+ for k, v in value.iteritems():
+ o[k] = to_primitive(v, convert_instances=convert_instances,
+ level=level)
+ return o
+ elif isinstance(value, datetime.datetime):
+ return timeutils.strtime(value)
+ elif hasattr(value, 'iteritems'):
+ return to_primitive(dict(value.iteritems()),
+ convert_instances=convert_instances,
+ level=level + 1)
+ elif hasattr(value, '__iter__'):
+ return to_primitive(list(value),
+ convert_instances=convert_instances,
+ level=level)
+ elif convert_instances and hasattr(value, '__dict__'):
+ # Likely an instance of something. Watch for cycles.
+ # Ignore class member vars.
+ return to_primitive(value.__dict__,
+ convert_instances=convert_instances,
+ level=level + 1)
+ else:
+ return value
+ except TypeError, e:
+ # Class objects are tricky since they may define something like
+ # __iter__ defined but it isn't callable as list().
+ return unicode(value)
+
+
+def dumps(value, default=to_primitive, **kwargs):
+ return json.dumps(value, default=default, **kwargs)
+
+
+def loads(s):
+ return json.loads(s)
+
+
+def load(s):
+ return json.load(s)
+
+
+try:
+ import anyjson
+except ImportError:
+ pass
+else:
+ anyjson._modules.append((__name__, 'dumps', TypeError,
+ 'loads', ValueError, 'load'))
+ anyjson.force_implementation(__name__)
diff --git a/keystoneclient/openstack/common/setup.py b/keystoneclient/openstack/common/setup.py
index e434968..e6f72f0 100644
--- a/keystoneclient/openstack/common/setup.py
+++ b/keystoneclient/openstack/common/setup.py
@@ -31,12 +31,13 @@ from setuptools.command import sdist
def parse_mailmap(mailmap='.mailmap'):
mapping = {}
if os.path.exists(mailmap):
- fp = open(mailmap, 'r')
- for l in fp:
- l = l.strip()
- if not l.startswith('#') and ' ' in l:
- canonical_email, alias = l.split(' ')
- mapping[alias] = canonical_email
+ with open(mailmap, 'r') as fp:
+ for l in fp:
+ l = l.strip()
+ if not l.startswith('#') and ' ' in l:
+ canonical_email, alias = [x for x in l.split(' ')
+ if x.startswith('<')]
+ mapping[alias] = canonical_email
return mapping
@@ -51,10 +52,10 @@ def canonicalize_emails(changelog, mapping):
# Get requirements from the first file that exists
def get_reqs_from_files(requirements_files):
- reqs_in = []
for requirements_file in requirements_files:
if os.path.exists(requirements_file):
- return open(requirements_file, 'r').read().split('\n')
+ with open(requirements_file, 'r') as fil:
+ return fil.read().split('\n')
return []
@@ -139,11 +140,19 @@ def _get_git_next_version_suffix(branch_name):
_run_shell_command("git fetch origin +refs/meta/*:refs/remotes/meta/*")
milestone_cmd = "git show meta/openstack/release:%s" % branch_name
milestonever = _run_shell_command(milestone_cmd)
- if not milestonever:
- milestonever = ""
+ if milestonever:
+ first_half = "%s~%s" % (milestonever, datestamp)
+ else:
+ first_half = datestamp
+
post_version = _get_git_post_version()
- revno = post_version.split(".")[-1]
- return "%s~%s.%s%s" % (milestonever, datestamp, revno_prefix, revno)
+ # post version should look like:
+ # 0.1.1.4.gcc9e28a
+ # where the bit after the last . is the short sha, and the bit between
+ # the last and second to last is the revno count
+ (revno, sha) = post_version.split(".")[-2:]
+ second_half = "%s%s.%s" % (revno_prefix, revno, sha)
+ return ".".join((first_half, second_half))
def _get_git_current_tag():
@@ -165,39 +174,48 @@ def _get_git_post_version():
cmd = "git --no-pager log --oneline"
out = _run_shell_command(cmd)
revno = len(out.split("\n"))
+ sha = _run_shell_command("git describe --always")
else:
tag_infos = tag_info.split("-")
base_version = "-".join(tag_infos[:-2])
- revno = tag_infos[-2]
- return "%s.%s" % (base_version, revno)
+ (revno, sha) = tag_infos[-2:]
+ return "%s.%s.%s" % (base_version, revno, sha)
def write_git_changelog():
"""Write a changelog based on the git changelog."""
- if os.path.isdir('.git'):
- git_log_cmd = 'git log --stat'
- changelog = _run_shell_command(git_log_cmd)
- mailmap = parse_mailmap()
- with open("ChangeLog", "w") as changelog_file:
- changelog_file.write(canonicalize_emails(changelog, mailmap))
+ new_changelog = 'ChangeLog'
+ if not os.getenv('SKIP_WRITE_GIT_CHANGELOG'):
+ if os.path.isdir('.git'):
+ git_log_cmd = 'git log --stat'
+ changelog = _run_shell_command(git_log_cmd)
+ mailmap = parse_mailmap()
+ with open(new_changelog, "w") as changelog_file:
+ changelog_file.write(canonicalize_emails(changelog, mailmap))
+ else:
+ open(new_changelog, 'w').close()
def generate_authors():
"""Create AUTHORS file using git commits."""
- jenkins_email = 'jenkins@review.openstack.org'
+ jenkins_email = 'jenkins@review.(openstack|stackforge).org'
old_authors = 'AUTHORS.in'
new_authors = 'AUTHORS'
- if os.path.isdir('.git'):
- # don't include jenkins email address in AUTHORS file
- git_log_cmd = ("git log --format='%aN <%aE>' | sort -u | "
- "grep -v " + jenkins_email)
- changelog = _run_shell_command(git_log_cmd)
- mailmap = parse_mailmap()
- with open(new_authors, 'w') as new_authors_fh:
- new_authors_fh.write(canonicalize_emails(changelog, mailmap))
- if os.path.exists(old_authors):
- with open(old_authors, "r") as old_authors_fh:
- new_authors_fh.write('\n' + old_authors_fh.read())
+ if not os.getenv('SKIP_GENERATE_AUTHORS'):
+ if os.path.isdir('.git'):
+ # don't include jenkins email address in AUTHORS file
+ git_log_cmd = ("git log --format='%aN <%aE>' | sort -u | "
+ "egrep -v '" + jenkins_email + "'")
+ changelog = _run_shell_command(git_log_cmd)
+ mailmap = parse_mailmap()
+ with open(new_authors, 'w') as new_authors_fh:
+ new_authors_fh.write(canonicalize_emails(changelog, mailmap))
+ if os.path.exists(old_authors):
+ with open(old_authors, "r") as old_authors_fh:
+ new_authors_fh.write('\n' + old_authors_fh.read())
+ else:
+ open(new_authors, 'w').close()
+
_rst_template = """%(heading)s
%(underline)s
@@ -211,7 +229,7 @@ _rst_template = """%(heading)s
def read_versioninfo(project):
"""Read the versioninfo file. If it doesn't exist, we're in a github
- zipball, and there's really know way to know what version we really
+ zipball, and there's really no way to know what version we really
are, but that should be ok, because the utility of that should be
just about nil if this code path is in use in the first place."""
versioninfo_path = os.path.join(project, 'versioninfo')
@@ -225,7 +243,8 @@ def read_versioninfo(project):
def write_versioninfo(project, version):
"""Write a simple file containing the version of the package."""
- open(os.path.join(project, 'versioninfo'), 'w').write("%s\n" % version)
+ with open(os.path.join(project, 'versioninfo'), 'w') as fil:
+ fil.write("%s\n" % version)
def get_cmdclass():
@@ -316,7 +335,8 @@ def get_git_branchname():
def get_pre_version(projectname, base_version):
- """Return a version which is based"""
+ """Return a version which is leading up to a version that will
+ be released in the future."""
if os.path.isdir('.git'):
current_tag = _get_git_current_tag()
if current_tag is not None:
@@ -328,10 +348,10 @@ def get_pre_version(projectname, base_version):
version_suffix = _get_git_next_version_suffix(branch_name)
version = "%s~%s" % (base_version, version_suffix)
write_versioninfo(projectname, version)
- return version.split('~')[0]
+ return version
else:
version = read_versioninfo(projectname)
- return version.split('~')[0]
+ return version
def get_post_version(projectname):
diff --git a/keystoneclient/openstack/common/timeutils.py b/keystoneclient/openstack/common/timeutils.py
new file mode 100644
index 0000000..8600439
--- /dev/null
+++ b/keystoneclient/openstack/common/timeutils.py
@@ -0,0 +1,137 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2011 OpenStack LLC.
+# All Rights Reserved.
+#
+# 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.
+
+"""
+Time related utilities and helper functions.
+"""
+
+import calendar
+import datetime
+
+import iso8601
+
+
+TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
+PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
+
+
+def isotime(at=None):
+ """Stringify time in ISO 8601 format"""
+ if not at:
+ at = utcnow()
+ str = at.strftime(TIME_FORMAT)
+ tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
+ str += ('Z' if tz == 'UTC' else tz)
+ return str
+
+
+def parse_isotime(timestr):
+ """Parse time from ISO 8601 format"""
+ try:
+ return iso8601.parse_date(timestr)
+ except iso8601.ParseError as e:
+ raise ValueError(e.message)
+ except TypeError as e:
+ raise ValueError(e.message)
+
+
+def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
+ """Returns formatted utcnow."""
+ if not at:
+ at = utcnow()
+ return at.strftime(fmt)
+
+
+def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT):
+ """Turn a formatted time back into a datetime."""
+ return datetime.datetime.strptime(timestr, fmt)
+
+
+def normalize_time(timestamp):
+ """Normalize time in arbitrary timezone to UTC naive object"""
+ offset = timestamp.utcoffset()
+ if offset is None:
+ return timestamp
+ return timestamp.replace(tzinfo=None) - offset
+
+
+def is_older_than(before, seconds):
+ """Return True if before is older than seconds."""
+ return utcnow() - before > datetime.timedelta(seconds=seconds)
+
+
+def is_newer_than(after, seconds):
+ """Return True if after is newer than seconds."""
+ return after - utcnow() > datetime.timedelta(seconds=seconds)
+
+
+def utcnow_ts():
+ """Timestamp version of our utcnow function."""
+ return calendar.timegm(utcnow().timetuple())
+
+
+def utcnow():
+ """Overridable version of utils.utcnow."""
+ if utcnow.override_time:
+ return utcnow.override_time
+ return datetime.datetime.utcnow()
+
+
+utcnow.override_time = None
+
+
+def set_time_override(override_time=datetime.datetime.utcnow()):
+ """Override utils.utcnow to return a constant time."""
+ utcnow.override_time = override_time
+
+
+def advance_time_delta(timedelta):
+ """Advance overridden time using a datetime.timedelta."""
+ assert(not utcnow.override_time is None)
+ utcnow.override_time += timedelta
+
+
+def advance_time_seconds(seconds):
+ """Advance overridden time by seconds."""
+ advance_time_delta(datetime.timedelta(0, seconds))
+
+
+def clear_time_override():
+ """Remove the overridden time."""
+ utcnow.override_time = None
+
+
+def marshall_now(now=None):
+ """Make an rpc-safe datetime with microseconds.
+
+ Note: tzinfo is stripped, but not required for relative times."""
+ if not now:
+ now = utcnow()
+ return dict(day=now.day, month=now.month, year=now.year, hour=now.hour,
+ minute=now.minute, second=now.second,
+ microsecond=now.microsecond)
+
+
+def unmarshall_time(tyme):
+ """Unmarshall a datetime dict."""
+ return datetime.datetime(day=tyme['day'],
+ month=tyme['month'],
+ year=tyme['year'],
+ hour=tyme['hour'],
+ minute=tyme['minute'],
+ second=tyme['second'],
+ microsecond=tyme['microsecond'])
diff --git a/keystoneclient/service_catalog.py b/keystoneclient/service_catalog.py
index cbe5c5d..11da572 100644
--- a/keystoneclient/service_catalog.py
+++ b/keystoneclient/service_catalog.py
@@ -42,7 +42,7 @@ class ServiceCatalog(object):
try:
token['user_id'] = self.catalog['user']['id']
token['tenant_id'] = self.catalog['token']['tenant']['id']
- except:
+ except Exception:
# just leave the tenant and user out if it doesn't exist
pass
return token
diff --git a/keystoneclient/shell.py b/keystoneclient/shell.py
index 963a996..3deda8d 100644
--- a/keystoneclient/shell.py
+++ b/keystoneclient/shell.py
@@ -71,35 +71,43 @@ class OpenStackIdentityShell(object):
parser.add_argument('--os-username',
metavar='<auth-user-name>',
default=env('OS_USERNAME'),
- help='Defaults to env[OS_USERNAME]')
+ help='Name used for authentication with the '
+ 'OpenStack Identity service. '
+ 'Defaults to env[OS_USERNAME]')
parser.add_argument('--os_username',
help=argparse.SUPPRESS)
parser.add_argument('--os-password',
metavar='<auth-password>',
default=env('OS_PASSWORD'),
- help='Defaults to env[OS_PASSWORD]')
+ help='Password used for authentication with the '
+ 'OpenStack Identity service. '
+ 'Defaults to env[OS_PASSWORD]')
parser.add_argument('--os_password',
help=argparse.SUPPRESS)
parser.add_argument('--os-tenant-name',
metavar='<auth-tenant-name>',
default=env('OS_TENANT_NAME'),
- help='Defaults to env[OS_TENANT_NAME]')
+ help='Tenant to request authorization on. '
+ 'Defaults to env[OS_TENANT_NAME]')
parser.add_argument('--os_tenant_name',
help=argparse.SUPPRESS)
parser.add_argument('--os-tenant-id',
metavar='<tenant-id>',
default=env('OS_TENANT_ID'),
- help='Defaults to env[OS_TENANT_ID]')
+ help='Tenant to request authorization on. '
+ 'Defaults to env[OS_TENANT_ID]')
parser.add_argument('--os_tenant_id',
help=argparse.SUPPRESS)
parser.add_argument('--os-auth-url',
metavar='<auth-url>',
default=env('OS_AUTH_URL'),
- help='Defaults to env[OS_AUTH_URL]')
+ help='Specify the Identity endpoint to use for '
+ 'authentication. '
+ 'Defaults to env[OS_AUTH_URL]')
parser.add_argument('--os_auth_url',
help=argparse.SUPPRESS)
@@ -122,12 +130,18 @@ class OpenStackIdentityShell(object):
parser.add_argument('--os-token',
metavar='<service-token>',
default=env('OS_SERVICE_TOKEN'),
- help='Defaults to env[OS_SERVICE_TOKEN]')
+ help='Specify an existing token to use instead of '
+ 'retrieving one via authentication (e.g. '
+ 'with username & password). '
+ 'Defaults to env[OS_SERVICE_TOKEN]')
parser.add_argument('--os-endpoint',
metavar='<service-endpoint>',
default=env('OS_SERVICE_ENDPOINT'),
- help='Defaults to env[OS_SERVICE_ENDPOINT]')
+ help='Specify an endpoint to use instead of '
+ 'retrieving one from the service catalog '
+ '(via authentication). '
+ 'Defaults to env[OS_SERVICE_ENDPOINT]')
parser.add_argument('--os-cacert',
metavar='<ca-certificate>',
@@ -153,26 +167,25 @@ class OpenStackIdentityShell(object):
parser.add_argument('--insecure',
default=False,
action="store_true",
- help="Explicitly allow keystoneclient to perform "
- "\"insecure\" SSL (https) requests. The "
- "server's certificate will not be verified "
- "against any certificate authorities. This "
- "option should be used with caution.")
+ help='Explicitly allow keystoneclient to perform '
+ '"insecure" SSL (https) requests. The '
+ 'server\'s certificate will not be verified '
+ 'against any certificate authorities. This '
+ 'option should be used with caution.')
+
#FIXME(heckj):
# deprecated command line options for essex compatibility. To be
# removed in Grizzly release cycle.
-
parser.add_argument('--token',
metavar='<service-token>',
dest='os_token',
default=env('SERVICE_TOKEN'),
- help='Deprecated. use --os-token')
-
+ help=argparse.SUPPRESS)
parser.add_argument('--endpoint',
dest='os_endpoint',
metavar='<service-endpoint>',
default=env('SERVICE_ENDPOINT'),
- help='Deprecated. use --os-endpoint')
+ help=argparse.SUPPRESS)
return parser
@@ -259,9 +272,6 @@ class OpenStackIdentityShell(object):
self.do_bash_completion(args)
return 0
- #FIXME(usrleon): Here should be restrict for project id same as
- # for username or apikey but for compatibility it is not.
-
# TODO(heckj): supporting backwards compatibility with environment
# variables. To be removed after DEVSTACK is updated, ideally in
# the Grizzly release cycle.
@@ -340,27 +350,27 @@ class OpenStackIdentityShell(object):
cacert=args.os_cacert,
key=args.os_key,
cert=args.os_cert,
- insecure=args.insecure)
+ insecure=args.insecure,
+ debug=args.debug)
else:
token = None
- endpoint = None
if args.os_token and args.os_endpoint:
token = args.os_token
- endpoint = args.os_endpoint
api_version = options.os_identity_api_version
self.cs = self.get_api_class(api_version)(
username=args.os_username,
tenant_name=args.os_tenant_name,
tenant_id=args.os_tenant_id,
token=token,
- endpoint=endpoint,
+ endpoint=args.os_endpoint,
password=args.os_password,
auth_url=args.os_auth_url,
region_name=args.os_region_name,
cacert=args.os_cacert,
key=args.os_key,
cert=args.os_cert,
- insecure=args.insecure)
+ insecure=args.insecure,
+ debug=args.debug)
try:
args.func(self.cs, args)
@@ -421,7 +431,7 @@ def main():
try:
OpenStackIdentityShell().main(sys.argv[1:])
- except Exception, e:
+ except Exception as e:
if httplib2.debuglevel == 1:
raise # dump stack.
else:
diff --git a/keystoneclient/utils.py b/keystoneclient/utils.py
index 36ec41b..225afe7 100644
--- a/keystoneclient/utils.py
+++ b/keystoneclient/utils.py
@@ -1,4 +1,5 @@
import uuid
+import hashlib
import prettytable
@@ -114,3 +115,9 @@ def string_to_bool(arg):
return arg
return arg.strip().lower() in ('t', 'true', 'yes', '1')
+
+
+def hash_signed_token(signed_text):
+ hash_ = hashlib.md5()
+ hash_.update(signed_text)
+ return hash_.hexdigest()
diff --git a/keystoneclient/v2_0/client.py b/keystoneclient/v2_0/client.py
index c241451..39725ac 100644
--- a/keystoneclient/v2_0/client.py
+++ b/keystoneclient/v2_0/client.py
@@ -14,6 +14,7 @@
# under the License.
import logging
+from keystoneclient import access
from keystoneclient import client
from keystoneclient import exceptions
from keystoneclient import service_catalog
@@ -35,8 +36,8 @@ class Client(client.HTTPClient):
:param string username: Username for authentication. (optional)
:param string password: Password for authentication. (optional)
:param string token: Token for authentication. (optional)
- :param string tenant_name: Tenant id. (optional)
- :param string tenant_id: Tenant name. (optional)
+ :param string tenant_id: Tenant id. (optional)
+ :param string tenant_name: Tenant name. (optional)
:param string auth_url: Keystone service endpoint for authorization.
:param string region_name: Name of a region to select when choosing an
endpoint from the service catalog.
@@ -49,6 +50,32 @@ class Client(client.HTTPClient):
:param string original_ip: The original IP of the requesting user
which will be sent to Keystone in a
'Forwarded' header. (optional)
+ :param string cert: If provided, used as a local certificate to communicate
+ with the keystone endpoint. If provided, requires the
+ additional parameter key. (optional)
+ :param string key: The key associated with the certificate for secure
+ keystone communication. (optional)
+ :param string cacert: the ca-certs to verify the secure communications
+ with keystone. (optional)
+ :param boolean insecure: If using an SSL endpoint, allows for the certicate
+ to be unsigned - does not verify the certificate
+ chain. default: False (optional)
+ :param dict auth_ref: To allow for consumers of the client to manage their
+ own caching strategy, you may initialize a client
+ with a previously captured auth_reference (token)
+ :param boolean debug: Enables debug logging of all request and responses
+ to keystone. default False (option)
+
+ .. warning::
+
+ If debug is enabled, it may show passwords in plain text as a part of its
+ output.
+
+
+ The client can be created and used like a user or in a strictly
+ bootstrap mode. Normal operation expects a username, password, auth_url,
+ and tenant_name or id to be provided. Other values will be lazily loaded
+ as needed from the service catalog.
Example::
@@ -62,84 +89,145 @@ class Client(client.HTTPClient):
>>> user = keystone.users.get(USER_ID)
>>> user.delete()
+ Once authenticated, you can store and attempt to re-use the
+ authenticated token. the auth_ref property on the client
+ returns as a dictionary-like-object so that you can export and
+ cache it, re-using it when initiating another client::
+
+ >>> from keystoneclient.v2_0 import client
+ >>> keystone = client.Client(username=USER,
+ password=PASS,
+ tenant_name=TENANT_NAME,
+ auth_url=KEYSTONE_URL)
+ >>> auth_ref = keystone.auth_ref
+ >>> # pickle or whatever you like here
+ >>> new_client = client.Client(auth_ref=auth_ref)
+
+ Alternatively, you can provide the administrative token configured in
+ keystone and an endpoint to communicate with directly. See
+ (``admin_token`` in ``keystone.conf``) In this case, authenticate()
+ is not needed, and no service catalog will be loaded.
+
+ Example::
+
+ >>> from keystoneclient.v2_0 import client
+ >>> admin_client = client.Client(
+ token='12345secret7890',
+ endpoint='http://localhost:35357/v2.0')
+ >>> keystone.tenants.list()
+
"""
- def __init__(self, endpoint=None, **kwargs):
+ def __init__(self, **kwargs):
""" Initialize a new client for the Keystone v2.0 API. """
- super(Client, self).__init__(endpoint=endpoint, **kwargs)
+ super(Client, self).__init__(**kwargs)
self.endpoints = endpoints.EndpointManager(self)
self.roles = roles.RoleManager(self)
self.services = services.ServiceManager(self)
self.tenants = tenants.TenantManager(self)
self.tokens = tokens.TokenManager(self)
self.users = users.UserManager(self)
- # NOTE(gabriel): If we have a pre-defined endpoint then we can
- # get away with lazy auth. Otherwise auth immediately.
# extensions
self.ec2 = ec2.CredentialsManager(self)
- self.management_url = endpoint
- if endpoint is None:
+ if self.management_url is None:
self.authenticate()
+ #TODO(heckj): move to a method on auth_ref
def has_service_catalog(self):
"""Returns True if this client provides a service catalog."""
return hasattr(self, 'service_catalog')
- def authenticate(self):
- """ Authenticate against the Identity API.
+ def authenticate(self, username=None, password=None, tenant_name=None,
+ tenant_id=None, auth_url=None, token=None):
+ """ Authenticate against the Keystone API.
Uses the data provided at instantiation to authenticate against
the Keystone server. This may use either a username and password
- or token for authentication. If a tenant id was provided
+ or token for authentication. If a tenant name or id was provided
then the resulting authenticated client will be scoped to that
tenant and contain a service catalog of available endpoints.
- Returns ``True`` if authentication was successful.
+ With the v2.0 API, if a tenant name or ID is not provided, the
+ authenication token returned will be 'unscoped' and limited in
+ capabilities until a fully-scoped token is acquired.
+
+ If successful, sets the self.auth_ref and self.auth_token with
+ the returned token. If not already set, will also set
+ self.management_url from the details provided in the token.
+
+ :returns: ``True`` if authentication was successful.
+ :raises: AuthorizationFailure if unable to authenticate or validate
+ the existing authorization token
+ :raises: ValueError if insufficient parameters are used.
"""
- self.management_url = self.auth_url
+ auth_url = auth_url or self.auth_url
+ username = username or self.username
+ password = password or self.password
+ tenant_name = tenant_name or self.tenant_name
+ tenant_id = tenant_id or self.tenant_id
+ token = token or self.auth_token
+
try:
- raw_token = self.tokens.authenticate(username=self.username,
- tenant_id=self.tenant_id,
- tenant_name=self.tenant_name,
- password=self.password,
- token=self.auth_token,
- return_raw=True)
- self._extract_service_catalog(self.auth_url, raw_token)
+ raw_token = self._base_authN(auth_url,
+ username=username,
+ tenant_id=tenant_id,
+ tenant_name=tenant_name,
+ password=password,
+ token=token)
+ self.auth_ref = access.AccessInfo(**raw_token)
+ # if we got a response without a service catalog, set the local
+ # list of tenants for introspection, and leave to client user
+ # to determine what to do. Otherwise, load up the service catalog
+ self.auth_token = self.auth_ref.auth_token
+ if self.auth_ref.scoped:
+ if self.management_url is None:
+ self.management_url = self.auth_ref.management_url[0]
+ self.tenant_name = self.auth_ref.tenant_name
+ self.tenant_id = self.auth_ref.tenant_id
+ self.user_id = self.auth_ref.user_id
+ self._extract_service_catalog(self.auth_url, self.auth_ref)
return True
except (exceptions.AuthorizationFailure, exceptions.Unauthorized):
_logger.debug("Authorization Failed.")
raise
- except Exception, e:
+ except Exception as e:
raise exceptions.AuthorizationFailure("Authorization Failed: "
"%s" % e)
+ def _base_authN(self, auth_url, username=None, password=None,
+ tenant_name=None, tenant_id=None, token=None):
+ """ Takes a username, password, and optionally a tenant_id or
+ tenant_name to get an authentication token from keystone.
+ May also take a token and a tenant_id to re-scope a token
+ to a tenant."""
+ headers = {}
+ url = auth_url + "/tokens"
+ if token:
+ headers['X-Auth-Token'] = token
+ params = {"auth": {"token": {"id": token}}}
+ elif username and password:
+ params = {"auth": {"passwordCredentials": {"username": username,
+ "password": password}}}
+ else:
+ raise ValueError('A username and password or token is required.')
+ if tenant_id:
+ params['auth']['tenantId'] = tenant_id
+ elif tenant_name:
+ params['auth']['tenantName'] = tenant_name
+ resp, body = self.request(url, 'POST', body=params, headers=headers)
+ return body['access']
+
+ # TODO(heckj): remove entirely in favor of access.AccessInfo and
+ # associated methods
def _extract_service_catalog(self, url, body):
""" Set the client's service catalog from the response data. """
self.service_catalog = service_catalog.ServiceCatalog(body)
try:
sc = self.service_catalog.get_token()
- self.auth_token = sc['id']
# Save these since we have them and they'll be useful later
self.auth_tenant_id = sc.get('tenant_id')
self.auth_user_id = sc.get('user_id')
except KeyError:
raise exceptions.AuthorizationFailure()
-
- # FIXME(ja): we should be lazy about setting managment_url.
- # in fact we should rewrite the client to support the service
- # catalog (api calls should be directable to any endpoints)
- try:
- self.management_url = self.service_catalog.url_for(
- attr='region', filter_value=self.region_name,
- endpoint_type='adminURL')
- except exceptions.EmptyCatalog:
- # Unscoped tokens don't return a service catalog;
- # allow those to pass while any other errors bubble up.
- pass
- except exceptions.EndpointNotFound:
- # the client shouldn't expect the authenticating user to
- # be authorized to view adminURL's, nor expect the identity
- # endpoint to publish one
- pass
diff --git a/keystoneclient/v2_0/shell.py b/keystoneclient/v2_0/shell.py
index 07968e9..a976134 100755
--- a/keystoneclient/v2_0/shell.py
+++ b/keystoneclient/v2_0/shell.py
@@ -96,7 +96,7 @@ def do_user_update(kc, args):
try:
kc.users.update(args.id, **kwargs)
print 'User has been updated.'
- except Exception, e:
+ except Exception as e:
print 'Unable to update user: %s' % e
@@ -321,7 +321,7 @@ def do_ec2_credentials_list(kc, args):
for cred in credentials:
try:
cred.tenant = getattr(kc.tenants.get(cred.tenant_id), 'name')
- except:
+ except Exception:
# FIXME(dtroyer): Retrieving the tenant name fails for normal
# users; stuff in the tenant_id instead.
cred.tenant = cred.tenant_id
@@ -340,7 +340,7 @@ def do_ec2_credentials_delete(kc, args):
try:
kc.ec2.delete(args.user_id, args.access)
print 'Credential has been deleted.'
- except Exception, e:
+ except Exception as e:
print 'Unable to delete credential: %s' % e
@@ -419,7 +419,7 @@ def do_endpoint_delete(kc, args):
try:
kc.endpoints.delete(args.id)
print 'Endpoint has been deleted.'
- except:
+ except Exception:
print 'Unable to delete endpoint.'
diff --git a/keystoneclient/v2_0/tenants.py b/keystoneclient/v2_0/tenants.py
index 4ced200..e15341d 100644
--- a/keystoneclient/v2_0/tenants.py
+++ b/keystoneclient/v2_0/tenants.py
@@ -107,7 +107,16 @@ class TenantManager(base.ManagerWithFind):
if params:
query = "?" + urllib.urlencode(params)
- return self._list("/tenants%s" % query, "tenants")
+ reset = 0
+ if self.api.management_url is None:
+ # special casing to allow tenant lists on the auth_url
+ # for unscoped tokens
+ reset = 1
+ self.api.management_url = self.api.auth_url
+ tenant_list = self._list("/tenants%s" % query, "tenants")
+ if reset:
+ self.api.management_url = None
+ return tenant_list
def update(self, tenant_id, tenant_name=None, description=None,
enabled=None):
diff --git a/keystoneclient/v2_0/tokens.py b/keystoneclient/v2_0/tokens.py
index 2505446..c129db7 100644
--- a/keystoneclient/v2_0/tokens.py
+++ b/keystoneclient/v2_0/tokens.py
@@ -34,7 +34,15 @@ class TokenManager(base.ManagerWithFind):
params['auth']['tenantId'] = tenant_id
elif tenant_name:
params['auth']['tenantName'] = tenant_name
- return self._create('/tokens', params, "access", return_raw=return_raw)
+ reset = 0
+ if self.api.management_url is None:
+ reset = 1
+ self.api.management_url = self.api.auth_url
+ token_ref = self._create('/tokens', params, "access",
+ return_raw=return_raw)
+ if reset:
+ self.api.management_url = None
+ return token_ref
def delete(self, token):
return self._delete("/tokens/%s" % base.getid(token))
diff --git a/openstack-common.conf b/openstack-common.conf
index de8f129..e6df21e 100644
--- a/openstack-common.conf
+++ b/openstack-common.conf
@@ -1,7 +1,7 @@
[DEFAULT]
# The list of modules to copy from openstack-common
-modules=setup
+modules=setup,cfg,iniparser,jsonutils,timeutils
# The base module to hold the copy of openstack.common
base=keystoneclient
diff --git a/run_tests.sh b/run_tests.sh
index d22a745..dff6948 100755
--- a/run_tests.sh
+++ b/run_tests.sh
@@ -92,8 +92,13 @@ function run_pep8 {
# other than what the PEP8 tool claims. It is deprecated in Python 3, so,
# perhaps the mistake was thinking that the deprecation applied to Python 2
# as well.
+ #
+ # NOTE(henry-nash): Added exlusion of the openstack.common dir (as
+ # is the case in other projects, since some of the common files
+ # don't pass pep8. Clearly we should come back a fix this
+ #
${wrapper} pep8 --repeat --show-pep8 --show-source \
- --ignore=E202,W602 \
+ --ignore=E202,W602 --exclude=openstack \
${srcfiles}
}
diff --git a/tests/client_fixtures.py b/tests/client_fixtures.py
new file mode 100644
index 0000000..f0b5137
--- /dev/null
+++ b/tests/client_fixtures.py
@@ -0,0 +1,72 @@
+UNSCOPED_TOKEN = {
+ u'access': {u'serviceCatalog': {},
+ u'token': {u'expires': u'2012-10-03T16:58:01Z',
+ u'id': u'3e2813b7ba0b4006840c3825860b86ed'},
+ u'user': {u'id': u'c4da488862bd435c9e6c0275a0d0e49a',
+ u'name': u'exampleuser',
+ u'roles': [],
+ u'roles_links': [],
+ u'username': u'exampleuser'}
+ }
+}
+
+PROJECT_SCOPED_TOKEN = {
+ u'access': {
+ u'serviceCatalog': [{
+ u'endpoints': [{
+ u'adminURL': u'http://admin:8776/v1/225da22d3ce34b15877ea70b2a575f58',
+ u'internalURL':
+ u'http://internal:8776/v1/225da22d3ce34b15877ea70b2a575f58',
+ u'publicURL':
+ u'http://public.com:8776/v1/225da22d3ce34b15877ea70b2a575f58',
+ u'region': u'RegionOne'
+ }],
+ u'endpoints_links': [],
+ u'name': u'Volume Service',
+ u'type': u'volume'},
+ {u'endpoints': [{
+ u'adminURL': u'http://admin:9292/v1',
+ u'internalURL': u'http://internal:9292/v1',
+ u'publicURL': u'http://public.com:9292/v1',
+ u'region': u'RegionOne'}],
+ u'endpoints_links': [],
+ u'name': u'Image Service',
+ u'type': u'image'},
+ {u'endpoints': [{
+u'adminURL': u'http://admin:8774/v2/225da22d3ce34b15877ea70b2a575f58',
+u'internalURL': u'http://internal:8774/v2/225da22d3ce34b15877ea70b2a575f58',
+u'publicURL': u'http://public.com:8774/v2/225da22d3ce34b15877ea70b2a575f58',
+u'region': u'RegionOne'}],
+ u'endpoints_links': [],
+ u'name': u'Compute Service',
+ u'type': u'compute'},
+ {u'endpoints': [{
+u'adminURL': u'http://admin:8773/services/Admin',
+u'internalURL': u'http://internal:8773/services/Cloud',
+u'publicURL': u'http://public.com:8773/services/Cloud',
+u'region': u'RegionOne'}],
+ u'endpoints_links': [],
+ u'name': u'EC2 Service',
+ u'type': u'ec2'},
+ {u'endpoints': [{
+u'adminURL': u'http://admin:35357/v2.0',
+u'internalURL': u'http://internal:5000/v2.0',
+u'publicURL': u'http://public.com:5000/v2.0',
+u'region': u'RegionOne'}],
+ u'endpoints_links': [],
+ u'name': u'Identity Service',
+ u'type': u'identity'}],
+ u'token': {u'expires': u'2012-10-03T16:53:36Z',
+ u'id': u'04c7d5ffaeef485f9dc69c06db285bdb',
+ u'tenant': {u'description': u'',
+ u'enabled': True,
+ u'id': u'225da22d3ce34b15877ea70b2a575f58',
+ u'name': u'exampleproject'}},
+ u'user': {u'id': u'c4da488862bd435c9e6c0275a0d0e49a',
+ u'name': u'exampleuser',
+ u'roles': [{u'id': u'edc12489faa74ee0aca0b8a0b4d74a74',
+ u'name': u'Member'}],
+ u'roles_links': [],
+ u'username': u'exampleuser'}
+ }
+}
diff --git a/tests/test_access.py b/tests/test_access.py
new file mode 100644
index 0000000..be2a186
--- /dev/null
+++ b/tests/test_access.py
@@ -0,0 +1,56 @@
+from keystoneclient import access
+from tests import utils
+from tests import client_fixtures
+
+UNSCOPED_TOKEN = client_fixtures.UNSCOPED_TOKEN
+PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN
+
+
+class AccessInfoTest(utils.TestCase):
+ def test_building_unscoped_accessinfo(self):
+ auth_ref = access.AccessInfo(UNSCOPED_TOKEN['access'])
+
+ self.assertTrue(auth_ref)
+ self.assertIn('token', auth_ref)
+ self.assertIn('serviceCatalog', auth_ref)
+ self.assertFalse(auth_ref['serviceCatalog'])
+
+ self.assertEquals(auth_ref.auth_token,
+ '3e2813b7ba0b4006840c3825860b86ed')
+ self.assertEquals(auth_ref.username, 'exampleuser')
+ self.assertEquals(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a')
+
+ self.assertEquals(auth_ref.tenant_name, None)
+ self.assertEquals(auth_ref.tenant_id, None)
+
+ self.assertEquals(auth_ref.auth_url, None)
+ self.assertEquals(auth_ref.management_url, None)
+
+ self.assertFalse(auth_ref.scoped)
+
+ def test_building_scoped_accessinfo(self):
+ auth_ref = access.AccessInfo(PROJECT_SCOPED_TOKEN['access'])
+
+ self.assertTrue(auth_ref)
+ self.assertIn('token', auth_ref)
+ self.assertIn('serviceCatalog', auth_ref)
+ self.assertTrue(auth_ref['serviceCatalog'])
+
+ self.assertEquals(auth_ref.auth_token,
+ '04c7d5ffaeef485f9dc69c06db285bdb')
+ self.assertEquals(auth_ref.username, 'exampleuser')
+ self.assertEquals(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a')
+
+ self.assertEquals(auth_ref.tenant_name, 'exampleproject')
+ self.assertEquals(auth_ref.tenant_id,
+ '225da22d3ce34b15877ea70b2a575f58')
+
+ self.assertEquals(auth_ref.tenant_name, auth_ref.project_name)
+ self.assertEquals(auth_ref.tenant_id, auth_ref.project_id)
+
+ self.assertEquals(auth_ref.auth_url,
+ ('http://public.com:5000/v2.0',))
+ self.assertEquals(auth_ref.management_url,
+ ('http://admin:35357/v2.0',))
+
+ self.assertTrue(auth_ref.scoped)
diff --git a/tests/test_auth_token_middleware.py b/tests/test_auth_token_middleware.py
new file mode 100644
index 0000000..79cbc91
--- /dev/null
+++ b/tests/test_auth_token_middleware.py
@@ -0,0 +1,670 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2012 OpenStack LLC
+#
+# 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 datetime
+import iso8601
+import os
+import string
+import tempfile
+import unittest2 as unittest
+
+import webob
+
+from keystoneclient.common import cms
+from keystoneclient import utils
+from keystoneclient.middleware import auth_token
+from keystoneclient.openstack.common import jsonutils
+from keystoneclient.openstack.common import timeutils
+from keystoneclient.middleware import test
+
+
+CERTDIR = test.rootdir("python-keystoneclient/examples/pki/certs")
+KEYDIR = test.rootdir("python-keystoneclient/examples/pki/private")
+CMSDIR = test.rootdir("python-keystoneclient/examples/pki/cms")
+SIGNING_CERT = os.path.join(CERTDIR, 'signing_cert.pem')
+SIGNING_KEY = os.path.join(KEYDIR, 'signing_key.pem')
+CA = os.path.join(CERTDIR, 'ca.pem')
+
+REVOCATION_LIST = None
+REVOKED_TOKEN = None
+REVOKED_TOKEN_HASH = None
+SIGNED_REVOCATION_LIST = None
+SIGNED_TOKEN_SCOPED = None
+SIGNED_TOKEN_UNSCOPED = None
+SIGNED_TOKEN_SCOPED_KEY = None
+SIGNED_TOKEN_UNSCOPED_KEY = None
+
+VALID_SIGNED_REVOCATION_LIST = None
+
+UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
+UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
+UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
+VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
+
+INVALID_SIGNED_TOKEN = string.replace(
+ """AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
+DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
+EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
+FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
+0000000000000000000000000000000000000000000000000000000000000000
+1111111111111111111111111111111111111111111111111111111111111111
+2222222222222222222222222222222222222222222222222222222222222222
+3333333333333333333333333333333333333333333333333333333333333333
+4444444444444444444444444444444444444444444444444444444444444444
+5555555555555555555555555555555555555555555555555555555555555555
+6666666666666666666666666666666666666666666666666666666666666666
+7777777777777777777777777777777777777777777777777777777777777777
+8888888888888888888888888888888888888888888888888888888888888888
+9999999999999999999999999999999999999999999999999999999999999999
+0000000000000000000000000000000000000000000000000000000000000000
+xg==""", "\n", "")
+
+# JSON responses keyed by token ID
+TOKEN_RESPONSES = {
+ UUID_TOKEN_DEFAULT: {
+ 'access': {
+ 'token': {
+ 'id': UUID_TOKEN_DEFAULT,
+ 'expires': '2999-01-01T00:00:10Z',
+ 'tenant': {
+ 'id': 'tenant_id1',
+ 'name': 'tenant_name1',
+ },
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ },
+ 'serviceCatalog': {}
+ },
+ },
+ VALID_DIABLO_TOKEN: {
+ 'access': {
+ 'token': {
+ 'id': VALID_DIABLO_TOKEN,
+ 'expires': '2999-01-01T00:00:10',
+ 'tenantId': 'tenant_id1',
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ },
+ },
+ },
+ UUID_TOKEN_UNSCOPED: {
+ 'access': {
+ 'token': {
+ 'id': UUID_TOKEN_UNSCOPED,
+ 'expires': '2999-01-01T00:00:10Z',
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ },
+ },
+ },
+ UUID_TOKEN_NO_SERVICE_CATALOG: {
+ 'access': {
+ 'token': {
+ 'id': 'valid-token',
+ 'expires': '2999-01-01T00:00:10Z',
+ 'tenant': {
+ 'id': 'tenant_id1',
+ 'name': 'tenant_name1',
+ },
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ }
+ },
+ },
+}
+
+FAKE_RESPONSE_STACK = []
+
+
+# The data for these tests are signed using openssl and are stored in files
+# in the signing subdirectory. In order to keep the values consistent between
+# the tests and the signed documents, we read them in for use in the tests.
+def setUpModule(self):
+ signing_path = CMSDIR
+ with open(os.path.join(signing_path, 'auth_token_scoped.pem')) as f:
+ self.SIGNED_TOKEN_SCOPED = cms.cms_to_token(f.read())
+ with open(os.path.join(signing_path, 'auth_token_unscoped.pem')) as f:
+ self.SIGNED_TOKEN_UNSCOPED = cms.cms_to_token(f.read())
+ with open(os.path.join(signing_path, 'auth_token_revoked.pem')) as f:
+ self.REVOKED_TOKEN = cms.cms_to_token(f.read())
+ self.REVOKED_TOKEN_HASH = utils.hash_signed_token(self.REVOKED_TOKEN)
+ with open(os.path.join(signing_path, 'revocation_list.json')) as f:
+ self.REVOCATION_LIST = jsonutils.loads(f.read())
+ with open(os.path.join(signing_path, 'revocation_list.pem')) as f:
+ self.VALID_SIGNED_REVOCATION_LIST = jsonutils.dumps(
+ {'signed': f.read()})
+ self.SIGNED_TOKEN_SCOPED_KEY =\
+ cms.cms_hash_token(self.SIGNED_TOKEN_SCOPED)
+ self.SIGNED_TOKEN_UNSCOPED_KEY =\
+ cms.cms_hash_token(self.SIGNED_TOKEN_UNSCOPED)
+
+ self.TOKEN_RESPONSES[self.SIGNED_TOKEN_SCOPED_KEY] = {
+ 'access': {
+ 'token': {
+ 'id': self.SIGNED_TOKEN_SCOPED_KEY,
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'tenantId': 'tenant_id1',
+ 'tenantName': 'tenant_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ },
+ },
+ }
+
+ self.TOKEN_RESPONSES[SIGNED_TOKEN_UNSCOPED_KEY] = {
+ 'access': {
+ 'token': {
+ 'id': SIGNED_TOKEN_UNSCOPED_KEY,
+ },
+ 'user': {
+ 'id': 'user_id1',
+ 'name': 'user_name1',
+ 'roles': [
+ {'name': 'role1'},
+ {'name': 'role2'},
+ ],
+ },
+ },
+ },
+
+
+class FakeMemcache(object):
+ def __init__(self):
+ self.set_key = None
+ self.set_value = None
+ self.token_expiration = None
+
+ def get(self, key):
+ data = TOKEN_RESPONSES[SIGNED_TOKEN_SCOPED_KEY].copy()
+ if not data or key != "tokens/%s" % (data['access']['token']['id']):
+ return
+ if not self.token_expiration:
+ dt = datetime.datetime.now() + datetime.timedelta(minutes=5)
+ self.token_expiration = dt.strftime("%s")
+ dt = datetime.datetime.now() + datetime.timedelta(hours=24)
+ ks_expires = dt.isoformat()
+ data['access']['token']['expires'] = ks_expires
+ return (data, str(self.token_expiration))
+
+ def set(self, key, value, time=None):
+ self.set_value = value
+ self.set_key = key
+
+
+class FakeHTTPResponse(object):
+ def __init__(self, status, body):
+ self.status = status
+ self.body = body
+
+ def read(self):
+ return self.body
+
+
+class FakeStackHTTPConnection(object):
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def getresponse(self):
+ if len(FAKE_RESPONSE_STACK):
+ return FAKE_RESPONSE_STACK.pop()
+ return FakeHTTPResponse(500, jsonutils.dumps('UNEXPECTED RESPONSE'))
+
+ def request(self, *_args, **_kwargs):
+ pass
+
+ def close(self):
+ pass
+
+
+class FakeHTTPConnection(object):
+
+ last_requested_url = ''
+
+ def __init__(self, *args):
+ self.send_valid_revocation_list = True
+
+ def request(self, method, path, **kwargs):
+ """Fakes out several http responses.
+
+ If a POST request is made, we assume the calling code is trying
+ to get a new admin token.
+
+ If a GET request is made to validate a token, return success
+ if the token is 'token1'. If a different token is provided, return
+ a 404, indicating an unknown (therefore unauthorized) token.
+
+ """
+ FakeHTTPConnection.last_requested_url = path
+ if method == 'POST':
+ status = 200
+ body = jsonutils.dumps({
+ 'access': {
+ 'token': {'id': 'admin_token2'},
+ },
+ })
+
+ else:
+ token_id = path.rsplit('/', 1)[1]
+ if token_id in TOKEN_RESPONSES.keys():
+ status = 200
+ body = jsonutils.dumps(TOKEN_RESPONSES[token_id])
+ elif token_id == "revoked":
+ status = 200
+ body = SIGNED_REVOCATION_LIST
+ else:
+ status = 404
+ body = str()
+
+ self.resp = FakeHTTPResponse(status, body)
+
+ def getresponse(self):
+ return self.resp
+
+ def close(self):
+ pass
+
+
+class FakeApp(object):
+ """This represents a WSGI app protected by the auth_token middleware."""
+ def __init__(self, expected_env=None):
+ expected_env = expected_env or {}
+ self.expected_env = {
+ 'HTTP_X_IDENTITY_STATUS': 'Confirmed',
+ 'HTTP_X_TENANT_ID': 'tenant_id1',
+ 'HTTP_X_TENANT_NAME': 'tenant_name1',
+ 'HTTP_X_USER_ID': 'user_id1',
+ 'HTTP_X_USER_NAME': 'user_name1',
+ 'HTTP_X_ROLES': 'role1,role2',
+ 'HTTP_X_USER': 'user_name1', # deprecated (diablo-compat)
+ 'HTTP_X_TENANT': 'tenant_name1', # deprecated (diablo-compat)
+ 'HTTP_X_ROLE': 'role1,role2', # deprecated (diablo-compat)
+ }
+ self.expected_env.update(expected_env)
+
+ def __call__(self, env, start_response):
+ for k, v in self.expected_env.items():
+ assert env[k] == v, '%s != %s' % (env[k], v)
+
+ resp = webob.Response()
+ resp.body = 'SUCCESS'
+ return resp(env, start_response)
+
+
+class BaseAuthTokenMiddlewareTest(unittest.TestCase):
+
+ def setUp(self, expected_env=None):
+ expected_env = expected_env or {}
+
+ conf = {
+ 'admin_token': 'admin_token1',
+ 'auth_host': 'keystone.example.com',
+ 'auth_port': 1234,
+ 'auth_admin_prefix': '/testadmin',
+ 'signing_dir': CERTDIR,
+ }
+
+ self.middleware = auth_token.AuthProtocol(FakeApp(expected_env), conf)
+ self.middleware.http_client_class = FakeHTTPConnection
+ self.middleware._iso8601 = iso8601
+
+ self.response_status = None
+ self.response_headers = None
+ self.middleware.revoked_file_name = tempfile.mkstemp()[1]
+ cache_timeout = datetime.timedelta(days=1)
+ self.middleware.token_revocation_list_cache_timeout = cache_timeout
+ self.middleware.token_revocation_list = jsonutils.dumps(
+ {"revoked": [], "extra": "success"})
+
+ signed_list = 'SIGNED_REVOCATION_LIST'
+ valid_signed_list = 'VALID_SIGNED_REVOCATION_LIST'
+ globals()[signed_list] = globals()[valid_signed_list]
+
+ super(BaseAuthTokenMiddlewareTest, self).setUp()
+
+ def tearDown(self):
+ super(BaseAuthTokenMiddlewareTest, self).tearDown()
+ try:
+ os.remove(self.middleware.revoked_file_name)
+ except OSError:
+ pass
+
+ def start_fake_response(self, status, headers):
+ self.response_status = int(status.split(' ', 1)[0])
+ self.response_headers = dict(headers)
+
+
+class StackResponseAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest):
+ """Auth Token middleware test setup that allows the tests to define
+ a stack of responses to HTTP requests in the test and get those
+ responses back in sequence for testing.
+
+ Example::
+
+ resp1 = FakeHTTPResponse(401, jsonutils.dumps(''))
+ resp2 = FakeHTTPResponse(200, jsonutils.dumps({
+ 'access': {
+ 'token': {'id': 'admin_token2'},
+ },
+ })
+ FAKE_RESPONSE_STACK.append(resp1)
+ FAKE_RESPONSE_STACK.append(resp2)
+
+ ... do your testing code here ...
+
+ """
+
+ def setUp(self, expected_env=None):
+ super(StackResponseAuthTokenMiddlewareTest, self).setUp(expected_env)
+ self.middleware.http_client_class = FakeStackHTTPConnection
+
+ def test_fetch_revocation_list_with_expire(self):
+ # first response to revocation list should return 401 Unauthorized
+ # to pretend to be an expired token
+ resp1 = FakeHTTPResponse(200, jsonutils.dumps({
+ 'access': {
+ 'token': {'id': 'admin_token2'},
+ },
+ }))
+ resp2 = FakeHTTPResponse(401, jsonutils.dumps(''))
+ resp3 = FakeHTTPResponse(200, jsonutils.dumps({
+ 'access': {
+ 'token': {'id': 'admin_token2'},
+ },
+ }))
+ resp4 = FakeHTTPResponse(200, SIGNED_REVOCATION_LIST)
+
+ # first get_admin_token() call
+ FAKE_RESPONSE_STACK.append(resp1)
+ # request revocation list, get "unauthorized" due to simulated expired
+ # token
+ FAKE_RESPONSE_STACK.append(resp2)
+ # request a new admin_token
+ FAKE_RESPONSE_STACK.append(resp3)
+ # request revocation list, get the revocation list properly
+ FAKE_RESPONSE_STACK.append(resp4)
+
+ fetched_list = jsonutils.loads(self.middleware.fetch_revocation_list())
+ self.assertEqual(fetched_list, REVOCATION_LIST)
+
+
+class DiabloAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest):
+ """Auth Token middleware should understand Diablo keystone responses."""
+ def setUp(self):
+ # pre-diablo only had Tenant ID, which was also the Name
+ expected_env = {
+ 'HTTP_X_TENANT_ID': 'tenant_id1',
+ 'HTTP_X_TENANT_NAME': 'tenant_id1',
+ # now deprecated (diablo-compat)
+ 'HTTP_X_TENANT': 'tenant_id1',
+ }
+ super(DiabloAuthTokenMiddlewareTest, self).setUp(expected_env)
+
+ def test_valid_diablo_response(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = VALID_DIABLO_TOKEN
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 200)
+ self.assertTrue('keystone.token_info' in req.environ)
+
+
+class AuthTokenMiddlewareTest(test.NoModule, BaseAuthTokenMiddlewareTest):
+ def assert_valid_request_200(self, token):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = token
+ body = self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 200)
+ self.assertTrue(req.headers.get('X-Service-Catalog'))
+ self.assertEqual(body, ['SUCCESS'])
+ self.assertTrue('keystone.token_info' in req.environ)
+
+ def test_valid_uuid_request(self):
+ self.assert_valid_request_200(UUID_TOKEN_DEFAULT)
+ self.assertEqual("/testadmin/v2.0/tokens/%s" % UUID_TOKEN_DEFAULT,
+ FakeHTTPConnection.last_requested_url)
+
+ def test_valid_signed_request(self):
+ FakeHTTPConnection.last_requested_url = ''
+ self.assert_valid_request_200(SIGNED_TOKEN_SCOPED)
+ self.assertEqual(self.middleware.conf['auth_admin_prefix'],
+ "/testadmin")
+ #ensure that signed requests do not generate HTTP traffic
+ self.assertEqual('', FakeHTTPConnection.last_requested_url)
+
+ def assert_unscoped_default_tenant_auto_scopes(self, token):
+ """Unscoped requests with a default tenant should "auto-scope."
+
+ The implied scope is the user's tenant ID.
+
+ """
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = token
+ body = self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 200)
+ self.assertEqual(body, ['SUCCESS'])
+ self.assertTrue('keystone.token_info' in req.environ)
+
+ def test_default_tenant_uuid_token(self):
+ self.assert_unscoped_default_tenant_auto_scopes(UUID_TOKEN_DEFAULT)
+
+ def test_default_tenant_signed_token(self):
+ self.assert_unscoped_default_tenant_auto_scopes(SIGNED_TOKEN_SCOPED)
+
+ def assert_unscoped_token_receives_401(self, token):
+ """Unscoped requests with no default tenant ID should be rejected."""
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = token
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+ self.assertEqual(self.response_headers['WWW-Authenticate'],
+ 'Keystone uri=\'https://keystone.example.com:1234\'')
+
+ def test_unscoped_uuid_token_receives_401(self):
+ self.assert_unscoped_token_receives_401(UUID_TOKEN_UNSCOPED)
+
+ def test_unscoped_pki_token_receives_401(self):
+ self.assert_unscoped_token_receives_401(SIGNED_TOKEN_UNSCOPED)
+
+ def test_revoked_token_receives_401(self):
+ self.middleware.token_revocation_list = self.get_revocation_list_json()
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = REVOKED_TOKEN
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+
+ def get_revocation_list_json(self, token_ids=None):
+ if token_ids is None:
+ token_ids = [REVOKED_TOKEN_HASH]
+ revocation_list = {'revoked': [{'id': x, 'expires': timeutils.utcnow()}
+ for x in token_ids]}
+ return jsonutils.dumps(revocation_list)
+
+ def test_is_signed_token_revoked_returns_false(self):
+ #explicitly setting an empty revocation list here to document intent
+ self.middleware.token_revocation_list = jsonutils.dumps(
+ {"revoked": [], "extra": "success"})
+ result = self.middleware.is_signed_token_revoked(REVOKED_TOKEN)
+ self.assertFalse(result)
+
+ def test_is_signed_token_revoked_returns_true(self):
+ self.middleware.token_revocation_list = self.get_revocation_list_json()
+ result = self.middleware.is_signed_token_revoked(REVOKED_TOKEN)
+ self.assertTrue(result)
+
+ def test_verify_signed_token_raises_exception_for_revoked_token(self):
+ self.middleware.token_revocation_list = self.get_revocation_list_json()
+ with self.assertRaises(auth_token.InvalidUserToken):
+ self.middleware.verify_signed_token(REVOKED_TOKEN)
+
+ def test_verify_signed_token_succeeds_for_unrevoked_token(self):
+ self.middleware.token_revocation_list = self.get_revocation_list_json()
+ self.middleware.verify_signed_token(SIGNED_TOKEN_SCOPED)
+
+ def test_get_token_revocation_list_fetched_time_returns_min(self):
+ self.middleware.token_revocation_list_fetched_time = None
+ self.middleware.revoked_file_name = ''
+ self.assertEqual(self.middleware.token_revocation_list_fetched_time,
+ datetime.datetime.min)
+
+ def test_get_token_revocation_list_fetched_time_returns_mtime(self):
+ self.middleware.token_revocation_list_fetched_time = None
+ mtime = os.path.getmtime(self.middleware.revoked_file_name)
+ fetched_time = datetime.datetime.fromtimestamp(mtime)
+ self.assertEqual(self.middleware.token_revocation_list_fetched_time,
+ fetched_time)
+
+ def test_get_token_revocation_list_fetched_time_returns_value(self):
+ expected = self.middleware._token_revocation_list_fetched_time
+ self.assertEqual(self.middleware.token_revocation_list_fetched_time,
+ expected)
+
+ def test_get_revocation_list_returns_fetched_list(self):
+ self.middleware.token_revocation_list_fetched_time = None
+ os.remove(self.middleware.revoked_file_name)
+ self.assertEqual(self.middleware.token_revocation_list,
+ REVOCATION_LIST)
+
+ def test_get_revocation_list_returns_current_list_from_memory(self):
+ self.assertEqual(self.middleware.token_revocation_list,
+ self.middleware._token_revocation_list)
+
+ def test_get_revocation_list_returns_current_list_from_disk(self):
+ in_memory_list = self.middleware.token_revocation_list
+ self.middleware._token_revocation_list = None
+ self.assertEqual(self.middleware.token_revocation_list, in_memory_list)
+
+ def test_invalid_revocation_list_raises_service_error(self):
+ globals()['SIGNED_REVOCATION_LIST'] = "{}"
+ with self.assertRaises(auth_token.ServiceError):
+ self.middleware.fetch_revocation_list()
+
+ def test_fetch_revocation_list(self):
+ fetched_list = jsonutils.loads(self.middleware.fetch_revocation_list())
+ self.assertEqual(fetched_list, REVOCATION_LIST)
+
+ def test_request_invalid_uuid_token(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = 'invalid-token'
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+ self.assertEqual(self.response_headers['WWW-Authenticate'],
+ 'Keystone uri=\'https://keystone.example.com:1234\'')
+
+ def test_request_invalid_signed_token(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = INVALID_SIGNED_TOKEN
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+ self.assertEqual(self.response_headers['WWW-Authenticate'],
+ 'Keystone uri=\'https://keystone.example.com:1234\'')
+
+ def test_request_no_token(self):
+ req = webob.Request.blank('/')
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+ self.assertEqual(self.response_headers['WWW-Authenticate'],
+ 'Keystone uri=\'https://keystone.example.com:1234\'')
+
+ def test_request_blank_token(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = ''
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 401)
+ self.assertEqual(self.response_headers['WWW-Authenticate'],
+ 'Keystone uri=\'https://keystone.example.com:1234\'')
+
+ def test_memcache(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = SIGNED_TOKEN_SCOPED
+ self.middleware._cache = FakeMemcache()
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.middleware._cache.set_value, None)
+
+ def test_memcache_set_invalid(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = 'invalid-token'
+ self.middleware._cache = FakeMemcache()
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.middleware._cache.set_value, "invalid")
+
+ def test_memcache_set_expired(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Auth-Token'] = SIGNED_TOKEN_SCOPED
+ self.middleware._cache = FakeMemcache()
+ expired = datetime.datetime.now() - datetime.timedelta(minutes=1)
+ self.middleware._cache.token_expiration = float(expired.strftime("%s"))
+ self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(len(self.middleware._cache.set_value), 2)
+
+ def test_nomemcache(self):
+ self.disable_module('memcache')
+
+ conf = {
+ 'admin_token': 'admin_token1',
+ 'auth_host': 'keystone.example.com',
+ 'auth_port': 1234,
+ 'memcache_servers': 'localhost:11211',
+ }
+
+ auth_token.AuthProtocol(FakeApp(), conf)
+
+ def test_request_prevent_service_catalog_injection(self):
+ req = webob.Request.blank('/')
+ req.headers['X-Service-Catalog'] = '[]'
+ req.headers['X-Auth-Token'] = UUID_TOKEN_NO_SERVICE_CATALOG
+ body = self.middleware(req.environ, self.start_fake_response)
+ self.assertEqual(self.response_status, 200)
+ self.assertFalse(req.headers.get('X-Service-Catalog'))
+ self.assertEqual(body, ['SUCCESS'])
+
+ def test_will_expire_soon(self):
+ tenseconds = datetime.datetime.utcnow() + datetime.timedelta(
+ seconds=10)
+ self.assertTrue(auth_token.will_expire_soon(tenseconds))
+ fortyseconds = datetime.datetime.utcnow() + datetime.timedelta(
+ seconds=40)
+ self.assertFalse(auth_token.will_expire_soon(fortyseconds))
diff --git a/tests/test_client.py b/tests/test_client.py
new file mode 100644
index 0000000..43d0d8d
--- /dev/null
+++ b/tests/test_client.py
@@ -0,0 +1,37 @@
+import httplib2
+import json
+import mock
+
+from keystoneclient.v2_0 import client
+from tests import client_fixtures
+from tests import utils
+
+
+fake_response = httplib2.Response({"status": 200})
+fake_body = json.dumps(client_fixtures.PROJECT_SCOPED_TOKEN)
+mock_request = mock.Mock(return_value=(fake_response, fake_body))
+
+
+class KeystoneclientTest(utils.TestCase):
+
+ def test_scoped_init(self):
+ with mock.patch.object(httplib2.Http, "request", mock_request):
+ cl = client.Client(username='exampleuser',
+ password='password',
+ auth_url='http://somewhere/')
+ self.assertIsNotNone(cl.auth_ref)
+ self.assertTrue(cl.auth_ref.scoped)
+
+ def test_auth_ref_load(self):
+ with mock.patch.object(httplib2.Http, "request", mock_request):
+ cl = client.Client(username='exampleuser',
+ password='password',
+ auth_url='http://somewhere/')
+ cache = json.dumps(cl.auth_ref)
+ new_client = client.Client(auth_ref=json.loads(cache))
+ self.assertIsNotNone(new_client.auth_ref)
+ self.assertTrue(new_client.auth_ref.scoped)
+ self.assertEquals(new_client.username, 'exampleuser')
+ self.assertIsNone(new_client.password)
+ self.assertEqual(new_client.management_url,
+ 'http://admin:35357/v2.0')
diff --git a/tests/test_http.py b/tests/test_http.py
index 2e09642..652d0c9 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -26,6 +26,13 @@ def get_authed_client():
class ClientTest(utils.TestCase):
+ def test_unauthorized_client_requests(self):
+ cl = get_client()
+ self.assertRaises(exceptions.AuthorizationFailure, cl.get, '/hi')
+ self.assertRaises(exceptions.AuthorizationFailure, cl.post, '/hi')
+ self.assertRaises(exceptions.AuthorizationFailure, cl.put, '/hi')
+ self.assertRaises(exceptions.AuthorizationFailure, cl.delete, '/hi')
+
def test_get(self):
cl = get_authed_client()
diff --git a/tests/v2_0/test_auth.py b/tests/v2_0/test_auth.py
index 62bbf10..37184ba 100644
--- a/tests/v2_0/test_auth.py
+++ b/tests/v2_0/test_auth.py
@@ -65,12 +65,6 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
}),
})
- # Implicit retry on API calls, so it gets called twice
- httplib2.Http.request(self.TEST_URL + "/tokens",
- 'POST',
- body=json.dumps(self.TEST_REQUEST_BODY),
- headers=self.TEST_REQUEST_HEADERS) \
- .AndReturn((resp, resp['body']))
httplib2.Http.request(self.TEST_URL + "/tokens",
'POST',
body=json.dumps(self.TEST_REQUEST_BODY),
diff --git a/tools/test-requires b/tools/test-requires
index 59afe9d..8d9547b 100644
--- a/tools/test-requires
+++ b/tools/test-requires
@@ -10,5 +10,7 @@ nosehtmloutput
pep8==1.2
sphinx>=1.1.2
unittest2>=0.5.1
+WebOb==1.0.8
+iso8601>=0.1.4
Babel