如何编写路由以使用 Flask 接收内容安全策略报告,而不会收到 400 错误请求错误 (flask_wtf.csrf.



TL;大卫:对长篇大论表示歉意。简而言之,我正在尝试调试CSPreport-uri。如果我缺少关键信息,请告诉我。

CSP 实现:烧瓶护身符
需要设置的属性:content_security_policy_report_uri

关于如何捕获此报告的信息似乎并不多
我在Flask-Talisman文档中找不到任何具体内容

由于Flask-Talisman只设置标头,包括report-uri,我想这无论如何都超出了扩展范围

路线

我找到的所有资源都有大致相同的功能:
https://www.merixstudio.com/blog/content-security-policy-flask-and-django-part-2/http://csplite.com/csp260/https://github.com/GoogleCloudPlatform/flask-talisman/issues/21

我为这条路线找到的唯一真正详细的解释如下(但是它与Flask-Talisman无关)

从 https://www.merixstudio.com/blog/content-security-policy-flask-and-django-part-2/(这是我目前正在使用的)

# app/routes/report.py
import json
import pprint

from flask import request, make_response, Blueprint
...
bp = Blueprint("report", __name__, url_prefix="report")
...
@bp.route('/csp-violations', methods=['POST'])
def report():
"""Receive a post request containing csp-resport.
This is the report-uri. Print report to console and 
return Response object.
:return: Flask Response object.
"""
pprint.pprint(json.loads(str(request.data, 'utf-8')))
response = make_response()
response.status_code = 200
return response
...

此路由仅收到 400 错误,我不知道如何实际调试它

127.0.0.1 - - [04/Nov/2021 14:29:09] "POST /report/csp-violations HTTP/1.1" 400 -

我尝试过使用 GET 请求,可以看到我收到一个空请求,这似乎意味着 CSP 报告未交付(来自https://127.0.0.1:5000/report/csp-violations的响应)

# app/routes/report.py
...
@bp.route('/csp-violations', methods=['GET', 'POST'])
def report():
...
b''
b''
127.0.0.1 - - [04/Nov/2021 18:03:52] "GET /report/csp_violations HTTP/1.1" 200 -

编辑:绝对什么也没收到

...
@bp.route("/csp_violations", methods=["GET", "POST"])
def report():
...
return str(request.args)  # ImmutableMultiDict([ ])

不适用于 GET 或 POST 请求(仍然为 400)

...
@bp.route("/csp_violations", methods=["GET", "POST"])
def report():
content = request.get_json(force=True)
...

没有force=True

@bp.route("/csp_violations", methods=["GET", "POST"])
def report():
content = request.get_json()  # json.decoder.JSONDecodeError
...

Chromium(在Chrome,Brave和FireFox上的结果相同)

当我在 CTRL-SHIFT-I>网络下的 Chromium 上查看时,我看到

Request URL: https://127.0.0.1:5000/report/csp_violations
Request Method: POST
Status Code: 400 BAD REQUEST
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin

但显然有效载荷确实存在于"请求有效载荷"下的底部......

{
"document-uri": "https://127.0.0.1:5000/",
"referrer": "",
"violated-directive": "script-src-elem",
"effective-directive": "script-src-elem",
"original-policy": "default-src 'self' https://cdnjs.cloudflare.com https://cdn.cloudflare.com https://cdn.jsdelivr.net https://gravatar.com jquery.js; report-uri /report/csp-violations",
"disposition": "enforce",
"blocked-uri": "inline",
"line-number": 319,
"source-file": "https://127.0.0.1:5000/",
"status-code": 200,
"script-sample": ""
}

云解决方案提供商是否阻止此请求?

阅读 Python Flask 400 错误请求错误后,我在 https://stackoverflow.com/a/63708394/13316671
的帮助下将所有请求设置为 HTTPS,这修复了一些单元测试,但对此特定路由的 400 错误没有变化

# app/config.py
from environs import Env
from flask import Flask
env = Env()

env.read_env()


class Config:
"""Load environment."""
...
@property
def PREFERRED_URL_SCHEME(self) -> str:  # noqa
return env.str("PREFERRED_URL_SCHEME", default="https")
...

# app/__init__.py
from app.config import Config

def create_app() -> Flask:
app = Flask(__name__)
app.config.from_object(Config())
...
return app
flask run --cert="$HOME/.openssl/cert.pem" --key="$HOME/.openssl/key.pem"

400 错误请求

通过我所阅读的内容,400错误请求错误通常发生在空请求或表单中

https://stackoverflow.com/a/14113958/13316671

...the issue is that Flask raises an HTTP error when it fails to find a key in 
the args and form dictionaries. What Flask assumes by default is that if you 
are asking for a particular key and it's not there then something got 
left out of the request and the entire request is invalid.

https://stackoverflow.com/a/37017020/13316671

99% of the time, this error is a key error caused by your requesting a key in 
the request.form dictionary that does not exist. To debug it, run
print(request.form)

request.data就我而言

通过尝试解决此问题,我已经陷入了兔子洞,只是看到了 400 错误的原因

我已经实现了以下内容

https://stackoverflow.com/a/34172382/13316671


import traceback

from flask import Flask  
...
app = Flask(__name__)
...
@app.errorhandler(400)
def internal_error(exception):  # noqa
print("400 error caught")
print(traceback.format_exc())

并将以下内容添加到我的配置
我没有检查,但我认为这些值已经与DEBUG一起设置


# app/config.py
from environs import Env

env = Env()

env.read_env()


class Config:
"""Load environment."""
...

@property
def TRAP_HTTP_EXCEPTIONS(self) -> bool:  # noqa
"""Report traceback on error."""
return env.bool("TRAP_HTTP_EXCEPTIONS", default=self.DEBUG)  # noqa

@property
def TRAP_BAD_REQUEST_ERRORS(self) -> bool:  # noqa
"""Report 400 traceback on error."""
return env.bool("TRAP_BAD_REQUEST_ERRORS", default=self.DEBUG)  # noqa   
...

我仍然没有得到回溯。werkzeug 唯一一次显示回溯是通过完全崩溃,例如语法错误

似乎,因为我没有初始化应用程序继续运行 400 代码的请求,所以没问题

总结

我得出的主要结论是,由于某种原因,report-uri无效,因为我可以看到有效载荷存在,我只是没有收到它

我使用了相对路由,因为本地主机和远程的子域会有所不同。不过,看起来请求似乎是对 Chromium 代码段中的完整 URL 发出的。

我可能会 https://stackoverflow.com/a/45682197 收到无效的标头吗?如果是这样,我该如何调试?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri
注意:report-uri已弃用,但我认为大多数浏览器不支持report-to参数

编辑:

我已经从我的应用程序工厂中取出了以下内容 (此代码呈现我的异常 - 我在此处发布为答案,因此可用于 https://stackoverflow.com/a/69671506/13316671

...
app = Flask(__name__)
config.init_app(app)
...
# exceptions.init_app(app)
...
return app

完成此操作后(在FireFox私人模式下),我做了另一个POST(我已经删除了GET方法) 我可以看到响应 - 在这里我终于设法收集了 Werkzeug 回溯:

wtforms.validators.ValidationError: The CSRF token is missing.

了解如何对来自浏览器的 CSP 报告进行身份验证

到目前为止,我已经看过这个:在Content-Security-Policy-Report-Only"report-uri"POST调用中添加一个新的Http标头

试试这段代码:

@app.route('/report-csp-violations', methods=['POST'])
def report():
content = request.get_json(force=True)   # that's where the shoe pinches
print(json.dumps(content, indent=4, sort_keys=True))
response = make_response()
response.status_code = 204
return response

我认为request.data尝试自动解析 JSON 数据,并且为了成功解析,它期望发送application/jsonMIME 类型。但是违规报告是用application/csp-reportMIME 类型发送的,因此 Flask 将其视为来自客户端的错误数据 -> 404 错误请求。

.get_json(force=True)表示忽略 mimetype 并始终尝试解析 JSON。

另外,我认为您不需要转换为utf-8,因为根据rfc4627"3。 编码":

JSON 文本应以 Unicode 编码。默认编码为 UTF-8。

现在我已经免除了CRSFProtect的观点。 我认为这应该没问题,因为此视图不返回模板,所以我无法添加

<form method="post">
{{ form.csrf_token }}
</form>

下面对我不起作用(不要认为这是一个有效的令牌)

# app/routes/report.py
...
def report():
response = make_response()
response.headers["X-CSRFToken"] = csrf.generate_csrf()
...
return response
...

使用实例化的CSRFProtect对象...

# app/extensions.py
...
from flask_wtf.csrf import CSRFProtect
...
csrf_protect = CSRFProtect()
...
def init_app(app: Flask) -> None:
...
csrf_protect.init_app(app)
...
...

。装饰视图

# app/routes/report.py
from app.extensions import csrf_protect
...
@blueprint.route("/csp_violations", methods=["POST"])
@csrf_protect.exempt
def report():
....
127.0.0.1 - - [06/Nov/2021 21:30:46] "POST /report/csp_violations HTTP/1.1" 204 -
{
"csp-report": {
"blocked-uri": "inline",
"column-number": 8118,
"document-uri": "https://127.0.0.1:5000/",
"line-number": 3,
"original-policy": "default-src" ...
"referrer": "",
"source-file": ...
}
}

我有一个系统在我的错误被混淆的地方,所以这是我的错误。这不是我第一次遇到CSRFProtect麻烦。

我已经解决了调试问题

# app/exceptions.py
...
def init_app(app: Flask) -> None:
...
def render_error(error: HTTPException) -> Tuple[str, int]:
# the below code is new
app.logger.error(error.description)
...
...

所以,如果我仍然收到此错误,这就是我现在会看到的

[2021-11-06 21:23:56,054] ERROR in exceptions: The CSRF token is missing.
127.0.0.1 - - [06/Nov/2021 21:23:56] "POST /report/csp_violations HTTP/1.1" 400 -

最新更新