Skip to content

Commit

Permalink
csrf wip
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Nov 1, 2019
1 parent e3593b7 commit 659d20c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 28 deletions.
21 changes: 8 additions & 13 deletions piccolo_api/csp/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@


@dataclass
class CSPConfig():
class CSPConfig:
report_uri: t.Optional[bytes] = None


class CSPMiddleware():
class CSPMiddleware:
"""
Adds Content Security Policy headers to the response.
Might consider replacing with: https://secure.readthedocs.io/en/latest/
"""

def __init__(self, app: ASGIApp, config: CSPConfig = CSPConfig()):
Expand All @@ -23,21 +25,14 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
@wraps(send)
async def wrapped_send(message: Message):
if message["type"] == "http.response.start":
headers = message.get('headers', [])
headers = message.get("headers", [])
header_value = b"default-src 'self'"
if self.config.report_uri:
header_value = (
header_value +
b'; report-uri ' +
self.config.report_uri
header_value + b"; report-uri " + self.config.report_uri
)
headers.append(
[
b'Content-Security-Policy',
header_value
]
)
message['headers'] = headers
headers.append([b"Content-Security-Policy", header_value])
message["headers"] = headers

await send(message)

Expand Down
29 changes: 14 additions & 15 deletions piccolo_api/csrf/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
from starlette.types import Scope, Receive, Send, ASGIApp
import random

from starlette.middleware.base import (
BaseHTTPMiddleware,
RequestResponseEndpoint,
Request,
)

class CSRFMiddleware():

class CSRFMiddleware(BaseHTTPMiddleware):
"""
For GET requests, set a random token as a cookie. For unsafe HTTP methods,
require a HTTP header to match the cookie value, otherwise the request
Expand All @@ -13,19 +19,12 @@ class CSRFMiddleware():
https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie
"""

def __init__(
self,
asgi: ASGIApp,
) -> None:
self.asgi = asgi

async def __call__(self, scope: Scope, receive: Receive, send: Send):
"""
Add the user_id to the scope if a JWT token is available, and the user
is recognised, otherwise raise a 403 HTTP error.
"""
if scope['method'] == 'GET':
# TODO - set cookies
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
):
if request.method == "GET":
response = await call_next()
response.set_cookie("csrftoken", random.random)
pass
else:
# TODO - verify header matches cookie value.
Expand Down

0 comments on commit 659d20c

Please sign in to comment.