跳转到主要内容

Morepath的内容安全策略

项目描述

用法

为了使用默认内容安全策略保护所有视图

from morepath import App
from more.content_security import ContentSecurityApp
from more.content_security import ContentSecurityPolicy
from more.content_security import SELF

class MyApp(App, ContentSecurityApp):
    pass

@MyApp.setting('content_security_policy', 'default')
def default_policy():
    return ContentSecurityPolicy(
        default_src={SELF},
        script_src={SELF, 'https://analytics.example.org'}
    )

为了扩展模型默认视图的默认策略

@MyApp.view(model=Document)
def view_document(self, request):

    # the actual default policy is not modified here!
    request.content_security_policy.script_src.add('https://cdnjs.com')

    ....

我们还可以使用完全不同的策略

@MyApp.view(model=Document)
def view_document(self, request):
    request.content_security_policy = ContentSecurityPolicy()

此外,我们可以在内联脚本/样式中使用nonce。这些将自动添加到“script-src”,“style-src”指令

@MyApp.html(model=Document)
def view_document(self, request):
    return """
        <html>
            ...

            <script nonce="{}">...</script>
        </html>
    """.format(request.content_security_policy_nonce('script'))

注意我们使用自定义请求类用于nonce。如果您有自己的,您需要如下扩展它

from morepath.request import Request
from more.content_security import ContentSecurityRequest

class CustomRequest(Request, ContentSecurityRequest):
    pass

class MyApp(App, ContentSecurityApp):
    request_class = CustomRequest

要仅使用“Content-Security-Policy-Report-Only”头,请使用此

@MyApp.setting('content_security_policy', 'default')
def default_policy():
    return ContentSecurityPolicy(
        report_only=True,
        default_src={SELF}
    )

运行测试

安装tox并运行它

pip install tox
tox

限制测试到特定的Python版本

tox -e py27

约定

more.content_security尽可能遵循PEP8。要测试它,请运行

tox -e pep8

more.content_security使用语义版本控制

构建状态

Build Status

覆盖率

Project Coverage

最新PyPI发布

Latest PyPI Release

许可证

more.content_security是在修订的BSD许可证下发布的

变更日志

0.2.0 (2018-02-02)

  • 添加了覆盖策略应用函数的能力。[链接]

  • 添加了缺失的UNSAFE_EVAL常量。[链接]

0.1.0 (2018-02-01)

  • 初始发布。[链接]

项目详情


下载文件

下载适合您平台的文件。如果您不确定要选择哪个,请了解有关安装软件包的更多信息。

源代码分发

more.content_security-0.2.0.tar.gz (7.0 kB 查看哈希值)

上传时间 源代码

构建分发

more.content_security-0.2.0-py3-none-any.whl (11.2 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面