AccessControl 7.6__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. AccessControl/AuthEncoding.py +48 -0
  2. AccessControl/ImplC.py +39 -0
  3. AccessControl/ImplPython.py +914 -0
  4. AccessControl/Implementation.py +111 -0
  5. AccessControl/Owned.py +30 -0
  6. AccessControl/Permission.py +179 -0
  7. AccessControl/PermissionMapping.py +165 -0
  8. AccessControl/PermissionRole.py +19 -0
  9. AccessControl/Permissions.py +65 -0
  10. AccessControl/Role.py +34 -0
  11. AccessControl/SecurityInfo.py +502 -0
  12. AccessControl/SecurityManagement.py +84 -0
  13. AccessControl/SecurityManager.py +30 -0
  14. AccessControl/SimpleObjectPolicies.py +151 -0
  15. AccessControl/SpecialUsers.py +25 -0
  16. AccessControl/User.py +54 -0
  17. AccessControl/ZopeGuards.py +712 -0
  18. AccessControl/ZopeSecurityPolicy.py +61 -0
  19. AccessControl/__init__.py +55 -0
  20. AccessControl/_compat.h +18 -0
  21. AccessControl/cAccessControl.c +2526 -0
  22. AccessControl/cAccessControl.cp315-win_amd64.pyd +0 -0
  23. AccessControl/class_init.py +94 -0
  24. AccessControl/configure.zcml +5 -0
  25. AccessControl/frozen.py +57 -0
  26. AccessControl/interfaces.py +390 -0
  27. AccessControl/logger_wrapper.py +8 -0
  28. AccessControl/meta.zcml +52 -0
  29. AccessControl/metaconfigure.py +61 -0
  30. AccessControl/owner.py +288 -0
  31. AccessControl/permissions.zcml +100 -0
  32. AccessControl/requestmethod.py +96 -0
  33. AccessControl/rolemanager.py +490 -0
  34. AccessControl/safe_formatter.py +86 -0
  35. AccessControl/security.py +203 -0
  36. AccessControl/tainted.py +195 -0
  37. AccessControl/tests/__init__.py +0 -0
  38. AccessControl/tests/actual_python.py +260 -0
  39. AccessControl/tests/mixed_module/__init__.py +9 -0
  40. AccessControl/tests/mixed_module/submodule/__init__.py +5 -0
  41. AccessControl/tests/private_module/__init__.py +5 -0
  42. AccessControl/tests/private_module/submodule/__init__.py +5 -0
  43. AccessControl/tests/public_module/__init__.py +11 -0
  44. AccessControl/tests/public_module/submodule/__init__.py +5 -0
  45. AccessControl/tests/testClassSecurityInfo.py +192 -0
  46. AccessControl/tests/testImplementation.py +65 -0
  47. AccessControl/tests/testModuleSecurity.py +335 -0
  48. AccessControl/tests/testPermissionMapping.py +12 -0
  49. AccessControl/tests/testPermissionRole.py +170 -0
  50. AccessControl/tests/testSecurityManager.py +264 -0
  51. AccessControl/tests/testZCML.py +489 -0
  52. AccessControl/tests/testZopeGuards.py +1086 -0
  53. AccessControl/tests/testZopeSecurityPolicy.py +799 -0
  54. AccessControl/tests/test_frozen.py +124 -0
  55. AccessControl/tests/test_owner.py +289 -0
  56. AccessControl/tests/test_requestmethod.py +138 -0
  57. AccessControl/tests/test_rolemanager.py +137 -0
  58. AccessControl/tests/test_safe_formatter.py +226 -0
  59. AccessControl/tests/test_safeiter.py +59 -0
  60. AccessControl/tests/test_tainted.py +320 -0
  61. AccessControl/tests/test_userfolder.py +198 -0
  62. AccessControl/tests/test_users.py +666 -0
  63. AccessControl/unauthorized.py +38 -0
  64. AccessControl/userfolder.py +432 -0
  65. AccessControl/users.py +502 -0
  66. accesscontrol-7.6.dist-info/METADATA +474 -0
  67. accesscontrol-7.6.dist-info/RECORD +71 -0
  68. accesscontrol-7.6.dist-info/WHEEL +5 -0
  69. accesscontrol-7.6.dist-info/entry_points.txt +2 -0
  70. accesscontrol-7.6.dist-info/licenses/LICENSE.txt +44 -0
  71. accesscontrol-7.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,914 @@
1
+ ##############################################################################
2
+ #
3
+ # Copyright (c) 2003 Zope Foundation and Contributors.
4
+ #
5
+ # This software is subject to the provisions of the Zope Public License,
6
+ # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
7
+ # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
8
+ # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
9
+ # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
10
+ # FOR A PARTICULAR PURPOSE.
11
+ #
12
+ ##############################################################################
13
+ # isort:skip_file
14
+ """Python implementation of the access control machinery."""
15
+
16
+ from AccessControl.ZopeSecurityPolicy import getRoles # XXX
17
+ from AccessControl.unauthorized import Unauthorized
18
+ from AccessControl.SimpleObjectPolicies import _noroles
19
+ from AccessControl.SimpleObjectPolicies import Containers
20
+ from AccessControl.SecurityManagement import getSecurityManager
21
+ from AccessControl.Permission import getPermissionIdentifier
22
+ from AccessControl.interfaces import ISecurityPolicy
23
+ from AccessControl.interfaces import ISecurityManager
24
+ import os
25
+ from logging import getLogger
26
+
27
+ from Acquisition import aq_acquire
28
+ from Acquisition import aq_base
29
+ from Acquisition import aq_inContextOf
30
+ from Acquisition import aq_inner
31
+ from Acquisition import aq_parent
32
+ from ExtensionClass import Base
33
+ from zope.interface import implementer
34
+ from zExceptions import Unauthorized as zExceptions_Unauthorized
35
+
36
+ PURE_PYTHON = int(os.environ.get('PURE_PYTHON', '0'))
37
+ if PURE_PYTHON:
38
+ # We need our own to not depend on the C implementation:
39
+ _what_not_even_god_should_do = []
40
+ else:
41
+ from AccessControl.cAccessControl import _what_not_even_god_should_do
42
+
43
+ from AccessControl.ZopeGuards import guarded_getitem # NOQA
44
+
45
+
46
+ # AccessControl.ZopeSecurityPolicy
47
+ # --------------------------------
48
+ #
49
+ # TODO: implement this in cAccessControl, and have Implementation
50
+ # do the indirection.
51
+ #
52
+
53
+
54
+ LOG = getLogger('ImplPython')
55
+
56
+ # AccessControl.PermissionRole
57
+ # ----------------------------
58
+
59
+ _default_roles = ('Manager',)
60
+
61
+ # If _embed_permission_in_roles is enabled, computed __roles__
62
+ # attributes will often include a special role that encodes the name
63
+ # of the permission from which the roles were derived. This is useful
64
+ # for verbose security exceptions.
65
+ _embed_permission_in_roles = 0
66
+
67
+
68
+ def rolesForPermissionOn(perm, object, default=_default_roles, n=None):
69
+ """Return the roles that have the given permission on the given object
70
+ """
71
+ n = n or getPermissionIdentifier(perm)
72
+ r = None
73
+
74
+ while True:
75
+ try:
76
+ roles = getattr(object, n)
77
+ except (AttributeError, zExceptions_Unauthorized):
78
+ pass
79
+ else:
80
+ if roles is None:
81
+ if _embed_permission_in_roles:
82
+ return (('Anonymous',), n)
83
+ return ('Anonymous',)
84
+
85
+ t = type(roles)
86
+ if t is tuple:
87
+ # If we get a tuple, then we don't acquire
88
+ if r is None:
89
+ if _embed_permission_in_roles:
90
+ return roles + (n,)
91
+ return roles
92
+ if _embed_permission_in_roles:
93
+ return r + list(roles) + [n]
94
+ return r + list(roles)
95
+
96
+ if t is str:
97
+ # We found roles set to a name. Start over
98
+ # with the new permission name. If the permission
99
+ # name is '', then treat as private!
100
+ if roles:
101
+ n = roles
102
+ else:
103
+ return _what_not_even_god_should_do
104
+
105
+ elif roles:
106
+ if r is None:
107
+ r = list(roles)
108
+ else:
109
+ r = r + list(roles)
110
+
111
+ object = aq_inner(object)
112
+ if object is None:
113
+ break
114
+ object = aq_parent(object)
115
+
116
+ if r is None:
117
+ if _embed_permission_in_roles:
118
+ if default:
119
+ if isinstance(default, tuple):
120
+ return default + (n,)
121
+ else:
122
+ return default + [n]
123
+ else:
124
+ return [n]
125
+ return default
126
+
127
+ if _embed_permission_in_roles:
128
+ return r + [n]
129
+ return r
130
+
131
+
132
+ class PermissionRole(Base):
133
+ """Implement permission-based roles.
134
+
135
+ Under normal circumstances, our __of__ method will be
136
+ called with an unwrapped object. The result will then be called
137
+ with a wrapped object, if the original object was wrapped.
138
+ To deal with this, we have to create an intermediate object.
139
+
140
+ """
141
+
142
+ def __init__(self, name, default=('Manager',)):
143
+ self.__name__ = name
144
+ self._p = getPermissionIdentifier(name)
145
+ self._d = self.__roles__ = default
146
+
147
+ def __of__(self, parent):
148
+ r = imPermissionRole()
149
+ r._p = self._p
150
+ r._pa = parent
151
+ r._d = self._d
152
+ p = getattr(parent, 'aq_inner', None)
153
+ if p is not None:
154
+ return r.__of__(p)
155
+ else:
156
+ return r
157
+
158
+ def rolesForPermissionOn(self, value):
159
+ return rolesForPermissionOn(None, value, self._d, self._p)
160
+
161
+
162
+ class imPermissionRole(Base):
163
+ """Implement permission-based roles"""
164
+
165
+ def __of__(self, value):
166
+ return rolesForPermissionOn(None, value, self._d, self._p)
167
+ rolesForPermissionOn = __of__
168
+
169
+ # The following methods are needed in the unlikely case that an unwrapped
170
+ # object is accessed:
171
+ def __getitem__(self, i):
172
+ try:
173
+ v = self._v
174
+ except: # noqa: E722 do not use bare 'except'
175
+ v = self._v = self.__of__(self._pa)
176
+ del self._pa
177
+
178
+ return v[i]
179
+
180
+ def __len__(self):
181
+ try:
182
+ v = self._v
183
+ except: # noqa: E722 do not use bare 'except'
184
+ v = self._v = self.__of__(self._pa)
185
+ del self._pa
186
+
187
+ return len(v)
188
+
189
+
190
+ @implementer(ISecurityPolicy)
191
+ class ZopeSecurityPolicy:
192
+
193
+ def __init__(self, ownerous=1, authenticated=1, verbose=0):
194
+ """Create a Zope security policy.
195
+
196
+ Optional arguments may be provided:
197
+
198
+ ownerous -- Untrusted users can create code
199
+ (e.g. Python scripts or templates),
200
+ so check that code owners can access resources.
201
+ The argument must have a truth value.
202
+ The default is true.
203
+
204
+ authenticated -- Allow access to resources based on the
205
+ privaledges of the authenticated user.
206
+ The argument must have a truth value.
207
+ The default is true.
208
+
209
+ This (somewhat experimental) option can be set
210
+ to false on sites that allow only public
211
+ (unauthenticated) access. An anticipated
212
+ scenario is a ZEO configuration in which some
213
+ clients allow only public access and other
214
+ clients allow full management.
215
+
216
+ verbose -- Include debugging information in Unauthorized
217
+ exceptions. Not suitable for public sites.
218
+ """
219
+ self._ownerous = ownerous
220
+ self._authenticated = authenticated
221
+ self._verbose = verbose
222
+
223
+ def validate(self, accessed, container, name, value, context,
224
+ roles=_noroles, getattr=getattr, _noroles=_noroles,
225
+ valid_aq_=('aq_parent', 'aq_inner', 'aq_explicit')):
226
+
227
+ ############################################################
228
+ # Provide special rules for the acquisition attributes
229
+ if isinstance(name, str):
230
+ if name.startswith('aq_') and name not in valid_aq_:
231
+ if self._verbose:
232
+ raiseVerbose(
233
+ 'aq_* names (other than %s) are not allowed'
234
+ % ', '.join(valid_aq_),
235
+ accessed,
236
+ container,
237
+ name,
238
+ value,
239
+ context,
240
+ )
241
+ raise Unauthorized(name, value)
242
+
243
+ containerbase = aq_base(container)
244
+ accessedbase = aq_base(accessed)
245
+ if accessedbase is accessed:
246
+ # accessed is not a wrapper, so assume that the
247
+ # value could not have been acquired.
248
+ accessedbase = container
249
+
250
+ ############################################################
251
+ # If roles weren't passed in, we'll try to get them from the object
252
+
253
+ if roles is _noroles:
254
+ roles = getRoles(container, name, value, _noroles)
255
+
256
+ ############################################################
257
+ # We still might not have any roles
258
+
259
+ if roles is _noroles:
260
+
261
+ ############################################################
262
+ # We have an object without roles and we didn't get a list
263
+ # of roles passed in. Presumably, the value is some simple
264
+ # object like a string or a list. We'll try to get roles
265
+ # from its container.
266
+ if container is None:
267
+ # Either container or a list of roles is required
268
+ # for ZopeSecurityPolicy to know whether access is
269
+ # allowable.
270
+ if self._verbose:
271
+ raiseVerbose(
272
+ 'No container provided',
273
+ accessed, container, name, value, context)
274
+ raise Unauthorized(name, value)
275
+
276
+ roles = getattr(container, '__roles__', roles)
277
+ if roles is _noroles:
278
+ if containerbase is container:
279
+ # Container is not wrapped.
280
+ if containerbase is not accessedbase:
281
+ if self._verbose:
282
+ raiseVerbose(
283
+ 'Unable to find __roles__ in the container '
284
+ 'and the container is not wrapped',
285
+ accessed,
286
+ container,
287
+ name,
288
+ value,
289
+ context,
290
+ )
291
+ raise Unauthorized(name, value)
292
+ else:
293
+ # Try to acquire roles
294
+ try:
295
+ roles = aq_acquire(container, '__roles__')
296
+ except AttributeError:
297
+ if containerbase is not accessedbase:
298
+ if self._verbose:
299
+ raiseVerbose(
300
+ 'Unable to find or acquire __roles__ '
301
+ 'from the container',
302
+ accessed, container, name, value, context)
303
+ raise Unauthorized(name, value)
304
+
305
+ # We need to make sure that we are allowed to
306
+ # get unprotected attributes from the container. We are
307
+ # allowed for certain simple containers and if the
308
+ # container says we can. Simple containers
309
+ # may also impose name restrictions.
310
+ p = Containers(type(container), None)
311
+ if p is None:
312
+ p = getattr(container,
313
+ '__allow_access_to_unprotected_subobjects__',
314
+ None)
315
+
316
+ if p is not None:
317
+ if not isinstance(p, (bool, int)):
318
+ if isinstance(p, dict):
319
+
320
+ if isinstance(name, str):
321
+ p = p.get(name)
322
+ else:
323
+ p = 1
324
+ else:
325
+ p = p(name, value)
326
+
327
+ if not p:
328
+ if self._verbose:
329
+ raiseVerbose(
330
+ 'The container has no security assertions',
331
+ accessed,
332
+ container,
333
+ name,
334
+ value,
335
+ context,
336
+ )
337
+ raise Unauthorized(name, value)
338
+
339
+ if roles is _noroles:
340
+ return 1
341
+
342
+ # We are going to need a security-aware object to pass
343
+ # to allowed(). We'll use the container.
344
+ value = container
345
+
346
+ # Short-circuit tests if we can:
347
+ try:
348
+ if roles is None or 'Anonymous' in roles:
349
+ return 1
350
+ except TypeError:
351
+ # 'roles' isn't a sequence
352
+ LOG.error(
353
+ "'%r' passed as roles"
354
+ " during validation of '%s' is not a sequence." % (
355
+ roles,
356
+ name,
357
+ ),
358
+ )
359
+ raise
360
+
361
+ # Check executable security
362
+ stack = context.stack
363
+ if stack:
364
+ eo = stack[-1]
365
+
366
+ # If the executable had an owner, can it execute?
367
+ if self._ownerous:
368
+ owner = eo.getOwner()
369
+ if (owner is not None) and not owner.allowed(value, roles):
370
+ # We don't want someone to acquire if they can't
371
+ # get an unacquired!
372
+ if self._verbose:
373
+ if len(roles) < 1:
374
+ raiseVerbose(
375
+ "The object is marked as private",
376
+ accessed,
377
+ container,
378
+ name,
379
+ value,
380
+ context,
381
+ )
382
+ elif userHasRolesButNotInContext(owner, value, roles):
383
+ raiseVerbose(
384
+ "The owner of the executing script is defined "
385
+ "outside the context of the object being "
386
+ "accessed",
387
+ accessed,
388
+ container,
389
+ name,
390
+ value,
391
+ context,
392
+ required_roles=roles,
393
+ eo_owner=owner,
394
+ eo=eo,
395
+ )
396
+ else:
397
+ raiseVerbose(
398
+ "The owner of the executing script does not "
399
+ "have the required permission",
400
+ accessed,
401
+ container,
402
+ name,
403
+ value,
404
+ context,
405
+ required_roles=roles,
406
+ eo_owner=owner,
407
+ eo=eo,
408
+ eo_owner_roles=getUserRolesInContext(owner,
409
+ value),
410
+ )
411
+ raise Unauthorized(name, value)
412
+
413
+ # Proxy roles, which are a lot safer now.
414
+ proxy_roles = getattr(eo, '_proxy_roles', None)
415
+ if proxy_roles:
416
+ # Verify that the owner actually can state the proxy role
417
+ # in the context of the accessed item; users in subfolders
418
+ # should not be able to use proxy roles to access items
419
+ # above their subfolder!
420
+ owner = eo.getWrappedOwner()
421
+
422
+ if owner is not None:
423
+ if container is not containerbase:
424
+ # Unwrapped objects don't need checking
425
+ if not owner._check_context(container):
426
+ # container is higher up than the owner,
427
+ # deny access
428
+ if self._verbose:
429
+ raiseVerbose(
430
+ "The owner of the executing script is "
431
+ "defined outside the context of the "
432
+ "object being accessed. The script has "
433
+ "proxy roles, but they do not apply in "
434
+ "this context.",
435
+ accessed, container, name, value, context,
436
+ required_roles=roles, eo_owner=owner,
437
+ eo=eo)
438
+ raise Unauthorized(name, value)
439
+
440
+ for r in proxy_roles:
441
+ if r in roles:
442
+ return 1
443
+
444
+ # Proxy roles actually limit access!
445
+ if self._verbose:
446
+ if len(roles) < 1:
447
+ raiseVerbose(
448
+ "The object is marked as private",
449
+ accessed, container, name, value, context)
450
+ else:
451
+ raiseVerbose(
452
+ "The proxy roles set on the executing script "
453
+ "do not allow access",
454
+ accessed, container, name, value, context,
455
+ eo=eo, eo_proxy_roles=proxy_roles,
456
+ required_roles=roles)
457
+ raise Unauthorized(name, value)
458
+
459
+ try:
460
+ if self._authenticated and context.user.allowed(value, roles):
461
+ return 1
462
+ except AttributeError:
463
+ pass
464
+
465
+ if self._verbose:
466
+ if len(roles) < 1:
467
+ raiseVerbose(
468
+ "The object is marked as private",
469
+ accessed, container, name, value, context)
470
+ elif not self._authenticated:
471
+ raiseVerbose(
472
+ "Authenticated access is not allowed by this "
473
+ "security policy",
474
+ accessed, container, name, value, context)
475
+ elif userHasRolesButNotInContext(context.user, value, roles):
476
+ raiseVerbose(
477
+ "Your user account is defined outside "
478
+ "the context of the object being accessed",
479
+ accessed, container, name, value, context,
480
+ required_roles=roles, user=context.user)
481
+ else:
482
+ raiseVerbose(
483
+ "Your user account does not "
484
+ "have the required permission",
485
+ accessed, container, name, value, context,
486
+ required_roles=roles, user=context.user,
487
+ user_roles=getUserRolesInContext(context.user, value))
488
+ raise Unauthorized(name, value)
489
+
490
+ def checkPermission(self, permission, object, context):
491
+ roles = rolesForPermissionOn(permission, object)
492
+ if isinstance(roles, str):
493
+ roles = [roles]
494
+
495
+ # check executable owner and proxy roles
496
+ stack = context.stack
497
+ if stack:
498
+ eo = stack[-1]
499
+ # If the executable had an owner, can it execute?
500
+ if self._ownerous:
501
+ owner = eo.getOwner()
502
+ if (owner is not None) and not owner.allowed(object, roles):
503
+ # We don't want someone to acquire if they can't
504
+ # get an unacquired!
505
+ return 0
506
+ proxy_roles = getattr(eo, '_proxy_roles', None)
507
+ if proxy_roles:
508
+ # Verify that the owner actually can state the proxy role
509
+ # in the context of the accessed item; users in subfolders
510
+ # should not be able to use proxy roles to access items
511
+ # above their subfolder!
512
+ owner = eo.getWrappedOwner()
513
+ if owner is not None:
514
+ if object is not aq_base(object):
515
+ if not owner._check_context(object):
516
+ # object is higher up than the owner,
517
+ # deny access
518
+ return 0
519
+
520
+ for r in proxy_roles:
521
+ if r in roles:
522
+ return 1
523
+ return 0
524
+
525
+ return context.user.allowed(object, roles)
526
+
527
+ # AccessControl.SecurityManager
528
+ # -----------------------------
529
+
530
+
531
+ # There is no corresponding control in the C implementation of the
532
+ # access control machinery (cAccessControl.c); this should probably go
533
+ # away in a future version. If you're concerned about the size of
534
+ # security stack, you probably have bigger problems.
535
+ #
536
+ try:
537
+ max_stack_size = int(os.environ.get('Z_MAX_STACK_SIZE', '100'))
538
+ except: # noqa: E722 do not use bare 'except'
539
+ max_stack_size = 100
540
+
541
+
542
+ def setDefaultBehaviors(ownerous, authenticated, verbose):
543
+ global _defaultPolicy
544
+ global _embed_permission_in_roles
545
+ _defaultPolicy = ZopeSecurityPolicy(
546
+ ownerous=ownerous,
547
+ authenticated=authenticated,
548
+ verbose=verbose)
549
+ _embed_permission_in_roles = verbose
550
+
551
+
552
+ setDefaultBehaviors(True, True, False)
553
+
554
+
555
+ @implementer(ISecurityManager)
556
+ class SecurityManager:
557
+ """A security manager provides methods for checking access and managing
558
+ executable context and policies
559
+ """
560
+ __allow_access_to_unprotected_subobjects__ = {
561
+ 'validate': 1,
562
+ 'checkPermission': 1,
563
+ 'getUser': 1,
564
+ 'calledByExecutable': 1,
565
+ }
566
+
567
+ def __init__(self, thread_id, context):
568
+ self._thread_id = thread_id
569
+ self._context = context
570
+ self._policy = _defaultPolicy
571
+
572
+ def validate(self,
573
+ accessed=None,
574
+ container=None,
575
+ name=None,
576
+ value=None,
577
+ roles=_noroles,
578
+ ):
579
+ """Validate access.
580
+
581
+ Arguments:
582
+
583
+ accessed -- the object that was being accessed
584
+
585
+ container -- the object the value was found in
586
+
587
+ name -- The name used to access the value
588
+
589
+ value -- The value retrieved though the access.
590
+
591
+ roles -- The roles of the object if already known.
592
+
593
+ The arguments may be provided as keyword arguments. Some of these
594
+ arguments may be ommitted, however, the policy may reject access
595
+ in some cases when arguments are ommitted. It is best to provide
596
+ all the values possible.
597
+ """
598
+ policy = self._policy
599
+ if roles is _noroles:
600
+ return policy.validate(accessed, container, name, value,
601
+ self._context)
602
+ else:
603
+ return policy.validate(accessed, container, name, value,
604
+ self._context, roles)
605
+
606
+ def DTMLValidate(self,
607
+ accessed=None,
608
+ container=None,
609
+ name=None,
610
+ value=None,
611
+ md=None,
612
+ ):
613
+ """Validate access.
614
+ * THIS EXISTS FOR DTML COMPATIBILITY *
615
+
616
+ Arguments:
617
+
618
+ accessed -- the object that was being accessed
619
+
620
+ container -- the object the value was found in
621
+
622
+ name -- The name used to access the value
623
+
624
+ value -- The value retrieved though the access.
625
+
626
+ md -- multidict for DTML (ignored)
627
+
628
+ The arguments may be provided as keyword arguments. Some of these
629
+ arguments may be ommitted, however, the policy may reject access
630
+ in some cases when arguments are ommitted. It is best to provide
631
+ all the values possible.
632
+
633
+ """
634
+ policy = self._policy
635
+ return policy.validate(accessed, container, name, value, self._context)
636
+
637
+ def checkPermission(self, permission, object):
638
+ """Check whether the security context allows the given permission on
639
+ the given object.
640
+
641
+ Arguments:
642
+
643
+ permission -- A permission name
644
+
645
+ object -- The object being accessed according to the permission
646
+ """
647
+ policy = self._policy
648
+ return policy.checkPermission(permission, object, self._context)
649
+
650
+ def addContext(self, anExecutableObject,
651
+ getattr=getattr):
652
+ """Add an ExecutableObject to the current security
653
+ context. Optionally, add a new SecurityPolicy as well.
654
+ """
655
+ stack = self._context.stack
656
+ if len(stack) > max_stack_size:
657
+ raise SystemError('Excessive recursion')
658
+ stack.append(anExecutableObject)
659
+ p = getattr(anExecutableObject, '_customSecurityPolicy', None)
660
+ if p is not None:
661
+ p = p()
662
+ else:
663
+ p = _defaultPolicy
664
+ self._policy = p
665
+
666
+ def removeContext(self, anExecutableObject):
667
+ """Remove an ExecutableObject, and optionally, a
668
+ SecurityPolicy, from the current security context.
669
+ """
670
+ stack = self._context.stack
671
+ if not stack:
672
+ return
673
+ top = stack[-1]
674
+ if top is anExecutableObject:
675
+ del stack[-1]
676
+ else:
677
+ indexes = range(len(stack))
678
+ for i in reversed(indexes):
679
+ top = stack[i]
680
+ if top is anExecutableObject:
681
+ del stack[i:]
682
+ break
683
+ else:
684
+ return
685
+
686
+ if stack:
687
+ top = stack[-1]
688
+ p = getattr(top, '_customSecurityPolicy', None)
689
+ if p is not None:
690
+ p = p()
691
+ else:
692
+ p = _defaultPolicy
693
+ self._policy = p
694
+ else:
695
+ self._policy = _defaultPolicy
696
+
697
+ def getUser(self):
698
+ """Get the current authenticated user"""
699
+ return self._context.user
700
+
701
+ def calledByExecutable(self):
702
+ """Return a boolean value indicating if this context was called
703
+ by an executable"""
704
+ return len(self._context.stack)
705
+
706
+
707
+ # AccessControl.ZopeGuards
708
+ # ------------------------
709
+
710
+
711
+ def aq_validate(inst, object, name, v, validate):
712
+ return validate(inst, object, name, v)
713
+
714
+
715
+ _marker = object()
716
+
717
+
718
+ def guarded_getattr(inst, name, default=_marker):
719
+ """Retrieves an attribute, checking security in the process.
720
+
721
+ Raises Unauthorized if the attribute is found but the user is
722
+ not allowed to access the attribute.
723
+ """
724
+ if name[:1] == '_':
725
+ raise Unauthorized(name)
726
+
727
+ if name in ('format', 'format_map'):
728
+ if isinstance(inst, str):
729
+ from AccessControl.safe_formatter import safe_format
730
+ from AccessControl.safe_formatter import safe_format_map
731
+ if name == 'format':
732
+ return safe_format(inst, name)
733
+ return safe_format_map(inst, name)
734
+ if isinstance(inst, type) and issubclass(inst, str):
735
+ raise Unauthorized(name)
736
+
737
+ # Try to get the attribute normally so that unusual
738
+ # exceptions are caught early.
739
+ try:
740
+ v = getattr(inst, name)
741
+ except AttributeError:
742
+ if default is not _marker:
743
+ return default
744
+ raise
745
+
746
+ # The container assertion must be keyed on the type of the accessed
747
+ # object, to match the C implementation (see ``cAccessControl.c``, which
748
+ # uses ``Containers(type(inst))``). Keying on ``type(v.__self__)``
749
+ # instead let a bound method whose ``__self__`` is an allow-listed simple
750
+ # type (e.g. ``tuple``, ``bytes``, ``range``) take the truthy-assertion
751
+ # short-circuit and be returned without calling ``validate()`` -- a
752
+ # divergence from the C engine.
753
+ assertion = Containers(type(inst))
754
+
755
+ if isinstance(assertion, dict):
756
+ # We got a table that lets us reason about individual
757
+ # attrs
758
+ assertion = assertion.get(name)
759
+ if assertion:
760
+ # There's an entry, but it may be a function.
761
+ if callable(assertion):
762
+ return assertion(inst, name)
763
+
764
+ # Nope, it's boolean
765
+ return v
766
+ raise Unauthorized(name)
767
+
768
+ if assertion:
769
+ if callable(assertion):
770
+ factory = assertion(name, v)
771
+ if callable(factory):
772
+ return factory(inst, name)
773
+ assert factory == 1
774
+ else:
775
+ assert assertion == 1
776
+ return v
777
+
778
+ # See if we can get the value doing a filtered acquire.
779
+ # aq_acquire will either return the same value as held by
780
+ # v or it will return an Unauthorized raised by validate.
781
+ validate = getSecurityManager().validate
782
+ aq_acquire(inst, name, aq_validate, validate)
783
+
784
+ return v
785
+
786
+
787
+ # Helpers for verbose authorization exceptions
788
+ # --------------------------------------------
789
+
790
+
791
+ def item_repr(ob):
792
+ """Generates a repr without angle brackets (to avoid HTML quoting)"""
793
+ return repr(ob).replace('<', '(').replace('>', ')')
794
+
795
+
796
+ def simplifyRoles(roles):
797
+ """Sorts and removes duplicates from a role list."""
798
+ return sorted(set(roles))
799
+
800
+
801
+ def raiseVerbose(msg, accessed, container, name, value, context,
802
+ required_roles=None,
803
+ user_roles=None,
804
+ user=None,
805
+ eo=None,
806
+ eo_owner=None,
807
+ eo_owner_roles=None,
808
+ eo_proxy_roles=None,
809
+ ):
810
+ """Raises an Unauthorized error with a verbose explanation."""
811
+
812
+ s = '{}. Access to {} of {}'.format(
813
+ msg, repr(name), item_repr(container))
814
+ if aq_base(container) is not aq_base(accessed):
815
+ s += ', acquired through %s,' % item_repr(accessed)
816
+ info = [s + ' denied.']
817
+
818
+ if user is not None:
819
+ try:
820
+ ufolder = '/'.join(aq_parent(aq_inner(user)).getPhysicalPath())
821
+ except: # noqa: E722 do not use bare 'except'
822
+ ufolder = '(unknown)'
823
+ info.append('Your user account, {}, exists at {}.'.format(
824
+ str(user), ufolder))
825
+
826
+ if required_roles is not None:
827
+ p = None
828
+ required_roles = list(required_roles)
829
+ for r in required_roles:
830
+ if r.startswith('_') and r.endswith('_Permission'):
831
+ p = r[1:]
832
+ required_roles.remove(r)
833
+ break
834
+ sr = simplifyRoles(required_roles)
835
+ if p:
836
+ # got a permission name
837
+ info.append('Access requires %s, '
838
+ 'granted to the following roles: %s.' %
839
+ (p, sr))
840
+ else:
841
+ # permission name unknown
842
+ info.append('Access requires one of the following roles: %s.'
843
+ % sr)
844
+
845
+ if user_roles is not None:
846
+ info.append(
847
+ 'Your roles in this context are %s.' % simplifyRoles(user_roles))
848
+
849
+ if eo is not None:
850
+ s = 'The executing script is %s' % item_repr(eo)
851
+ if eo_proxy_roles is not None:
852
+ s += ', with proxy roles: %s' % simplifyRoles(eo_proxy_roles)
853
+ if eo_owner is not None:
854
+ s += ', owned by %s' % repr(eo_owner)
855
+ if eo_owner_roles is not None:
856
+ s += ', who has the roles %s' % simplifyRoles(eo_owner_roles)
857
+ info.append(s + '.')
858
+
859
+ text = ' '.join(info)
860
+ LOG.debug('Unauthorized: %s' % text)
861
+ raise Unauthorized(text)
862
+
863
+
864
+ def getUserRolesInContext(user, context):
865
+ """Returns user roles for a context."""
866
+ if hasattr(aq_base(user), 'getRolesInContext'):
867
+ return user.getRolesInContext(context)
868
+ else:
869
+ return ()
870
+
871
+
872
+ def userHasRolesButNotInContext(user, object, object_roles):
873
+ '''Returns 1 if the user has any of the listed roles but
874
+ is not defined in a context which is not an ancestor of object.
875
+ '''
876
+ if object_roles is None or 'Anonymous' in object_roles:
877
+ return 0
878
+ usr_roles = getUserRolesInContext(user, object)
879
+ for role in object_roles:
880
+ if role in usr_roles:
881
+ # User has the roles.
882
+ return (not verifyAcquisitionContext(
883
+ user, object, object_roles))
884
+ return 0
885
+
886
+
887
+ def verifyAcquisitionContext(user, object, object_roles=None):
888
+ """Mimics the relevant section of User.allowed().
889
+
890
+ Returns true if the object is in the context of the user's user folder.
891
+ """
892
+ ufolder = aq_parent(user)
893
+ ucontext = aq_parent(ufolder)
894
+ if ucontext is not None:
895
+ if object is None:
896
+ # This is a strange rule, though
897
+ # it doesn't cause any security holes. SDH
898
+ return 1
899
+ if getattr(object, '__self__', None) is not None:
900
+ # This is a method. Grab its self.
901
+ object = object.__self__
902
+ if not aq_inContextOf(object, ucontext, 1):
903
+ if 'Shared' in object_roles:
904
+ # Old role setting. Waaa
905
+ object_roles = user._shared_roles(object)
906
+ if 'Anonymous' in object_roles:
907
+ return 1
908
+ return None
909
+ # Note that if the user were not wrapped, it would
910
+ # not be possible to determine the user's context
911
+ # and this method would return 1.
912
+ # However, as long as user folders always return
913
+ # wrapped user objects, this is safe.
914
+ return 1