Skip to content

Instantly share code, notes, and snippets.

@gfranxman
Last active February 12, 2021 15:41
Show Gist options
  • Save gfranxman/7e49f74c915c4ef8f2bc8a8066107a89 to your computer and use it in GitHub Desktop.
Save gfranxman/7e49f74c915c4ef8f2bc8a8066107a89 to your computer and use it in GitHub Desktop.
POC suggestion for coarse grained view security policies -- BAST Pructise?
import re
from logging import getLogger
from django.conf import settings
from django.http.response import HttpResponseForbidden
logger = getLogger(__file__)
def is_authenticated(r):
logger.warning("is_authenticated call")
return r.user.is_authenticated
def is_staff(r):
return r.user.is_staff
ANON = {'GET': None, 'POST': None}
PRIVATE = {'GET': is_authenticated, 'POST': is_authenticated}
STAFF = {'GET': is_staff, 'POST': is_staff}
SEC_POLICY = [
(settings.LOGIN_URL, ANON),
('/admin/login/', ANON),
('/admin/', STAFF),
# ('/notes/', PRIVATE), # note the effects of this on the /notes/should_be_private/ view
('/api/private', PRIVATE),
('', ANON), # DEFAULT
]
def sec_policy_middleware(get_response):
def middleware(request):
response = get_response(request)
# check that 200's are allowed:
if response.status_code in [
200,
]:
for pattern, policy in SEC_POLICY:
if re.match(pattern, request.path):
check = policy.get(request.method)
if check:
if not check(request):
return HttpResponseForbidden("0xHA1 this request violates the BAST")
else:
logger.error(f"no policy for {request.method}")
break
return response
return middleware
# TODO: pre-compile the patterns,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment