Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_overlapping_request_ctx() -> None:
app = Quart(__name__)
request = Request(
"GET", "http", "/", b"", CIMultiDict(), "", "1.1", send_push_promise=no_op_push
)
ctx1 = app.request_context(request)
await ctx1.__aenter__()
ctx2 = app.request_context(request)
await ctx2.__aenter__()
await ctx1.__aexit__(None, None, None)
assert has_app_context() # Ensure the app context still exists for ctx2
await ctx2.__aexit__(None, None, None)
def test_access_log_header_atoms() -> None:
request_headers = CIMultiDict({
'Random': 'Request',
'Remote-Addr': '127.0.0.1',
})
request = Request('GET', 'http', '/', b'', request_headers)
response_headers = CIMultiDict({
'Random': 'Response',
})
response = Response('Hello', 200, response_headers)
atoms = AccessLogAtoms(request, response, 'h2', 0)
assert atoms['{random}i'] == 'Request'
assert atoms['{RANDOM}i'] == 'Request'
assert atoms['{not-atom}i'] == '-'
assert atoms['{random}o'] == 'Response'
assert atoms['{RANDOM}o'] == 'Response'
async def test_secure_cookie_session_interface_open_session() -> None:
session = SecureCookieSession()
session["something"] = "else"
interface = SecureCookieSessionInterface()
app = Quart(__name__)
app.secret_key = "secret"
response = Response("")
await interface.save_session(app, session, response)
request = Request(
"GET", "http", "/", b"", CIMultiDict(), "", "1.1", send_push_promise=no_op_push
)
request.headers["Cookie"] = response.headers["Set-Cookie"]
new_session = await interface.open_session(app, request)
assert new_session == session
def test_digest_authorization() -> None:
headers = CIMultiDict()
headers["Authorization"] = (
"Digest "
'username="identity", '
'realm="realm@rea.lm", '
'nonce="abcd1234", '
'uri="/path", '
'response="abcd1235", '
'opaque="abcd1236"'
)
request = BaseRequestWebsocket("GET", "http", "/", b"", headers, "", "1.1")
auth = request.authorization
assert auth.username == "identity"
assert auth.realm == "realm@rea.lm"
assert auth.nonce == "abcd1234"
assert auth.uri == "/path"
assert auth.response == "abcd1235"
def _handle_events(self, events: List[h2.events.Event]) -> None:
for event in events:
if isinstance(event, h2.events.RequestReceived):
headers = CIMultiDict()
for name, value in event.headers:
headers.add(name.title(), value)
self.handle_request(
event.stream_id, headers[':method'].upper(), headers[':path'], headers,
)
elif isinstance(event, h2.events.DataReceived):
self.streams[event.stream_id].append(event.data)
elif isinstance(event, h2.events.StreamReset):
self.streams.pop(event.stream_id).task.cancel()
elif isinstance(event, h2.events.StreamEnded):
self.streams[event.stream_id].complete()
elif isinstance(event, h2.events.WindowUpdated):
self._window_updated(event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
self.close()
return
def __init__(self, headers: Optional[Union[dict, CIMultiDict]]) -> None:
self.headers: CIMultiDict
if headers is None:
self.headers = CIMultiDict()
elif isinstance(headers, CIMultiDict):
self.headers = headers
elif headers is not None:
self.headers = CIMultiDict(headers)
def _server_push(self, stream_id: int, path: str) -> None:
push_stream_id = self.connection.get_next_available_stream_id()
request_headers = [
(':method', 'GET'), (':path', path),
(':scheme', self.streams[stream_id].request.headers[':scheme']),
(':authority', self.streams[stream_id].request.headers[':authority']),
]
try:
self.connection.push_stream(
stream_id=stream_id, promised_stream_id=push_stream_id,
request_headers=request_headers,
)
except h2.exceptions.ProtocolError:
pass # Client does not accept push promises
else:
self.handle_request(push_stream_id, 'GET', path, CIMultiDict(request_headers)) # type: ignore # noqa: E501
def _create_websocket_from_scope(self, send: Callable) -> Websocket:
headers = CIMultiDict()
headers['Remote-Addr'] = (self.scope.get('client') or [''])[0]
for name, value in self.scope['headers']:
headers.add(name.decode("latin1").title(), value.decode("latin1"))
path = self.scope["path"]
path = path if path[0] == "/" else urlparse(path).path
path = f"{self.scope['root_path']}{path}"
return self.app.websocket_class(
path, self.scope['query_string'], self.scope['scheme'],
headers, self.scope.get('subprotocols', []), self.queue.get,
partial(self.send_data, send), partial(self.accept_connection, send),
)
def _handle_events(self) -> None:
while True:
if self.connection.they_are_waiting_for_100_continue:
self._send(
h11.InformationalResponse(status_code=100, headers=self.response_headers()),
)
try:
event = self.connection.next_event()
except h11.RemoteProtocolError:
self._handle_error()
self.close()
break
else:
if isinstance(event, h11.Request):
headers = CIMultiDict()
if event.http_version < b'1.1':
headers.setdefault('host', self.app.config['SERVER_NAME'] or '')
for name, value in event.headers:
headers.add(name.decode().title(), value.decode())
if 'Upgrade' in headers:
self._handle_upgrade_request(headers, event)
self.handle_request(
0, event.method.decode().upper(), event.target.decode(), headers,
)
elif isinstance(event, h11.EndOfMessage):
self.streams[0].complete()
elif isinstance(event, h11.Data):
self.streams[0].append(event.data)
elif event is h11.NEED_DATA or event is h11.PAUSED:
break
elif isinstance(event, h11.ConnectionClosed):
def __init__(self, headers: Optional[Union[dict, CIMultiDict]]) -> None:
self.headers: CIMultiDict
if headers is None:
self.headers = CIMultiDict()
elif isinstance(headers, CIMultiDict):
self.headers = headers
elif headers is not None:
self.headers = CIMultiDict(headers)