def protectLikeUnto(class_, like_unto): """Use the protections from like_unto for class_""" unto_checker = getCheckerForInstancesOf(like_unto) if unto_checker is None: return # We know a dictionary was used because we set it # Note however, that if a checker was created manually # and the caller used say NamesChecker or MultiChecker, # then set_permissions may be None here as Checker # defaults a missing set_permissions parameter to None. # Jim says this doensn't happens with the C version of the # checkers because they use a 'shared dummy dict'. unto_get_protections = unto_checker.get_permissions unto_set_protections = unto_checker.set_permissions checker = getCheckerForInstancesOf(class_) if checker is None: checker = Checker({}, {}) defineChecker(class_, checker) get_protections = checker.get_permissions for name in unto_get_protections: get_protections[name] = unto_get_protections[name] set_protections = checker.set_permissions for name in unto_set_protections: set_protections[name] = unto_set_protections[name]
def getMethods(self): """Get all methods of an object. Get a list of dicts, describing the methods of an object. The dicts support keys ``name`` (name of method), ``signature``, ``doc`` (method's docstring or ``None``) and ``interface`` (the interface, where the method was defined or ``None``). """ klass = removeSecurityProxy(self.__klass) obj = removeSecurityProxy(self.obj) for name in dir(obj): value = getattr(obj, name, None) if value is None: continue if not (inspect.ismethod(value) and not inspect.ismethoddescriptor(value)): continue if inspect.ismethod(value): signature = utilities.getFunctionSignature(value) else: signature = '(...)' entry = { 'name': name, 'signature': signature, 'doc': getattr(value, '__doc__', None), 'interface': utilities.getInterfaceForAttribute(name, klass=klass), 'value_linkable': self.isLinkable(value), } entry.update( utilities.getPermissionIds(name, getCheckerForInstancesOf(klass))) yield entry
def getAttributes(self): """Get all attributes of an object. See objectinfo.txt to learn more. """ klass = removeSecurityProxy(self.__klass) obj = removeSecurityProxy(self.obj) for name in dir(obj): value = getattr(obj, name, None) if value is None: continue if inspect.ismethod(value) or inspect.ismethoddescriptor(value): continue entry = { 'name': name, 'value': ` value `, 'value_linkable': self.isLinkable(value), 'type': type(value), # type_link is a very browser oriented data # element. Move it to a view? 'type_link': self.getTypeLink(type(value)), 'interface': utilities.getInterfaceForAttribute(name, klass=klass) } entry.update( utilities.getPermissionIds(name, getCheckerForInstancesOf(klass))) yield entry
def __init__(self, name, context_interface, request_interface=IDefaultBrowserLayer, replacement=None): super(ZopeViewReplacementFixture, self).__init__() self.name = name self.context_interface = context_interface self.request_interface = request_interface self.gsm = getGlobalSiteManager() # It can be convenient--bordering on necessary--to use this original # class as a base for the replacement. self.original = self.gsm.adapters.registered((context_interface, request_interface), Interface, name) self.checker = getCheckerForInstancesOf(self.original) if self.original is None: # The adapter registry does not provide good methods to introspect # it. If it did, we might try harder here. raise ValueError("No existing view to replace. Wrong request interface? " "Try a layer.") self.replacement = replacement
def protectName(class_, name, permission): """Set a permission on a particular name.""" checker = getCheckerForInstancesOf(class_) if checker is None: checker = Checker({}, {}) defineChecker(class_, checker) if permission == 'zope.Public': # Translate public permission to CheckerPublic permission = CheckerPublic # We know a dictionary was used because we set it protections = checker.get_permissions protections[name] = permission
def getPermissionIds(name, checker=_marker, klass=_marker): """Get the permissions of an attribute.""" assert (klass is _marker) != (checker is _marker) entry = {} if klass is not _marker: checker = getCheckerForInstancesOf(klass) if checker is not None and INameBasedChecker.providedBy(checker): entry['read_perm'] = _evalId(checker.permission_id(name)) \ or _('n/a') entry['write_perm'] = _evalId(checker.setattr_permission_id(name)) \ or _('n/a') else: entry['read_perm'] = entry['write_perm'] = None return entry
def _select_checker(value, interaction): checker = getCheckerForInstancesOf(type(value)) if not checker: if get_config().getboolean('auth', 'enforce_attribute_rights_definition'): perms = {} else: if get_config().getboolean('auth', 'audit_all_missing_attribute_rights_definitions'): perms = AuditingPermissionDictionary() else: perms = strong_defaultdict(lambda: CheckerPublic) return Checker(perms, perms, interaction=interaction) # handle checkers for "primitive" types like str if type(checker) is object: return checker return Checker(checker.get_permissions, checker.set_permissions, interaction=interaction)
def protectSetAttribute(class_, name, permission): """Set a permission on a particular name.""" checker = getCheckerForInstancesOf(class_) if checker is None: checker = Checker({}, {}) defineChecker(class_, checker) if permission == zope_Public: # Translate public permission to CheckerPublic permission = CheckerPublic # We know a dictionary was used because we set it # Note however, that if a checker was created manually # and the caller used say NamesChecker or MultiChecker, # then set_permissions may be None here as Checker # defaults a missing set_permissions parameter to None. # Jim says this doensn't happens with the C version of the # checkers because they use a 'shared dummy dict'. protections = checker.set_permissions protections[name] = permission
def register_service(_context, configuration, content, method, layer, default_permission, name=''): logger.debug(configuration) factory = configuration['factory'] if isinstance(factory, str): factory = import_class(factory) if factory is None: raise TypeError('Factory not defined {0:s} '.format( configuration['factory'])) if getCheckerForInstancesOf(factory): # in case already exist remove old checker undefineChecker(factory) if 'permission' in configuration: permission = configuration['permission'] else: permission = default_permission required = {} for n in ('__call__', 'publishTraverse'): required[n] = permission # prevent circular import from plone.server.security import ViewPermissionChecker from plone.server import app_settings defineChecker(factory, ViewPermissionChecker(required)) logger.debug('Defining adapter for ' # noqa '{0:s} {1:s} {2:s} to {3:s} name {4:s}'.format( content.__identifier__, app_settings['http_methods'][method].__identifier__, layer.__identifier__, str(factory), name)) adapter(_context, factory=(factory, ), provides=app_settings['http_methods'][method], for_=(content, layer), name=name)
def register_service(_context, configuration, content, method, layer, default_permission, name=''): logger.debug(configuration) factory = configuration['factory'] if isinstance(factory, str): factory = import_class(factory) if factory is None: raise TypeError( 'Factory not defined {0:s} '.format(configuration['factory'])) if getCheckerForInstancesOf(factory): # in case already exist remove old checker undefineChecker(factory) if 'permission' in configuration: permission = configuration['permission'] else: permission = default_permission required = {} for n in ('__call__', 'publishTraverse'): required[n] = permission # prevent circular import from plone.server.auth.checker import ViewPermissionChecker from plone.server import app_settings defineChecker(factory, ViewPermissionChecker(required)) logger.debug('Defining adapter for ' # noqa '{0:s} {1:s} {2:s} to {3:s} name {4:s}'.format( content.__identifier__, app_settings['http_methods'][method].__identifier__, layer.__identifier__, str(factory), name)) adapter( _context, factory=(factory,), provides=app_settings['http_methods'][method], for_=(content, layer), name=name )
def _select_checker(value, interaction): checker = getCheckerForInstancesOf(type(value)) if not checker: if get_config().getboolean('auth', 'enforce_attribute_rights_definition'): perms = {} else: if get_config().getboolean( 'auth', 'audit_all_missing_attribute_rights_definitions'): perms = AuditingPermissionDictionary() else: perms = strong_defaultdict(lambda: CheckerPublic) return Checker(perms, perms, interaction=interaction) # handle checkers for "primitive" types like str if type(checker) is object: return checker return Checker(checker.get_permissions, checker.set_permissions, interaction=interaction)
def __init__(self, name, context_interface, request_interface=IDefaultBrowserLayer, replacement=None): super(ZopeViewReplacementFixture, self).__init__() self.name = name self.context_interface = context_interface self.request_interface = request_interface self.gsm = getGlobalSiteManager() # It can be convenient--bordering on necessary--to use this original # class as a base for the replacement. self.original = self.gsm.adapters.registered( (context_interface, request_interface), Interface, name) self.checker = getCheckerForInstancesOf(self.original) if self.original is None: # The adapter registry does not provide good methods to introspect # it. If it did, we might try harder here. raise ValueError( 'No existing view to replace. Wrong request interface? ' 'Try a layer.') self.replacement = replacement
def __new__(self, ob, short_name=None): checker = getCheckerForInstancesOf(type(ob)) ob = ProxyBase.__new__(self, ob) ob.__Security_checker__ = checker return ob
def __new__(self, ob, container=None, name=None): checker = getCheckerForInstancesOf(type(removeAllProxies(ob))) ob = ProxyBase.__new__(self, ob) ob.__Security_checker__ = checker return ob
def __new__(self, ob, target): checker = getCheckerForInstancesOf(type(removeAllProxies(ob))) ob = ProxyBase.__new__(self, ob) ob.__Security_checker__ = checker return ob
def __new__(self, ob, title=None, description=None): checker = getCheckerForInstancesOf(type(removeAllProxies(ob))) ob = ProxyBase.__new__(self, ob) ob.__Security_checker__ = checker return ob
def proxyView(context, request, class_=class_): view = class_(context, request) view.__Security_checker__ = getCheckerForInstancesOf( original_class) return view
def getSecurityChecker(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" return getCheckerForInstancesOf(self.__klass)
async def real_resolve(self, request): """Main function to resolve a request.""" alsoProvides(request, IRequest) alsoProvides(request, IDefaultLayer) request._futures = {} request.security = IInteraction(request) method = app_settings['http_methods'][request.method] language = language_negotiation(request) language_object = language(request) try: resource, tail = await self.traverse(request) except Exception as _exc: request.resource = request.tail = None request.exc = _exc # XXX should only should traceback if in some sort of dev mode? raise HTTPBadRequest(text=json.dumps({ 'success': False, 'exception_message': str(_exc), 'exception_type': getattr(type(_exc), '__name__', str(type(_exc))), # noqa 'traceback': traceback.format_exc() })) request.resource = resource request.tail = tail if request.resource is None: raise HTTPBadRequest(text='Resource not found') traverse_to = None if tail and len(tail) == 1: view_name = tail[0] elif tail is None or len(tail) == 0: view_name = '' else: view_name = tail[0] traverse_to = tail[1:] await self.apply_authorization(request) translator = queryMultiAdapter( (language_object, resource, request), ITranslated) if translator is not None: resource = translator.translate() # Add anonymous participation if len(request.security.participations) == 0: # logger.info("Anonymous User") request.security.add(AnonymousParticipation(request)) # Site registry lookup try: view = queryMultiAdapter( (resource, request), method, name=view_name) except AttributeError: view = None # Traverse view if its needed if traverse_to is not None and view is not None: if not ITraversableView.providedBy(view): return None else: try: view = view.publishTraverse(traverse_to) except Exception as e: logger.error( "Exception on view execution", exc_info=e) return None permission = getUtility(IPermission, name='plone.AccessContent') allowed = request.security.checkPermission(permission.id, resource) if not allowed: # Check if its a CORS call: if IOPTIONS != method or not app_settings['cors']: # Check if the view has permissions explicit if view is None or not view.__allow_access__: logger.warn("No access content {content} with {auths}".format( content=resource, auths=str([x.principal.id for x in request.security.participations]))) raise HTTPUnauthorized() if view is None and method == IOPTIONS: view = DefaultOPTIONS(resource, request) checker = getCheckerForInstancesOf(view.__class__) if checker is not None: view = ProxyFactory(view, checker) # We want to check for the content negotiation renderer = content_type_negotiation(request, resource, view) renderer_object = renderer(request) rendered = queryMultiAdapter( (renderer_object, view, request), IRendered) if rendered is not None: return MatchInfo(resource, request, view, rendered) else: return None
def getSecurityChecker(self): """See IClassDocumentation.""" return getCheckerForInstancesOf(self.__klass)
def proxyView(context, request, class_=class_): view = class_(context, request) view.__Security_checker__ = getCheckerForInstancesOf(original_class) return view