Commit 3ef28aa2 authored by Hanno Schlichting's avatar Hanno Schlichting

Removed strange non-package

parent a3a1e991
Architecture of the Zope SecuritySuite
The base class of the suite is "SecurityBase" and contains
the basic function of perform tests for permissions, roles
and perform ZPublisher request:
- _checkPermission()
- _checkRoles()
- _request()
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
class ResultObject:
""" result object used for keeping results from the
ZPublisher.Zope() calls
$Id$
"""
def __str__(self,expected=-1,with_output=1):
s = '\n'
s+= '-'*78
s+= "\nRequest: %s" % self.request
s+= "\nUser: %s" % self.user
s+= "\nExpected: %s" % expected + " got: %s %s" % (self.code,self.return_text)
if with_output:
s+= "\nOutput:"
s+= self.output
s+= "\n"
return s
__repr__ = __str__
def __call__(self,expected=-1):
return self.__str__(expected)
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import sys, re, unittest, cStringIO
import ZPublisher, ResultObject
import OFS.Application
import AccessControl.SecurityManagement
# Set up a publishable, non-ZODB Zope application.
app = OFS.Application.Application()
def index_html():
" "
return "This is index_html."
app.index_html = index_html # Will index_html ever go away? ;-)
class BoboApplication:
# OFS.Application has a __bobo_traverse__ that ZPublisher thinks
# it should use to find the "real" root of the application.
# This class gets around that.
def __bobo_traverse__(self, request, name=None):
return app
# ZPublisher will look for these vars.
bobo_application = BoboApplication()
zpublisher_validated_hook=AccessControl.SecurityManagement.newSecurityManager
__bobo_before__=AccessControl.SecurityManagement.noSecurityManager
class SecurityBase(unittest.TestCase) :
""" Base class for all security tests
$Id$
"""
status_regex = re.compile("Status: ([0-9]{1,4}) (.*)",re.I)\
################################################################
# print the object hierachy
################################################################
def _testHierarchy(self):
""" print all test objects, permissions and roles """
self._PrintTestEnvironment(root=self.root.test)
def _PrintTestEnvironment(self,root):
""" print recursive all objects """
print '....'*len(root.getPhysicalPath()),root.getId()
folderObjs = []
for id,obj in root.objectItems():
if obj.meta_type in ['Folder','TestFolder']:
folderObjs.append(obj)
else:
print ' '*(1+len(root.getPhysicalPath())),obj.getId(),
print getattr(obj,"__roles__",(None,))
for folder in folderObjs:
self._PrintTestEnvironment(folder)
################################################################
# Check functions for permissions, roles and friends
################################################################
def _checkPermission(self, user, hier, perm, expected):
""" permission check on an objects for a given user.
-- 'user' is a user object as returned from a user folder
-- 'hier' is the path to the object in the notation 'f1.f2.f3.obj'
-- 'perm' is a permission name
-- 'expected' is either 0 or 1
"""
s = "self.root.%s" % hier
obj = eval(s)
res = user.has_permission(perm,obj)
if res != expected:
raise AssertionError, \
self._perm_debug (s,perm,res,expected)
def _checkRoles(self,hier,expected_roles=()):
""" check roles for a given object.
-- 'hier' is the path to the object in the notation 'f1.f2.f3.obj'
-- 'expected_roles' is a sequence of expected roles
"""
s = "self.root.%s.__roles__" % hier
roles = eval(s)
same = 0
if roles is None or expected_roles is None:
if (roles is None or tuple(roles) == ('Anonymous',)) and (
expected_roles is None or
tuple(expected_roles) == ('Anonymous',)):
same = 1
else:
got = {}
for r in roles: got[r] = 1
expected = {}
for r in expected_roles: expected[r] = 1
if got == expected: # Dict compare does the Right Thing.
same = 1
if not same:
raise AssertionError, self._roles_debug(hier,roles,expected_roles)
def _checkRequest(self,*args,**kw):
""" perform a ZPublisher request """
expected_code = kw.get('expected',200)
del kw['expected']
res = apply(self._request,args,kw)
if expected_code != res.code:
raise AssertionError, \
self._request_debug(res,expected_code,args,kw)
################################################################
# Debugging helpers when raising AssertionError
################################################################
def _perm_debug(self, obj , perm, res, expected):
s+= 'Object: %s' % obj
s+= ', Permission: %s' % perm
s+= ', has permission: %s' % res
s+= ', expected: %s' % expected
return s
def _roles_debug(self,hier,got_roles,expected_roles):
s = 'Object: %s' % hier
s+= ', has roles: %s' % `got_roles`
s+= ', expected roles: %s' % `expected_roles`
return s
def _request_debug(self,res,expected,args,kw):
s = 'Args: %s' % str(args)
s+= ', KW: %s' % str(kw)
s+= '\n%s\n' % res.__str__(with_output=0,expected=expected)
return s
def _request(self,*args,**kw):
""" perform a Zope request """
io =cStringIO.StringIO()
kw['fp']=io
# Publish this module.
testargs = (__name__,) + args
real_stdout = sys.stdout
garbage_out = cStringIO.StringIO()
sys.stdout = garbage_out # Silence, ZPublisher!
try:
ZPublisher.test(*testargs,**kw)
finally:
sys.stdout = real_stdout
outp = io.getvalue()
mo = self.status_regex.search(outp)
code,txt = mo.groups()
res = ResultObject.ResultObject()
res.request = args
res.user = kw.get('u','')
res.code = int(code)
res.return_text = txt
res.output = outp
return res
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
######################################################################
# Set up unit testing framework
#
# The following code should be at the top of every test module:
#
# import os, sys
# execfile(os.path.join(sys.path[0], 'framework.py'))
#
# ...and the following at the bottom:
#
# framework()
# Find the Testing package
if not sys.modules.has_key('Testing'):
p0 = sys.path[0]
if p0 and __name__ == '__main__':
os.chdir(p0)
p0 = ''
p = d = os.path.abspath(os.curdir)
while d:
if os.path.isdir(os.path.join(p, 'Testing')):
sys.path[:1] = [p0, os.pardir, p]
break
p, d = os.path.split(p)
else:
print 'Unable to locate Testing package.'
sys.exit(1)
import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
# $Id$
import unittest
from AccessControl.class_init import InitializeClass
from AccessControl.SecurityInfo import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.User import nobody
from AccessControl.securitySuite import SecurityBase
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
# let's define some permissions first
MAGIC_PERMISSION1 = 'Magic Permission 1'
MAGIC_PERMISSION2 = 'Magic Permission 2'
##############################################################################
# TestObject class
##############################################################################
class TestObject(SimpleItem):
""" test object """
security = ClassSecurityInfo()
__allow_access_to_unprotected_subobjects__ = 0
public_attr = 1
_protected_attr = 2
def __init__(self,id):
self.id = id
security.declarePrivate("private_func")
def private_func(self):
""" private func """
return "i am private"
def manage_func(self):
""" should be protected by manager role """
return "i am your manager function"
security.declareProtected(MAGIC_PERMISSION2,"manage_func2")
def manage_func2(self):
""" should be protected by manager role """
return "i am your manager function2"
security.declareProtected(MAGIC_PERMISSION1,"protected_func")
def protected_func(self):
""" proteced func """
return "i am protected "
security.declarePublic("public_func")
def public_func(self):
""" public func """
return "i am public"
security.setPermissionDefault(MAGIC_PERMISSION1, ("Manager","Owner"))
security.setPermissionDefault(MAGIC_PERMISSION2, ("TestRole",))
InitializeClass(TestObject)
##############################################################################
# Testfolder class
##############################################################################
class TestFolder(Folder):
""" test class """
def __init__(self,id):
self.id = id
def getId(self): return self.id
meta_type = 'TestFolder'
security = ClassSecurityInfo()
InitializeClass(TestFolder)
##############################################################################
# User Class
##############################################################################
class User:
def __init__(self,username,password,roles):
self.username = username
self.password = password
self.roles = roles
def auth(self):
return "%s:%s" % (self.username,self.password)
def __str__(self):
return "User(%s:%s:%s)" % (self.username,self.password,self.roles)
__repr__ = __str__
USERS = (
User('user1','123',[]),
User('user2','123',[]),
User('owner','123',('Owner',)),
User('manager','123',('Manager',))
)
def getAuth(username):
for user in USERS:
if user.username==username:
return "%s:%s" % (user.username,user.password)
raise KeyError,"no such username: %" % username
class AVeryBasicSecurityTest(SecurityBase.SecurityBase):
################################################################
# set up the test hierachy of objects
################################################################
def setUp(self):
""" my setup """
self.root = SecurityBase.app
acl = self.root.acl_users
for user in USERS:
try: acl._delUsers( user.username )
except: pass
for user in USERS:
acl._addUser(user.username,user.password,user.password,
user.roles, [])
# try to remove old crap
if 'test' in self.root.objectIds():
self.root._delObject('test')
# setup Folder hierarchy
test = TestFolder('test')
f1 = TestFolder('f1')
f2 = TestFolder('f2')
f3 = TestFolder('f3')
obj = TestObject('obj3')
anonobj = TestObject('anonobj')
anonobj.__roles__ = ('Anonymous',)
self.root._setObject('test',test)
self.root.test._setObject('f1',f1)
self.root.test._setObject('f2',f2)
self.root.test.f1._setObject('anonobj',anonobj)
self.root.test.f2._setObject('f3',f3)
self.root.test.f2.f3._setObject('obj3',obj)
def testNobody(self):
""" check permissions for nobody user """
self._checkPermission(nobody,'test.f1', 'View',1)
self._checkPermission(nobody,'test.f2', 'View',1)
self._checkPermission(nobody,'test.f2.f3','View',1)
self._checkPermission(nobody,'test.f1', MAGIC_PERMISSION1, None)
self._checkPermission(nobody,'test.f2', MAGIC_PERMISSION1, None)
self._checkPermission(nobody,'test.f2.f3',MAGIC_PERMISSION1, None)
def testPermissionAccess(self):
""" check permission based access """
self._checkRoles('test.f2.f3.obj3.public_func', None)
self._checkRoles('test.f2.f3.obj3.protected_func', ('Manager','Owner'))
self._checkRoles('test.f2.f3.obj3.manage_func', ('Manager',))
self._checkRoles('test.f2.f3.obj3.private_func', ())
def testZPublisherAccess(self):
""" test access through ZPublisher """
_r = [
('/test/f1/', None, 200),
('/test/f2', None, 200),
('/test/f2/f3', None, 200),
('/test/f2/f3/obj3/public_func', None, 200),
('/test/f2/f3/obj3/protected_func', None, 401),
('/test/f2/f3/obj3/manage_func', None, 401),
('/test/f2/f3/obj3/private_func', None, 401),
('/test/f1/', getAuth('manager'), 200),
('/test/f2', getAuth('manager'), 200),
('/test/f2/f3', getAuth('manager'), 200),
('/test/f2/f3/obj3/public_func', getAuth('manager'), 200),
('/test/f2/f3/obj3/protected_func', getAuth('manager'), 200),
('/test/f2/f3/obj3/manage_func', getAuth('manager'), 200),
('/test/f2/f3/obj3/private_func', getAuth('manager'), 401),
('/test/f1/', getAuth('owner'), 200),
('/test/f2', getAuth('owner'), 200),
('/test/f2/f3', getAuth('owner'), 200),
('/test/f2/f3/obj3/public_func', getAuth('owner'), 200),
('/test/f2/f3/obj3/protected_func', getAuth('owner'), 200),
('/test/f2/f3/obj3/manage_func', getAuth('owner'), 401),
('/test/f2/f3/obj3/private_func', getAuth('owner'), 401),
]
for path,auth,expected in _r:
if auth:
res = self._checkRequest(path,u=auth,expected=expected)
else:
res = self._checkRequest(path,expected=expected)
def test_suite():
return unittest.makeSuite(AVeryBasicSecurityTest)
def main():
unittest.TextTestRunner().run(test_suite())
if __name__ == '__main__':
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment