mirror of
https://gitlab.archlinux.org/archlinux/aurweb.git
synced 2025-02-03 10:43:03 +01:00
style: Run pre-commit
This commit is contained in:
parent
b47882b114
commit
9c6c13b78a
235 changed files with 7180 additions and 5628 deletions
104
aurweb/asgi.py
104
aurweb/asgi.py
|
@ -6,11 +6,9 @@ import re
|
|||
import sys
|
||||
import traceback
|
||||
import typing
|
||||
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
import requests
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
@ -26,7 +24,6 @@ import aurweb.config
|
|||
import aurweb.filters # noqa: F401
|
||||
import aurweb.logging
|
||||
import aurweb.pkgbase.util as pkgbaseutil
|
||||
|
||||
from aurweb import logging, prometheus, util
|
||||
from aurweb.auth import BasicAuthBackend
|
||||
from aurweb.db import get_engine, query
|
||||
|
@ -60,33 +57,33 @@ async def app_startup():
|
|||
# provided by the user. Docker uses .env's TEST_RECURSION_LIMIT
|
||||
# when running test suites.
|
||||
# TODO: Find a proper fix to this issue.
|
||||
recursion_limit = int(os.environ.get(
|
||||
"TEST_RECURSION_LIMIT", sys.getrecursionlimit() + 1000))
|
||||
recursion_limit = int(
|
||||
os.environ.get("TEST_RECURSION_LIMIT", sys.getrecursionlimit() + 1000)
|
||||
)
|
||||
sys.setrecursionlimit(recursion_limit)
|
||||
|
||||
backend = aurweb.config.get("database", "backend")
|
||||
if backend not in aurweb.db.DRIVERS:
|
||||
raise ValueError(
|
||||
f"The configured database backend ({backend}) is unsupported. "
|
||||
f"Supported backends: {str(aurweb.db.DRIVERS.keys())}")
|
||||
f"Supported backends: {str(aurweb.db.DRIVERS.keys())}"
|
||||
)
|
||||
|
||||
session_secret = aurweb.config.get("fastapi", "session_secret")
|
||||
if not session_secret:
|
||||
raise Exception("[fastapi] session_secret must not be empty")
|
||||
|
||||
if not os.environ.get("PROMETHEUS_MULTIPROC_DIR", None):
|
||||
logger.warning("$PROMETHEUS_MULTIPROC_DIR is not set, the /metrics "
|
||||
"endpoint is disabled.")
|
||||
logger.warning(
|
||||
"$PROMETHEUS_MULTIPROC_DIR is not set, the /metrics "
|
||||
"endpoint is disabled."
|
||||
)
|
||||
|
||||
app.mount("/static/css",
|
||||
StaticFiles(directory="web/html/css"),
|
||||
name="static_css")
|
||||
app.mount("/static/js",
|
||||
StaticFiles(directory="web/html/js"),
|
||||
name="static_js")
|
||||
app.mount("/static/images",
|
||||
StaticFiles(directory="web/html/images"),
|
||||
name="static_images")
|
||||
app.mount("/static/css", StaticFiles(directory="web/html/css"), name="static_css")
|
||||
app.mount("/static/js", StaticFiles(directory="web/html/js"), name="static_js")
|
||||
app.mount(
|
||||
"/static/images", StaticFiles(directory="web/html/images"), name="static_images"
|
||||
)
|
||||
|
||||
# Add application middlewares.
|
||||
app.add_middleware(AuthenticationMiddleware, backend=BasicAuthBackend())
|
||||
|
@ -95,6 +92,7 @@ async def app_startup():
|
|||
# Add application routes.
|
||||
def add_router(module):
|
||||
app.include_router(module.router)
|
||||
|
||||
util.apply_all(APP_ROUTES, add_router)
|
||||
|
||||
# Initialize the database engine and ORM.
|
||||
|
@ -102,8 +100,8 @@ async def app_startup():
|
|||
|
||||
|
||||
def child_exit(server, worker): # pragma: no cover
|
||||
""" This function is required for gunicorn customization
|
||||
of prometheus multiprocessing. """
|
||||
"""This function is required for gunicorn customization
|
||||
of prometheus multiprocessing."""
|
||||
multiprocess.mark_process_dead(worker.pid)
|
||||
|
||||
|
||||
|
@ -177,9 +175,7 @@ async def internal_server_error(request: Request, exc: Exception) -> Response:
|
|||
else:
|
||||
# post
|
||||
form_data = str(dict(request.state.form_data))
|
||||
desc = desc + [
|
||||
f"- Data: `{form_data}`"
|
||||
] + ["", f"```{tb}```"]
|
||||
desc = desc + [f"- Data: `{form_data}`"] + ["", f"```{tb}```"]
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
data = {
|
||||
|
@ -191,11 +187,12 @@ async def internal_server_error(request: Request, exc: Exception) -> Response:
|
|||
logger.info(endp)
|
||||
resp = requests.post(endp, json=data, headers=headers)
|
||||
if resp.status_code != http.HTTPStatus.CREATED:
|
||||
logger.error(
|
||||
f"Unable to report exception to {repo}: {resp.text}")
|
||||
logger.error(f"Unable to report exception to {repo}: {resp.text}")
|
||||
else:
|
||||
logger.warning("Unable to report an exception found due to "
|
||||
"unset notifications.error-{{project,token}}")
|
||||
logger.warning(
|
||||
"Unable to report an exception found due to "
|
||||
"unset notifications.error-{{project,token}}"
|
||||
)
|
||||
|
||||
# Log details about the exception traceback.
|
||||
logger.error(f"FATAL[{tb_id}]: An unexpected exception has occurred.")
|
||||
|
@ -203,14 +200,17 @@ async def internal_server_error(request: Request, exc: Exception) -> Response:
|
|||
else:
|
||||
retval = retval.decode()
|
||||
|
||||
return render_template(request, "errors/500.html", context,
|
||||
status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR)
|
||||
return render_template(
|
||||
request,
|
||||
"errors/500.html",
|
||||
context,
|
||||
status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) \
|
||||
-> Response:
|
||||
""" Handle an HTTPException thrown in a route. """
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
|
||||
"""Handle an HTTPException thrown in a route."""
|
||||
phrase = http.HTTPStatus(exc.status_code).phrase
|
||||
context = make_context(request, phrase)
|
||||
context["exc"] = exc
|
||||
|
@ -228,16 +228,16 @@ async def http_exception_handler(request: Request, exc: HTTPException) \
|
|||
pass
|
||||
|
||||
try:
|
||||
return render_template(request, f"errors/{exc.status_code}.html",
|
||||
context, exc.status_code)
|
||||
return render_template(
|
||||
request, f"errors/{exc.status_code}.html", context, exc.status_code
|
||||
)
|
||||
except TemplateNotFound:
|
||||
return render_template(request, "errors/detail.html",
|
||||
context, exc.status_code)
|
||||
return render_template(request, "errors/detail.html", context, exc.status_code)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_security_headers(request: Request, call_next: typing.Callable):
|
||||
""" This middleware adds the CSP, XCTO, XFO and RP security
|
||||
"""This middleware adds the CSP, XCTO, XFO and RP security
|
||||
headers to the HTTP response associated with request.
|
||||
|
||||
CSP: Content-Security-Policy
|
||||
|
@ -254,7 +254,7 @@ async def add_security_headers(request: Request, call_next: typing.Callable):
|
|||
nonce = request.user.nonce
|
||||
csp = "default-src 'self'; "
|
||||
script_hosts = []
|
||||
csp += f"script-src 'self' 'nonce-{nonce}' " + ' '.join(script_hosts)
|
||||
csp += f"script-src 'self' 'nonce-{nonce}' " + " ".join(script_hosts)
|
||||
# It's fine if css is inlined.
|
||||
csp += "; style-src 'self' 'unsafe-inline'"
|
||||
response.headers["Content-Security-Policy"] = csp
|
||||
|
@ -276,17 +276,25 @@ async def add_security_headers(request: Request, call_next: typing.Callable):
|
|||
|
||||
@app.middleware("http")
|
||||
async def check_terms_of_service(request: Request, call_next: typing.Callable):
|
||||
""" This middleware function redirects authenticated users if they
|
||||
have any outstanding Terms to agree to. """
|
||||
"""This middleware function redirects authenticated users if they
|
||||
have any outstanding Terms to agree to."""
|
||||
if request.user.is_authenticated() and request.url.path != "/tos":
|
||||
unaccepted = query(Term).join(AcceptedTerm).filter(
|
||||
or_(AcceptedTerm.UsersID != request.user.ID,
|
||||
and_(AcceptedTerm.UsersID == request.user.ID,
|
||||
AcceptedTerm.TermsID == Term.ID,
|
||||
AcceptedTerm.Revision < Term.Revision)))
|
||||
unaccepted = (
|
||||
query(Term)
|
||||
.join(AcceptedTerm)
|
||||
.filter(
|
||||
or_(
|
||||
AcceptedTerm.UsersID != request.user.ID,
|
||||
and_(
|
||||
AcceptedTerm.UsersID == request.user.ID,
|
||||
AcceptedTerm.TermsID == Term.ID,
|
||||
AcceptedTerm.Revision < Term.Revision,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
if query(Term).count() > unaccepted.count():
|
||||
return RedirectResponse(
|
||||
"/tos", status_code=int(http.HTTPStatus.SEE_OTHER))
|
||||
return RedirectResponse("/tos", status_code=int(http.HTTPStatus.SEE_OTHER))
|
||||
|
||||
return await util.error_or_result(call_next, request)
|
||||
|
||||
|
@ -301,9 +309,9 @@ async def id_redirect_middleware(request: Request, call_next: typing.Callable):
|
|||
for k, v in request.query_params.items():
|
||||
if k != "id":
|
||||
qs.append(f"{k}={quote_plus(str(v))}")
|
||||
qs = str() if not qs else '?' + '&'.join(qs)
|
||||
qs = str() if not qs else "?" + "&".join(qs)
|
||||
|
||||
path = request.url.path.rstrip('/')
|
||||
path = request.url.path.rstrip("/")
|
||||
return RedirectResponse(f"{path}/{id}{qs}")
|
||||
|
||||
return await util.error_or_result(call_next, request)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue