Bowe Strickland
2018-10-27 323fa95deea50f49c119728fc2eeacb9e0c51241
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import inspect
 
from zope.interface import implementer, provider
 
from pyramid.security import NO_PERMISSION_REQUIRED, Authenticated
from pyramid.csrf import check_csrf_origin, check_csrf_token
from pyramid.response import Response
 
from pyramid.interfaces import (
    IAuthenticationPolicy,
    IAuthorizationPolicy,
    IDefaultCSRFOptions,
    IDefaultPermission,
    IDebugLogger,
    IResponse,
    IViewMapper,
    IViewMapperFactory,
)
 
from pyramid.compat import is_bound_method, is_unbound_method
 
from pyramid.exceptions import ConfigurationError
from pyramid.httpexceptions import HTTPForbidden, HTTPUnauthorized
from pyramid.util import object_description, takes_one_arg
from pyramid.view import render_view_to_response
from pyramid import renderers
 
 
def view_description(view):
    try:
        return view.__text__
    except AttributeError:
        # custom view mappers might not add __text__
        return object_description(view)
 
 
def requestonly(view, attr=None):
    return takes_one_arg(view, attr=attr, argname='request')
 
 
@implementer(IViewMapper)
@provider(IViewMapperFactory)
class DefaultViewMapper(object):
    def __init__(self, **kw):
        self.attr = kw.get('attr')
 
    def __call__(self, view):
        if is_unbound_method(view) and self.attr is None:
            raise ConfigurationError(
                (
                    'Unbound method calls are not supported, please set the '
                    'class as your `view` and the method as your `attr`'
                )
            )
 
        if inspect.isclass(view):
            view = self.map_class(view)
        else:
            view = self.map_nonclass(view)
        return view
 
    def map_class(self, view):
        ronly = requestonly(view, self.attr)
        if ronly:
            mapped_view = self.map_class_requestonly(view)
        else:
            mapped_view = self.map_class_native(view)
        mapped_view.__text__ = 'method %s of %s' % (
            self.attr or '__call__',
            object_description(view),
        )
        return mapped_view
 
    def map_nonclass(self, view):
        # We do more work here than appears necessary to avoid wrapping the
        # view unless it actually requires wrapping (to avoid function call
        # overhead).
        mapped_view = view
        ronly = requestonly(view, self.attr)
        if ronly:
            mapped_view = self.map_nonclass_requestonly(view)
        elif self.attr:
            mapped_view = self.map_nonclass_attr(view)
        if inspect.isroutine(mapped_view):
            # This branch will be true if the view is a function or a method.
            # We potentially mutate an unwrapped object here if it's a
            # function.  We do this to avoid function call overhead of
            # injecting another wrapper.  However, we must wrap if the
            # function is a bound method because we can't set attributes on a
            # bound method.
            if is_bound_method(view):
                _mapped_view = mapped_view
 
                def mapped_view(context, request):
                    return _mapped_view(context, request)
 
            if self.attr is not None:
                mapped_view.__text__ = 'attr %s of %s' % (
                    self.attr,
                    object_description(view),
                )
            else:
                mapped_view.__text__ = object_description(view)
        return mapped_view
 
    def map_class_requestonly(self, view):
        # its a class that has an __init__ which only accepts request
        attr = self.attr
 
        def _class_requestonly_view(context, request):
            inst = view(request)
            request.__view__ = inst
            if attr is None:
                response = inst()
            else:
                response = getattr(inst, attr)()
            return response
 
        return _class_requestonly_view
 
    def map_class_native(self, view):
        # its a class that has an __init__ which accepts both context and
        # request
        attr = self.attr
 
        def _class_view(context, request):
            inst = view(context, request)
            request.__view__ = inst
            if attr is None:
                response = inst()
            else:
                response = getattr(inst, attr)()
            return response
 
        return _class_view
 
    def map_nonclass_requestonly(self, view):
        # its a function that has a __call__ which accepts only a single
        # request argument
        attr = self.attr
 
        def _requestonly_view(context, request):
            if attr is None:
                response = view(request)
            else:
                response = getattr(view, attr)(request)
            return response
 
        return _requestonly_view
 
    def map_nonclass_attr(self, view):
        # its a function that has a __call__ which accepts both context and
        # request, but still has an attr
        def _attr_view(context, request):
            response = getattr(view, self.attr)(context, request)
            return response
 
        return _attr_view
 
 
def wraps_view(wrapper):
    def inner(view, info):
        wrapper_view = wrapper(view, info)
        return preserve_view_attrs(view, wrapper_view)
 
    return inner
 
 
def preserve_view_attrs(view, wrapper):
    if view is None:
        return wrapper
 
    if wrapper is view:
        return view
 
    original_view = getattr(view, '__original_view__', None)
 
    if original_view is None:
        original_view = view
 
    wrapper.__wraps__ = view
    wrapper.__original_view__ = original_view
    wrapper.__module__ = view.__module__
    wrapper.__doc__ = view.__doc__
 
    try:
        wrapper.__name__ = view.__name__
    except AttributeError:
        wrapper.__name__ = repr(view)
 
    # attrs that may not exist on "view", but, if so, must be attached to
    # "wrapped view"
    for attr in (
        '__permitted__',
        '__call_permissive__',
        '__permission__',
        '__predicated__',
        '__predicates__',
        '__accept__',
        '__order__',
        '__text__',
    ):
        try:
            setattr(wrapper, attr, getattr(view, attr))
        except AttributeError:
            pass
 
    return wrapper
 
 
def mapped_view(view, info):
    mapper = info.options.get('mapper')
    if mapper is None:
        mapper = getattr(view, '__view_mapper__', None)
        if mapper is None:
            mapper = info.registry.queryUtility(IViewMapperFactory)
            if mapper is None:
                mapper = DefaultViewMapper
 
    mapped_view = mapper(**info.options)(view)
    return mapped_view
 
 
mapped_view.options = ('mapper', 'attr')
 
 
def owrapped_view(view, info):
    wrapper_viewname = info.options.get('wrapper')
    viewname = info.options.get('name')
    if not wrapper_viewname:
        return view
 
    def _owrapped_view(context, request):
        response = view(context, request)
        request.wrapped_response = response
        request.wrapped_body = response.body
        request.wrapped_view = view
        wrapped_response = render_view_to_response(
            context, request, wrapper_viewname
        )
        if wrapped_response is None:
            raise ValueError(
                'No wrapper view named %r found when executing view '
                'named %r' % (wrapper_viewname, viewname)
            )
        return wrapped_response
 
    return _owrapped_view
 
 
owrapped_view.options = ('name', 'wrapper')
 
 
def http_cached_view(view, info):
    if info.settings.get('prevent_http_cache', False):
        return view
 
    seconds = info.options.get('http_cache')
 
    if seconds is None:
        return view
 
    options = {}
 
    if isinstance(seconds, (tuple, list)):
        try:
            seconds, options = seconds
        except ValueError:
            raise ConfigurationError(
                'If http_cache parameter is a tuple or list, it must be '
                'in the form (seconds, options); not %s' % (seconds,)
            )
 
    def wrapper(context, request):
        response = view(context, request)
        prevent_caching = getattr(
            response.cache_control, 'prevent_auto', False
        )
        if not prevent_caching:
            response.cache_expires(seconds, **options)
        return response
 
    return wrapper
 
 
http_cached_view.options = ('http_cache',)
 
 
def secured_view(view, info):
    for wrapper in (_secured_view, _authdebug_view):
        view = wraps_view(wrapper)(view, info)
    return view
 
 
secured_view.options = ('permission',)
 
 
def _secured_view(view, info):
    permission = explicit_val = info.options.get('permission')
    if permission is None:
        permission = info.registry.queryUtility(IDefaultPermission)
    if permission == NO_PERMISSION_REQUIRED:
        # allow views registered within configurations that have a
        # default permission to explicitly override the default
        # permission, replacing it with no permission at all
        permission = None
 
    wrapped_view = view
    authn_policy = info.registry.queryUtility(IAuthenticationPolicy)
    authz_policy = info.registry.queryUtility(IAuthorizationPolicy)
 
    # no-op on exception-only views without an explicit permission
    if explicit_val is None and info.exception_only:
        return view
 
    if authn_policy and authz_policy and (permission is not None):
 
        def permitted(context, request):
            principals = authn_policy.effective_principals(request)
            return authz_policy.permits(context, principals, permission)
 
        def secured_view(context, request):
            result = permitted(context, request)
            if result:
                return view(context, request)
            view_name = getattr(view, '__name__', view)
            msg = getattr(
                request,
                'authdebug_message',
                'Unauthorized: %s failed permission check' % view_name,
            )
            if Authenticated in result.principals:
                raise HTTPForbidden(msg, result=result)
            raise HTTPUnauthorized(msg)
 
        wrapped_view = secured_view
        wrapped_view.__call_permissive__ = view
        wrapped_view.__permitted__ = permitted
        wrapped_view.__permission__ = permission
 
    return wrapped_view
 
 
def _authdebug_view(view, info):
    wrapped_view = view
    settings = info.settings
    permission = explicit_val = info.options.get('permission')
    if permission is None:
        permission = info.registry.queryUtility(IDefaultPermission)
    authn_policy = info.registry.queryUtility(IAuthenticationPolicy)
    authz_policy = info.registry.queryUtility(IAuthorizationPolicy)
    logger = info.registry.queryUtility(IDebugLogger)
 
    # no-op on exception-only views without an explicit permission
    if explicit_val is None and info.exception_only:
        return view
 
    if settings and settings.get('debug_authorization', False):
 
        def authdebug_view(context, request):
            view_name = getattr(request, 'view_name', None)
 
            if authn_policy and authz_policy:
                if permission is NO_PERMISSION_REQUIRED:
                    msg = 'Allowed (NO_PERMISSION_REQUIRED)'
                elif permission is None:
                    msg = 'Allowed (no permission registered)'
                else:
                    principals = authn_policy.effective_principals(request)
                    msg = str(
                        authz_policy.permits(context, principals, permission)
                    )
            else:
                msg = 'Allowed (no authorization policy in use)'
 
            view_name = getattr(request, 'view_name', None)
            url = getattr(request, 'url', None)
            msg = (
                'debug_authorization of url %s (view name %r against '
                'context %r): %s' % (url, view_name, context, msg)
            )
            if logger:
                logger.debug(msg)
            if request is not None:
                request.authdebug_message = msg
            return view(context, request)
 
        wrapped_view = authdebug_view
 
    return wrapped_view
 
 
def rendered_view(view, info):
    # one way or another this wrapper must produce a Response (unless
    # the renderer is a NullRendererHelper)
    renderer = info.options.get('renderer')
    if renderer is None:
        # register a default renderer if you want super-dynamic
        # rendering.  registering a default renderer will also allow
        # override_renderer to work if a renderer is left unspecified for
        # a view registration.
        def viewresult_to_response(context, request):
            result = view(context, request)
            if result.__class__ is Response:  # common case
                response = result
            else:
                response = info.registry.queryAdapterOrSelf(result, IResponse)
                if response is None:
                    if result is None:
                        append = (
                            ' You may have forgotten to return a value '
                            'from the view callable.'
                        )
                    elif isinstance(result, dict):
                        append = (
                            ' You may have forgotten to define a '
                            'renderer in the view configuration.'
                        )
                    else:
                        append = ''
 
                    msg = (
                        'Could not convert return value of the view '
                        'callable %s into a response object. '
                        'The value returned was %r.' + append
                    )
 
                    raise ValueError(msg % (view_description(view), result))
 
            return response
 
        return viewresult_to_response
 
    if renderer is renderers.null_renderer:
        return view
 
    def rendered_view(context, request):
        result = view(context, request)
        if result.__class__ is Response:  # potential common case
            response = result
        else:
            # this must adapt, it can't do a simple interface check
            # (avoid trying to render webob responses)
            response = info.registry.queryAdapterOrSelf(result, IResponse)
            if response is None:
                attrs = getattr(request, '__dict__', {})
                if 'override_renderer' in attrs:
                    # renderer overridden by newrequest event or other
                    renderer_name = attrs.pop('override_renderer')
                    view_renderer = renderers.RendererHelper(
                        name=renderer_name,
                        package=info.package,
                        registry=info.registry,
                    )
                else:
                    view_renderer = renderer.clone()
                if '__view__' in attrs:
                    view_inst = attrs.pop('__view__')
                else:
                    view_inst = getattr(view, '__original_view__', view)
                response = view_renderer.render_view(
                    request, result, view_inst, context
                )
        return response
 
    return rendered_view
 
 
rendered_view.options = ('renderer',)
 
 
def decorated_view(view, info):
    decorator = info.options.get('decorator')
    if decorator is None:
        return view
    return decorator(view)
 
 
decorated_view.options = ('decorator',)
 
 
def csrf_view(view, info):
    explicit_val = info.options.get('require_csrf')
    defaults = info.registry.queryUtility(IDefaultCSRFOptions)
    if defaults is None:
        default_val = False
        token = 'csrf_token'
        header = 'X-CSRF-Token'
        safe_methods = frozenset(["GET", "HEAD", "OPTIONS", "TRACE"])
        callback = None
    else:
        default_val = defaults.require_csrf
        token = defaults.token
        header = defaults.header
        safe_methods = defaults.safe_methods
        callback = defaults.callback
 
    enabled = (
        explicit_val is True
        or
        # fallback to the default val if not explicitly enabled
        # but only if the view is not an exception view
        (explicit_val is not False and default_val and not info.exception_only)
    )
    # disable if both header and token are disabled
    enabled = enabled and (token or header)
    wrapped_view = view
    if enabled:
 
        def csrf_view(context, request):
            if request.method not in safe_methods and (
                callback is None or callback(request)
            ):
                check_csrf_origin(request, raises=True)
                check_csrf_token(request, token, header, raises=True)
            return view(context, request)
 
        wrapped_view = csrf_view
    return wrapped_view
 
 
csrf_view.options = ('require_csrf',)
 
VIEW = 'VIEW'
INGRESS = 'INGRESS'