Commit 89b1075e authored by Shane Hathaway's avatar Shane Hathaway

- Merged cAccessControl-review-branch.

- Made some corrections to the DTML tests, which aren't currently working
in testrunner but work when run directly. ??
parent 9f506076
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. DAMAGE.
$Id: Acquisition.h,v 1.1 2001/07/03 19:38:20 matt Exp $ $Id: Acquisition.h,v 1.2 2001/10/19 15:12:24 shane Exp $
If you have questions regarding this software, If you have questions regarding this software,
contact: contact:
...@@ -79,10 +79,8 @@ static ACQUISITIONCAPI *AcquisitionCAPI = NULL; ...@@ -79,10 +79,8 @@ static ACQUISITIONCAPI *AcquisitionCAPI = NULL;
#define aq_init() { \ #define aq_init() { \
PyObject *module; \ PyObject *module; \
PyObject *api; \ PyObject *api; \
if ((module = PyImport_ImportModule("Acquisition")) == NULL) \ if (! (module = PyImport_ImportModule("Acquisition"))) return; \
Py_FatalError("Acquisition CAPI failed to load Acquisition"); \ if (! (api = PyObject_GetAttrString(module,"AcquisitionCAPI"))) return; \
if ((api = PyObject_GetAttrString(module,"AcquisitionCAPI")) \
== NULL) Py_FatalError("Acquisition CAPI failed to load AcquistionCAPI"); \
Py_DECREF(module); \ Py_DECREF(module); \
AcquisitionCAPI = PyCObject_AsVoidPtr(api); \ AcquisitionCAPI = PyCObject_AsVoidPtr(api); \
Py_DECREF(api); \ Py_DECREF(api); \
......
...@@ -85,19 +85,139 @@ ...@@ -85,19 +85,139 @@
__doc__='''Objects that implement Permission-based roles. __doc__='''Objects that implement Permission-based roles.
$Id: PermissionRole.py,v 1.11 2001/10/17 22:01:43 tseaver Exp $''' $Id: PermissionRole.py,v 1.12 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.11 $'[11:-2] __version__='$Revision: 1.12 $'[11:-2]
if 0: # cAccessControl is not working _use_python_impl = 0
import cAccessControl import os
rolesForPermissionOn=cAccessControl.rolesForPermissionOn if os.environ.get("ZOPE_SECURITY_POLICY", None) == "PYTHON":
PermissionRole=cAccessControl.PermissionRole _use_python_impl = 1
imPermissionRole=cAccessControl.imPermissionRole
_what_not_even_god_should_do= cAccessControl._what_not_even_god_should_do
else: else:
import pPermissionRole try:
from pPermissionRole import rolesForPermissionOn, PermissionRole # C Optimization:
from pPermissionRole import imPermissionRole, _what_not_even_god_should_do from cAccessControl import rolesForPermissionOn, \
PermissionRole, imPermissionRole, _what_not_even_god_should_do
except ImportError:
# Fall back to Python implementation.
_use_python_impl = 1
if _use_python_impl:
import sys
from ExtensionClass import Base
import string
name_trans=filter(lambda c, an=string.letters+string.digits+'_': c not in an,
map(chr,range(256)))
name_trans=string.maketrans(string.join(name_trans,''), '_'*len(name_trans))
def rolesForPermissionOn(perm, object, default=('Manager',)):
"""Return the roles that have the given permission on the given object
"""
im=imPermissionRole()
im._p='_'+string.translate(perm, name_trans)+"_Permission"
im._d=default
return im.__of__(object)
class PermissionRole(Base):
"""Implement permission-based roles.
Under normal circumstances, our __of__ method will be
called with an unwrapped object. The result will then be called
with a wrapped object, if the original object was wrapped.
To deal with this, we have to create an intermediate object.
"""
def __init__(self, name, default=('Manager',)):
self.__name__=name
self._p='_'+string.translate(name,name_trans)+"_Permission"
self._d=default
def __of__(self, parent, None=None, getattr=getattr):
r=imPermissionRole()
r._p=self._p
r._pa=parent
r._d=self._d
p=getattr(parent, 'aq_inner', None)
if p is not None:
return r.__of__(p)
else:
return r
# This is used when a permission maps explicitly to no permission.
_what_not_even_god_should_do=[]
class imPermissionRole(Base):
"""Implement permission-based roles
"""
def __of__(self, parent,tt=type(()),st=type(''),getattr=getattr,None=None):
obj=parent
n=self._p
r=None
while 1:
if hasattr(obj,n):
roles=getattr(obj, n)
if roles is None: return 'Anonymous',
t=type(roles)
if t is tt:
# If we get a tuple, then we don't acquire
if r is None: return roles
return r+list(roles)
if t is st:
# We found roles set to a name. Start over
# with the new permission name. If the permission
# name is '', then treat as private!
if roles:
if roles != n:
n=roles
# If we find a name that is the same as the
# current name, we just ignore it.
roles=None
else:
return _what_not_even_god_should_do
elif roles:
if r is None: r=list(roles)
else: r=r+list(roles)
obj=getattr(obj, 'aq_inner', None)
if obj is None: break
obj=obj.aq_parent
if r is None: r=self._d
return r
# The following methods are needed in the unlikely case that an unwrapped
# object is accessed:
def __getitem__(self, i):
try:
v=self._v
except:
v=self._v=self.__of__(self._pa)
del self._pa
return v[i]
def __len__(self):
try:
v=self._v
except:
v=self._v=self.__of__(self._pa)
del self._pa
return len(v)
############################################################################## ##############################################################################
# Test functions: # Test functions:
......
...@@ -85,8 +85,8 @@ ...@@ -85,8 +85,8 @@
__doc__='''short description __doc__='''short description
$Id: SecurityManager.py,v 1.6 2001/10/01 21:03:15 matt Exp $''' $Id: SecurityManager.py,v 1.7 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
import ZopeSecurityPolicy, os, string import ZopeSecurityPolicy, os, string
...@@ -145,6 +145,10 @@ class SecurityManager: ...@@ -145,6 +145,10 @@ class SecurityManager:
""" """
policy=self._policy policy=self._policy
if policy is None: policy=_defaultPolicy if policy is None: policy=_defaultPolicy
if roles is _noroles:
return policy.validate(accessed, container, name, value,
self._context)
else:
return policy.validate(accessed, container, name, value, return policy.validate(accessed, container, name, value,
self._context, roles) self._context, roles)
...@@ -175,13 +179,17 @@ class SecurityManager: ...@@ -175,13 +179,17 @@ class SecurityManager:
policy=self._policy policy=self._policy
if policy is None: policy=_defaultPolicy if policy is None: policy=_defaultPolicy
return policy.validate(accessed, container, name, value, return policy.validate(accessed, container, name, value,
self._context, _noroles) self._context)
def validateValue(self, value, roles=_noroles): def validateValue(self, value, roles=_noroles):
"""Convenience for common case of simple value validation. """Convenience for common case of simple value validation.
""" """
policy=self._policy policy=self._policy
if policy is None: policy=_defaultPolicy if policy is None: policy=_defaultPolicy
if roles is _noroles:
return policy.validate(None, None, None, value,
self._context)
else:
return policy.validate(None, None, None, value, return policy.validate(None, None, None, value,
self._context, roles) self._context, roles)
......
...@@ -84,7 +84,7 @@ ...@@ -84,7 +84,7 @@
############################################################################## ##############################################################################
"""Access control package""" """Access control package"""
__version__='$Revision: 1.159 $'[11:-2] __version__='$Revision: 1.160 $'[11:-2]
import Globals, socket, SpecialUsers,re import Globals, socket, SpecialUsers,re
import os import os
...@@ -98,7 +98,8 @@ from App.ImageFile import ImageFile ...@@ -98,7 +98,8 @@ from App.ImageFile import ImageFile
from Role import RoleManager, DEFAULTMAXLISTUSERS from Role import RoleManager, DEFAULTMAXLISTUSERS
from PermissionRole import _what_not_even_god_should_do, rolesForPermissionOn from PermissionRole import _what_not_even_god_should_do, rolesForPermissionOn
import AuthEncoding import AuthEncoding
from AccessControl import getSecurityManager, Unauthorized from AccessControl import getSecurityManager
from zExceptions import Unauthorized
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.ZopeSecurityPolicy import _noroles from AccessControl.ZopeSecurityPolicy import _noroles
......
...@@ -83,7 +83,7 @@ ...@@ -83,7 +83,7 @@
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
from RestrictedPython.Guards import safe_builtins, _full_read_guard, \ from RestrictedPython.Guards import safe_builtins, _full_read_guard, \
full_write_guard full_write_guard
...@@ -91,8 +91,7 @@ from RestrictedPython.Utilities import utility_builtins ...@@ -91,8 +91,7 @@ from RestrictedPython.Utilities import utility_builtins
from SecurityManagement import getSecurityManager from SecurityManagement import getSecurityManager
from SecurityInfo import secureModule from SecurityInfo import secureModule
from SimpleObjectPolicies import Containers from SimpleObjectPolicies import Containers
from zExceptions import Unauthorized
Unauthorized = 'Unauthorized'
_marker = [] # Create a new marker object. _marker = [] # Create a new marker object.
......
##############################################################################
# #
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
__doc__='''Define Zope\'s default security policy
from SimpleObjectPolicies import _noroles $Id: ZopeSecurityPolicy.py,v 1.14 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.14 $'[11:-2]
if 0: # cAccessControl is not working
import cAccessControl
ZopeSecurityPolicy = cAccessControl.ZopeSecurityPolicy _use_python_impl = 0
import os
if os.environ.get("ZOPE_SECURITY_POLICY", None) == "PYTHON":
_use_python_impl = 1
else: else:
from pZopeSecurityPolicy import ZopeSecurityPolicy try:
# C Optimization:
from cAccessControl import ZopeSecurityPolicy
from SimpleObjectPolicies import _noroles
except ImportError:
# Fall back to Python implementation.
_use_python_impl = 1
if _use_python_impl:
from types import StringType
import SimpleObjectPolicies
from AccessControl import Unauthorized
_noroles=SimpleObjectPolicies._noroles
from zLOG import LOG, PROBLEM
from Acquisition import aq_base
from PermissionRole import _what_not_even_god_should_do, \
rolesForPermissionOn
class ZopeSecurityPolicy:
def __init__(self, ownerous=1):
self._ownerous=ownerous
def validate(self, accessed, container, name, value, context,
roles=_noroles, None=None, type=type, IntType=type(0),
DictType=type({}), getattr=getattr, _noroles=_noroles,
StringType=type(''),
Containers=SimpleObjectPolicies.Containers,
valid_aq_=('aq_parent','aq_explicit')):
############################################################
# Provide special rules for the acquisition attributes
if type(name) is StringType:
if name[:3]=='aq_' and name not in valid_aq_:
return 0
containerbase = aq_base(container)
accessedbase=getattr(accessed, 'aq_base', container)
############################################################
# If roles weren't passed in, we'll try to get them from the object
if roles is _noroles:
roles=getattr(value, '__roles__', _noroles)
############################################################
# We still might not have any roles
if roles is _noroles:
############################################################
# We have an object without roles and we didn't get a list
# of roles passed in. Presumably, the value is some simple
# object like a string or a list. We'll try to get roles
# from its container.
if container is None: return 0 # Bail if no container
roles=getattr(container, '__roles__', _noroles)
if roles is _noroles:
aq=getattr(container, 'aq_acquire', None)
if aq is None:
roles=_noroles
if containerbase is not accessedbase: return 0
else:
# Try to acquire roles
try: roles=aq('__roles__')
except AttributeError:
roles=_noroles
if containerbase is not accessedbase: return 0
# We need to make sure that we are allowed to
# get unprotected attributes from the container. We are
# allowed for certain simple containers and if the
# container says we can. Simple containers
# may also impose name restrictions.
p=Containers(type(container), None)
if p is None:
p=getattr(container,
'__allow_access_to_unprotected_subobjects__', None)
if p is not None:
tp=type(p)
if tp is not IntType:
if tp is DictType:
p=p.get(name, None)
else:
p=p(name, value)
if not p:
if (containerbase is accessedbase):
raise Unauthorized(name, value)
else:
return 0
if roles is _noroles: return 1
# We are going to need a security-aware object to pass
# to allowed(). We'll use the container.
value=container
# Short-circuit tests if we can:
try:
if roles is None or 'Anonymous' in roles: return 1
except TypeError:
# 'roles' isn't a sequence
LOG('Zope Security Policy', PROBLEM, "'%s' passed as roles"
" during validation of '%s' is not a sequence." % (
`roles`, name))
raise
# Check executable security
stack=context.stack
if stack:
eo=stack[-1]
# If the executable had an owner, can it execute?
if self._ownerous:
owner=eo.getOwner()
if (owner is not None) and not owner.allowed(value, roles):
# We don't want someone to acquire if they can't
# get an unacquired!
if accessedbase is containerbase:
raise Unauthorized(name, value)
return 0
# Proxy roles, which are a lot safer now.
proxy_roles=getattr(eo, '_proxy_roles', None)
if proxy_roles:
for r in proxy_roles:
if r in roles: return 1
# Proxy roles actually limit access!
if accessedbase is containerbase:
raise Unauthorized(name, value)
return 0
try:
if context.user.allowed(value, roles): return 1
except AttributeError: pass
# We don't want someone to acquire if they can't get an unacquired!
if accessedbase is containerbase:
raise Unauthorized(name, value)
return 0
def checkPermission(self, permission, object, context):
# XXX proxy roles and executable owner are not checked
roles=rolesForPermissionOn(permission, object)
if type(roles) is StringType:
roles=[roles]
return context.user.allowed(object, roles)
...@@ -83,7 +83,7 @@ ...@@ -83,7 +83,7 @@
# #
############################################################################## ##############################################################################
Unauthorized = 'Unauthorized' from unauthorized import Unauthorized
import DTML import DTML
del DTML del DTML
......
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. DAMAGE.
$Id: cAccessControl.c,v 1.10 2001/10/04 19:40:26 matt Exp $ $Id: cAccessControl.c,v 1.11 2001/10/19 15:12:25 shane Exp $
If you have questions regarding this software, If you have questions regarding this software,
contact: contact:
...@@ -53,13 +53,50 @@ ...@@ -53,13 +53,50 @@
#include "ExtensionClass.h" #include "ExtensionClass.h"
#include "Acquisition.h" #include "Acquisition.h"
static void
PyVar_Assign(PyObject **v, PyObject *e)
{
Py_XDECREF(*v);
*v=e;
}
#define ASSIGN(V,E) PyVar_Assign(&(V),(E))
#define UNLESS(E) if (!(E))
#define OBJECT(o) ((PyObject *) (o)) #define OBJECT(o) ((PyObject *) (o))
#ifdef win32 static PyObject *
#define PUBLIC callmethod1(PyObject *self, PyObject *name, PyObject *arg)
#else {
#define PUBLIC UNLESS(self = PyObject_GetAttr(self,name)) return NULL;
#endif name = PyTuple_New(1);
if (name == NULL) {
Py_DECREF(self);
return NULL;
}
Py_INCREF(arg);
PyTuple_SET_ITEM(name, 0, arg);
ASSIGN(self, PyObject_CallObject(self, name));
Py_DECREF(name);
return self;
}
static PyObject *
callfunction2(PyObject *function, PyObject *arg0, PyObject *arg1)
{
PyObject *t, *r;
t = PyTuple_New(2);
if (t == NULL)
return NULL;
Py_INCREF(arg0);
Py_INCREF(arg1);
PyTuple_SET_ITEM(t, 0, arg0);
PyTuple_SET_ITEM(t, 1, arg1);
r = PyObject_CallObject(function, t);
Py_DECREF(t);
return r;
}
/* /*
** Structures ** Structures
...@@ -84,23 +121,6 @@ typedef struct { ...@@ -84,23 +121,6 @@ typedef struct {
PyObject *_v; PyObject *_v;
} imPermissionRole; } imPermissionRole;
/* ZSPCACHE does NOT work securely; don't turn it on! */
#define ZSPCACHE 0
#if ZSPCACHE
typedef struct {
long accessed;
long container;
long name;
long value;
long context;
long roles;
PyObject *result;
} ZSPCacheLine;
#define ZSPCACHEENTRIES 512
#endif
/* /*
** Prototypes ** Prototypes
*/ */
...@@ -111,32 +131,22 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self, ...@@ -111,32 +131,22 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
static void ZopeSecurityPolicy_dealloc(ZopeSecurityPolicy *self); static void ZopeSecurityPolicy_dealloc(ZopeSecurityPolicy *self);
static PyObject *PermissionRole_getattr(PermissionRole *self, char *name);
static int PermissionRole_setattr(PermissionRole *self, char *name,
PyObject *value);
static PyObject *PermissionRole_init(PermissionRole *self, PyObject *args); static PyObject *PermissionRole_init(PermissionRole *self, PyObject *args);
static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args); static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args);
static void PermissionRole_dealloc(PermissionRole *self); static void PermissionRole_dealloc(PermissionRole *self);
static PyObject *imPermissionRole_getattr(imPermissionRole *self, char *name);
static int imPermissionRole_setattr(imPermissionRole *self, char *name,
PyObject *value);
static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args); static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args);
static int imPermissionRole_length(imPermissionRole *self); static int imPermissionRole_length(imPermissionRole *self);
static PyObject *imPermissionRole_getitem(imPermissionRole *self,
PyObject *item);
static PyObject *imPermissionRole_get(imPermissionRole *self, static PyObject *imPermissionRole_get(imPermissionRole *self,
int item); int item);
static void imPermissionRole_dealloc(imPermissionRole *self); static void imPermissionRole_dealloc(imPermissionRole *self);
static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args); static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args);
static PyObject *c_rolesForPermissionOn(PyObject *self, PyObject *perm,
PyObject *object, PyObject *deflt);
static PyObject *permissionName(PyObject *name); static PyObject *permissionName(PyObject *name);
#if ZSPCACHE
static ZSPCacheLine ZSPCache[ZSPCACHEENTRIES];
#endif
/* /*
** Constants ** Constants
*/ */
...@@ -228,8 +238,8 @@ static PyExtensionClass PermissionRoleType = { ...@@ -228,8 +238,8 @@ static PyExtensionClass PermissionRoleType = {
/* Standard methods */ /* Standard methods */
(destructor) PermissionRole_dealloc, /* tp_dealloc */ (destructor) PermissionRole_dealloc, /* tp_dealloc */
NULL, /* tp_print */ NULL, /* tp_print */
(getattrfunc) PermissionRole_getattr, /* tp_getattr */ NULL, /* tp_getattr */
(setattrfunc) PermissionRole_setattr, /* tp_setattr */ NULL, /* tp_setattr */
NULL, /* tp_compare */ NULL, /* tp_compare */
NULL, /* tp_repr */ NULL, /* tp_repr */
/* Method suites */ /* Method suites */
...@@ -285,13 +295,6 @@ static PySequenceMethods imSequenceMethods = { ...@@ -285,13 +295,6 @@ static PySequenceMethods imSequenceMethods = {
(intargfunc) NULL /* sq_inplace_repeat */ (intargfunc) NULL /* sq_inplace_repeat */
}; };
static PyMappingMethods imMappingMethods = {
(inquiry) imPermissionRole_length, /* mp_length */
(binaryfunc) imPermissionRole_getitem, /* mp_subscript */
(objobjargproc) NULL /* mp_ass_subscr*/
};
static PyExtensionClass imPermissionRoleType = { static PyExtensionClass imPermissionRoleType = {
PyObject_HEAD_INIT(NULL) 0, PyObject_HEAD_INIT(NULL) 0,
"imPermissionRole", /* tp_name */ "imPermissionRole", /* tp_name */
...@@ -300,14 +303,14 @@ static PyExtensionClass imPermissionRoleType = { ...@@ -300,14 +303,14 @@ static PyExtensionClass imPermissionRoleType = {
/* Standard methods */ /* Standard methods */
(destructor) imPermissionRole_dealloc, /* tp_dealloc */ (destructor) imPermissionRole_dealloc, /* tp_dealloc */
NULL, /* tp_print */ NULL, /* tp_print */
(getattrfunc) imPermissionRole_getattr, /* tp_getattr */ NULL, /* tp_getattr */
(setattrfunc) imPermissionRole_setattr, /* tp_setattr */ NULL, /* tp_setattr */
NULL, /* tp_compare */ NULL, /* tp_compare */
NULL, /* tp_repr */ NULL, /* tp_repr */
/* Method suites */ /* Method suites */
NULL, /* tp_as_number */ NULL, /* tp_as_number */
&imSequenceMethods, /* tp_as_sequence*/ &imSequenceMethods, /* tp_as_sequence*/
&imMappingMethods, /* tp_as_mapping */ NULL, /* tp_as_mapping */
/* More standard ops */ /* More standard ops */
NULL, /* tp_hash */ NULL, /* tp_hash */
NULL, /* tp_call */ NULL, /* tp_call */
...@@ -326,11 +329,7 @@ static PyExtensionClass imPermissionRoleType = { ...@@ -326,11 +329,7 @@ static PyExtensionClass imPermissionRoleType = {
NULL, /* tp_next */ NULL, /* tp_next */
#endif #endif
METHOD_CHAIN(imPermissionRole_methods), /* methods */ METHOD_CHAIN(imPermissionRole_methods), /* methods */
EXTENSIONCLASS_BINDABLE_FLAG/*| EXTENSIONCLASS_BINDABLE_FLAG, /* flags */
EXTENSIONCLASS_INSTDICT_FLAG*/, /* flags */
NULL, /* Class dict */
NULL, /* bases */
NULL, /* reserved */
}; };
...@@ -340,15 +339,23 @@ static PyExtensionClass imPermissionRoleType = { ...@@ -340,15 +339,23 @@ static PyExtensionClass imPermissionRoleType = {
*/ */
static PyObject *Containers = NULL; static PyObject *Containers = NULL;
static PyObject *_noroles = NULL;
static PyObject *Unauthorized = NULL; static PyObject *Unauthorized = NULL;
static PyObject *LOG = NULL; static PyObject *LOG = NULL;
static PyObject *PROBLEM = NULL; static PyObject *PROBLEM = NULL;
static PyObject *NoSequenceFormat = NULL;
static PyObject *_what_not_even_god_should_do = NULL; static PyObject *_what_not_even_god_should_do = NULL;
static PyObject *Anonymous = NULL; static PyObject *Anonymous = NULL;
static PyObject *AnonymousTuple = NULL;
static PyObject *imPermissionRoleObj = NULL; static PyObject *imPermissionRoleObj = NULL;
static PyObject *defaultPermission = NULL; static PyObject *defaultPermission = NULL;
static PyObject *__roles__ = NULL; static PyObject *__roles__ = NULL;
static PyObject *__of__ = NULL;
static PyObject *__allow_access_to_unprotected_subobjects__ = NULL;
static PyObject *stack_str = NULL;
static PyObject *user_str = NULL;
static PyObject *_proxy_roles_str = NULL;
static PyObject *allowed_str = NULL;
static PyObject *getOwner_str = NULL;
/* -------------------------------------------------------------- /* --------------------------------------------------------------
** ZopeSecurityPolicy Methods ** ZopeSecurityPolicy Methods
...@@ -361,44 +368,30 @@ static PyObject *__roles__ = NULL; ...@@ -361,44 +368,30 @@ static PyObject *__roles__ = NULL;
** elsewhere... (e.g. imports) ** elsewhere... (e.g. imports)
*/ */
static int ZopeSecurityPolicy_setup(void) { static int
PyObject *module; ZopeSecurityPolicy_setup(void) {
UNLESS (NoSequenceFormat = PyString_FromString(
#define IMPORT(module, name) if ((module = PyImport_ImportModule(name)) == NULL) Py_FatalError("ZopeSecurityPolicy failed to load module " #name) "'%s' passed as roles"
#define GETATTR(module, name) if ((name = PyObject_GetAttrString(module, #name)) == NULL) Py_FatalError("ZopeSecurity policy failed to load attribute " #name) " during validation of '%s' is not a sequence."
)) return -1;
/*| from SimpleObjectPolicies import Containers, _noroles
*/ UNLESS (defaultPermission = Py_BuildValue("(s)", "Manager")) return -1;
UNLESS (_what_not_even_god_should_do = Py_BuildValue("[]")) return -1;
IMPORT(module, "AccessControl.SimpleObjectPolicies"); UNLESS (__roles__ = PyString_FromString("__roles__")) return -1;
GETATTR(module, Containers); UNLESS (__of__ = PyString_FromString("__of__")) return -1;
GETATTR(module, _noroles); UNLESS (Anonymous = PyString_FromString("Anonymous")) return -1;
Py_DECREF(module); UNLESS (AnonymousTuple = Py_BuildValue("(s)", "Anonymous")) return -1;
module = NULL; UNLESS (stack_str = PyString_FromString("stack")) return -1;
UNLESS (user_str = PyString_FromString("user")) return -1;
/*| from AccessControl import Unauthorized UNLESS (_proxy_roles_str = PyString_FromString("_proxy_roles"))
*/ return -1;
UNLESS (allowed_str = PyString_FromString("allowed")) return -1;
IMPORT(module, "AccessControl"); UNLESS (getOwner_str = PyString_FromString("getOwner")) return -1;
GETATTR(module, Unauthorized); UNLESS (__allow_access_to_unprotected_subobjects__ =
Py_DECREF(module); PyString_FromString(
module = NULL; "__allow_access_to_unprotected_subobjects__"))
return -1;
/*| from zLOG import LOG, PROBLEM return 0;
*/
IMPORT(module, "zLOG");
GETATTR(module, LOG);
GETATTR(module, PROBLEM);
Py_DECREF(module);
module = NULL;
defaultPermission = Py_BuildValue("(s)", "Manager");
_what_not_even_god_should_do = Py_BuildValue("[]");
__roles__ = PyString_FromString("__roles__");
return 1;
} }
/* /*
...@@ -409,206 +402,15 @@ static int ZopeSecurityPolicy_setup(void) { ...@@ -409,206 +402,15 @@ static int ZopeSecurityPolicy_setup(void) {
static void unauthErr(PyObject *name, PyObject *value) { static void unauthErr(PyObject *name, PyObject *value) {
char msgbuff[512]; PyObject *v;
PyObject *_name = NULL;
PyObject *_name1 = NULL;
char *s;
/*| _name = name
**| if _name is None and value is not None
**| try: _name = value.id
**| except:
**| try:
**| _name = value.__name__
**| except: pass
**| if callable(_name):
**| try: _name = _name()
**| except: pass
**| return _name
*/
_name = name;
Py_INCREF(_name);
if (_name == Py_None && value != Py_None) {
Py_DECREF(_name);
_name = PyObject_GetAttrString(value,"id");
if (_name == NULL) {
PyErr_Clear();
_name = PyObject_GetAttrString(value,"__name__");
if (_name == NULL) {
PyErr_Clear();
}
}
if (_name != NULL && PyCallable_Check(_name)) {
_name1 = PyObject_CallObject(_name, NULL);
Py_DECREF(_name);
_name = _name1;
if (_name == NULL) {
PyErr_Clear();
}
}
}
if (_name == NULL) {
Py_INCREF(Py_None);
_name = Py_None;
}
_name1 = PyObject_Str(_name);
if (_name1 == NULL) {
PyErr_Clear();
s = "? (non-printable object)";
}
else s = PyString_AsString(_name1);
snprintf(msgbuff,sizeof(msgbuff)-1,
"You are not authorized to access <em>%s</em>.", s);
Py_XDECREF(_name1);
_name1 = PyString_FromString(msgbuff);
PyErr_SetObject(Unauthorized, _name1);
Py_DECREF(_name);
Py_DECREF(_name1);
}
#if ZSPCACHE
static void ZSPCacheInit(void) {
int i;
for (i = 0; i < ZSPCACHEENTRIES; i++) {
ZSPCache[i].accessed = 0;
ZSPCache[i].container = 0;
ZSPCache[i].name = 0;
ZSPCache[i].value = 0;
ZSPCache[i].context = 0;
ZSPCache[i].roles = 0;
ZSPCache[i].result = NULL;
}
}
/* ZSPCacheGet
*/
static PyObject *ZSPCacheGet(PyObject *accessed, PyObject *container,
PyObject *name, PyObject *value, PyObject *context, PyObject *roles) {
unsigned long hash;
int h;
int i;
long a_hash;
long c_hash;
long n_hash;
long v_hash;
long t_hash;
long r_hash;
a_hash = (long)(accessed);
c_hash = (long)(container);
n_hash = /* PyObject_Hash(name) */ 0;
v_hash = /* PyObject_Hash(value) */ 0;
t_hash = PyObject_Hash(context);
r_hash = (long)(roles);
hash = (unsigned long) a_hash +
(unsigned long) c_hash +
(unsigned long) n_hash +
(unsigned long) v_hash +
(unsigned long) t_hash +
(unsigned long) r_hash;
h = hash % ZSPCACHEENTRIES;
i = (h + 1) % ZSPCACHEENTRIES;
#if 0
fprintf(stderr,"zspcacheget: %d %08x %08x %08x %08x %08x %08x\n", i,
(unsigned long) a_hash, (unsigned long) c_hash,
(unsigned long) n_hash, (unsigned long) v_hash, (unsigned long) t_hash,
(unsigned long) r_hash);
#endif
while(i != h) {
if ( ZSPCache[i].accessed == a_hash &&
ZSPCache[i].container == c_hash &&
ZSPCache[i].name == n_hash &&
ZSPCache[i].value == v_hash &&
ZSPCache[i].context == t_hash &&
ZSPCache[i].roles == r_hash
) {
Py_INCREF(ZSPCache[i].result);
#if 0
fprintf(stderr,"zspcache hit!\n");
#endif
return ZSPCache[i].result;
}
i = (i+1) % ZSPCACHEENTRIES; if ((v=Py_BuildValue("OO", name, value)))
{
PyErr_SetObject(Unauthorized, v);
Py_DECREF(v);
} }
return NULL;
} }
/*
** ZSPCacheSet
*/
static void ZSPCacheSet(PyObject *accessed, PyObject *container,
PyObject *name, PyObject *value, PyObject *context, PyObject *roles,
PyObject *result) {
unsigned long hash;
int h;
int i;
long a_hash;
long c_hash;
long n_hash;
long v_hash;
long t_hash;
long r_hash;
a_hash = (long)(accessed);
c_hash = (long)(container);
n_hash = /* PyObject_Hash(name) */ 0;
v_hash = /* PyObject_Hash(value) */ 0;
t_hash = PyObject_Hash(context);
r_hash = (long)(roles);
hash = (unsigned long) a_hash +
(unsigned long) c_hash +
(unsigned long) n_hash +
(unsigned long) v_hash +
(unsigned long) t_hash +
(unsigned long) r_hash;
h = hash % ZSPCACHEENTRIES;
i = (h + 1) % ZSPCACHEENTRIES;
ZSPCache[i].accessed = a_hash;
ZSPCache[i].container = c_hash;
ZSPCache[i].name = n_hash;
ZSPCache[i].value = v_hash;
ZSPCache[i].context = t_hash;
ZSPCache[i].roles = r_hash;
Py_XDECREF(ZSPCache[i].result);
ZSPCache[i].result = result;
Py_INCREF(result);
#if 0
fprintf(stderr,"zspcacheset: %d %08x %08x %08x %08x %08x %08x\n", i,
(unsigned long) a_hash, (unsigned long) c_hash,
(unsigned long) n_hash, (unsigned long) v_hash, (unsigned long) t_hash,
(unsigned long) r_hash);
#endif
}
#endif
/* /*
** ZopeSecurityPolicy_validate ** ZopeSecurityPolicy_validate
*/ */
...@@ -619,17 +421,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -619,17 +421,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
PyObject *name = NULL; PyObject *name = NULL;
PyObject *value = NULL; PyObject *value = NULL;
PyObject *context = NULL; PyObject *context = NULL;
PyObject *roles = NULL; /* Import from SimpleObject Policy._noroles */ PyObject *roles = NULL;
/* Import from SimpleObject Policy._noroles */
/* Note that _noroles means missing roles, spelled with a NULL in C.
Jim. */
PyObject *containerbase = NULL; PyObject *containerbase = NULL;
PyObject *accessedbase = NULL; PyObject *accessedbase = NULL;
PyObject *p = NULL; PyObject *p = NULL;
PyObject *rval = NULL; PyObject *rval = NULL;
PyObject *stack = NULL; PyObject *stack = NULL;
PyObject *user = NULL; PyObject *user = NULL;
#if ZSPCACHE
PyObject *iroles = NULL;
PyObject *ivalue = NULL;
#endif
char *sname; char *sname;
...@@ -640,8 +441,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -640,8 +441,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
if (!PyArg_ParseTuple(args, "OOOOO|O", &accessed, &container, if (!PyArg_ParseTuple(args, "OOOOO|O", &accessed, &container,
&name, &value, &context, &roles)) return NULL; &name, &value, &context, &roles)) return NULL;
Py_XINCREF(roles); /* Convert the borrowed ref to a real one */
/*| # Provide special rules for acquisition attributes /*| # Provide special rules for acquisition attributes
**| if type(name) is StringType: **| if type(name) is StringType:
**| if name[:3] == 'aq_' and name not in valid_aq_: **| if name[:3] == 'aq_' and name not in valid_aq_:
...@@ -649,18 +448,18 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -649,18 +448,18 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
*/ */
if (PyString_Check(name)) { /* XXX what about unicode? */ if (PyString_Check(name)) { /* XXX what about unicode? */
sname = PyString_AsString(name); sname = PyString_AS_STRING(name);
if (strncmp(sname,"aq_", 4) == 0) { if (*sname == 'a' && sname[1]=='q' && sname[2]=='_') {
if (!strncmp(sname,"aq_parent", 10) && if (strcmp(sname,"aq_parent") != 0 &&
!strncmp(sname,"aq_explicit", 12)) { strcmp(sname,"aq_explicit") != 0) {
/* Access control violation, return 0 */ /* Access control violation, return 0 */
return PyInt_FromLong(0);
rval = PyInt_FromLong(0);
goto err;
} }
} }
} }
Py_XINCREF(roles); /* Convert the borrowed ref to a real one */
/*| containerbase = aq_base(container) /*| containerbase = aq_base(container)
**| accessedbase = getattr(accessed, 'aq_base', container) **| accessedbase = getattr(accessed, 'aq_base', container)
*/ */
...@@ -675,20 +474,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -675,20 +474,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
accessedbase = container; accessedbase = container;
} }
#if ZSPCACHE
if ((rval = ZSPCacheGet(accessedbase, containerbase, name, value,
context, roles)) != NULL) {
Py_DECREF(containerbase);
Py_DECREF(accessedbase);
Py_XDECREF(roles);
return rval;
}
iroles = roles;
ivalue = value;
#endif
/*| # If roles weren't passed in, we'll try to get them from /*| # If roles weren't passed in, we'll try to get them from
**| # the object **| # the object
**| **|
...@@ -696,14 +481,10 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -696,14 +481,10 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| roles = getattr(value, "__roles__", _noroles) **| roles = getattr(value, "__roles__", _noroles)
*/ */
if (roles == NULL || roles == _noroles) {
Py_XDECREF(roles);
roles = PyObject_GetAttr(value, __roles__);
if (roles == NULL) { if (roles == NULL) {
roles = PyObject_GetAttr(value, __roles__);
if (roles == NULL)
PyErr_Clear(); PyErr_Clear();
Py_INCREF(_noroles);
roles = _noroles;
}
} }
/*| # We still might not have any roles /*| # We still might not have any roles
...@@ -711,7 +492,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -711,7 +492,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| if roles is _noroles: **| if roles is _noroles:
*/ */
if (roles == _noroles) { if (roles == NULL) {
/*| # We have an object without roles and we didn't get /*| # We have an object without roles and we didn't get
**| # a list of roles passed in. Presumably, the value **| # a list of roles passed in. Presumably, the value
...@@ -739,38 +520,30 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -739,38 +520,30 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| roles = _noroles **| roles = _noroles
**| if containerbase is not accessedbase: return 0 **| if containerbase is not accessedbase: return 0
*/ */
Py_XDECREF(roles);
roles = PyObject_GetAttr(container, __roles__); roles = PyObject_GetAttr(container, __roles__);
if (roles == NULL) { if (roles == NULL) {
PyErr_Clear(); PyErr_Clear();
Py_INCREF(_noroles);
roles = _noroles;
}
if (roles == _noroles) { if (!aq_isWrapper(container)) {
if (aq_isWrapper(container) != 1) {
Py_DECREF(roles);
if (containerbase != accessedbase) { if (containerbase != accessedbase) {
rval = PyInt_FromLong(0); rval = PyInt_FromLong(0);
goto err; goto err;
} }
}
Py_INCREF(_noroles); else {
roles = _noroles;
} else {
Py_DECREF(roles);
roles = aq_acquire(container, __roles__); roles = aq_acquire(container, __roles__);
if (roles == NULL) { if (roles == NULL) {
/* XXX not JUST AttributeError*/ if (PyErr_ExceptionMatches(
/* XXX should we clear the error? */ PyExc_AttributeError))
{
PyErr_Clear();
if (containerbase != accessedbase) { if (containerbase != accessedbase) {
rval = PyInt_FromLong(0); rval = PyInt_FromLong(0);
goto err; goto err;
} }
Py_INCREF(_noroles); }
roles = _noroles; else
goto err;
} }
} }
} }
...@@ -788,20 +561,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -788,20 +561,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
*/ */
/** XXX do we need to incref this stuff? I dont think so */ /** XXX do we need to incref this stuff? I dont think so */
p = PyObject_CallFunction(Containers, "OO", p = callfunction2(Containers, OBJECT(container->ob_type),
container->ob_type, Py_None); Py_None);
if (p == NULL)
if (p == NULL) goto err; goto err;
if (p == Py_None) { if (p == Py_None) {
Py_DECREF(p); ASSIGN(p, PyObject_GetAttr(container,
p = PyObject_GetAttrString(container, __allow_access_to_unprotected_subobjects__));
"__allow_access_to_unprotected_subobjects__"); if (p == NULL)
if (p == NULL) {
PyErr_Clear(); PyErr_Clear();
Py_INCREF(Py_None);
p = Py_None;
}
} }
/*| if p is not None: /*| if p is not None:
...@@ -813,25 +582,17 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -813,25 +582,17 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| p = p(name, value) **| p = p(name, value)
*/ */
if (p != Py_None) { if (p) {
if (!PyInt_Check(p)) { if (! PyInt_Check(p)) {
PyObject *temp;
if (PyDict_Check(p)) { if (PyDict_Check(p)) {
temp = PyObject_GetItem(p, name); ASSIGN(p, PyObject_GetItem(p, name));
Py_DECREF(p); if (p == NULL)
if (temp == NULL) { PyErr_Clear();
Py_INCREF(Py_None);
p = Py_None;
} else p = temp;
} else { } else {
temp = PyObject_CallFunction(p, ASSIGN(p, callfunction2(p, name, value));
"OO", name, value); if (p == NULL)
Py_DECREF(p);
if (temp == NULL) {
goto err; goto err;
} }
p = temp;
}
} }
} }
...@@ -842,22 +603,23 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -842,22 +603,23 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| return 0 **| return 0
*/ */
if (p == NULL || !PyObject_IsTrue(p)) { if (p == NULL || ! PyObject_IsTrue(p)) {
Py_XDECREF(p); Py_XDECREF(p);
if (containerbase == accessedbase) { if (containerbase == accessedbase) {
unauthErr(name, value); unauthErr(name, value);
goto err; goto err;
} else { } else {
rval = PyInt_FromLong(0); rval = PyInt_FromLong(0);
goto err; goto err;
} }
} }
else
Py_DECREF(p);
/*| if roles is _noroles: return 1 /*| if roles is _noroles: return 1
*/ */
if (roles == _noroles) { if (roles == NULL) {
rval = PyInt_FromLong(1); rval = PyInt_FromLong(1);
goto err; goto err;
} }
...@@ -870,7 +632,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -870,7 +632,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
value = container; /* Both are borrowed references */ value = container; /* Both are borrowed references */
} /* if (roles == _noroles) */ } /* if (roles == NULL) */
/*| # Short-circuit tests if we can /*| # Short-circuit tests if we can
**| try: **| try:
...@@ -886,40 +648,31 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -886,40 +648,31 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
rval = PyInt_FromLong(1); rval = PyInt_FromLong(1);
goto err; goto err;
} }
else
if (!PySequence_Check(roles)) { {
char pbuff[512];
PyObject *rolerepr = NULL;
rolerepr = PyObject_Repr(roles);
snprintf(pbuff, sizeof(pbuff)-1,
"'%s' passed as roles during validation of '%s'"
" is not a sequence.", PyString_AsString(rolerepr),
PyString_AsString(name));
Py_XDECREF(rolerepr);
PyObject_CallFunction(LOG, "sOs", "Zope Security Policy",
PROBLEM, pbuff);
PyErr_SetObject(PyExc_TypeError, roles);
goto err;
} else {
int i; int i;
int found = 0; i = PySequence_Contains(roles, Anonymous);
int pl; if (i > 0)
PyObject *item; {
pl = PySequence_Length(roles);
/* Iterate through the sequence looking for "Anonymous" */
for (i = 0; i < pl; i++) {
item = PySequence_GetItem(roles, i);
if (PyString_Check(item)) { /* XXX No unicode */
if (strncmp(PyString_AsString(item),
"Anonymous", 10) == 0) found = 1;
}
Py_DECREF(item);
if (found) {
rval = PyInt_FromLong(1); rval = PyInt_FromLong(1);
goto err; goto err;
} }
else if (i < 0)
{ /* Error */
PyObject *m, *t, *v, *tb;
if (!PyErr_ExceptionMatches(PyExc_TypeError))
goto err;
PyErr_Fetch(&t, &v, &tb);
m=PyObject_Repr(roles);
if (m) ASSIGN(m, Py_BuildValue("OO", m, name));
if (m) ASSIGN(m, PyString_Format(NoSequenceFormat, m));
if (m) ASSIGN(m, PyObject_CallFunction(LOG, "sOO",
"Zope Security Policy", PROBLEM, m));
Py_XDECREF(m);
PyErr_Restore(t, v, tb);
goto err;
} }
} }
...@@ -928,7 +681,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -928,7 +681,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| if stack: **| if stack:
*/ */
stack = PyObject_GetAttrString(context, "stack"); stack = PyObject_GetAttr(context, stack_str);
if (stack == NULL) goto err; if (stack == NULL) goto err;
if (PyObject_IsTrue(stack)) { if (PyObject_IsTrue(stack)) {
...@@ -951,32 +704,34 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -951,32 +704,34 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
eo = PySequence_GetItem(stack, -1); eo = PySequence_GetItem(stack, -1);
if (eo == NULL) goto err; if (eo == NULL) goto err;
owner = PyObject_CallMethod(eo, "getOwner", NULL); owner = PyObject_GetAttr(eo, getOwner_str);
if (owner == NULL) { if (owner) ASSIGN(owner, PyObject_CallObject(owner, NULL));
if (owner ==NULL)
{
Py_DECREF(eo); Py_DECREF(eo);
goto err; goto err;
} }
if (owner != Py_None) { if (owner != Py_None) {
PyObject *allowed; owner = PyObject_GetAttr(owner, allowed_str);
allowed = PyObject_CallMethod(owner, "allowed", "OO", if (owner)
value, roles); ASSIGN(owner, callfunction2(owner, value, roles));
if (allowed == NULL) { if (owner == NULL)
{
Py_DECREF(eo); Py_DECREF(eo);
Py_DECREF(owner);
goto err; goto err;
} }
if (!PyObject_IsTrue(allowed)) {
Py_DECREF(allowed); if (! PyObject_IsTrue(owner))
{
Py_DECREF(owner); Py_DECREF(owner);
Py_DECREF(eo); Py_DECREF(eo);
if (accessedbase == containerbase) { if (accessedbase == containerbase) {
unauthErr(name, value); unauthErr(name, value);
} else rval = PyInt_FromLong(0); }
else rval = PyInt_FromLong(0);
goto err; goto err;
} }
Py_DECREF(allowed);
} }
Py_DECREF(owner); Py_DECREF(owner);
...@@ -993,80 +748,83 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -993,80 +748,83 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| **|
**| return 0 **| return 0
*/ */
proxy_roles = PyObject_GetAttrString(eo, "_proxy_roles"); proxy_roles = PyObject_GetAttr(eo, _proxy_roles_str);
if (proxy_roles == NULL) { Py_DECREF(eo);
if (proxy_roles == NULL)
{
PyErr_Clear(); PyErr_Clear();
Py_INCREF(Py_None);
proxy_roles = Py_None;
} }
else if (PyObject_IsTrue(proxy_roles))
if (PyObject_IsTrue(proxy_roles)) { {
int i; int i, l, contains=0;
int j;
int pl;
int rl;
int found = 0;
PyObject *r; PyObject *r;
PyObject *r2; if (PyTuple_Check(proxy_roles))
pl = PySequence_Length(proxy_roles); {
rl = PySequence_Length(roles); l=PyTuple_GET_SIZE(proxy_roles);
for (i = 0; !found && i < pl; i++) { for (i=0; i < l; i++)
r = PySequence_GetItem(proxy_roles, i); {
for (j = 0; !found && j < rl; j++) { r=PyTuple_GET_ITEM(proxy_roles, i);
r2 = PySequence_GetItem(roles, j); if ((contains = PySequence_Contains(roles, r)))
if (PyObject_Compare(r, r2) == 0) break;
found=1; }
Py_DECREF(r2);
} }
else
{
l=PySequence_Size(proxy_roles);
if (l < 0) contains = -1;
for (i=0; i < l; i++)
{
if ((r=PySequence_GetItem(proxy_roles, i)))
{
contains = PySequence_Contains(roles, r);
Py_DECREF(r); Py_DECREF(r);
} }
if (found) { else
Py_DECREF(proxy_roles); contains = -1;
Py_DECREF(eo); if (contains < 0)
rval = PyInt_FromLong(1); break;
goto err; }
} }
Py_DECREF(proxy_roles);
if (contains > 0)
rval = PyInt_FromLong(contains);
else if (contains == 0) {
if (accessedbase == containerbase) { if (accessedbase == containerbase) {
Py_DECREF(proxy_roles);
Py_DECREF(eo);
unauthErr(name, value); unauthErr(name, value);
goto err;
} }
else rval = PyInt_FromLong(contains);
Py_DECREF(proxy_roles); }
Py_DECREF(eo);
rval = PyInt_FromLong(0);
goto err; goto err;
} }
else
Py_DECREF(proxy_roles); Py_DECREF(proxy_roles);
Py_DECREF(eo);
} /* End of stack check */ } /* End of stack check */
/*| try: /*| try:
**| if context.user.allowed(value, roles): return 1 **| if context.user.allowed(value, roles): return 1
**| except AttributeError: pass **| except AttributeError: pass
*/ */
user = PyObject_GetAttr(context, user_str);
user = PyObject_GetAttrString(context, "user"); if (user) ASSIGN(user, PyObject_GetAttr(user, allowed_str));
if (user != NULL) { if (user == NULL)
PyObject *allowed; {
allowed = PyObject_CallMethod(user, "allowed", "OO", if (PyErr_ExceptionMatches(PyExc_AttributeError))
value, roles); PyErr_Clear();
if (allowed != NULL) { else
if (PyObject_IsTrue(allowed)) {
Py_DECREF(allowed);
Py_DECREF(user);
rval = PyInt_FromLong(1);
goto err; goto err;
} }
Py_DECREF(allowed); else
{
ASSIGN(user, callfunction2(user, value, roles));
if (user == NULL) goto err;
if (PyObject_IsTrue(user))
{
rval = PyInt_FromLong(1);
Py_DECREF(user);
goto err;
} }
Py_DECREF(user); Py_DECREF(user);
} else {
PyErr_Clear();
} }
/*| # we don't want someone to acquire if they can't get an /*| # we don't want someone to acquire if they can't get an
...@@ -1077,22 +835,13 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) { ...@@ -1077,22 +835,13 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| return 0 **| return 0
*/ */
if (accessedbase == containerbase) {
unauthErr(name, value);
goto err;
}
if (accessedbase == containerbase)
unauthErr(name, value);
else
rval = PyInt_FromLong(0); rval = PyInt_FromLong(0);
err: err:
if (rval != NULL) PyErr_Clear();
#if ZSPCACHE
if (rval != NULL) ZSPCacheSet(accessedbase, containerbase, name, ivalue,
context, iroles, rval);
#endif
Py_XDECREF(stack); Py_XDECREF(stack);
Py_XDECREF(roles); Py_XDECREF(roles);
Py_XDECREF(containerbase); Py_XDECREF(containerbase);
...@@ -1116,7 +865,6 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self, ...@@ -1116,7 +865,6 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
PyObject *roles; PyObject *roles;
PyObject *result = NULL; PyObject *result = NULL;
PyObject *user; PyObject *user;
PyObject *arg;
/*| def checkPermission(self, permission, object, context) /*| def checkPermission(self, permission, object, context)
*/ */
...@@ -1127,11 +875,9 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self, ...@@ -1127,11 +875,9 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
/*| roles = rolesForPermissionOn(permission, object) /*| roles = rolesForPermissionOn(permission, object)
*/ */
arg = Py_BuildValue("OO", permission, object); roles = c_rolesForPermissionOn(self, permission, object, OBJECT(NULL));
roles = rolesForPermissionOn(self, arg); if (roles == NULL)
Py_DECREF(arg); return NULL;
if (roles == NULL) return NULL;
/*| if type(roles) is StringType: /*| if type(roles) is StringType:
**| roles = [roles] **| roles = [roles]
...@@ -1139,20 +885,28 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self, ...@@ -1139,20 +885,28 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
if (PyString_Check(roles)) { if (PyString_Check(roles)) {
PyObject *r; PyObject *r;
r = Py_BuildValue("[O]", roles);
r = PyList_New(1);
if (r == NULL) {
Py_DECREF(roles); Py_DECREF(roles);
return NULL;
}
/* Note: ref to roles is passed to the list object. */
PyList_SET_ITEM(r, 0, roles);
roles = r; roles = r;
} }
/*| return context.user.allowed(object, roles) /*| return context.user.allowed(object, roles)
*/ */
user = PyObject_GetAttrString(context, "user"); user = PyObject_GetAttr(context, user_str);
if (user != NULL) { if (user != NULL) {
result = PyObject_CallMethod(user,"allowed", "OO", object, roles); ASSIGN(user, PyObject_GetAttr(user, allowed_str));
if (user != NULL) {
result = callfunction2(user, object, roles);
Py_DECREF(user); Py_DECREF(user);
} }
}
Py_DECREF(roles); Py_DECREF(roles);
...@@ -1171,42 +925,6 @@ static void ZopeSecurityPolicy_dealloc(ZopeSecurityPolicy *self) { ...@@ -1171,42 +925,6 @@ static void ZopeSecurityPolicy_dealloc(ZopeSecurityPolicy *self) {
PyMem_DEL(self); PyMem_DEL(self);
} }
/*
** PermissionRole_getatro
*/
static PyObject *PermissionRole_getattr(PermissionRole *self, char *name) {
#define IZZIT(n) if (strcmp(#n, name) == 0) { Py_INCREF(self->n); return self->n; }
IZZIT(__name__);
IZZIT(_p);
IZZIT(__roles__);
return Py_FindAttrString(OBJECT(self), name);
}
/*
** PermissionRole_setattro
*/
static int PermissionRole_setattr(PermissionRole *self, char *name,
PyObject *value) {
PyObject *sname;
#define IZZITA(n) if (strcmp(#n, name) == 0) { Py_XDECREF(self->n); Py_INCREF(value); self->n = value; return 0; }
IZZITA(__name__);
IZZITA(_p);
IZZITA(__roles__);
sname = PyString_FromString(name);
PyErr_SetObject(PyExc_AttributeError, sname);
Py_DECREF(sname);
return -1;
}
/* /*
** PermissionRole_init ** PermissionRole_init
** **
...@@ -1227,11 +945,11 @@ static PyObject *PermissionRole_init(PermissionRole *self, PyObject *args) { ...@@ -1227,11 +945,11 @@ static PyObject *PermissionRole_init(PermissionRole *self, PyObject *args) {
if (deflt == NULL) deflt = defaultPermission; if (deflt == NULL) deflt = defaultPermission;
UNLESS(self->_p = permissionName(name)) return NULL;
self->__name__ = name; self->__name__ = name;
Py_INCREF(name); Py_INCREF(name);
self->_p = permissionName(name);
self->__roles__ = deflt; self->__roles__ = deflt;
Py_INCREF(deflt); Py_INCREF(deflt);
...@@ -1259,7 +977,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) { ...@@ -1259,7 +977,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
/*| r = imPermissionRole() /*| r = imPermissionRole()
*/ */
r = (imPermissionRole *) PyObject_CallObject(imPermissionRoleObj,NULL); r = (imPermissionRole*)PyObject_CallObject(imPermissionRoleObj, NULL);
if (r == NULL) return NULL; if (r == NULL) return NULL;
/*| r._p = self._p /*| r._p = self._p
...@@ -1272,7 +990,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) { ...@@ -1272,7 +990,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
*/ */
r->_pa = parent; r->_pa = parent;
Py_INCREF(r->_pa); Py_INCREF(parent);
/*| r._d = self._d /*| r._d = self._d
*/ */
...@@ -1291,16 +1009,15 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) { ...@@ -1291,16 +1009,15 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
if (aq_isWrapper(parent)) { if (aq_isWrapper(parent)) {
_p = aq_inner(parent); _p = aq_inner(parent);
result = PyObject_CallMethod(OBJECT(r),"__of__","O", _p); result = callmethod1(OBJECT(r), __of__, _p);
Py_DECREF(_p); Py_DECREF(_p);
/* Dont need goto */ /* Dont need goto */
} else { } else {
result = OBJECT(r); result = OBJECT(r);
Py_INCREF(r); Py_INCREF(r);
PyErr_Clear();
} }
Py_XDECREF(r); Py_DECREF(r);
return result; return result;
} }
...@@ -1312,52 +1029,17 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) { ...@@ -1312,52 +1029,17 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
static void PermissionRole_dealloc(PermissionRole *self) { static void PermissionRole_dealloc(PermissionRole *self) {
Py_XDECREF(self->__name__); Py_DECREF(self->__name__);
Py_XDECREF(self->_p); Py_DECREF(self->_p);
Py_XDECREF(self->__roles__); Py_DECREF(self->__roles__);
Py_DECREF(self->ob_type); /* Extensionclass init incref'd */ Py_DECREF(self->ob_type); /* Extensionclass init incref'd */
PyMem_DEL(self); PyMem_DEL(self);
} }
/*
** imPermissionRole_getatro
*/
static PyObject *imPermissionRole_getattr(imPermissionRole *self, char *name) {
IZZIT(_p);
IZZIT(_pa);
IZZIT(__roles__);
IZZIT(_v);
return Py_FindAttrString(OBJECT(self), name);
}
/*
** imPermissionRole_setattro
*/
static int imPermissionRole_setattr(imPermissionRole *self, char *name,
PyObject *value) {
PyObject *sname;
IZZITA(_p);
IZZITA(_pa);
IZZITA(__roles__);
IZZITA(_v);
sname = PyString_FromString(name);
PyErr_SetObject(PyExc_AttributeError, sname);
Py_DECREF(sname);
return -1;
}
/* /*
** imPermissionRole_of ** imPermissionRole_of
** **
...@@ -1386,8 +1068,10 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1386,8 +1068,10 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
n = self->_p; n = self->_p;
if (n == NULL) { if (n == NULL) {
/* XXX Should not be possible */
PyErr_SetString(PyExc_AttributeError, "_p"); PyErr_SetString(PyExc_AttributeError, "_p");
goto err; Py_DECREF(obj);
return NULL;
} }
Py_INCREF(n); Py_INCREF(n);
...@@ -1409,7 +1093,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1409,7 +1093,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
if (roles != NULL) { if (roles != NULL) {
if (roles == Py_None) { if (roles == Py_None) {
result = Anonymous; result = AnonymousTuple;
Py_INCREF(result); Py_INCREF(result);
goto err; goto err;
} }
...@@ -1429,13 +1113,11 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1429,13 +1113,11 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
goto err; goto err;
} else { } else {
PyObject *list; PyObject *list;
PyObject *cat;
list = PySequence_List(roles); list = PySequence_List(roles);
cat = PySequence_Concat(r, list); if (list != NULL) {
result = PySequence_Concat(r, list);
Py_DECREF(list); Py_DECREF(list);
result = cat; }
goto err; goto err;
} }
} }
...@@ -1461,7 +1143,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1461,7 +1143,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
**| **|
*/ */
if (PyObject_IsTrue(roles)) { if (PyObject_IsTrue(roles)) {
if (PyObject_Compare(roles, n)) { if (PyObject_Compare(roles, n) != 0) {
Py_DECREF(n); Py_DECREF(n);
n = roles; n = roles;
Py_INCREF(n); Py_INCREF(n);
...@@ -1471,6 +1153,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1471,6 +1153,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
Py_INCREF(roles); Py_INCREF(roles);
} else { } else {
result = _what_not_even_god_should_do; result = _what_not_even_god_should_do;
Py_INCREF(result);
goto err; goto err;
} }
} else { } else {
...@@ -1485,15 +1168,16 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1485,15 +1168,16 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
r = PySequence_List(roles); r = PySequence_List(roles);
} else { } else {
PyObject *list; PyObject *list;
PyObject *cat;
list = PySequence_List(roles); list = PySequence_List(roles);
cat = PySequence_Concat(r, if (list != NULL) {
list); ASSIGN(r, PySequence_Concat(r, list));
Py_DECREF(list); Py_DECREF(list);
Py_DECREF(r); if (r == NULL)
r = cat; goto err;
}
else
goto err;
} }
} }
} }
...@@ -1506,14 +1190,14 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) { ...@@ -1506,14 +1190,14 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
**| obj = obj.aq_parent **| obj = obj.aq_parent
*/ */
if (aq_isWrapper(obj) <= 0) break; if (!aq_isWrapper(obj)) break;
tobj = aq_inner(obj); tobj = aq_inner(obj);
if (tobj == NULL) break; if (tobj == NULL) goto err;
Py_DECREF(obj); Py_DECREF(obj);
obj = tobj; obj = tobj;
if (obj == Py_None) break; if (obj == Py_None) break;
if (aq_isWrapper(obj) <= 0) break; if (!aq_isWrapper(obj)) break;
tobj = aq_parent(obj); tobj = aq_parent(obj);
if (tobj == NULL) goto err; if (tobj == NULL) goto err;
Py_DECREF(obj); Py_DECREF(obj);
...@@ -1571,60 +1255,21 @@ static int imPermissionRole_length(imPermissionRole *self) { ...@@ -1571,60 +1255,21 @@ static int imPermissionRole_length(imPermissionRole *self) {
v = self->_v; v = self->_v;
if (v == NULL) { if (v == NULL) {
pa = self->_pa; pa = self->_pa;
if (pa == NULL) return -1; if (pa == NULL) {
PyErr_SetString(PyExc_AttributeError, "_pa");
v = PyObject_CallMethod(OBJECT(self), "__of__", return -1;
"O", pa); }
v = callmethod1(OBJECT(self), __of__, pa);
if (v == NULL)
return -1;
self->_v = v; self->_v = v;
Py_DECREF(pa);
Py_XDECREF(self->_pa);
self->_pa = NULL; self->_pa = NULL;
} }
l = PyObject_Length(v); l = PyObject_Length(v);
return l; return l;
}
/*
** imPermissionRole_getitem
*/
static PyObject *imPermissionRole_getitem(imPermissionRole *self,
PyObject *item) {
PyObject *v;
PyObject *pa;
PyObject *result;
/*| try:
**| v = self._v
**| except:
**| v = self._v = self.__of__(self._pa)
**| del self._pa
**| return v[i]
*/
v = self->_v;
if (v == NULL) {
pa = self->_pa;
if (pa == NULL) return NULL;
v = PyObject_CallMethod(OBJECT(self), "__of__",
"O", pa);
self->_v = v;
Py_XDECREF(self->_pa);
self->_pa = NULL;
}
result = PyObject_GetItem(v, item);
return result;
} }
/* /*
...@@ -1650,14 +1295,15 @@ static PyObject *imPermissionRole_get(imPermissionRole *self, ...@@ -1650,14 +1295,15 @@ static PyObject *imPermissionRole_get(imPermissionRole *self,
if (v == NULL) { if (v == NULL) {
pa = self->_pa; pa = self->_pa;
if (pa == NULL) return NULL; if (pa == NULL) {
PyErr_SetString(PyExc_AttributeError, "_pa");
v = PyObject_CallMethod(OBJECT(self), "__of__", return NULL;
"O", pa); }
v = callmethod1(OBJECT(self), __of__, pa);
if (v == NULL)
return NULL;
self->_v = v; self->_v = v;
Py_DECREF(pa);
Py_XDECREF(self->_pa);
self->_pa = NULL; self->_pa = NULL;
} }
...@@ -1673,16 +1319,12 @@ static PyObject *imPermissionRole_get(imPermissionRole *self, ...@@ -1673,16 +1319,12 @@ static PyObject *imPermissionRole_get(imPermissionRole *self,
static void imPermissionRole_dealloc(imPermissionRole *self) { static void imPermissionRole_dealloc(imPermissionRole *self) {
Py_XDECREF(self->_p); Py_XDECREF(self->_p);
self->_p = NULL;
Py_XDECREF(self->_pa); Py_XDECREF(self->_pa);
self->_pa = NULL;
Py_XDECREF(self->__roles__); Py_XDECREF(self->__roles__);
self->__roles__ = NULL;
Py_XDECREF(self->_v); Py_XDECREF(self->_v);
self->_v = NULL;
Py_DECREF(self->ob_type); /* Extensionclass init incref'd */ Py_DECREF(self->ob_type); /* Extensionclass init incref'd */
...@@ -1697,41 +1339,52 @@ static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args) { ...@@ -1697,41 +1339,52 @@ static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args) {
PyObject *perm = NULL; PyObject *perm = NULL;
PyObject *object = NULL; PyObject *object = NULL;
PyObject *deflt = NULL; PyObject *deflt = NULL;
imPermissionRole *im = NULL;
PyObject *result;
/*|def rolesForPermissionOn(perm, object, default=('Manager',)): /*|def rolesForPermissionOn(perm, object, default=('Manager',)):
**| **|
**| """Return the roles that have the permisson on the given object""" **| """Return the roles that have the permisson on the given object"""
**| */
**| im = imPermissionRole()
if (!PyArg_ParseTuple(args, "OO|O", &perm, &object, &deflt))
return NULL;
return c_rolesForPermissionOn(self, perm, object, deflt);
}
static PyObject *
c_rolesForPermissionOn(PyObject *self, PyObject *perm, PyObject *object,
PyObject *deflt) {
imPermissionRole *im = NULL;
PyObject *result;
/*| im = imPermissionRole()
**| **|
**| im._p="_"+string.translate(perm, name_trans)+"_Permission" **| im._p="_"+string.translate(perm, name_trans)+"_Permission"
**| im._d = default **| im._d = default
**| return im.__of__(object) **| return im.__of__(object)
*/ */
if (!PyArg_ParseTuple(args, "OO|O", &perm, &object, &deflt)) im = (imPermissionRole*)PyObject_CallObject(imPermissionRoleObj, NULL);
if (im == NULL)
return NULL; return NULL;
im = (imPermissionRole *) PyObject_CallObject(imPermissionRoleObj,
NULL);
if (im == NULL) return NULL;
im->_p = permissionName(perm); im->_p = permissionName(perm);
if (im->_p == NULL) {
Py_DECREF(im);
return NULL;
}
if (deflt == NULL) deflt = defaultPermission; if (deflt == NULL) deflt = defaultPermission;
im->__roles__ = deflt; im->__roles__ = deflt;
Py_INCREF(deflt); Py_INCREF(deflt);
result = PyObject_CallMethod(OBJECT(im), "__of__", "O", object); result = callmethod1(OBJECT(im), __of__, object);
Py_DECREF(im); Py_DECREF(im);
return result; return result;
} }
/* /*
** permissionName ** permissionName
** **
...@@ -1751,6 +1404,8 @@ static PyObject *permissionName(PyObject *name) { ...@@ -1751,6 +1404,8 @@ static PyObject *permissionName(PyObject *name) {
len--; len--;
in = PyString_AsString(name); in = PyString_AsString(name);
if (in == NULL)
return NULL;
while (len && *in) { while (len && *in) {
r = *(in++); r = *(in++);
...@@ -1777,24 +1432,33 @@ static PyObject *permissionName(PyObject *name) { ...@@ -1777,24 +1432,33 @@ static PyObject *permissionName(PyObject *name) {
** Module initialization ** Module initialization
** ---------------------------------------------------------------- ** ----------------------------------------------------------------
*/ */
#define IMPORT(module, name) if ((module = PyImport_ImportModule(name)) == NULL) return;
#define GETATTR(module, name) if ((name = PyObject_GetAttrString(module, #name)) == NULL) return;
PUBLIC void initcAccessControl(void) { void initcAccessControl(void) {
PyObject *module; PyObject *module;
PyObject *dict; PyObject *dict;
char *rev = "$Revision: 1.10 $"; char *rev = "$Revision: 1.11 $";
if (!ExtensionClassImported) return; if (!ExtensionClassImported) return;
aq_init(); if (ZopeSecurityPolicy_setup() < 0) return;
ZopeSecurityPolicyType.tp_getattro = ZopeSecurityPolicyType.tp_getattro =
(getattrofunc) PyExtensionClassCAPI->getattro; (getattrofunc) PyExtensionClassCAPI->getattro;
module = Py_InitModule4("cAccessControl", PermissionRoleType.tp_getattro =
(getattrofunc) PyExtensionClassCAPI->getattro;
imPermissionRoleType.tp_getattro =
(getattrofunc) PyExtensionClassCAPI->getattro;
module = Py_InitModule3("cAccessControl",
cAccessControl_methods, cAccessControl_methods,
"$Id: %\n", "$Id: cAccessControl.c,v 1.11 2001/10/19 15:12:25 shane Exp $\n");
OBJECT(NULL),
PYTHON_API_VERSION); aq_init(); /* For Python <= 2.1.1, aq_init() should be after
Py_InitModule(). */
dict = PyModule_GetDict(module); dict = PyModule_GetDict(module);
...@@ -1813,12 +1477,6 @@ PUBLIC void initcAccessControl(void) { ...@@ -1813,12 +1477,6 @@ PUBLIC void initcAccessControl(void) {
PyDict_SetItemString(dict, "__version__", PyDict_SetItemString(dict, "__version__",
PyString_FromStringAndSize(rev+11,strlen(rev+11)-2)); PyString_FromStringAndSize(rev+11,strlen(rev+11)-2));
if (!ZopeSecurityPolicy_setup()) {
Py_FatalError("Can't initialize module cAccessControl "
"-- dependancies failed to load.");
return;
}
PyDict_SetItemString(dict, "_what_not_even_god_should_do", PyDict_SetItemString(dict, "_what_not_even_god_should_do",
_what_not_even_god_should_do); _what_not_even_god_should_do);
...@@ -1833,11 +1491,29 @@ PUBLIC void initcAccessControl(void) { ...@@ -1833,11 +1491,29 @@ PUBLIC void initcAccessControl(void) {
imPermissionRoleObj = PyDict_GetItemString(dict, "imPermissionRole"); imPermissionRoleObj = PyDict_GetItemString(dict, "imPermissionRole");
#if ZSPCACHE /*| from SimpleObjectPolicies import Containers
ZSPCacheInit(); */
#endif
IMPORT(module, "AccessControl.SimpleObjectPolicies");
GETATTR(module, Containers);
Py_DECREF(module);
module = NULL;
/*| from unauthorized import Unauthorized
*/
if (PyErr_Occurred()) IMPORT(module, "AccessControl.unauthorized");
Py_FatalError("Can't initialize module cAccessControl"); GETATTR(module, Unauthorized);
Py_DECREF(module);
module = NULL;
/*| from zLOG import LOG, PROBLEM
*/
IMPORT(module, "zLOG");
GETATTR(module, LOG);
GETATTR(module, PROBLEM);
Py_DECREF(module);
module = NULL;
} }
#
from SimpleObjectPolicies import _noroles
import cAccessControl
ZopeSecurityPolicy = cAccessControl.ZopeSecurityPolicy
...@@ -82,69 +82,25 @@ ...@@ -82,69 +82,25 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
__doc__='''Objects that implement Permission-based roles. """Access control exceptions
"""
import zExceptions
$Id: cPermissionRole.py,v 1.1 2001/08/08 15:57:49 matt Exp $''' class Unauthorized(zExceptions.Unauthorized):
__version__='$Revision: 1.1 $'[11:-2]
import cAccessControl def getValueName(self):
rolesForPermissionOn=cAccessControl.rolesForPermissionOn v=self.value
PermissionRole=cAccessControl.PermissionRole n=getattr(v, 'getId', v)
imPermisionRole=cAccessControl.imPermissionRole if n is v: n=getattr(v, 'id', v)
_what_not_even_god_should_do= cAccessControl._what_not_even_god_should_do if n is v: n=getattr(v, '__name__', v)
if n is not v:
if callable(n):
try: n = n()
except TypeError: pass
return n
############################################################################## c = getattr(v, '__class__', type(v))
# Test functions: c = getattr(c, '__name__', 'object')
# return "a particular %s" % c
def main():
# The "main" program for this module
import sys
sys.path.append('/projects/_/ExtensionClass')
from Acquisition import Implicit
class I(Implicit):
x__roles__=PermissionRole('x')
y__roles__=PermissionRole('y')
z__roles__=PermissionRole('z')
def x(self): pass
def y(self): pass
def z(self): pass
a=I()
a.b=I()
a.b.c=I()
a.q=I()
a.q._x_Permission=('foo',)
a._y_Permission=('bar',)
a._z_Permission=('zee',)
a.b.c._y_Permission=('Manage',)
a.b._z_Permission=['also']
print a.x.__roles__, list(a.x.__roles__)
print a.b.x.__roles__
print a.b.c.x.__roles__
print a.q.x.__roles__
print a.b.q.x.__roles__
print a.b.c.q.x.__roles__
print
print a.y.__roles__, list(a.y.__roles__)
print a.b.y.__roles__
print a.b.c.y.__roles__
print a.q.y.__roles__
print a.b.q.y.__roles__
print a.b.c.q.y.__roles__
print
print a.z.__roles__, list(a.z.__roles__)
print a.b.z.__roles__
print a.b.c.z.__roles__
print a.q.z.__roles__
print a.b.q.z.__roles__
print a.b.c.q.z.__roles__
print
...@@ -85,15 +85,15 @@ ...@@ -85,15 +85,15 @@
"""Standard management interface support """Standard management interface support
$Id: Management.py,v 1.50 2001/09/04 16:50:48 shane Exp $""" $Id: Management.py,v 1.51 2001/10/19 15:12:25 shane Exp $"""
__version__='$Revision: 1.50 $'[11:-2] __version__='$Revision: 1.51 $'[11:-2]
import sys, Globals, ExtensionClass, urllib import sys, Globals, ExtensionClass, urllib
from Dialogs import MessageDialog from Dialogs import MessageDialog
from Globals import DTMLFile, HTMLFile from Globals import DTMLFile, HTMLFile
from string import split, join, find from string import split, join, find
from AccessControl import getSecurityManager from AccessControl import getSecurityManager, Unauthorized
class Tabs(ExtensionClass.Base): class Tabs(ExtensionClass.Base):
"""Mix-in provides management folder tab support.""" """Mix-in provides management folder tab support."""
...@@ -145,8 +145,8 @@ class Tabs(ExtensionClass.Base): ...@@ -145,8 +145,8 @@ class Tabs(ExtensionClass.Base):
m=options[0]['action'] m=options[0]['action']
if m=='manage_workspace': raise TypeError if m=='manage_workspace': raise TypeError
except: except:
raise 'Unauthorized', ( raise Unauthorized, (
'You are not authorized to view this object.<p>') 'You are not authorized to view this object.')
if find(m,'/'): if find(m,'/'):
raise 'Redirect', ( raise 'Redirect', (
......
...@@ -118,6 +118,7 @@ from Permission import PermissionManager ...@@ -118,6 +118,7 @@ from Permission import PermissionManager
import ZClasses, ZClasses.ZClass import ZClasses, ZClasses.ZClass
from HelpSys.HelpSys import ProductHelp from HelpSys.HelpSys import ProductHelp
import RefreshFuncs import RefreshFuncs
from AccessControl import Unauthorized
class ProductFolder(Folder): class ProductFolder(Folder):
...@@ -447,7 +448,7 @@ class Product(Folder, PermissionManager): ...@@ -447,7 +448,7 @@ class Product(Folder, PermissionManager):
Attempts to perform a refresh operation. Attempts to perform a refresh operation.
''' '''
if self._readRefreshTxt() is None: if self._readRefreshTxt() is None:
raise 'Unauthorized', 'refresh.txt not found' raise Unauthorized, 'refresh.txt not found'
message = None message = None
if RefreshFuncs.performFullRefresh(self._p_jar, self.id): if RefreshFuncs.performFullRefresh(self._p_jar, self.id):
from ZODB import Connection from ZODB import Connection
...@@ -463,7 +464,7 @@ class Product(Folder, PermissionManager): ...@@ -463,7 +464,7 @@ class Product(Folder, PermissionManager):
Changes the auto refresh flag for this product. Changes the auto refresh flag for this product.
''' '''
if self._readRefreshTxt() is None: if self._readRefreshTxt() is None:
raise 'Unauthorized', 'refresh.txt not created' raise Unauthorized, 'refresh.txt not created'
RefreshFuncs.enableAutoRefresh(self._p_jar, self.id, enable) RefreshFuncs.enableAutoRefresh(self._p_jar, self.id, enable)
if enable: if enable:
message = 'Enabled auto refresh.' message = 'Enabled auto refresh.'
...@@ -477,7 +478,7 @@ class Product(Folder, PermissionManager): ...@@ -477,7 +478,7 @@ class Product(Folder, PermissionManager):
Selects which products to refresh simultaneously. Selects which products to refresh simultaneously.
''' '''
if self._readRefreshTxt() is None: if self._readRefreshTxt() is None:
raise 'Unauthorized', 'refresh.txt not created' raise Unauthorized, 'refresh.txt not created'
RefreshFuncs.setDependentProducts(self._p_jar, self.id, selections) RefreshFuncs.setDependentProducts(self._p_jar, self.id, selections)
if REQUEST is not None: if REQUEST is not None:
return self.manage_refresh(REQUEST) return self.manage_refresh(REQUEST)
......
...@@ -82,8 +82,8 @@ ...@@ -82,8 +82,8 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
'''$Id: DT_Util.py,v 1.83 2001/09/04 13:46:43 evan Exp $''' '''$Id: DT_Util.py,v 1.84 2001/10/19 15:12:26 shane Exp $'''
__version__='$Revision: 1.83 $'[11:-2] __version__='$Revision: 1.84 $'[11:-2]
import re, os import re, os
from html_quote import html_quote # for import by other modules, dont remove! from html_quote import html_quote # for import by other modules, dont remove!
...@@ -98,7 +98,7 @@ LIMITED_BUILTINS = 1 ...@@ -98,7 +98,7 @@ LIMITED_BUILTINS = 1
str=__builtins__['str'] # Waaaaa, waaaaaaaa needed for pickling waaaaa str=__builtins__['str'] # Waaaaa, waaaaaaaa needed for pickling waaaaa
ParseError='Document Template Parse Error' ParseError='Document Template Parse Error'
ValidationError='Unauthorized' from zExceptions import Unauthorized as ValidationError
def int_param(params,md,name,default=0, st=type('')): def int_param(params,md,name,default=0, st=type('')):
try: v=params[name] try: v=params[name]
......
...@@ -85,19 +85,16 @@ ...@@ -85,19 +85,16 @@
"""Document Template Tests """Document Template Tests
""" """
__rcs_id__='$Id: testDTML.py,v 1.6 2001/07/02 16:30:46 shane Exp $' __rcs_id__='$Id: testDTML.py,v 1.7 2001/10/19 15:12:26 shane Exp $'
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
import sys, os import sys, os
import unittest import unittest
if __name__=='__main__': if __name__=='__main__':
sys.path.append(os.path.join(os.pardir, os.pardir))
here = os.curdir here = os.curdir
else: else:
from DocumentTemplate import tests here = os.path.split(__file__)[0]
from App.Common import package_home
here = package_home(tests.__dict__)
def read_file(name): def read_file(name):
f = open(os.path.join(here, name), 'rb') f = open(os.path.join(here, name), 'rb')
...@@ -122,7 +119,7 @@ class DTMLTests (unittest.TestCase): ...@@ -122,7 +119,7 @@ class DTMLTests (unittest.TestCase):
doc_class = HTML doc_class = HTML
def checkBatchingEtc(self): def testBatchingEtc(self):
def item(key,**kw): return (key,kw) def item(key,**kw): return (key,kw)
def item2(key,**kw): return kw def item2(key,**kw): return kw
...@@ -239,7 +236,7 @@ class DTMLTests (unittest.TestCase): ...@@ -239,7 +236,7 @@ class DTMLTests (unittest.TestCase):
expected = read_file('dealers.out') expected = read_file('dealers.out')
assert res == expected, res assert res == expected, res
def checkSequenceSummaries(self): def testSequenceSummaries(self):
def d(**kw): return kw def d(**kw): return kw
data=(d(name='jim', age=38), data=(d(name='jim', age=38),
# d(name='kak', age=40), # d(name='kak', age=40),
...@@ -274,7 +271,7 @@ class DTMLTests (unittest.TestCase): ...@@ -274,7 +271,7 @@ class DTMLTests (unittest.TestCase):
'median=5 mean=12.5 s.d.=17') 'median=5 mean=12.5 s.d.=17')
assert res == expected, res assert res == expected, res
def checkDTMLDateFormatting(self): def testDTMLDateFormatting(self):
import DateTime import DateTime
html = self.doc_class( html = self.doc_class(
"<dtml-var name capitalize spacify> is " "<dtml-var name capitalize spacify> is "
...@@ -285,13 +282,13 @@ class DTMLTests (unittest.TestCase): ...@@ -285,13 +282,13 @@ class DTMLTests (unittest.TestCase):
expected = 'Christmas day is 1995/12/25' expected = 'Christmas day is 1995/12/25'
assert res == expected, res assert res == expected, res
def checkSimpleString(self): def testSimpleString(self):
dt = String('%(name)s') dt = String('%(name)s')
res = dt(name='Chris') res = dt(name='Chris')
expected = 'Chris' expected = 'Chris'
assert res == expected, res assert res == expected, res
def checkStringDateFormatting(self): def testStringDateFormatting(self):
import DateTime import DateTime
html = String("%(name capitalize spacify)s is " html = String("%(name capitalize spacify)s is "
"%(date fmt=year)s/%(date fmt=month)s/%(date fmt=day)s") "%(date fmt=year)s/%(date fmt=month)s/%(date fmt=day)s")
...@@ -300,7 +297,7 @@ class DTMLTests (unittest.TestCase): ...@@ -300,7 +297,7 @@ class DTMLTests (unittest.TestCase):
expected = 'The date is 2001/4/27' expected = 'The date is 2001/4/27'
assert res == expected, res assert res == expected, res
def checkSequence1(self): def testSequence1(self):
html=self.doc_class( html=self.doc_class(
'<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item> ' '<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item> '
'</dtml-in sequence-item></dtml-in spam>') '</dtml-in sequence-item></dtml-in spam>')
...@@ -308,7 +305,7 @@ class DTMLTests (unittest.TestCase): ...@@ -308,7 +305,7 @@ class DTMLTests (unittest.TestCase):
res = html(spam=[[1,2,3],[4,5,6]]) res = html(spam=[[1,2,3],[4,5,6]])
assert res == expected, res assert res == expected, res
def checkSequence2(self): def testSequence2(self):
html=self.doc_class( html=self.doc_class(
'<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item>-' '<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item>-'
'</dtml-in sequence-item></dtml-in spam>') '</dtml-in sequence-item></dtml-in spam>')
...@@ -316,14 +313,14 @@ class DTMLTests (unittest.TestCase): ...@@ -316,14 +313,14 @@ class DTMLTests (unittest.TestCase):
res = html(spam=[[1,2,3],[4,5,6]]) res = html(spam=[[1,2,3],[4,5,6]])
assert res == expected, res assert res == expected, res
def checkNull(self): def testNull(self):
html=self.doc_class('<dtml-var spam fmt="$%.2f bobs your uncle" ' html=self.doc_class('<dtml-var spam fmt="$%.2f bobs your uncle" '
'null="spam%eggs!|">') 'null="spam%eggs!|">')
expected = '$42.00 bobs your unclespam%eggs!|' expected = '$42.00 bobs your unclespam%eggs!|'
res = html(spam=42) + html(spam=None) res = html(spam=42) + html(spam=None)
assert res == expected, res assert res == expected, res
def check_fmt(self): def test_fmt(self):
html=self.doc_class( html=self.doc_class(
""" """
<dtml-var spam> <dtml-var spam>
...@@ -369,7 +366,7 @@ foo bar ...@@ -369,7 +366,7 @@ foo bar
spam='<a href="spam">\nfoo bar') spam='<a href="spam">\nfoo bar')
assert res == expected, res assert res == expected, res
def checkPropogatedError(self): def testPropogatedError(self):
class foo: class foo:
def __len__(self): return 9 def __len__(self): return 9
...@@ -408,7 +405,7 @@ foo bar ...@@ -408,7 +405,7 @@ foo bar
else: else:
assert 0, 'Puke error not propogated' assert 0, 'Puke error not propogated'
def checkRenderCallable(self): def testRenderCallable(self):
"Test automatic rendering of callable objects" "Test automatic rendering of callable objects"
class C (Base): class C (Base):
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
...@@ -433,7 +430,7 @@ foo bar ...@@ -433,7 +430,7 @@ foo bar
<dtml-var expr="_.render(i.h2)">''')(i=C()) <dtml-var expr="_.render(i.h2)">''')(i=C())
assert res == expected, res assert res == expected, res
def checkWith(self): def testWith(self):
class person: class person:
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
name='Jim' name='Jim'
...@@ -448,7 +445,7 @@ foo bar ...@@ -448,7 +445,7 @@ foo bar
'cm.</dtml-with>')(person=person) 'cm.</dtml-with>')(person=person)
assert res == expected, res assert res == expected, res
def checkRaise(self): def testRaise(self):
try: try:
res = self.doc_class( res = self.doc_class(
"<dtml-raise IndexError>success!</dtml-raise>")() "<dtml-raise IndexError>success!</dtml-raise>")()
...@@ -457,7 +454,7 @@ foo bar ...@@ -457,7 +454,7 @@ foo bar
assert str(res) == 'success!', `res` assert str(res) == 'success!', `res`
def checkBasicHTMLIn(self): def testBasicHTMLIn(self):
data=( data=(
d(name='jim', age=39), d(name='jim', age=39),
d(name='kak', age=29), d(name='kak', age=29),
...@@ -481,7 +478,7 @@ foo bar ...@@ -481,7 +478,7 @@ foo bar
result = self.doc_class(html)(data=data) result = self.doc_class(html)(data=data)
assert result == expected, result assert result == expected, result
def checkBasicHTMLIn2(self): def testBasicHTMLIn2(self):
xxx=(D(name=1), D(name=2), D(name=3)) xxx=(D(name=1), D(name=2), D(name=3))
html = """ html = """
<!--#in xxx--> <!--#in xxx-->
...@@ -496,7 +493,7 @@ foo bar ...@@ -496,7 +493,7 @@ foo bar
result = self.doc_class(html)(xxx=xxx) result = self.doc_class(html)(xxx=xxx)
assert result == expected, result assert result == expected, result
def checkBasicHTMLIn3(self): def testBasicHTMLIn3(self):
ns = {'prop_ids': ('title', 'id'), 'title': 'good', 'id': 'times'} ns = {'prop_ids': ('title', 'id'), 'title': 'good', 'id': 'times'}
html = """:<dtml-in prop_ids><dtml-var sequence-item>=<dtml-var html = """:<dtml-in prop_ids><dtml-var sequence-item>=<dtml-var
expr="_[_['sequence-item']]">:</dtml-in>""" expr="_[_['sequence-item']]">:</dtml-in>"""
...@@ -505,7 +502,7 @@ foo bar ...@@ -505,7 +502,7 @@ foo bar
assert result == expected, result assert result == expected, result
def checkHTMLInElse(self): def testHTMLInElse(self):
xxx=(D(name=1), D(name=2), D(name=3)) xxx=(D(name=1), D(name=2), D(name=3))
html=""" html="""
<!--#in data mapping--> <!--#in data mapping-->
...@@ -524,7 +521,7 @@ foo bar ...@@ -524,7 +521,7 @@ foo bar
result = self.doc_class(html)(xxx=xxx, data={}) result = self.doc_class(html)(xxx=xxx, data={})
assert result == expected, result assert result == expected, result
def checkBasicStringIn(self): def testBasicStringIn(self):
data=( data=(
d(name='jim', age=39), d(name='jim', age=39),
d(name='kak', age=29), d(name='kak', age=29),
...@@ -548,22 +545,12 @@ foo bar ...@@ -548,22 +545,12 @@ foo bar
assert expected == result, result assert expected == result, result
def test_suite(): def test_suite():
return unittest.makeSuite(DTMLTests, 'check') suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( DTMLTests ) )
return suite
def main(): def main():
alltests = test_suite() unittest.TextTestRunner().run(test_suite())
runner = unittest.TextTestRunner()
runner.run(alltests)
def debug(): if __name__ == '__main__':
test_suite().debug()
def pdebug():
import pdb
pdb.run('debug()')
if __name__=='__main__':
if len(sys.argv) > 1:
globals()[sys.argv[1]]()
else:
main() main()
...@@ -84,9 +84,9 @@ ...@@ -84,9 +84,9 @@
############################################################################## ##############################################################################
__doc__="""Cacheable object and cache management base classes. __doc__="""Cacheable object and cache management base classes.
$Id: Cache.py,v 1.6 2001/02/08 15:24:16 shane Exp $""" $Id: Cache.py,v 1.7 2001/10/19 15:12:26 shane Exp $"""
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
import time, sys import time, sys
from string import join from string import join
...@@ -96,6 +96,7 @@ from Acquisition import aq_get, aq_acquire, aq_inner, aq_parent, aq_base ...@@ -96,6 +96,7 @@ from Acquisition import aq_get, aq_acquire, aq_inner, aq_parent, aq_base
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from AccessControl.Role import _isBeingUsedAsAMethod from AccessControl.Role import _isBeingUsedAsAMethod
from AccessControl import Unauthorized
ZCM_MANAGERS = '__ZCacheManager_ids__' ZCM_MANAGERS = '__ZCacheManager_ids__'
...@@ -585,7 +586,7 @@ class CacheManager: ...@@ -585,7 +586,7 @@ class CacheManager:
path = key[10:] path = key[10:]
ob = parent.restrictedTraverse(path) ob = parent.restrictedTraverse(path)
if not sm.checkPermission('Change cache settings', ob): if not sm.checkPermission('Change cache settings', ob):
raise 'Unauthorized' raise Unauthorized
if not isCacheable(ob): if not isCacheable(ob):
# Not a cacheable object. # Not a cacheable object.
continue continue
......
...@@ -83,7 +83,7 @@ ...@@ -83,7 +83,7 @@
# #
############################################################################## ##############################################################################
__doc__="""Copy interface""" __doc__="""Copy interface"""
__version__='$Revision: 1.74 $'[11:-2] __version__='$Revision: 1.75 $'[11:-2]
import sys, string, Globals, Moniker, tempfile, ExtensionClass import sys, string, Globals, Moniker, tempfile, ExtensionClass
from marshal import loads, dumps from marshal import loads, dumps
...@@ -410,9 +410,9 @@ class CopyContainer(ExtensionClass.Base): ...@@ -410,9 +410,9 @@ class CopyContainer(ExtensionClass.Base):
except: parent=None except: parent=None
if getSecurityManager().validate(None, parent, None, object): if getSecurityManager().validate(None, parent, None, object):
return return
raise 'Unauthorized', absattr(object.id) raise Unauthorized, absattr(object.id)
else: else:
raise 'Unauthorized', mt_permission raise Unauthorized(permission=mt_permission)
# #
# XXX: Ancient cruft, left here in true co-dependent fashion # XXX: Ancient cruft, left here in true co-dependent fashion
# to keep from breaking old products which don't put # to keep from breaking old products which don't put
...@@ -434,9 +434,9 @@ class CopyContainer(ExtensionClass.Base): ...@@ -434,9 +434,9 @@ class CopyContainer(ExtensionClass.Base):
except: parent=None except: parent=None
if getSecurityManager().validate(None, parent, None, object): if getSecurityManager().validate(None, parent, None, object):
return return
raise 'Unauthorized', absattr(object.id) raise Unauthorized, absattr(object.id)
else: else:
raise 'Unauthorized', method_name raise Unauthorized, method_name
raise CopyError, MessageDialog( raise CopyError, MessageDialog(
title='Not Supported', title='Not Supported',
......
...@@ -87,13 +87,14 @@ ...@@ -87,13 +87,14 @@
Folders are the basic container objects and are analogous to directories. Folders are the basic container objects and are analogous to directories.
$Id: Folder.py,v 1.95 2001/10/15 14:38:13 evan Exp $""" $Id: Folder.py,v 1.96 2001/10/19 15:12:26 shane Exp $"""
__version__='$Revision: 1.95 $'[11:-2] __version__='$Revision: 1.96 $'[11:-2]
import Globals, SimpleItem, ObjectManager, PropertyManager import Globals, SimpleItem, ObjectManager, PropertyManager
import AccessControl.Role, webdav.Collection, FindSupport import AccessControl.Role, webdav.Collection, FindSupport
from webdav.WriteLockInterface import WriteLockInterface from webdav.WriteLockInterface import WriteLockInterface
from AccessControl import Unauthorized
from Globals import DTMLFile from Globals import DTMLFile
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
...@@ -121,14 +122,14 @@ def manage_addFolder(self, id, title='', ...@@ -121,14 +122,14 @@ def manage_addFolder(self, id, title='',
if createUserF: if createUserF:
if not checkPermission('Add User Folders', ob): if not checkPermission('Add User Folders', ob):
raise 'Unauthorized', ( raise Unauthorized, (
'You are not authorized to add User Folders.' 'You are not authorized to add User Folders.'
) )
ob.manage_addUserFolder() ob.manage_addUserFolder()
if createPublic: if createPublic:
if not checkPermission('Add Page Templates', ob): if not checkPermission('Add Page Templates', ob):
raise 'Unauthorized', ( raise Unauthorized, (
'You are not authorized to add Page Templates.' 'You are not authorized to add Page Templates.'
) )
ob.manage_addProduct['PageTemplates'].manage_addPageTemplate( ob.manage_addProduct['PageTemplates'].manage_addPageTemplate(
......
...@@ -84,12 +84,13 @@ ...@@ -84,12 +84,13 @@
############################################################################## ##############################################################################
'''This module implements a mix-in for traversable objects. '''This module implements a mix-in for traversable objects.
$Id: Traversable.py,v 1.11 2001/09/11 14:31:25 evan Exp $''' $Id: Traversable.py,v 1.12 2001/10/19 15:12:26 shane Exp $'''
__version__='$Revision: 1.11 $'[11:-2] __version__='$Revision: 1.12 $'[11:-2]
from Acquisition import Acquired, aq_inner, aq_parent, aq_base from Acquisition import Acquired, aq_inner, aq_parent, aq_base
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from AccessControl import Unauthorized
from string import split, join from string import split, join
from urllib import quote from urllib import quote
...@@ -165,7 +166,7 @@ class Traversable: ...@@ -165,7 +166,7 @@ class Traversable:
pop() pop()
self=self.getPhysicalRoot() self=self.getPhysicalRoot()
if (restricted and not securityManager.validateValue(self)): if (restricted and not securityManager.validateValue(self)):
raise 'Unauthorized', name raise Unauthorized, name
try: try:
object = self object = self
...@@ -181,7 +182,7 @@ class Traversable: ...@@ -181,7 +182,7 @@ class Traversable:
if o is not M: if o is not M:
if (restricted and not securityManager.validate( if (restricted and not securityManager.validate(
object, object,name, o)): object, object,name, o)):
raise 'Unauthorized', name raise Unauthorized, name
object=o object=o
continue continue
...@@ -198,7 +199,7 @@ class Traversable: ...@@ -198,7 +199,7 @@ class Traversable:
container = object container = object
if (not securityManager.validate(object, if (not securityManager.validate(object,
container, name, o)): container, name, o)):
raise 'Unauthorized', name raise Unauthorized, name
else: else:
o=get(object, name, M) o=get(object, name, M)
...@@ -209,17 +210,17 @@ class Traversable: ...@@ -209,17 +210,17 @@ class Traversable:
# value wasn't acquired # value wasn't acquired
if not securityManager.validate( if not securityManager.validate(
object, object, name, o): object, object, name, o):
raise 'Unauthorized', name raise Unauthorized, name
else: else:
if not securityManager.validate( if not securityManager.validate(
object, N, name, o): object, N, name, o):
raise 'Unauthorized', name raise Unauthorized, name
else: else:
o=object[name] o=object[name]
if (restricted and not securityManager.validate( if (restricted and not securityManager.validate(
object, object, N, o)): object, object, N, o)):
raise 'Unauthorized', name raise Unauthorized, name
object=o object=o
......
...@@ -84,12 +84,13 @@ ...@@ -84,12 +84,13 @@
############################################################################## ##############################################################################
'''CGI Response Output formatter '''CGI Response Output formatter
$Id: BaseResponse.py,v 1.8 2001/04/26 14:40:07 andreas Exp $''' $Id: BaseResponse.py,v 1.9 2001/10/19 15:12:27 shane Exp $'''
__version__='$Revision: 1.8 $'[11:-2] __version__='$Revision: 1.9 $'[11:-2]
import string, types, sys import string, types, sys
from string import find, rfind, lower, upper, strip, split, join, translate from string import find, rfind, lower, upper, strip, split, join, translate
from types import StringType, InstanceType from types import StringType, InstanceType
from zExceptions import Unauthorized
class BaseResponse: class BaseResponse:
"""Base Response Class """Base Response Class
...@@ -226,4 +227,4 @@ class BaseResponse: ...@@ -226,4 +227,4 @@ class BaseResponse:
Make sure to generate an appropriate challenge, as appropriate. Make sure to generate an appropriate challenge, as appropriate.
""" """
raise 'Unauthorized' raise Unauthorized
...@@ -84,13 +84,14 @@ ...@@ -84,13 +84,14 @@
############################################################################## ##############################################################################
'''CGI Response Output formatter '''CGI Response Output formatter
$Id: HTTPResponse.py,v 1.48 2001/08/07 18:36:48 evan Exp $''' $Id: HTTPResponse.py,v 1.49 2001/10/19 15:12:27 shane Exp $'''
__version__='$Revision: 1.48 $'[11:-2] __version__='$Revision: 1.49 $'[11:-2]
import string, types, sys, re import string, types, sys, re
from string import find, rfind, lower, upper, strip, split, join, translate from string import find, rfind, lower, upper, strip, split, join, translate
from types import StringType, InstanceType, LongType from types import StringType, InstanceType, LongType
from BaseResponse import BaseResponse from BaseResponse import BaseResponse
from zExceptions import Unauthorized
nl2sp=string.maketrans('\n',' ') nl2sp=string.maketrans('\n',' ')
...@@ -578,7 +579,7 @@ class HTTPResponse(BaseResponse): ...@@ -578,7 +579,7 @@ class HTTPResponse(BaseResponse):
m=m+'<p>\nUsername and password are not correct.' m=m+'<p>\nUsername and password are not correct.'
else: else:
m=m+'<p>\nNo Authorization header found.' m=m+'<p>\nNo Authorization header found.'
raise 'Unauthorized', m raise Unauthorized, m
def exception(self, fatal=0, info=None, def exception(self, fatal=0, info=None,
absuri_match=re.compile(r'\w+://[\w\.]+').match, absuri_match=re.compile(r'\w+://[\w\.]+').match,
...@@ -588,7 +589,11 @@ class HTTPResponse(BaseResponse): ...@@ -588,7 +589,11 @@ class HTTPResponse(BaseResponse):
if type(info) is type(()) and len(info)==3: t,v,tb = info if type(info) is type(()) and len(info)==3: t,v,tb = info
else: t,v,tb = sys.exc_info() else: t,v,tb = sys.exc_info()
if str(t)=='Unauthorized': self._unauthorized() if t=='Unauthorized' or t == Unauthorized or (
isinstance(t, types.ClassType) and issubclass(t, Unauthorized)
):
t = 'Unauthorized'
self._unauthorized()
stb=tb stb=tb
......
...@@ -85,7 +85,7 @@ ...@@ -85,7 +85,7 @@
"""WebDAV support - null resource objects.""" """WebDAV support - null resource objects."""
__version__='$Revision: 1.32 $'[11:-2] __version__='$Revision: 1.33 $'[11:-2]
import sys, os, string, mimetypes, Globals, davcmds import sys, os, string, mimetypes, Globals, davcmds
import Acquisition, OFS.content_types import Acquisition, OFS.content_types
...@@ -96,6 +96,7 @@ from Resource import Resource ...@@ -96,6 +96,7 @@ from Resource import Resource
from Globals import Persistent, DTMLFile from Globals import Persistent, DTMLFile
from WriteLockInterface import WriteLockInterface from WriteLockInterface import WriteLockInterface
import OFS.SimpleItem import OFS.SimpleItem
from zExceptions import Unauthorized
class NullResource(Persistent, Acquisition.Implicit, Resource): class NullResource(Persistent, Acquisition.Implicit, Resource):
"""Null resources are used to handle HTTP method calls on """Null resources are used to handle HTTP method calls on
...@@ -179,8 +180,8 @@ class NullResource(Persistent, Acquisition.Implicit, Resource): ...@@ -179,8 +180,8 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
# check the clipboard. # check the clipboard.
try: try:
parent._verifyObjectPaste(ob.__of__(parent), 0) parent._verifyObjectPaste(ob.__of__(parent), 0)
except 'Unauthorized': except Unauthorized:
raise 'Unauthorized', sys.exc_info()[1] raise
except: except:
raise 'Forbidden', sys.exc_info()[1] raise 'Forbidden', sys.exc_info()[1]
...@@ -429,8 +430,8 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__): ...@@ -429,8 +430,8 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
# Verify that the user can create this type of object # Verify that the user can create this type of object
try: try:
parent._verifyObjectPaste(ob.__of__(parent), 0) parent._verifyObjectPaste(ob.__of__(parent), 0)
except 'Unauthorized': except Unauthorized:
raise 'Unauthorized', sys.exc_info()[1] raise
except: except:
raise 'Forbidden', sys.exc_info()[1] raise 'Forbidden', sys.exc_info()[1]
......
...@@ -85,7 +85,7 @@ ...@@ -85,7 +85,7 @@
"""WebDAV support - resource objects.""" """WebDAV support - resource objects."""
__version__='$Revision: 1.47 $'[11:-2] __version__='$Revision: 1.48 $'[11:-2]
import sys, os, string, mimetypes, davcmds, ExtensionClass, Lockable import sys, os, string, mimetypes, davcmds, ExtensionClass, Lockable
from common import absattr, aq_base, urlfix, rfc1123_date, tokenFinder, urlbase from common import absattr, aq_base, urlfix, rfc1123_date, tokenFinder, urlbase
...@@ -95,6 +95,7 @@ from AccessControl import getSecurityManager ...@@ -95,6 +95,7 @@ from AccessControl import getSecurityManager
from WriteLockInterface import WriteLockInterface from WriteLockInterface import WriteLockInterface
import Globals, time import Globals, time
from ZPublisher.HTTPRangeSupport import HTTPRangeInterface from ZPublisher.HTTPRangeSupport import HTTPRangeInterface
from zExceptions import Unauthorized
class Resource(ExtensionClass.Base, Lockable.LockableItem): class Resource(ExtensionClass.Base, Lockable.LockableItem):
"""The Resource mixin class provides basic WebDAV support for """The Resource mixin class provides basic WebDAV support for
...@@ -155,7 +156,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem): ...@@ -155,7 +156,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
method) method)
except: pass except: pass
raise 'Unauthorized', msg raise Unauthorized, msg
def dav__simpleifhandler(self, request, response, method='PUT', def dav__simpleifhandler(self, request, response, method='PUT',
col=0, url=None, refresh=0): col=0, url=None, refresh=0):
...@@ -394,8 +395,8 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem): ...@@ -394,8 +395,8 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
try: parent._checkId(name, allow_dup=1) try: parent._checkId(name, allow_dup=1)
except: raise 'Forbidden', sys.exc_info()[1] except: raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self) try: parent._verifyObjectPaste(self)
except 'Unauthorized': except Unauthorized:
raise 'Unauthorized', sys.exc_info()[1] raise
except: raise 'Forbidden', sys.exc_info()[1] except: raise 'Forbidden', sys.exc_info()[1]
# Now check locks. The If header on a copy only cares about the # Now check locks. The If header on a copy only cares about the
...@@ -483,8 +484,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem): ...@@ -483,8 +484,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
except: except:
raise 'Forbidden', sys.exc_info()[1] raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self) try: parent._verifyObjectPaste(self)
except 'Unauthorized': except Unauthorized: raise
raise 'Unauthorized', sys.exc_info()[1]
except: raise 'Forbidden', sys.exc_info()[1] except: raise 'Forbidden', sys.exc_info()[1]
# Now check locks. Since we're affecting the resource that we're # Now check locks. Since we're affecting the resource that we're
......
...@@ -82,172 +82,12 @@ ...@@ -82,172 +82,12 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
__doc__='''Define Zope\'s default security policy """General exceptions that wish they were standard exceptions
These exceptions are so general purpose that they don't belong in Zope
application-specific packages.
$Id: pZopeSecurityPolicy.py,v 1.1 2001/08/08 15:57:49 matt Exp $''' $Id: __init__.py,v 1.2 2001/10/19 15:12:28 shane Exp $
__version__='$Revision: 1.1 $'[11:-2] """
from types import StringType from unauthorized import Unauthorized
import SimpleObjectPolicies
from AccessControl import Unauthorized
_noroles=SimpleObjectPolicies._noroles
from zLOG import LOG, PROBLEM
from Acquisition import aq_base
from PermissionRole import _what_not_even_god_should_do, rolesForPermissionOn
class ZopeSecurityPolicy:
def validate(self, accessed, container, name, value, context,
roles=_noroles, None=None, type=type, IntType=type(0),
DictType=type({}), getattr=getattr, _noroles=_noroles,
StringType=type(''),
Containers=SimpleObjectPolicies.Containers,
valid_aq_=('aq_parent','aq_explicit')):
############################################################
# Provide special rules for the acquisition attributes
if type(name) is StringType:
if name[:3]=='aq_' and name not in valid_aq_:
return 0
containerbase = aq_base(container)
accessedbase=getattr(accessed, 'aq_base', container)
############################################################
# If roles weren't passed in, we'll try to get them from the object
if roles is _noroles:
roles=getattr(value, '__roles__', _noroles)
############################################################
# We still might not have any roles
if roles is _noroles:
############################################################
# We have an object without roles and we didn't get a list
# of roles passed in. Presumably, the value is some simple
# object like a string or a list. We'll try to get roles
# from its container.
if container is None: return 0 # Bail if no container
roles=getattr(container, '__roles__', _noroles)
if roles is _noroles:
aq=getattr(container, 'aq_acquire', None)
if aq is None:
roles=_noroles
if containerbase is not accessedbase: return 0
else:
# Try to acquire roles
try: roles=aq('__roles__')
except AttributeError:
roles=_noroles
if containerbase is not accessedbase: return 0
# We need to make sure that we are allowed to
# get unprotected attributes from the container. We are
# allowed for certain simple containers and if the
# container says we can. Simple containers
# may also impose name restrictions.
p=Containers(type(container), None)
if p is None:
p=getattr(container,
'__allow_access_to_unprotected_subobjects__', None)
if p is not None:
tp=type(p)
if tp is not IntType:
if tp is DictType:
p=p.get(name, None)
else:
p=p(name, value)
if not p:
if (containerbase is accessedbase):
raise Unauthorized, cleanupName(name, value)
else:
return 0
if roles is _noroles: return 1
# We are going to need a security-aware object to pass
# to allowed(). We'll use the container.
value=container
# Short-circuit tests if we can:
try:
if roles is None or 'Anonymous' in roles: return 1
except TypeError:
# 'roles' isn't a sequence
LOG('Zope Security Policy', PROBLEM, "'%s' passed as roles"
" during validation of '%s' is not a sequence." % (
`roles`, name))
raise
# Check executable security
stack=context.stack
if stack:
eo=stack[-1]
# If the executable had an owner, can it execute?
owner=eo.getOwner()
if (owner is not None) and not owner.allowed(value, roles):
# We don't want someone to acquire if they can't
# get an unacquired!
if accessedbase is containerbase:
raise Unauthorized, (
'You are not authorized to access <em>%s</em>.' \
% cleanupName(name, value))
return 0
# Proxy roles, which are a lot safer now.
proxy_roles=getattr(eo, '_proxy_roles', None)
if proxy_roles:
for r in proxy_roles:
if r in roles: return 1
# Proxy roles actually limit access!
if accessedbase is containerbase:
raise Unauthorized, (
'You are not authorized to access <em>%s</em>.' \
% cleanupName(name, value))
return 0
try:
if context.user.allowed(value, roles): return 1
except AttributeError: pass
# We don't want someone to acquire if they can't get an unacquired!
if accessedbase is containerbase:
raise Unauthorized, (
'You are not authorized to access <em>%s</em>.' \
% cleanupName(name, value))
return 0
def checkPermission(self, permission, object, context):
roles=rolesForPermissionOn(permission, object)
if type(roles) is StringType:
roles=[roles]
return context.user.allowed(object, roles)
def cleanupName(name, value):
# If name is not available, tries to get it from the value.
_name = name
if _name is None and value is not None:
try: _name = value.id
except:
try: _name = value.__name__
except: pass
if callable(_name):
try: _name = _name()
except: pass
return _name
...@@ -82,178 +82,57 @@ ...@@ -82,178 +82,57 @@
# attributions are listed in the accompanying credits file. # attributions are listed in the accompanying credits file.
# #
############################################################################## ##############################################################################
__doc__='''Objects that implement Permission-based roles. """
$Id: unauthorized.py,v 1.2 2001/10/19 15:12:28 shane Exp $
"""
$Id: pPermissionRole.py,v 1.1 2001/08/08 15:57:49 matt Exp $'''
__version__='$Revision: 1.1 $'[11:-2] class Unauthorized(Exception):
"""Some user wasn't allowed to access a resource"""
import sys
def __init__(self, message=None, value=None, needed=None, name=None, **kw):
from ExtensionClass import Base """Possible signatures:
import string Unauthorized()
Unauthorized(message) # Note that message includes a space
name_trans=filter(lambda c, an=string.letters+string.digits+'_': c not in an, Unauthorized(name)
map(chr,range(256))) Unauthorized(name, value)
name_trans=string.maketrans(string.join(name_trans,''), '_'*len(name_trans)) Unauthorized(name, value, needed)
Unauthorized(message, value, needed, name)
def rolesForPermissionOn(perm, object, default=('Manager',)):
"""Return the roles that have the given permission on the given object Where needed is a mapping objects with items represnting requirements
(e.g. {'permission': 'add spam'}). Any extra keyword arguments
provides are added to needed.
""" """
im=imPermissionRole() if name is None and message is not None and len(message.split()) <= 1:
im._p='_'+string.translate(perm, name_trans)+"_Permission" # First arg is a name, not a message
im._d=default name=message
return im.__of__(object) message=None
self.name=name
class PermissionRole(Base): self.message=message
"""Implement permission-based roles. self.value=value
Under normal circumstances, our __of__ method will be if kw:
called with an unwrapped object. The result will then be called if needed: needed.update(kw)
with a wrapped object, if the original object was wrapped. else: needed=kw
To deal with this, we have to create an intermediate object.
self.needed=needed
"""
def __str__(self):
def __init__(self, name, default=('Manager',)): if self.message is not None: return self.message
self.__name__=name if self.name is not None:
self._p='_'+string.translate(name,name_trans)+"_Permission" return ("You are not allowed to access %s in this context"
self._d=default % self.name)
elif self.value is not None:
def __of__(self, parent, None=None, getattr=getattr): return ("You are not allowed to access %s in this context"
r=imPermissionRole() % self.getValueName(self.value))
r._p=self._p
r._pa=parent
r._d=self._d def getValueName(self):
p=getattr(parent, 'aq_inner', None) v=self.value
if p is not None: vname=getattr(v, '__name__', None)
return r.__of__(p) if vname: return vname
else: c = getattr(v, '__class__', type(v))
return r c = getattr(c, '__name__', 'object')
return "a particular %s" % c
# This is used when a permission maps explicitly to no permission.
_what_not_even_god_should_do=[]
class imPermissionRole(Base):
"""Implement permission-based roles
"""
def __of__(self, parent,tt=type(()),st=type(''),getattr=getattr,None=None):
obj=parent
n=self._p
r=None
while 1:
if hasattr(obj,n):
roles=getattr(obj, n)
if roles is None: return 'Anonymous',
t=type(roles)
if t is tt:
# If we get a tuple, then we don't acquire
if r is None: return roles
return r+list(roles)
if t is st:
# We found roles set to a name. Start over
# with the new permission name. If the permission
# name is '', then treat as private!
if roles:
if roles != n:
n=roles
# If we find a name that is the same as the
# current name, we just ignore it.
roles=None
else:
return _what_not_even_god_should_do
elif roles:
if r is None: r=list(roles)
else: r=r+list(roles)
obj=getattr(obj, 'aq_inner', None)
if obj is None: break
obj=obj.aq_parent
if r is None: r=self._d
return r
# The following methods are needed in the unlikely case that an unwrapped
# object is accessed:
def __getitem__(self, i):
try:
v=self._v
except:
v=self._v=self.__of__(self._pa)
del self._pa
return v[i]
def __len__(self):
try:
v=self._v
except:
v=self._v=self.__of__(self._pa)
del self._pa
return len(v)
##############################################################################
# Test functions:
#
def main():
# The "main" program for this module
import sys
sys.path.append('/projects/_/ExtensionClass')
from Acquisition import Implicit
class I(Implicit):
x__roles__=PermissionRole('x')
y__roles__=PermissionRole('y')
z__roles__=PermissionRole('z')
def x(self): pass
def y(self): pass
def z(self): pass
a=I()
a.b=I()
a.b.c=I()
a.q=I()
a.q._x_Permission=('foo',)
a._y_Permission=('bar',)
a._z_Permission=('zee',)
a.b.c._y_Permission=('Manage',)
a.b._z_Permission=['also']
print a.x.__roles__, list(a.x.__roles__)
print a.b.x.__roles__
print a.b.c.x.__roles__
print a.q.x.__roles__
print a.b.q.x.__roles__
print a.b.c.q.x.__roles__
print
print a.y.__roles__, list(a.y.__roles__)
print a.b.y.__roles__
print a.b.c.y.__roles__
print a.q.y.__roles__
print a.b.q.y.__roles__
print a.b.c.q.y.__roles__
print
print a.z.__roles__, list(a.z.__roles__)
print a.b.z.__roles__
print a.b.c.z.__roles__
print a.q.z.__roles__
print a.b.q.z.__roles__
print a.b.c.q.z.__roles__
print
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