Exemplo n.º 1
0
    def decorator(function):
        context = Context()
        context.addService(Logger("SECURITY_MODULE"))

        def wrapper(self, *__args, **__kw):
            # Check if there is a user.
            token = SecurityToken()
            context.Logger().message("Checking authentication for user %s" %
                                     (token.dn))

            # NOTE: this part should be clarified once front-end/back-end
            # certificate-based auth. rules will be in place
            # so we we should just fail over to login/pw schema
            ### If user browser provide cert, extract this info and update token
            userDN = ""
            try:
                import cherrypy, time
                #                print "###",cherrypy.request.headers
                #                userDN  = cherrypy.request.headers['Ssl-Client-S-Dn']
                #                access  = cherrypy.request.headers['Ssl-Client-Verify']
                #                if  userDN!='(null)' and access=='SUCCESS':
                userDN = cherrypy.request.headers['Cms-Client-S-Dn']
                access = cherrypy.request.headers['Cms-Auth-Status']
                if userDN != '(null)' and access == 'OK':
                    context.Logger().message("Found DN in user certificate")
                    # SiteDB usees token.dn as username rather then DN itself, so name is misleading
                    userName = self.securityApi.getUsernameFromDN(
                        userDN)[0]['username']
                    token.impl.dn = userName
                    #                    token.impl.dn = userDN
                    aTime = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
                    token.impl.authenticationTime = aTime
            except:
                #                traceback.print_exc()
                # redirect to https://cmsweb.cern.ch/sitedb/people/showAllEntries
                #                return redirectionToSiteDB(userDN)
                pass

            if token.dn in (None, "guest"):
                return onFail(self)
            # Check that the session has not expired.
            if not token.authenticationTime:
                return onFail(self)
            authenticationTime = datetime(
                *strptime(token.authenticationTime, "%Y-%m-%dT%H:%M:%S")[0:6])
            currentTime = datetime.now()
            # TODO: this should come from the configuration file.
            maxPeriod = timedelta(seconds=3600 * 24)
            if authenticationTime + maxPeriod < currentTime:
                context.Logger().message(
                    "Cookie has expired, authorisation failed.")
                return onFail(self)
            return function(self, *__args, **__kw)

        return wrapper
Exemplo n.º 2
0
    def decorator (function):
        context = Context ()
        context.addService (Logger ("SECURITY_MODULE"))
        def wrapper (self, *__args, **__kw):
            # Check if there is a user.
            token = SecurityToken ()
            context.Logger().message("Checking authentication for user %s" % (token.dn) )

            # NOTE: this part should be clarified once front-end/back-end
            # certificate-based auth. rules will be in place
            # so we we should just fail over to login/pw schema
            ### If user browser provide cert, extract this info and update token
            userDN = ""
            try:
                import cherrypy,time
#                print "###",cherrypy.request.headers
#                userDN  = cherrypy.request.headers['Ssl-Client-S-Dn']
#                access  = cherrypy.request.headers['Ssl-Client-Verify']
#                if  userDN!='(null)' and access=='SUCCESS':
                userDN  = cherrypy.request.headers['Cms-Client-S-Dn']
                access  = cherrypy.request.headers['Cms-Auth-Status']
                if  userDN!='(null)' and access=='OK':
                    context.Logger().message("Found DN in user certificate")
                    # SiteDB usees token.dn as username rather then DN itself, so name is misleading
                    userName = self.securityApi.getUsernameFromDN(userDN)[0]['username']
                    token.impl.dn = userName
#                    token.impl.dn = userDN
                    aTime = time.strftime("%Y-%m-%dT%H:%M:%S",time.gmtime())
                    token.impl.authenticationTime = aTime
            except:
#                traceback.print_exc()
                # redirect to https://cmsweb.cern.ch/sitedb/people/showAllEntries
#                return redirectionToSiteDB(userDN)
                pass

            if token.dn in (None, "guest"):
                return onFail (self)
            # Check that the session has not expired.
            if not token.authenticationTime:
                return onFail (self)
            authenticationTime = datetime(*strptime(token.authenticationTime, "%Y-%m-%dT%H:%M:%S")[0:6])
            currentTime = datetime.now ()
            # TODO: this should come from the configuration file.
            maxPeriod = timedelta (seconds=3600*24)
            if authenticationTime + maxPeriod < currentTime:
                context.Logger().message("Cookie has expired, authorisation failed.")
                return onFail (self)
            return function (self, *__args, **__kw)
        return wrapper
Exemplo n.º 3
0
from Framework import Context
from Framework.Logger import Logger

from Tools.SiteDBCore import SiteDBApi

context = Context ()
context.addService (Logger ("sitedbtest"))
api = SiteDBApi (context)

api.connect ()
print api.getTierList ()
Exemplo n.º 4
0
from Framework import Context


class A:
    def __init__(self, arg):
        self.__arg = arg

    def arg(self):
        return self.__arg


mainContext = Context()
mainContext.addService(A(0))
context = {}

for i in range(1, 3):
    context[i] = Context(mainContext)
    context[i].addService(A(i))

for i in range(1, 3):
    assert context[i].A().arg() != 0
    assert context[i].A().arg() == i
Exemplo n.º 5
0
 def __init__ (self):
     self.context = Context ()
     self.context.addService (OptionParser ())
     self.parser = self.context.OptionParser ()
     self.__addOptions ()
Exemplo n.º 6
0
class CmsWebApplication (object):
    def __init__ (self):
        self.context = Context ()
        self.context.addService (OptionParser ())
        self.parser = self.context.OptionParser ()
        self.__addOptions ()
        
    def __addOptions (self):
        self.parser.add_option ("--profile",
                           help="start server in profiler mode",
                           default=False,
                           action="store_true",
                           dest="profile")

        self.parser.add_option ("--pid-file",
                           help="File in which it is specified the pid of wanted instance",
                           default="pid.txt",
                           dest="pidFile",
                           metavar="FILE")

        self.parser.add_option ("--force-kill",
                           help="Uses SIGKILL rather than SIGTERM",
                           default=False,
                           action="store_true",
                           dest="forceKill",
                           metavar="FILE")
                           
        def openFilename (option, opt_str, value, parser, *args, **kwargs):
            try:
                f=open (value, 'a')
            except IOError:
                print "WARNING: Unable to open log file %s. Using stderr." % value
                f=sys.stderr
            setattr (parser.values, option.dest, f)
        
        self.parser.add_option ("--log-file",
                           help="FILE to which redirect log messages",
                           dest="logFile",
                           default=sys.stderr,
                           action="callback",
                           callback=openFilename,
                           metavar="FILENAME",
                           type="str",
                           nargs=1)
                           
        self.parser.add_option ("--log-level",
                            help="detail LEVEL for the main log",
                            dest="logLevel",
                            default=10,
                            metavar="LEVEL",
                            type="int")
    
    def run (self):
        if "--help" in sys.argv:
            g_Logger.detailLevel = -100
        validOptions = getValidOptions (sys.argv)

        opts, args = self.parser.parse_args (args=validOptions)

        g_Logger.stream = opts.logFile
        if "--help" not in sys.argv:
            g_Logger.detailLevel = opts.logLevel
        
        if not len (args):
            args = ["start"]
        
        factory = CommandFactory (self.context, opts, args)
        startCommand = factory.createByName (args[0])
        if not startCommand:
            "Command %s not known." % args[0]
            sys.exit (1)
        startCommand.run ()
        startCommand.finish ()
Exemplo n.º 7
0
from Framework import Context


class A:
    def __init__(self, arg):
        self.__arg = arg

    def arg(self):
        return self.__arg


mainContext = Context()
mainContext.addService(A(0))
context = {}

for i in range(1, 3):
    context[i] = Context(mainContext)
    context[i].addService(A(i))

for i in range(1, 3):
    assert context[i].A().arg() != 0
    assert context[i].A().arg() == i
Exemplo n.º 8
0
from Framework import Context
from Framework.Logger import Logger

from Tools.SiteDBCore import SiteDBApi

context = Context()
context.addService(Logger("sitedbtest"))
api = SiteDBApi(context)

api.connect()
print api.getTierList()
Exemplo n.º 9
0
from Framework import Context
from Framework.Logger import Logger

from Crypto.Cipher import Blowfish
from base64 import b64encode, b64decode
import crypt

import time, calendar, datetime

from Tools.SecurityModuleCore.SecurityDBApi import SecurityDBApi

print "**** Security Module tests ****"
context = Context()
context.addService(Logger("securitymoduletest"))
api = SecurityDBApi(context)

context.Logger().message("Test roles:")
context.Logger().message(
    "    swakef as prod operator: %s" %
    api.hasGroupResponsibility("swakef", "production", "Production Operator"))
context.Logger().message(
    "    metson as RAL DM: %s" %
    api.hasSiteResponsibility("metson", "RAL", "Data Manager"))
context.Logger().message(
    "    metson as site 1 Site Admin: %s" %
    api.hasSiteResponsibility("metson", "1", "Site Admin"))

context.Logger().message("hasGroup:")
context.Logger().message("    swakef as member of production group: %s" %
                         api.hasGroup("swakef", "production"))
context.Logger().message("    metson as member of production group: %s" %
Exemplo n.º 10
0
    def __init__(self, foo):
        self.__foo = foo

    def foo(self):
        return self.__foo


class C(object):
    def __init__(self, foo):
        self.__foo = foo

    def foo(self):
        return self.__foo


c1 = Context()
c2 = Context(c1)
c1.addService(A("Service A on C1"))
c2.addService(A("Service A on C2"))
c1.addService(B("Service B on C1"))
c2.addService(C("Service C on C2"))

assert type(c1.A()) == type(A(""))
assert type(c2.A()) == type(A(""))
assert type(c1.B()) == type(B(""))
assert type(c2.B()) == type(B(""))
assert type(c2.C()) == type(C(""))
assert type(c1.A().foo()) == type(str())

assert c1.A().foo() == "Service A on C1"
assert c2.A().foo() == "Service A on C2"
Exemplo n.º 11
0
from Framework import Context


class Component(object):
    def foo(self):
        return "A component"


c = Context()
c.addService(Component())
assert c.Component().foo() == "A component"
Exemplo n.º 12
0
from Framework import Context
from Framework.Logger import Logger

from Crypto.Cipher import Blowfish
from base64 import b64encode, b64decode
import crypt

import time, calendar, datetime

from Tools.SecurityModuleCore.SecurityDBApi import SecurityDBApi
print "**** Security Module tests ****"
context = Context ()
context.addService (Logger ("securitymoduletest"))
api = SecurityDBApi (context)

context.Logger().message("Test roles:")
context.Logger().message("    swakef as prod operator: %s" % api.hasGroupResponsibility ("swakef", "production", "Production Operator"))
context.Logger().message("    metson as RAL DM: %s" % api.hasSiteResponsibility ("metson", "RAL", "Data Manager"))
context.Logger().message("    metson as site 1 Site Admin: %s" % api.hasSiteResponsibility ("metson", "1", "Site Admin"))

context.Logger().message("hasGroup:")
context.Logger().message("    swakef as member of production group: %s" % api.hasGroup ("swakef", "production"))
context.Logger().message("    metson as member of production group: %s" % api.hasGroup ("metson", "production"))
context.Logger().message("    metson as member of global group: %s" % api.hasGroup ("metson", "global"))

context.Logger().message("hasSite:")
context.Logger().message("    swakef as associated to RAL: %s" % api.hasSite ("swakef", "RAL"))
context.Logger().message("    metson as associated to RAL: %s" % api.hasSite("metson", "RAL"))
context.Logger().message("    metson as associated to site 1: %s" % api.hasSite("metson", "1"))

context.Logger().message("hasResponsibility:")
Exemplo n.º 13
0
from Framework import Context

class A(object):
    """docstring for A"""
    def __init__(self, arg):
        self.arg = arg
        
class B(object):
    """docstring for B"""
    def __init__(self, arg):
        self.arg = arg
        

c1=Context ()
c2=Context (c1)
c3=Context (c1)
c1.addService (A("Foo"))
assert c2.A ().arg == "Foo"
c2.addService (A("Bar"))
c2.addService (B("Bar"))
assert c1.A ().arg == "Foo"
assert c2.A ().arg == "Bar"
assert c3.A ().arg == "Foo"
c4=Context (c2)
assert c4.A ().arg == "Bar"