source: TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/paster_templates/template.py @ 7790

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/paster_templates/template.py@7790
Revision 7790, 10.0 KB checked in by pjkersha, 9 years ago (diff)

Incomplete - task 16: NDG Security 2.x.x - incl. updated Paster templates

  • Working unit tests for Attribute and Authorisation Service templates
  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2"""NDG Security Paster template classes
3
4NERC DataGrid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "20/10/2010"
8__copyright__ = "(C) 2010 Science and Technology Facilities Council"
9__license__ = "BSD - see top-level directory for LICENSE file"
10__contact__ = "Philip.Kershaw@stfc.ac.uk"
11__revision__ = "$Id$"
12
13import os
14import socket
15import base64
16import string
17import re
18from urlparse import urlunsplit
19from paste.script.templates import Template, var
20from paste.script.copydir import LaxTemplate
21
22_hostTuple = socket.gethostbyaddr(socket.gethostname())
23try:
24    # Get first alias from list if present
25    _hostname = _hostTuple[1][0]
26except IndexError:
27    # ... or default to hostname
28    _hostname = _hostTuple[0]
29   
30from ndg.saml.saml2.core import Issuer   
31
32
33class ServicesTemplate(Template):
34    """Make a template containing all the Security Services available with
35    NDG Security.  These are provided together in one template but deployers
36    should consider adapting this and dividing up into separate WSGI apps
37    to suit
38    """
39    DEFAULT_PORT_NUM = 7443
40    DEFAULT_URI = urlunsplit(('https', _hostname, '/', None, None))
41   
42    ATTRIBUTE_SERVICE_DEFAULT_MOUNT_POINT = '/AttributeService'
43    ATTRIBUTE_SERVICE_DEFAULT_ISSUER_NAME = '/O=Site A/CN=Attribute Authority'
44    ATTRIBUTE_SERVICE_DEFAULT_ISSUER_FORMAT = Issuer.X509_SUBJECT
45   
46    AUTHORISATION_SERVICE_DEFAULT_ISSUER_NAME = \
47        '/O=Site A/CN=Authorisation Service'
48    AUTHORISATION_SERVICE_DEFAULT_ISSUER_FORMAT = Issuer.X509_SUBJECT
49    AUTHORISATION_SERVICE_DEFAULT_MOUNT_POINT = '/AuthorisationService'
50   
51    MYPROXY_SERVER_XRD_ENTRY_TMPL = """    <XRD>
52        <Service priority="10">
53            <Type>urn:esg:security:myproxy-service</Type>
54            <URI>%%{myProxyServerURI}</URI>
55            <LocalID>$user_url</LocalID>
56        </Service>
57    </XRD>
58    """
59   
60    ATTRIBUTE_SERVICE_XRD_ENTRY_TMPL = """    <XRD>
61        <Service priority="20">
62            <Type>urn:esg:security:attribute-service</Type>
63            <URI>%%{attributeServiceURI}</URI>
64            <LocalID>$user_url</LocalID>
65        </Service>
66    </XRD>
67    """
68   
69    _template_dir = 'services'
70    summary = ('NERC DataGrid Security services full deployment template '
71               'including the SAML Attribute and Authorisation Services, '
72               'OpenID Provider application, OpenID Relying Party and SSL '
73               'client authentication services')
74    vars = [
75        var('portNumber',
76            'Port number to run service on (applies to paster ONLY)',
77            default=DEFAULT_PORT_NUM),
78           
79        var('baseURI',
80            'Base URI for the service',
81            default=DEFAULT_URI),
82           
83        var('attributeServiceMountPoint',
84            'Mount point for Attribute Service',
85            ATTRIBUTE_SERVICE_DEFAULT_MOUNT_POINT),
86           
87        var('authorisationServiceMountPoint',
88            'Mount point for Authorisation Service',
89            AUTHORISATION_SERVICE_DEFAULT_MOUNT_POINT),
90           
91        var('attributeServiceIssuerName',
92            'SAML Issuer Name field for Attribute Service SAML responses',
93            ATTRIBUTE_SERVICE_DEFAULT_ISSUER_NAME),
94           
95        var('attributeServiceIssuerFormat',
96            'SAML Issuer Name field for Attribute Service SAML responses',
97            ATTRIBUTE_SERVICE_DEFAULT_ISSUER_FORMAT),
98           
99        var('authorisationServiceIssuerName',
100            'SAML Issuer Name field for Authorisation Service SAML responses',
101            AUTHORISATION_SERVICE_DEFAULT_ISSUER_NAME),
102           
103        var('authorisationServiceIssuerFormat',
104            'SAML Issuer Name field for Authorisation Service SAML responses',
105            AUTHORISATION_SERVICE_DEFAULT_ISSUER_FORMAT),
106
107        var('authkitCookieSecret', 
108            ('Cookie secret for AuthKit authentication middleware.  This value '
109             'MUST agree with the one used for the ini file of the application '
110             'to be secured'),
111            default=base64.b64encode(os.urandom(32))[:32]),
112
113        var('beakerSessionCookieSecret', 
114            'Secret for securing the OpenID Provider and SSL Client '
115            'authentication session cookie',
116            default=base64.b64encode(os.urandom(32))[:32]),
117           
118        var('openidRelyingPartyCookieSecret',
119            'Secret for securing OpenID Relying Party session cookie',
120            default=base64.b64encode(os.urandom(32))[:32]),
121           
122        var('myproxyServerURI',
123            'MyProxy Server address to advertise in OpenID Provider Yadis '
124            'document - defaults to omit this entry',
125            default=''),
126           
127        var('includeAttributeServiceInYadis',
128            'Include Attribute Service address in OpenID Provider Yadis '
129            'document',
130            default=True)
131        ]
132   
133    def __init__(self, *arg, **kw):
134        """Extend to enable custom setting for template substitution.  This
135        enables the special variable in service.ini_tmpl "userIdentifier" to
136        be ignored
137        """
138        self._laxTemplatePattern = LaxTemplate.pattern
139        LaxTemplate.pattern = re.compile(r"""
140        \%%(?:
141          (?P<escaped>\$)             |   # Escape sequence of two delimiters
142          (?P<named>[_a-z][_a-z0-9]*) |   # delimiter and a Python identifier
143          {(?P<braced>.*?)}           |   # delimiter and a braced identifier
144          (?P<invalid>)                   # Other ill-formed delimiter exprs
145        )
146        """)
147        super(ServicesTemplate, self).__init__(*arg, **kw)
148       
149    def __del__(self):
150        """Restore default setting for template pattern to its original value
151        """
152        LaxTemplate.pattern = self._laxTemplatePattern
153        _super = super(ServicesTemplate, self)
154        if hasattr(_super, "__del__"):
155            _super.__del__()
156
157    def write_files(self, command, output_dir, vars):
158        '''Extend to enable substitutions for OpenID Provider Yadis templates''' 
159        vars['extraXrdEntries'] = ''
160       
161        class XrdsTemplate(string.Template):
162            delimiter = "%%"
163               
164        attributeServiceURI = vars['baseURI'] + vars[
165                                'attributeServiceMountPoint'].lstrip('/')
166       
167        if vars['includeAttributeServiceInYadis']:
168            attributeServiceEntryTmpl = XrdsTemplate(
169                            self.__class__.ATTRIBUTE_SERVICE_XRD_ENTRY_TMPL)
170            vars['extraXrdEntries'] += attributeServiceEntryTmpl.substitute(
171                            attributeServiceURI=attributeServiceURI)
172
173        del vars['includeAttributeServiceInYadis']
174        if vars['myproxyServerURI']:
175            myProxyServerEntryTmpl = XrdsTemplate(
176                            self.__class__.MYPROXY_SERVER_XRD_ENTRY_TMPL)
177            vars['extraXrdEntries'] += myProxyServerEntryTmpl.substitute(
178                            attributeServiceURI=vars['myproxyServerURI'])
179       
180        del vars['myproxyServerURI']   
181        super(ServicesTemplate, self).write_files(command, output_dir, vars)
182
183       
184class SecuredAppTemplate(Template):
185    """Create a template for a secured application with authentication and
186    authorisation filters"""
187   
188    _template_dir = 'secured_application'
189    summary = (
190        'Template to secure an application with NERC DataGrid Security '
191        'authentication and authorisation filters')
192    vars = [
193        var('hostname', 
194            ('Virtual host name to mount services on'),
195            default=_hostname),
196
197        var('authkitCookieSecret', 
198            ('Cookie secret for AuthKit authentication middleware (if using a '
199             'separate SSL based OpenID Relying Party then this value MUST '
200             'agree with the one used for that ini file'),
201            default=base64.b64encode(os.urandom(32))[:32]),
202
203        var('beakerSessionSecret', 
204            'Cookie secret for keeping security session state',
205            default=base64.b64encode(os.urandom(32))[:32])
206    ]
207
208
209class AttributeServiceTemplate(Template):
210    """Paster template for the SAML attribute service"""
211   
212    DEFAULT_MOUNT_POINT = '/AttributeService'
213    DEFAULT_ISSUER_NAME = 'O=NDG, OU=Security, CN=localhost'
214    DEFAULT_ISSUER_FORMAT = Issuer.X509_SUBJECT
215   
216    _template_dir = 'attributeservice'
217    summary = 'Create an NDG Security SAML Attribute Service'
218    vars = [
219        var('mountPoint', 
220            ('URI path to mount service i.e. https://myhost/<mountPoint>'),
221            default=DEFAULT_MOUNT_POINT),
222
223        var('issuerName', 
224            ('ID of this service used in SAML queries and responses'),
225            default=DEFAULT_ISSUER_NAME),
226
227        var('issuerFormat', 
228            ('Format of issuerName string; if using the default, ensure that '
229             'the issuerName value is a correctly formatted X.509 Subject '
230             'Name'),
231            default=DEFAULT_ISSUER_FORMAT)
232    ]
233   
234
235class AuthorisationServiceTemplate(Template):
236    """Paster template for the SAML authorisation service"""
237   
238    DEFAULT_MOUNT_POINT = '/AuthorisationService'
239    DEFAULT_ISSUER_NAME = 'O=NDG, OU=Security, CN=localhost'
240    DEFAULT_ISSUER_FORMAT = Issuer.X509_SUBJECT
241   
242    _template_dir = 'authorisationservice'
243    summary = 'Create an NDG Security Authorisation Service'
244    vars = [
245        var('mountPoint', 
246            ('URI path to mount service i.e. https://myhost/<mountPoint>'),
247            default=DEFAULT_MOUNT_POINT),
248
249        var('issuerName', 
250            ('ID of this service used in SAML queries and responses'),
251            default=DEFAULT_ISSUER_NAME),
252
253        var('issuerFormat', 
254            ('Format of issuerName string; if using the default, ensure that '
255             'the issuerName value is a correctly formatted X.509 Subject '
256             'Name'),
257            default=DEFAULT_ISSUER_FORMAT)
258    ]
259
260     
261class OpenIDProviderTemplate(Template):
262    """Paster template for OpenID Provider service"""
263    _template_dir = 'openid-provider'
264    summary = (
265        'Template to create an NDG Security Authorisation Service')
266
Note: See TracBrowser for help on using the repository browser.