source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py @ 4129

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py@4129
Revision 4129, 6.5 KB checked in by cbyrom, 11 years ago (diff)

General refactoring and updating of code, including:

Removal of refC14nKw and singnedInfoC14nKw keywords in wsssecurity session manager config
(the refC14nInclNS and signedInfoC14nInclNS keywords are sufficient);
Creation of new DOM signature handler class, dom.py, based on the wsSecurity
class;
Abstraction of common code between dom.py and etree.py into new parent
class, BaseSignatureHandler?.py.
Fixing and extending use of properties in the SignatureHandler? code.
Fixing a few bugs with the original SignatureHandler? code.
Updating of test cases to new code/code structure.

Line 
1"""NDG Security wssecurity package - contains signature handler and config
2
3NERC Data Grid Project
4"""
5__author__ = "P J Kershaw"
6__date__ = "01/04/08"
7__copyright__ = "(C) 2008 STFC & NERC"
8__contact__ = "P.J.Kershaw@rl.ac.uk"
9__license__ = \
10"""This software may be distributed under the terms of the Q Public
11License, version 1.0 or later."""
12__contact__ = "P.J.Kershaw@rl.ac.uk"
13__revision__ = "$Id$"
14
15from ZSI.wstools.Namespaces import OASIS
16from ConfigParser import SafeConfigParser
17from os.path import expandvars as exVar
18import copy
19
20class WSSecurityConfigOpNotPermitted(Exception):
21    "Raise for dict methods not allowed in WSSecurityConfig"
22   
23class WSSecurityConfig(dict):
24    """Parser for WS-Security configuration.  Extends dict to enable
25    convenient interface for access to params.
26    """
27    defParam = dict(
28             reqBinSecTokValType=OASIS.X509TOKEN.X509,
29             verifyingCert=None,
30             verifyingCertFilePath=None,
31             signingCert=None,
32             signingCertFilePath=None, 
33             signingCertChain=[],
34             signingPriKey=None,
35             signingPriKeyFilePath=None, 
36             signingPriKeyPwd=None,
37             caCertDirPath=None,
38             caCertFilePathList=[],
39             addTimestamp=True,
40             applySignatureConfirmation=False,
41             refC14nInclNS=[],
42             signedInfoC14nInclNS=[])
43   
44    def __init__(self, cfg=SafeConfigParser()):
45        '''Initialise settings from an existing config file object or the
46        given path to config file
47       
48        @type cfg: SafeConfigParser or string
49        @param cfg: config object instance or file path to config file to be
50        parsed'''
51       
52        dict.__init__(self)
53       
54        # Initialise parameters from ref in class var
55        self._param = WSSecurityConfig.defParam.copy()
56       
57        if isinstance(cfg, basestring):
58            # Assume file path to be read
59            self.read(cfg)
60        else:
61            # Assume existing config type object
62            self._cfg = cfg
63       
64
65    def read(self, *arg):
66        '''Read ConfigParser object'''
67        self._cfg = SafeConfigParser()
68        self._cfg.read(*arg)
69
70
71    def parse(self, **kw):
72        '''Extract items from config file and place in dict
73        @type **kw: dict
74        @param **kw: this enables WS-Security params to be set in a config file
75        with other sections e.g. params could be under the section 'wssecurity'
76        '''
77        if 'section' in kw:
78            section = kw['section']
79        else:
80            section = 'DEFAULT'
81             
82        for paramName in self._param:
83            # Options may be omitted and set later
84            if self._cfg.has_option(section, paramName):
85                if isinstance(WSSecurityConfig.defParam[paramName], list):
86                    try:
87                        self._param[paramName] = \
88                            exVar(self._cfg.get(section, paramName)).split()
89                    except AttributeError:
90                        raise SecurityConfigError('Setting "%s"' % paramName)
91                   
92                elif isinstance(WSSecurityConfig.defParam[paramName], bool):           
93                    self._param[paramName] = self._cfg.getboolean(section, 
94                                                                  paramName)
95                else:
96                    # Default to None if setting is an empty string.  Settings
97                    # of '' causes problems for M2Crypto parsing
98                    self._param[paramName] = \
99                        exVar(self._cfg.get(section, paramName)) or None
100
101    def __len__(self):
102        return len(self._param)
103   
104    def __iter__(self):
105        return self._param.__iter__()
106   
107    def __repr__(self):
108        """Return file properties dictionary as representation"""
109        return repr(self._param)
110
111    def __delitem__(self, key):
112        "Session Manager keys cannot be removed"       
113        raise KeyError('Keys cannot be deleted from ' + \
114                        WSSecurityConfig.__name__)
115
116    def __getitem__(self, key):
117        WSSecurityConfig.__name__ + \
118        """ behaves as data dictionary of WS-Security properties
119        """
120        if key not in self.defParam:
121            raise KeyError("Invalid key '%s'" % key)
122       
123        return self._param[key] 
124   
125    def __setitem__(self, key, item):
126        WSSecurityConfig.__name__ + \
127        """ behaves as data dictionary of WS-Security properties"""
128        if key not in WSSecurityConfig.defParam:
129            raise KeyError("Parameter key '%s' is not recognised" % key)
130       
131        self._param[key] = item
132
133    def copy(self):
134        wsSecurityConfig = WSSecurityConfig()
135        wsSecurityConfig._param = self._param.copy()
136        return wsSecurityConfig
137   
138    def get(self, key, *arg):
139        return self._param.get(key, *arg)
140
141    def clear(self):
142        raise WSSecurityConfigOpNotPermitted("Data cannot be cleared from "+\
143                                             WSSecurityConfig.__name__)
144   
145    def keys(self):
146        return self._param.keys()
147
148    def items(self):
149        return self._param.items()
150
151    def values(self):
152        return self._param.values()
153
154    def has_key(self, key):
155        return self._param.has_key(key)
156
157    # 'in' operator
158    def __contains__(self, key):
159        return key in self._param
160   
161    def update(self, seq, *arg):
162        badKeys = [i for i in seq if i not in WSSecurityConfig.defParam]
163        if badKeys:
164            raise KeyError("Parameter key(s) %s not recognised" % \
165                           ','.join(badKeys))
166        return self._param.update(seq, *arg)
167   
168    def fromkeys(self, seq):
169        badKeys = [i for i in seq if i not in WSSecurityConfig.defParam]
170        if badKeys:
171            raise KeyError("Parameter key(s) %s not recognised" % \
172                           ','.join(badKeys))
173        return self._param.fromkeys(*arg)
174   
175    def setdefault(self, key, *arg):
176        badKeys = [i for i in b if i not in WSSecurityConfig.defParam]
177        if badKeys:
178            raise KeyError("Parameter keys '%s' not recognised" % badKeys)
179        return self._param.setdefault(key, *arg)
180
181    def pop(self, key, *arg):
182        raise WSSecurityConfigOpNotPermitted("Params should not be deleted")
183   
184    def popitem(self):
185        raise WSSecurityConfigOpNotPermitted("Params should not be deleted")
186   
187    def iteritems(self):
188        return self._param.iteritems()
189   
190    def iterkeys(self):
191        return self._param.iterkeys()
192   
193    def itervalues(self):
194        return self._param.itervalues()
195   
Note: See TracBrowser for help on using the repository browser.