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 @@
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
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,
contact:
......@@ -77,15 +77,13 @@ typedef struct {
static ACQUISITIONCAPI *AcquisitionCAPI = NULL;
#define aq_init() { \
PyObject *module; \
PyObject *api; \
if ((module = PyImport_ImportModule("Acquisition")) == NULL) \
Py_FatalError("Acquisition CAPI failed to load Acquisition"); \
if ((api = PyObject_GetAttrString(module,"AcquisitionCAPI")) \
== NULL) Py_FatalError("Acquisition CAPI failed to load AcquistionCAPI"); \
Py_DECREF(module); \
AcquisitionCAPI = PyCObject_AsVoidPtr(api); \
Py_DECREF(api); \
PyObject *module; \
PyObject *api; \
if (! (module = PyImport_ImportModule("Acquisition"))) return; \
if (! (api = PyObject_GetAttrString(module,"AcquisitionCAPI"))) return; \
Py_DECREF(module); \
AcquisitionCAPI = PyCObject_AsVoidPtr(api); \
Py_DECREF(api); \
}
......
......@@ -85,19 +85,139 @@
__doc__='''Objects that implement Permission-based roles.
$Id: PermissionRole.py,v 1.11 2001/10/17 22:01:43 tseaver Exp $'''
__version__='$Revision: 1.11 $'[11:-2]
if 0: # cAccessControl is not working
import cAccessControl
rolesForPermissionOn=cAccessControl.rolesForPermissionOn
PermissionRole=cAccessControl.PermissionRole
imPermissionRole=cAccessControl.imPermissionRole
_what_not_even_god_should_do= cAccessControl._what_not_even_god_should_do
$Id: PermissionRole.py,v 1.12 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.12 $'[11:-2]
_use_python_impl = 0
import os
if os.environ.get("ZOPE_SECURITY_POLICY", None) == "PYTHON":
_use_python_impl = 1
else:
import pPermissionRole
from pPermissionRole import rolesForPermissionOn, PermissionRole
from pPermissionRole import imPermissionRole, _what_not_even_god_should_do
try:
# C Optimization:
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:
......
......@@ -85,8 +85,8 @@
__doc__='''short description
$Id: SecurityManager.py,v 1.6 2001/10/01 21:03:15 matt Exp $'''
__version__='$Revision: 1.6 $'[11:-2]
$Id: SecurityManager.py,v 1.7 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.7 $'[11:-2]
import ZopeSecurityPolicy, os, string
......@@ -145,8 +145,12 @@ class SecurityManager:
"""
policy=self._policy
if policy is None: policy=_defaultPolicy
return policy.validate(accessed, container, name, value,
self._context, roles)
if roles is _noroles:
return policy.validate(accessed, container, name, value,
self._context)
else:
return policy.validate(accessed, container, name, value,
self._context, roles)
def DTMLValidate(self, accessed=None, container=None, name=None,
value=None,md=None):
......@@ -175,15 +179,19 @@ class SecurityManager:
policy=self._policy
if policy is None: policy=_defaultPolicy
return policy.validate(accessed, container, name, value,
self._context, _noroles)
self._context)
def validateValue(self, value, roles=_noroles):
"""Convenience for common case of simple value validation.
"""
policy=self._policy
if policy is None: policy=_defaultPolicy
return policy.validate(None, None, None, value,
self._context, roles)
if roles is _noroles:
return policy.validate(None, None, None, value,
self._context)
else:
return policy.validate(None, None, None, value,
self._context, roles)
def checkPermission(self, permission, object):
"""Check whether the security context allows the given permission on
......
......@@ -84,7 +84,7 @@
##############################################################################
"""Access control package"""
__version__='$Revision: 1.159 $'[11:-2]
__version__='$Revision: 1.160 $'[11:-2]
import Globals, socket, SpecialUsers,re
import os
......@@ -98,7 +98,8 @@ from App.ImageFile import ImageFile
from Role import RoleManager, DEFAULTMAXLISTUSERS
from PermissionRole import _what_not_even_god_should_do, rolesForPermissionOn
import AuthEncoding
from AccessControl import getSecurityManager, Unauthorized
from AccessControl import getSecurityManager
from zExceptions import Unauthorized
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.ZopeSecurityPolicy import _noroles
......
......@@ -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, \
full_write_guard
......@@ -91,8 +91,7 @@ from RestrictedPython.Utilities import utility_builtins
from SecurityManagement import getSecurityManager
from SecurityInfo import secureModule
from SimpleObjectPolicies import Containers
Unauthorized = 'Unauthorized'
from zExceptions import Unauthorized
_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
if 0: # cAccessControl is not working
import cAccessControl
$Id: ZopeSecurityPolicy.py,v 1.14 2001/10/19 15:12:25 shane Exp $'''
__version__='$Revision: 1.14 $'[11:-2]
ZopeSecurityPolicy = cAccessControl.ZopeSecurityPolicy
_use_python_impl = 0
import os
if os.environ.get("ZOPE_SECURITY_POLICY", None) == "PYTHON":
_use_python_impl = 1
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 @@
#
##############################################################################
Unauthorized = 'Unauthorized'
from unauthorized import Unauthorized
import DTML
del DTML
......
......@@ -36,7 +36,7 @@
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
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,
contact:
......@@ -53,13 +53,50 @@
#include "ExtensionClass.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))
#ifdef win32
#define PUBLIC
#else
#define PUBLIC
#endif
static PyObject *
callmethod1(PyObject *self, PyObject *name, PyObject *arg)
{
UNLESS(self = PyObject_GetAttr(self,name)) return NULL;
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
......@@ -84,23 +121,6 @@ typedef struct {
PyObject *_v;
} 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
*/
......@@ -111,32 +131,22 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *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_of(PermissionRole *self, PyObject *args);
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 int imPermissionRole_length(imPermissionRole *self);
static PyObject *imPermissionRole_getitem(imPermissionRole *self,
PyObject *item);
static PyObject *imPermissionRole_get(imPermissionRole *self,
int item);
static void imPermissionRole_dealloc(imPermissionRole *self);
static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args);
static PyObject *c_rolesForPermissionOn(PyObject *self, PyObject *perm,
PyObject *object, PyObject *deflt);
static PyObject *permissionName(PyObject *name);
#if ZSPCACHE
static ZSPCacheLine ZSPCache[ZSPCACHEENTRIES];
#endif
/*
** Constants
*/
......@@ -228,8 +238,8 @@ static PyExtensionClass PermissionRoleType = {
/* Standard methods */
(destructor) PermissionRole_dealloc, /* tp_dealloc */
NULL, /* tp_print */
(getattrfunc) PermissionRole_getattr, /* tp_getattr */
(setattrfunc) PermissionRole_setattr, /* tp_setattr */
NULL, /* tp_getattr */
NULL, /* tp_setattr */
NULL, /* tp_compare */
NULL, /* tp_repr */
/* Method suites */
......@@ -285,13 +295,6 @@ static PySequenceMethods imSequenceMethods = {
(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 = {
PyObject_HEAD_INIT(NULL) 0,
"imPermissionRole", /* tp_name */
......@@ -300,14 +303,14 @@ static PyExtensionClass imPermissionRoleType = {
/* Standard methods */
(destructor) imPermissionRole_dealloc, /* tp_dealloc */
NULL, /* tp_print */
(getattrfunc) imPermissionRole_getattr, /* tp_getattr */
(setattrfunc) imPermissionRole_setattr, /* tp_setattr */
NULL, /* tp_getattr */
NULL, /* tp_setattr */
NULL, /* tp_compare */
NULL, /* tp_repr */
/* Method suites */
NULL, /* tp_as_number */
&imSequenceMethods, /* tp_as_sequence*/
&imMappingMethods, /* tp_as_mapping */
NULL, /* tp_as_mapping */
/* More standard ops */
NULL, /* tp_hash */
NULL, /* tp_call */
......@@ -326,11 +329,7 @@ static PyExtensionClass imPermissionRoleType = {
NULL, /* tp_next */
#endif
METHOD_CHAIN(imPermissionRole_methods), /* methods */
EXTENSIONCLASS_BINDABLE_FLAG/*|
EXTENSIONCLASS_INSTDICT_FLAG*/, /* flags */
NULL, /* Class dict */
NULL, /* bases */
NULL, /* reserved */
EXTENSIONCLASS_BINDABLE_FLAG, /* flags */
};
......@@ -340,15 +339,23 @@ static PyExtensionClass imPermissionRoleType = {
*/
static PyObject *Containers = NULL;
static PyObject *_noroles = NULL;
static PyObject *Unauthorized = NULL;
static PyObject *LOG = NULL;
static PyObject *PROBLEM = NULL;
static PyObject *NoSequenceFormat = NULL;
static PyObject *_what_not_even_god_should_do = NULL;
static PyObject *Anonymous = NULL;
static PyObject *AnonymousTuple = NULL;
static PyObject *imPermissionRoleObj = NULL;
static PyObject *defaultPermission = 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
......@@ -361,44 +368,30 @@ static PyObject *__roles__ = NULL;
** elsewhere... (e.g. imports)
*/
static int ZopeSecurityPolicy_setup(void) {
PyObject *module;
#define IMPORT(module, name) if ((module = PyImport_ImportModule(name)) == NULL) Py_FatalError("ZopeSecurityPolicy failed to load module " #name)
#define GETATTR(module, name) if ((name = PyObject_GetAttrString(module, #name)) == NULL) Py_FatalError("ZopeSecurity policy failed to load attribute " #name)
/*| from SimpleObjectPolicies import Containers, _noroles
*/
IMPORT(module, "AccessControl.SimpleObjectPolicies");
GETATTR(module, Containers);
GETATTR(module, _noroles);
Py_DECREF(module);
module = NULL;
/*| from AccessControl import Unauthorized
*/
IMPORT(module, "AccessControl");
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;
defaultPermission = Py_BuildValue("(s)", "Manager");
_what_not_even_god_should_do = Py_BuildValue("[]");
__roles__ = PyString_FromString("__roles__");
return 1;
static int
ZopeSecurityPolicy_setup(void) {
UNLESS (NoSequenceFormat = PyString_FromString(
"'%s' passed as roles"
" during validation of '%s' is not a sequence."
)) return -1;
UNLESS (defaultPermission = Py_BuildValue("(s)", "Manager")) return -1;
UNLESS (_what_not_even_god_should_do = Py_BuildValue("[]")) return -1;
UNLESS (__roles__ = PyString_FromString("__roles__")) return -1;
UNLESS (__of__ = PyString_FromString("__of__")) return -1;
UNLESS (Anonymous = PyString_FromString("Anonymous")) return -1;
UNLESS (AnonymousTuple = Py_BuildValue("(s)", "Anonymous")) return -1;
UNLESS (stack_str = PyString_FromString("stack")) return -1;
UNLESS (user_str = PyString_FromString("user")) return -1;
UNLESS (_proxy_roles_str = PyString_FromString("_proxy_roles"))
return -1;
UNLESS (allowed_str = PyString_FromString("allowed")) return -1;
UNLESS (getOwner_str = PyString_FromString("getOwner")) return -1;
UNLESS (__allow_access_to_unprotected_subobjects__ =
PyString_FromString(
"__allow_access_to_unprotected_subobjects__"))
return -1;
return 0;
}
/*
......@@ -409,206 +402,15 @@ static int ZopeSecurityPolicy_setup(void) {
static void unauthErr(PyObject *name, PyObject *value) {
char msgbuff[512];
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);
PyObject *v;
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 ((v=Py_BuildValue("OO", name, value)))
{
PyErr_SetObject(Unauthorized, v);
Py_DECREF(v);
}
}
#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;
}
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
*/
......@@ -619,17 +421,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
PyObject *name = NULL;
PyObject *value = 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 *accessedbase = NULL;
PyObject *p = NULL;
PyObject *rval = NULL;
PyObject *stack = NULL;
PyObject *user = NULL;
#if ZSPCACHE
PyObject *iroles = NULL;
PyObject *ivalue = NULL;
#endif
char *sname;
......@@ -640,8 +441,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
if (!PyArg_ParseTuple(args, "OOOOO|O", &accessed, &container,
&name, &value, &context, &roles)) return NULL;
Py_XINCREF(roles); /* Convert the borrowed ref to a real one */
/*| # Provide special rules for acquisition attributes
**| if type(name) is StringType:
**| if name[:3] == 'aq_' and name not in valid_aq_:
......@@ -649,18 +448,18 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
*/
if (PyString_Check(name)) { /* XXX what about unicode? */
sname = PyString_AsString(name);
if (strncmp(sname,"aq_", 4) == 0) {
if (!strncmp(sname,"aq_parent", 10) &&
!strncmp(sname,"aq_explicit", 12)) {
sname = PyString_AS_STRING(name);
if (*sname == 'a' && sname[1]=='q' && sname[2]=='_') {
if (strcmp(sname,"aq_parent") != 0 &&
strcmp(sname,"aq_explicit") != 0) {
/* Access control violation, return 0 */
rval = PyInt_FromLong(0);
goto err;
return PyInt_FromLong(0);
}
}
}
Py_XINCREF(roles); /* Convert the borrowed ref to a real one */
/*| containerbase = aq_base(container)
**| accessedbase = getattr(accessed, 'aq_base', container)
*/
......@@ -675,20 +474,6 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
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
**| # the object
**|
......@@ -696,14 +481,10 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| roles = getattr(value, "__roles__", _noroles)
*/
if (roles == NULL || roles == _noroles) {
Py_XDECREF(roles);
roles = PyObject_GetAttr(value, __roles__);
if (roles == NULL) {
PyErr_Clear();
Py_INCREF(_noroles);
roles = _noroles;
}
if (roles == NULL) {
roles = PyObject_GetAttr(value, __roles__);
if (roles == NULL)
PyErr_Clear();
}
/*| # We still might not have any roles
......@@ -711,7 +492,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| if roles is _noroles:
*/
if (roles == _noroles) {
if (roles == NULL) {
/*| # We have an object without roles and we didn't get
**| # a list of roles passed in. Presumably, the value
......@@ -739,38 +520,30 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| roles = _noroles
**| if containerbase is not accessedbase: return 0
*/
Py_XDECREF(roles);
roles = PyObject_GetAttr(container, __roles__);
roles = PyObject_GetAttr(container, __roles__);
if (roles == NULL) {
PyErr_Clear();
Py_INCREF(_noroles);
roles = _noroles;
}
if (roles == _noroles) {
if (aq_isWrapper(container) != 1) {
Py_DECREF(roles);
if (!aq_isWrapper(container)) {
if (containerbase != accessedbase) {
rval = PyInt_FromLong(0);
goto err;
}
Py_INCREF(_noroles);
roles = _noroles;
} else {
Py_DECREF(roles);
}
else {
roles = aq_acquire(container, __roles__);
if (roles == NULL) {
/* XXX not JUST AttributeError*/
/* XXX should we clear the error? */
if (PyErr_ExceptionMatches(
PyExc_AttributeError))
{
PyErr_Clear();
if (containerbase != accessedbase) {
rval = PyInt_FromLong(0);
goto err;
}
Py_INCREF(_noroles);
roles = _noroles;
}
else
goto err;
}
}
}
......@@ -788,20 +561,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
*/
/** XXX do we need to incref this stuff? I dont think so */
p = PyObject_CallFunction(Containers, "OO",
container->ob_type, Py_None);
if (p == NULL) goto err;
p = callfunction2(Containers, OBJECT(container->ob_type),
Py_None);
if (p == NULL)
goto err;
if (p == Py_None) {
Py_DECREF(p);
p = PyObject_GetAttrString(container,
"__allow_access_to_unprotected_subobjects__");
if (p == NULL) {
PyErr_Clear();
Py_INCREF(Py_None);
p = Py_None;
}
ASSIGN(p, PyObject_GetAttr(container,
__allow_access_to_unprotected_subobjects__));
if (p == NULL)
PyErr_Clear();
}
/*| if p is not None:
......@@ -813,24 +582,16 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| p = p(name, value)
*/
if (p != Py_None) {
if (!PyInt_Check(p)) {
PyObject *temp;
if (p) {
if (! PyInt_Check(p)) {
if (PyDict_Check(p)) {
temp = PyObject_GetItem(p, name);
Py_DECREF(p);
if (temp == NULL) {
Py_INCREF(Py_None);
p = Py_None;
} else p = temp;
ASSIGN(p, PyObject_GetItem(p, name));
if (p == NULL)
PyErr_Clear();
} else {
temp = PyObject_CallFunction(p,
"OO", name, value);
Py_DECREF(p);
if (temp == NULL) {
goto err;
}
p = temp;
ASSIGN(p, callfunction2(p, name, value));
if (p == NULL)
goto err;
}
}
}
......@@ -841,23 +602,24 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| else:
**| return 0
*/
if (p == NULL || !PyObject_IsTrue(p)) {
if (p == NULL || ! PyObject_IsTrue(p)) {
Py_XDECREF(p);
if (containerbase == accessedbase) {
unauthErr(name, value);
goto err;
} else {
rval = PyInt_FromLong(0);
goto err;
}
}
else
Py_DECREF(p);
/*| if roles is _noroles: return 1
*/
if (roles == _noroles) {
if (roles == NULL) {
rval = PyInt_FromLong(1);
goto err;
}
......@@ -870,7 +632,7 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
value = container; /* Both are borrowed references */
} /* if (roles == _noroles) */
} /* if (roles == NULL) */
/*| # Short-circuit tests if we can
**| try:
......@@ -886,49 +648,40 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
rval = PyInt_FromLong(1);
goto err;
}
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 found = 0;
int pl;
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);
goto err;
}
}
}
else
{
int i;
i = PySequence_Contains(roles, Anonymous);
if (i > 0)
{
rval = PyInt_FromLong(1);
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;
}
}
/*| # Check executable security
**| stack = context.stack
**| if stack:
*/
stack = PyObject_GetAttrString(context, "stack");
stack = PyObject_GetAttr(context, stack_str);
if (stack == NULL) goto err;
if (PyObject_IsTrue(stack)) {
......@@ -951,32 +704,34 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
eo = PySequence_GetItem(stack, -1);
if (eo == NULL) goto err;
owner = PyObject_CallMethod(eo, "getOwner", NULL);
if (owner == NULL) {
Py_DECREF(eo);
goto err;
}
owner = PyObject_GetAttr(eo, getOwner_str);
if (owner) ASSIGN(owner, PyObject_CallObject(owner, NULL));
if (owner ==NULL)
{
Py_DECREF(eo);
goto err;
}
if (owner != Py_None) {
PyObject *allowed;
allowed = PyObject_CallMethod(owner, "allowed", "OO",
value, roles);
if (allowed == NULL) {
Py_DECREF(eo);
Py_DECREF(owner);
goto err;
}
if (!PyObject_IsTrue(allowed)) {
Py_DECREF(allowed);
Py_DECREF(owner);
Py_DECREF(eo);
if (accessedbase == containerbase) {
unauthErr(name, value);
} else rval = PyInt_FromLong(0);
goto err;
}
Py_DECREF(allowed);
owner = PyObject_GetAttr(owner, allowed_str);
if (owner)
ASSIGN(owner, callfunction2(owner, value, roles));
if (owner == NULL)
{
Py_DECREF(eo);
goto err;
}
if (! PyObject_IsTrue(owner))
{
Py_DECREF(owner);
Py_DECREF(eo);
if (accessedbase == containerbase) {
unauthErr(name, value);
}
else rval = PyInt_FromLong(0);
goto err;
}
}
Py_DECREF(owner);
......@@ -993,81 +748,84 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**|
**| return 0
*/
proxy_roles = PyObject_GetAttrString(eo, "_proxy_roles");
if (proxy_roles == NULL) {
PyErr_Clear();
Py_INCREF(Py_None);
proxy_roles = Py_None;
}
if (PyObject_IsTrue(proxy_roles)) {
int i;
int j;
int pl;
int rl;
int found = 0;
PyObject *r;
PyObject *r2;
pl = PySequence_Length(proxy_roles);
rl = PySequence_Length(roles);
for (i = 0; !found && i < pl; i++) {
r = PySequence_GetItem(proxy_roles, i);
for (j = 0; !found && j < rl; j++) {
r2 = PySequence_GetItem(roles, j);
if (PyObject_Compare(r, r2) == 0)
found=1;
Py_DECREF(r2);
}
Py_DECREF(r);
}
if (found) {
Py_DECREF(proxy_roles);
Py_DECREF(eo);
rval = PyInt_FromLong(1);
goto err;
}
if (accessedbase == containerbase) {
Py_DECREF(proxy_roles);
Py_DECREF(eo);
unauthErr(name, value);
goto err;
}
Py_DECREF(proxy_roles);
Py_DECREF(eo);
rval = PyInt_FromLong(0);
goto err;
}
Py_DECREF(proxy_roles);
Py_DECREF(eo);
proxy_roles = PyObject_GetAttr(eo, _proxy_roles_str);
Py_DECREF(eo);
if (proxy_roles == NULL)
{
PyErr_Clear();
}
else if (PyObject_IsTrue(proxy_roles))
{
int i, l, contains=0;
PyObject *r;
if (PyTuple_Check(proxy_roles))
{
l=PyTuple_GET_SIZE(proxy_roles);
for (i=0; i < l; i++)
{
r=PyTuple_GET_ITEM(proxy_roles, i);
if ((contains = PySequence_Contains(roles, r)))
break;
}
}
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);
}
else
contains = -1;
if (contains < 0)
break;
}
}
Py_DECREF(proxy_roles);
if (contains > 0)
rval = PyInt_FromLong(contains);
else if (contains == 0) {
if (accessedbase == containerbase) {
unauthErr(name, value);
}
else rval = PyInt_FromLong(contains);
}
goto err;
}
else
Py_DECREF(proxy_roles);
} /* End of stack check */
/*| try:
**| if context.user.allowed(value, roles): return 1
**| except AttributeError: pass
*/
user = PyObject_GetAttrString(context, "user");
if (user != NULL) {
PyObject *allowed;
allowed = PyObject_CallMethod(user, "allowed", "OO",
value, roles);
if (allowed != NULL) {
if (PyObject_IsTrue(allowed)) {
Py_DECREF(allowed);
Py_DECREF(user);
rval = PyInt_FromLong(1);
goto err;
}
Py_DECREF(allowed);
}
Py_DECREF(user);
} else {
PyErr_Clear();
}
user = PyObject_GetAttr(context, user_str);
if (user) ASSIGN(user, PyObject_GetAttr(user, allowed_str));
if (user == NULL)
{
if (PyErr_ExceptionMatches(PyExc_AttributeError))
PyErr_Clear();
else
goto err;
}
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);
}
/*| # we don't want someone to acquire if they can't get an
**| # unacquired!
......@@ -1077,21 +835,12 @@ static PyObject *ZopeSecurityPolicy_validate(PyObject *self, PyObject *args) {
**| return 0
*/
if (accessedbase == containerbase) {
unauthErr(name, value);
goto err;
}
rval = PyInt_FromLong(0);
err:
if (rval != NULL) PyErr_Clear();
#if ZSPCACHE
if (rval != NULL) ZSPCacheSet(accessedbase, containerbase, name, ivalue,
context, iroles, rval);
#endif
if (accessedbase == containerbase)
unauthErr(name, value);
else
rval = PyInt_FromLong(0);
err:
Py_XDECREF(stack);
Py_XDECREF(roles);
......@@ -1116,7 +865,6 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
PyObject *roles;
PyObject *result = NULL;
PyObject *user;
PyObject *arg;
/*| def checkPermission(self, permission, object, context)
*/
......@@ -1127,31 +875,37 @@ static PyObject *ZopeSecurityPolicy_checkPermission(PyObject *self,
/*| roles = rolesForPermissionOn(permission, object)
*/
arg = Py_BuildValue("OO", permission, object);
roles = rolesForPermissionOn(self, arg);
Py_DECREF(arg);
if (roles == NULL) return NULL;
roles = c_rolesForPermissionOn(self, permission, object, OBJECT(NULL));
if (roles == NULL)
return NULL;
/*| if type(roles) is StringType:
**| roles = [roles]
*/
if (PyString_Check(roles)) {
PyObject *r;
r = Py_BuildValue("[O]", roles);
Py_DECREF(roles);
roles = r;
PyObject *r;
r = PyList_New(1);
if (r == NULL) {
Py_DECREF(roles);
return NULL;
}
/* Note: ref to roles is passed to the list object. */
PyList_SET_ITEM(r, 0, roles);
roles = r;
}
/*| return context.user.allowed(object, roles)
*/
user = PyObject_GetAttrString(context, "user");
user = PyObject_GetAttr(context, user_str);
if (user != NULL) {
result = PyObject_CallMethod(user,"allowed", "OO", object, roles);
Py_DECREF(user);
ASSIGN(user, PyObject_GetAttr(user, allowed_str));
if (user != NULL) {
result = callfunction2(user, object, roles);
Py_DECREF(user);
}
}
Py_DECREF(roles);
......@@ -1171,42 +925,6 @@ static void ZopeSecurityPolicy_dealloc(ZopeSecurityPolicy *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
**
......@@ -1227,11 +945,11 @@ static PyObject *PermissionRole_init(PermissionRole *self, PyObject *args) {
if (deflt == NULL) deflt = defaultPermission;
UNLESS(self->_p = permissionName(name)) return NULL;
self->__name__ = name;
Py_INCREF(name);
self->_p = permissionName(name);
self->__roles__ = deflt;
Py_INCREF(deflt);
......@@ -1259,7 +977,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
/*| r = imPermissionRole()
*/
r = (imPermissionRole *) PyObject_CallObject(imPermissionRoleObj,NULL);
r = (imPermissionRole*)PyObject_CallObject(imPermissionRoleObj, NULL);
if (r == NULL) return NULL;
/*| r._p = self._p
......@@ -1272,7 +990,7 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
*/
r->_pa = parent;
Py_INCREF(r->_pa);
Py_INCREF(parent);
/*| r._d = self._d
*/
......@@ -1291,16 +1009,15 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
if (aq_isWrapper(parent)) {
_p = aq_inner(parent);
result = PyObject_CallMethod(OBJECT(r),"__of__","O", _p);
result = callmethod1(OBJECT(r), __of__, _p);
Py_DECREF(_p);
/* Dont need goto */
} else {
result = OBJECT(r);
Py_INCREF(r);
PyErr_Clear();
}
Py_XDECREF(r);
Py_DECREF(r);
return result;
}
......@@ -1312,52 +1029,17 @@ static PyObject *PermissionRole_of(PermissionRole *self, PyObject *args) {
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 */
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
**
......@@ -1386,8 +1068,10 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
n = self->_p;
if (n == NULL) {
/* XXX Should not be possible */
PyErr_SetString(PyExc_AttributeError, "_p");
goto err;
Py_DECREF(obj);
return NULL;
}
Py_INCREF(n);
......@@ -1409,7 +1093,7 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
if (roles != NULL) {
if (roles == Py_None) {
result = Anonymous;
result = AnonymousTuple;
Py_INCREF(result);
goto err;
}
......@@ -1429,13 +1113,11 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
goto err;
} else {
PyObject *list;
PyObject *cat;
list = PySequence_List(roles);
cat = PySequence_Concat(r, list);
Py_DECREF(list);
result = cat;
if (list != NULL) {
result = PySequence_Concat(r, list);
Py_DECREF(list);
}
goto err;
}
}
......@@ -1461,17 +1143,18 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
**|
*/
if (PyObject_IsTrue(roles)) {
if (PyObject_Compare(roles, n)) {
Py_DECREF(n);
n = roles;
Py_INCREF(n);
}
Py_DECREF(roles);
roles = Py_None;
Py_INCREF(roles);
if (PyObject_Compare(roles, n) != 0) {
Py_DECREF(n);
n = roles;
Py_INCREF(n);
}
Py_DECREF(roles);
roles = Py_None;
Py_INCREF(roles);
} else {
result = _what_not_even_god_should_do;
goto err;
result = _what_not_even_god_should_do;
Py_INCREF(result);
goto err;
}
} else {
......@@ -1479,23 +1162,24 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
**| if r is None: r = list(roles)
**| else: r = r+list(roles)
*/
if (PyObject_IsTrue(roles)) {
if (r == Py_None) {
Py_DECREF(r);
r = PySequence_List(roles);
} else {
PyObject *list;
PyObject *cat;
list = PySequence_List(roles);
cat = PySequence_Concat(r,
list);
Py_DECREF(list);
Py_DECREF(r);
r = cat;
}
}
if (PyObject_IsTrue(roles)) {
if (r == Py_None) {
Py_DECREF(r);
r = PySequence_List(roles);
} else {
PyObject *list;
list = PySequence_List(roles);
if (list != NULL) {
ASSIGN(r, PySequence_Concat(r, list));
Py_DECREF(list);
if (r == NULL)
goto err;
}
else
goto err;
}
}
}
}
else
......@@ -1506,14 +1190,14 @@ static PyObject *imPermissionRole_of(imPermissionRole *self, PyObject *args) {
**| obj = obj.aq_parent
*/
if (aq_isWrapper(obj) <= 0) break;
if (!aq_isWrapper(obj)) break;
tobj = aq_inner(obj);
if (tobj == NULL) break;
if (tobj == NULL) goto err;
Py_DECREF(obj);
obj = tobj;
if (obj == Py_None) break;
if (aq_isWrapper(obj) <= 0) break;
if (!aq_isWrapper(obj)) break;
tobj = aq_parent(obj);
if (tobj == NULL) goto err;
Py_DECREF(obj);
......@@ -1571,60 +1255,21 @@ static int imPermissionRole_length(imPermissionRole *self) {
v = self->_v;
if (v == NULL) {
pa = self->_pa;
if (pa == NULL) return -1;
v = PyObject_CallMethod(OBJECT(self), "__of__",
"O", pa);
if (pa == NULL) {
PyErr_SetString(PyExc_AttributeError, "_pa");
return -1;
}
v = callmethod1(OBJECT(self), __of__, pa);
if (v == NULL)
return -1;
self->_v = v;
Py_XDECREF(self->_pa);
Py_DECREF(pa);
self->_pa = NULL;
}
l = PyObject_Length(v);
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;
}
/*
......@@ -1649,16 +1294,17 @@ static PyObject *imPermissionRole_get(imPermissionRole *self,
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;
pa = self->_pa;
if (pa == NULL) {
PyErr_SetString(PyExc_AttributeError, "_pa");
return NULL;
}
v = callmethod1(OBJECT(self), __of__, pa);
if (v == NULL)
return NULL;
self->_v = v;
Py_DECREF(pa);
self->_pa = NULL;
}
result = PySequence_GetItem(v, item);
......@@ -1673,16 +1319,12 @@ static PyObject *imPermissionRole_get(imPermissionRole *self,
static void imPermissionRole_dealloc(imPermissionRole *self) {
Py_XDECREF(self->_p);
self->_p = NULL;
Py_XDECREF(self->_pa);
self->_pa = NULL;
Py_XDECREF(self->__roles__);
self->__roles__ = NULL;
Py_XDECREF(self->_v);
self->_v = NULL;
Py_DECREF(self->ob_type); /* Extensionclass init incref'd */
......@@ -1697,41 +1339,52 @@ static PyObject *rolesForPermissionOn(PyObject *self, PyObject *args) {
PyObject *perm = NULL;
PyObject *object = NULL;
PyObject *deflt = NULL;
imPermissionRole *im = NULL;
PyObject *result;
/*|def rolesForPermissionOn(perm, object, default=('Manager',)):
**|
**| """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._d = default
**| return im.__of__(object)
*/
if (!PyArg_ParseTuple(args, "OO|O", &perm, &object, &deflt))
return NULL;
im = (imPermissionRole *) PyObject_CallObject(imPermissionRoleObj,
NULL);
if (im == NULL) return NULL;
im = (imPermissionRole*)PyObject_CallObject(imPermissionRoleObj, NULL);
if (im == NULL)
return NULL;
im->_p = permissionName(perm);
if (im->_p == NULL) {
Py_DECREF(im);
return NULL;
}
if (deflt == NULL) deflt = defaultPermission;
im->__roles__ = deflt;
Py_INCREF(deflt);
result = PyObject_CallMethod(OBJECT(im), "__of__", "O", object);
result = callmethod1(OBJECT(im), __of__, object);
Py_DECREF(im);
return result;
}
/*
** permissionName
**
......@@ -1751,6 +1404,8 @@ static PyObject *permissionName(PyObject *name) {
len--;
in = PyString_AsString(name);
if (in == NULL)
return NULL;
while (len && *in) {
r = *(in++);
......@@ -1777,24 +1432,33 @@ static PyObject *permissionName(PyObject *name) {
** 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 *dict;
char *rev = "$Revision: 1.10 $";
char *rev = "$Revision: 1.11 $";
if (!ExtensionClassImported) return;
aq_init();
if (ZopeSecurityPolicy_setup() < 0) return;
ZopeSecurityPolicyType.tp_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,
"$Id: %\n",
OBJECT(NULL),
PYTHON_API_VERSION);
"$Id: cAccessControl.c,v 1.11 2001/10/19 15:12:25 shane Exp $\n");
aq_init(); /* For Python <= 2.1.1, aq_init() should be after
Py_InitModule(). */
dict = PyModule_GetDict(module);
......@@ -1813,12 +1477,6 @@ PUBLIC void initcAccessControl(void) {
PyDict_SetItemString(dict, "__version__",
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",
_what_not_even_god_should_do);
......@@ -1831,13 +1489,31 @@ PUBLIC void initcAccessControl(void) {
PyExtensionClass_Export(dict, "imPermissionRole",
imPermissionRoleType);
imPermissionRoleObj = PyDict_GetItemString(dict, "imPermissionRole");
imPermissionRoleObj = PyDict_GetItemString(dict, "imPermissionRole");
#if ZSPCACHE
ZSPCacheInit();
#endif
/*| from SimpleObjectPolicies import Containers
*/
if (PyErr_Occurred())
Py_FatalError("Can't initialize module cAccessControl");
IMPORT(module, "AccessControl.SimpleObjectPolicies");
GETATTR(module, Containers);
Py_DECREF(module);
module = NULL;
/*| from unauthorized import Unauthorized
*/
IMPORT(module, "AccessControl.unauthorized");
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 @@
# 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 $'''
__version__='$Revision: 1.1 $'[11:-2]
class Unauthorized(zExceptions.Unauthorized):
def getValueName(self):
v=self.value
n=getattr(v, 'getId', v)
if n is v: n=getattr(v, 'id', v)
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
import cAccessControl
rolesForPermissionOn=cAccessControl.rolesForPermissionOn
PermissionRole=cAccessControl.PermissionRole
imPermisionRole=cAccessControl.imPermissionRole
_what_not_even_god_should_do= cAccessControl._what_not_even_god_should_do
##############################################################################
# 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
c = getattr(v, '__class__', type(v))
c = getattr(c, '__name__', 'object')
return "a particular %s" % c
......@@ -85,15 +85,15 @@
"""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
from Dialogs import MessageDialog
from Globals import DTMLFile, HTMLFile
from string import split, join, find
from AccessControl import getSecurityManager
from AccessControl import getSecurityManager, Unauthorized
class Tabs(ExtensionClass.Base):
"""Mix-in provides management folder tab support."""
......@@ -145,8 +145,8 @@ class Tabs(ExtensionClass.Base):
m=options[0]['action']
if m=='manage_workspace': raise TypeError
except:
raise 'Unauthorized', (
'You are not authorized to view this object.<p>')
raise Unauthorized, (
'You are not authorized to view this object.')
if find(m,'/'):
raise 'Redirect', (
......
......@@ -118,6 +118,7 @@ from Permission import PermissionManager
import ZClasses, ZClasses.ZClass
from HelpSys.HelpSys import ProductHelp
import RefreshFuncs
from AccessControl import Unauthorized
class ProductFolder(Folder):
......@@ -447,7 +448,7 @@ class Product(Folder, PermissionManager):
Attempts to perform a refresh operation.
'''
if self._readRefreshTxt() is None:
raise 'Unauthorized', 'refresh.txt not found'
raise Unauthorized, 'refresh.txt not found'
message = None
if RefreshFuncs.performFullRefresh(self._p_jar, self.id):
from ZODB import Connection
......@@ -463,7 +464,7 @@ class Product(Folder, PermissionManager):
Changes the auto refresh flag for this product.
'''
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)
if enable:
message = 'Enabled auto refresh.'
......@@ -477,7 +478,7 @@ class Product(Folder, PermissionManager):
Selects which products to refresh simultaneously.
'''
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)
if REQUEST is not None:
return self.manage_refresh(REQUEST)
......
......@@ -82,8 +82,8 @@
# attributions are listed in the accompanying credits file.
#
##############################################################################
'''$Id: DT_Util.py,v 1.83 2001/09/04 13:46:43 evan Exp $'''
__version__='$Revision: 1.83 $'[11:-2]
'''$Id: DT_Util.py,v 1.84 2001/10/19 15:12:26 shane Exp $'''
__version__='$Revision: 1.84 $'[11:-2]
import re, os
from html_quote import html_quote # for import by other modules, dont remove!
......@@ -98,7 +98,7 @@ LIMITED_BUILTINS = 1
str=__builtins__['str'] # Waaaaa, waaaaaaaa needed for pickling waaaaa
ParseError='Document Template Parse Error'
ValidationError='Unauthorized'
from zExceptions import Unauthorized as ValidationError
def int_param(params,md,name,default=0, st=type('')):
try: v=params[name]
......
......@@ -85,19 +85,16 @@
"""Document Template Tests
"""
__rcs_id__='$Id: testDTML.py,v 1.6 2001/07/02 16:30:46 shane Exp $'
__version__='$Revision: 1.6 $'[11:-2]
__rcs_id__='$Id: testDTML.py,v 1.7 2001/10/19 15:12:26 shane Exp $'
__version__='$Revision: 1.7 $'[11:-2]
import sys, os
import unittest
if __name__=='__main__':
sys.path.append(os.path.join(os.pardir, os.pardir))
here = os.curdir
else:
from DocumentTemplate import tests
from App.Common import package_home
here = package_home(tests.__dict__)
here = os.path.split(__file__)[0]
def read_file(name):
f = open(os.path.join(here, name), 'rb')
......@@ -122,7 +119,7 @@ class DTMLTests (unittest.TestCase):
doc_class = HTML
def checkBatchingEtc(self):
def testBatchingEtc(self):
def item(key,**kw): return (key,kw)
def item2(key,**kw): return kw
......@@ -239,7 +236,7 @@ class DTMLTests (unittest.TestCase):
expected = read_file('dealers.out')
assert res == expected, res
def checkSequenceSummaries(self):
def testSequenceSummaries(self):
def d(**kw): return kw
data=(d(name='jim', age=38),
# d(name='kak', age=40),
......@@ -274,7 +271,7 @@ class DTMLTests (unittest.TestCase):
'median=5 mean=12.5 s.d.=17')
assert res == expected, res
def checkDTMLDateFormatting(self):
def testDTMLDateFormatting(self):
import DateTime
html = self.doc_class(
"<dtml-var name capitalize spacify> is "
......@@ -285,13 +282,13 @@ class DTMLTests (unittest.TestCase):
expected = 'Christmas day is 1995/12/25'
assert res == expected, res
def checkSimpleString(self):
def testSimpleString(self):
dt = String('%(name)s')
res = dt(name='Chris')
expected = 'Chris'
assert res == expected, res
def checkStringDateFormatting(self):
def testStringDateFormatting(self):
import DateTime
html = String("%(name capitalize spacify)s is "
"%(date fmt=year)s/%(date fmt=month)s/%(date fmt=day)s")
......@@ -300,7 +297,7 @@ class DTMLTests (unittest.TestCase):
expected = 'The date is 2001/4/27'
assert res == expected, res
def checkSequence1(self):
def testSequence1(self):
html=self.doc_class(
'<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item> '
'</dtml-in sequence-item></dtml-in spam>')
......@@ -308,7 +305,7 @@ class DTMLTests (unittest.TestCase):
res = html(spam=[[1,2,3],[4,5,6]])
assert res == expected, res
def checkSequence2(self):
def testSequence2(self):
html=self.doc_class(
'<dtml-in spam><dtml-in sequence-item><dtml-var sequence-item>-'
'</dtml-in sequence-item></dtml-in spam>')
......@@ -316,14 +313,14 @@ class DTMLTests (unittest.TestCase):
res = html(spam=[[1,2,3],[4,5,6]])
assert res == expected, res
def checkNull(self):
def testNull(self):
html=self.doc_class('<dtml-var spam fmt="$%.2f bobs your uncle" '
'null="spam%eggs!|">')
expected = '$42.00 bobs your unclespam%eggs!|'
res = html(spam=42) + html(spam=None)
assert res == expected, res
def check_fmt(self):
def test_fmt(self):
html=self.doc_class(
"""
<dtml-var spam>
......@@ -369,7 +366,7 @@ foo bar
spam='<a href="spam">\nfoo bar')
assert res == expected, res
def checkPropogatedError(self):
def testPropogatedError(self):
class foo:
def __len__(self): return 9
......@@ -408,7 +405,7 @@ foo bar
else:
assert 0, 'Puke error not propogated'
def checkRenderCallable(self):
def testRenderCallable(self):
"Test automatic rendering of callable objects"
class C (Base):
__allow_access_to_unprotected_subobjects__ = 1
......@@ -433,7 +430,7 @@ foo bar
<dtml-var expr="_.render(i.h2)">''')(i=C())
assert res == expected, res
def checkWith(self):
def testWith(self):
class person:
__allow_access_to_unprotected_subobjects__ = 1
name='Jim'
......@@ -448,7 +445,7 @@ foo bar
'cm.</dtml-with>')(person=person)
assert res == expected, res
def checkRaise(self):
def testRaise(self):
try:
res = self.doc_class(
"<dtml-raise IndexError>success!</dtml-raise>")()
......@@ -457,7 +454,7 @@ foo bar
assert str(res) == 'success!', `res`
def checkBasicHTMLIn(self):
def testBasicHTMLIn(self):
data=(
d(name='jim', age=39),
d(name='kak', age=29),
......@@ -481,7 +478,7 @@ foo bar
result = self.doc_class(html)(data=data)
assert result == expected, result
def checkBasicHTMLIn2(self):
def testBasicHTMLIn2(self):
xxx=(D(name=1), D(name=2), D(name=3))
html = """
<!--#in xxx-->
......@@ -496,7 +493,7 @@ foo bar
result = self.doc_class(html)(xxx=xxx)
assert result == expected, result
def checkBasicHTMLIn3(self):
def testBasicHTMLIn3(self):
ns = {'prop_ids': ('title', 'id'), 'title': 'good', 'id': 'times'}
html = """:<dtml-in prop_ids><dtml-var sequence-item>=<dtml-var
expr="_[_['sequence-item']]">:</dtml-in>"""
......@@ -505,7 +502,7 @@ foo bar
assert result == expected, result
def checkHTMLInElse(self):
def testHTMLInElse(self):
xxx=(D(name=1), D(name=2), D(name=3))
html="""
<!--#in data mapping-->
......@@ -524,7 +521,7 @@ foo bar
result = self.doc_class(html)(xxx=xxx, data={})
assert result == expected, result
def checkBasicStringIn(self):
def testBasicStringIn(self):
data=(
d(name='jim', age=39),
d(name='kak', age=29),
......@@ -548,22 +545,12 @@ foo bar
assert expected == result, result
def test_suite():
return unittest.makeSuite(DTMLTests, 'check')
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( DTMLTests ) )
return suite
def main():
alltests = test_suite()
runner = unittest.TextTestRunner()
runner.run(alltests)
unittest.TextTestRunner().run(test_suite())
def debug():
test_suite().debug()
def pdebug():
import pdb
pdb.run('debug()')
if __name__=='__main__':
if len(sys.argv) > 1:
globals()[sys.argv[1]]()
else:
main()
if __name__ == '__main__':
main()
......@@ -84,9 +84,9 @@
##############################################################################
__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
from string import join
......@@ -96,6 +96,7 @@ from Acquisition import aq_get, aq_acquire, aq_inner, aq_parent, aq_base
from zLOG import LOG, WARNING
from AccessControl import getSecurityManager
from AccessControl.Role import _isBeingUsedAsAMethod
from AccessControl import Unauthorized
ZCM_MANAGERS = '__ZCacheManager_ids__'
......@@ -585,7 +586,7 @@ class CacheManager:
path = key[10:]
ob = parent.restrictedTraverse(path)
if not sm.checkPermission('Change cache settings', ob):
raise 'Unauthorized'
raise Unauthorized
if not isCacheable(ob):
# Not a cacheable object.
continue
......
......@@ -83,7 +83,7 @@
#
##############################################################################
__doc__="""Copy interface"""
__version__='$Revision: 1.74 $'[11:-2]
__version__='$Revision: 1.75 $'[11:-2]
import sys, string, Globals, Moniker, tempfile, ExtensionClass
from marshal import loads, dumps
......@@ -410,9 +410,9 @@ class CopyContainer(ExtensionClass.Base):
except: parent=None
if getSecurityManager().validate(None, parent, None, object):
return
raise 'Unauthorized', absattr(object.id)
raise Unauthorized, absattr(object.id)
else:
raise 'Unauthorized', mt_permission
raise Unauthorized(permission=mt_permission)
#
# XXX: Ancient cruft, left here in true co-dependent fashion
# to keep from breaking old products which don't put
......@@ -434,9 +434,9 @@ class CopyContainer(ExtensionClass.Base):
except: parent=None
if getSecurityManager().validate(None, parent, None, object):
return
raise 'Unauthorized', absattr(object.id)
raise Unauthorized, absattr(object.id)
else:
raise 'Unauthorized', method_name
raise Unauthorized, method_name
raise CopyError, MessageDialog(
title='Not Supported',
......
......@@ -87,13 +87,14 @@
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 AccessControl.Role, webdav.Collection, FindSupport
from webdav.WriteLockInterface import WriteLockInterface
from AccessControl import Unauthorized
from Globals import DTMLFile
from AccessControl import getSecurityManager
......@@ -121,14 +122,14 @@ def manage_addFolder(self, id, title='',
if createUserF:
if not checkPermission('Add User Folders', ob):
raise 'Unauthorized', (
raise Unauthorized, (
'You are not authorized to add User Folders.'
)
ob.manage_addUserFolder()
if createPublic:
if not checkPermission('Add Page Templates', ob):
raise 'Unauthorized', (
raise Unauthorized, (
'You are not authorized to add Page Templates.'
)
ob.manage_addProduct['PageTemplates'].manage_addPageTemplate(
......
......@@ -84,12 +84,13 @@
##############################################################################
'''This module implements a mix-in for traversable objects.
$Id: Traversable.py,v 1.11 2001/09/11 14:31:25 evan Exp $'''
__version__='$Revision: 1.11 $'[11:-2]
$Id: Traversable.py,v 1.12 2001/10/19 15:12:26 shane Exp $'''
__version__='$Revision: 1.12 $'[11:-2]
from Acquisition import Acquired, aq_inner, aq_parent, aq_base
from AccessControl import getSecurityManager
from AccessControl import Unauthorized
from string import split, join
from urllib import quote
......@@ -165,7 +166,7 @@ class Traversable:
pop()
self=self.getPhysicalRoot()
if (restricted and not securityManager.validateValue(self)):
raise 'Unauthorized', name
raise Unauthorized, name
try:
object = self
......@@ -181,7 +182,7 @@ class Traversable:
if o is not M:
if (restricted and not securityManager.validate(
object, object,name, o)):
raise 'Unauthorized', name
raise Unauthorized, name
object=o
continue
......@@ -198,7 +199,7 @@ class Traversable:
container = object
if (not securityManager.validate(object,
container, name, o)):
raise 'Unauthorized', name
raise Unauthorized, name
else:
o=get(object, name, M)
......@@ -209,17 +210,17 @@ class Traversable:
# value wasn't acquired
if not securityManager.validate(
object, object, name, o):
raise 'Unauthorized', name
raise Unauthorized, name
else:
if not securityManager.validate(
object, N, name, o):
raise 'Unauthorized', name
raise Unauthorized, name
else:
o=object[name]
if (restricted and not securityManager.validate(
object, object, N, o)):
raise 'Unauthorized', name
raise Unauthorized, name
object=o
......
......@@ -84,12 +84,13 @@
##############################################################################
'''CGI Response Output formatter
$Id: BaseResponse.py,v 1.8 2001/04/26 14:40:07 andreas Exp $'''
__version__='$Revision: 1.8 $'[11:-2]
$Id: BaseResponse.py,v 1.9 2001/10/19 15:12:27 shane Exp $'''
__version__='$Revision: 1.9 $'[11:-2]
import string, types, sys
from string import find, rfind, lower, upper, strip, split, join, translate
from types import StringType, InstanceType
from zExceptions import Unauthorized
class BaseResponse:
"""Base Response Class
......@@ -226,4 +227,4 @@ class BaseResponse:
Make sure to generate an appropriate challenge, as appropriate.
"""
raise 'Unauthorized'
raise Unauthorized
......@@ -84,13 +84,14 @@
##############################################################################
'''CGI Response Output formatter
$Id: HTTPResponse.py,v 1.48 2001/08/07 18:36:48 evan Exp $'''
__version__='$Revision: 1.48 $'[11:-2]
$Id: HTTPResponse.py,v 1.49 2001/10/19 15:12:27 shane Exp $'''
__version__='$Revision: 1.49 $'[11:-2]
import string, types, sys, re
from string import find, rfind, lower, upper, strip, split, join, translate
from types import StringType, InstanceType, LongType
from BaseResponse import BaseResponse
from zExceptions import Unauthorized
nl2sp=string.maketrans('\n',' ')
......@@ -578,7 +579,7 @@ class HTTPResponse(BaseResponse):
m=m+'<p>\nUsername and password are not correct.'
else:
m=m+'<p>\nNo Authorization header found.'
raise 'Unauthorized', m
raise Unauthorized, m
def exception(self, fatal=0, info=None,
absuri_match=re.compile(r'\w+://[\w\.]+').match,
......@@ -588,7 +589,11 @@ class HTTPResponse(BaseResponse):
if type(info) is type(()) and len(info)==3: t,v,tb = 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
......
......@@ -85,7 +85,7 @@
"""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 Acquisition, OFS.content_types
......@@ -96,6 +96,7 @@ from Resource import Resource
from Globals import Persistent, DTMLFile
from WriteLockInterface import WriteLockInterface
import OFS.SimpleItem
from zExceptions import Unauthorized
class NullResource(Persistent, Acquisition.Implicit, Resource):
"""Null resources are used to handle HTTP method calls on
......@@ -179,8 +180,8 @@ class NullResource(Persistent, Acquisition.Implicit, Resource):
# check the clipboard.
try:
parent._verifyObjectPaste(ob.__of__(parent), 0)
except 'Unauthorized':
raise 'Unauthorized', sys.exc_info()[1]
except Unauthorized:
raise
except:
raise 'Forbidden', sys.exc_info()[1]
......@@ -429,8 +430,8 @@ class LockNullResource(NullResource, OFS.SimpleItem.Item_w__name__):
# Verify that the user can create this type of object
try:
parent._verifyObjectPaste(ob.__of__(parent), 0)
except 'Unauthorized':
raise 'Unauthorized', sys.exc_info()[1]
except Unauthorized:
raise
except:
raise 'Forbidden', sys.exc_info()[1]
......
......@@ -85,7 +85,7 @@
"""WebDAV support - resource objects."""
__version__='$Revision: 1.47 $'[11:-2]
__version__='$Revision: 1.48 $'[11:-2]
import sys, os, string, mimetypes, davcmds, ExtensionClass, Lockable
from common import absattr, aq_base, urlfix, rfc1123_date, tokenFinder, urlbase
......@@ -95,6 +95,7 @@ from AccessControl import getSecurityManager
from WriteLockInterface import WriteLockInterface
import Globals, time
from ZPublisher.HTTPRangeSupport import HTTPRangeInterface
from zExceptions import Unauthorized
class Resource(ExtensionClass.Base, Lockable.LockableItem):
"""The Resource mixin class provides basic WebDAV support for
......@@ -155,7 +156,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
method)
except: pass
raise 'Unauthorized', msg
raise Unauthorized, msg
def dav__simpleifhandler(self, request, response, method='PUT',
col=0, url=None, refresh=0):
......@@ -394,8 +395,8 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
try: parent._checkId(name, allow_dup=1)
except: raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self)
except 'Unauthorized':
raise 'Unauthorized', sys.exc_info()[1]
except Unauthorized:
raise
except: raise 'Forbidden', sys.exc_info()[1]
# Now check locks. The If header on a copy only cares about the
......@@ -483,8 +484,7 @@ class Resource(ExtensionClass.Base, Lockable.LockableItem):
except:
raise 'Forbidden', sys.exc_info()[1]
try: parent._verifyObjectPaste(self)
except 'Unauthorized':
raise 'Unauthorized', sys.exc_info()[1]
except Unauthorized: raise
except: raise 'Forbidden', sys.exc_info()[1]
# Now check locks. Since we're affecting the resource that we're
......
......@@ -82,172 +82,12 @@
# 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 $'''
__version__='$Revision: 1.1 $'[11:-2]
$Id: __init__.py,v 1.2 2001/10/19 15:12:28 shane Exp $
"""
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 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
from unauthorized import Unauthorized
......@@ -82,178 +82,57 @@
# attributions are listed in the accompanying credits file.
#
##############################################################################
__doc__='''Objects that implement Permission-based roles.
$Id: pPermissionRole.py,v 1.1 2001/08/08 15:57:49 matt Exp $'''
__version__='$Revision: 1.1 $'[11:-2]
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]
"""
$Id: unauthorized.py,v 1.2 2001/10/19 15:12:28 shane Exp $
"""
class Unauthorized(Exception):
"""Some user wasn't allowed to access a resource"""
def __init__(self, message=None, value=None, needed=None, name=None, **kw):
"""Possible signatures:
Unauthorized()
Unauthorized(message) # Note that message includes a space
Unauthorized(name)
Unauthorized(name, value)
Unauthorized(name, value, needed)
Unauthorized(message, value, needed, name)
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
Where needed is a mapping objects with items represnting requirements
(e.g. {'permission': 'add spam'}). Any extra keyword arguments
provides are added to needed.
"""
if name is None and message is not None and len(message.split()) <= 1:
# First arg is a name, not a message
name=message
message=None
self.name=name
self.message=message
self.value=value
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
if kw:
if needed: needed.update(kw)
else: needed=kw
self.needed=needed
def __str__(self):
if self.message is not None: return self.message
if self.name is not None:
return ("You are not allowed to access %s in this context"
% self.name)
elif self.value is not None:
return ("You are not allowed to access %s in this context"
% self.getValueName(self.value))
def getValueName(self):
v=self.value
vname=getattr(v, '__name__', None)
if vname: return vname
c = getattr(v, '__class__', type(v))
c = getattr(c, '__name__', 'object')
return "a particular %s" % c
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