repo_name
stringclasses
1 value
repo_url
stringclasses
1 value
repo_description
stringclasses
1 value
repo_stars
int64
667
667
repo_forks
int64
26
26
repo_last_updated
stringclasses
1 value
repo_created_at
stringclasses
1 value
repo_size
int64
160
160
repo_license
stringclasses
1 value
language
stringclasses
6 values
text
stringclasses
22 values
avg_line_length
float64
0
47.6
max_line_length
int64
0
630
alphnanum_fraction
float64
0
0.82
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Config
/build /dist /secure.egg-info .DS_Store __pycache__ docs/build docs/source/_build .idea .vscode .flake8 *.pyc
9
18
0.724771
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
YAML
# .readthedocs.yaml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Build documentation in the docs/ directory with Sphinx sphinx: configuration: docs/conf.py # Optionally build your docs in additional formats such as PDF formats: - pdf # Optionally set the version of Python and requirements required to build your docs python: version: 3.7
22.157895
83
0.769932
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
YAML
language: python python: - "3.6" cache: - pip install: - pip install -r dev-requirements.txt script: - python -m pytest
11.9
39
0.664063
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
MIT License Copyright (c) 2021 Caleb Kinney Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
47.636364
78
0.805426
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
include README.md LICENSE prune tests* prune docs*
16
25
0.82
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
29.789474
72
0.686644
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
Supported Frameworks ===================== Framework Agnostic -------------------- | Return Dictionary of Headers: | ``secure.Secure().headers()`` .. _example-4: **Example:** .. code:: python csp = secure.ContentSecurityPolicy() secure_headers = secure.Secure(csp=csp) print(secure_headers.headers()) **Printed Value:** ``{'Strict-Transport-Security': 'max-age=63072000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': '0', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "script-src 'self'; object-src 'self'", 'Referrer-Policy': 'no-referrer, strict-origin-when-cross-origin', 'Cache-Control': 'no-store'}`` aiohttp -------- ``secure_headers.framework.aiohttp(resp)`` .. _example-5: **Example:** .. code:: python from aiohttp import web from aiohttp.web import middleware import secure secure_headers = secure.Secure() . . . @middleware async def set_secure_headers(request, handler): resp = await handler(request) secure_headers.framework.aiohttp(resp) return resp . . . app = web.Application(middlewares=[set_secure_headers]) . . . Bottle ------ ``secure_headers.framework.bottle(response)`` .. _example-7: **Example:** .. code:: python from bottle import route, run, response, hook import secure secure_headers = secure.Secure() . . . @hook("after_request") def set_secure_headers(): secure_headers.framework.bottle(response) . . . CherryPy -------- ``"tools.response_headers.headers": secure_headers.framework.cherrypy()`` .. _example-9: **Example:** CherryPy `Application Configuration <http://docs.cherrypy.org/en/latest/config.html#application-config>`__: .. code:: python import cherrypy import secure secure_headers = secure.Secure() . . . config = { "/": { "tools.response_headers.on": True, "tools.response_headers.headers": secure_headers.framework.cherrypy(), } } . . . Django ------ ``secure_headers.framework.django(response)`` .. _example-11: **Example:** Django `Middleware Documentation <https://docs.djangoproject.com/en/2.1/topics/http/middleware/>`__: .. code:: python # securemiddleware.py import secure secure_headers = secure.Secure() . . . def set_secure_headers(get_response): def middleware(request): response = get_response(request) secure_headers.framework.django(response) return response return middleware . . . .. code:: python # settings.py ... MIDDLEWARE = [ 'app.securemiddleware.set_secure_headers' ] ... FastAPI ------ ``secure_headers.framework.fastapi(resp)`` .. _example-13: **Example:** .. code:: python from fastapi import FastAPI import secure secure_headers = secure.Secure() . . . @app.middleware("http") async def set_secure_headers(request, call_next): response = await call_next(request) secure_headers.framework.fastapi(response) return response . . . Falcon ------ ``secure_headers.framework.falcon(resp)`` .. _example-13: **Example:** .. code:: python import falcon import secure secure_headers = secure.Secure() . . . class SetSecureHeaders(object): def process_request(self, req, resp): secure_headers.framework.falcon(resp) . . . app = api = falcon.API(middleware=[SetSecureHeaders()]) . . . Flask ----- ``secure_headers.framework.flask(response)`` .. _example-15: **Example:** .. code:: python from flask import Flask, Response import secure secure_headers = secure.Secure() app = Flask(__name__) . . . @app.after_request def set_secure_headers(response): secure_headers.framework.flask(response) return response . . . hug --- ``secure_headers.framework.hug(response)`` .. _example-17: **Example:** .. code:: python import hug import secure secure_headers = secure.Secure() . . . @hug.response_middleware() def set_secure_headers(request, response, resource): secure_headers.framework.hug(response) . . . Masonite -------- ``secure_headers.framework.masonite(self.request)`` .. _example-19: **Example:** Masonite `Middleware <https://docs.masoniteproject.com/advanced/middleware#creating-middleware>`__: .. code:: python # SecureMiddleware.py from masonite.request import Request import secure secure_headers = secure.Secure() class SecureMiddleware: def __init__(self, request: Request): self.request = request def before(self): secure_headers.framework.masonite(self.request) . . . .. code:: python # middleware.py ... HTTP_MIDDLEWARE = [ SecureMiddleware, ] ... Pyramid ------- Pyramid `Tween <https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#registering-tweens>`__: .. code:: python def set_secure_headers(handler, registry): def tween(request): response = handler(request) secure_headers.framework.pyramid(response) return response return tween .. _example-21: **Example:** .. code:: python from pyramid.config import Configurator from pyramid.response import Response import secure secure_headers = secure.Secure() . . . def set_secure_headers(handler, registry): def tween(request): response = handler(request) secure_headers.framework.pyramid(response) return response return tween . . . config.add_tween(".set_secure_headers") . . . Quart ----- ``secure_headers.framework.quart(response)`` .. _example-23: **Example:** .. code:: python from quart import Quart, Response import secure secure_headers = secure.Secure() app = Quart(__name__) . . . @app.after_request async def set_secure_headers(response): secure_headers.framework.quart(response) return response . . . Responder --------- ``secure_headers.framework.responder(resp)`` .. _example-25: **Example:** .. code:: python import responder import secure secure_headers = secure.Secure() api = responder.API() . . . @api.route(before_request=True) def set_secure_headers(req, resp): secure_headers.framework.responder(resp) . . . You should use Responder’s `built in HSTS <https://python-responder.org/en/latest/tour.html#hsts-redirect-to-https>`__ and pass the ``hsts=False`` option. Sanic ----- ``secure_headers.framework.sanic(response)`` .. _example-27: **Example:** .. code:: python from sanic import Sanic import secure secure_headers = secure.Secure() app = Sanic() . . . @app.middleware("response") async def set_secure_headers(request, response): secure_headers.framework.sanic(response) . . . *To set Cross Origin Resource Sharing (CORS) headers, please see* `sanic-cors <https://github.com/ashleysommer/sanic-cors>`__ *.* Starlette --------- ``secure_headers.framework.starlette(response)`` .. _example-29: **Example:** .. code:: python from starlette.applications import Starlette import uvicorn import secure secure_headers = secure.Secure() app = Starlette() . . . @app.middleware("http") async def set_secure_headers(request, call_next): response = await call_next(request) secure_headers.framework.starlette(response) return response . . . Tornado ------- ``secure_headers.framework.tornado(self)`` .. _example-31: **Example:** .. code:: python import tornado.ioloop import tornado.web import secure secure_headers = secure.Secure() . . . class BaseHandler(tornado.web.RequestHandler): def set_default_headers(self): secure_headers.framework.tornado(self) . . .
14.908549
330
0.627172
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
Secure Headers ---------------- Security Headers are HTTP response headers that, when set, can enhance the security of your web application by enabling browser security policies. You can assess the security of your HTTP response headers at `securityheaders.com <https://securityheaders.com>`__ *Recommendations used by secure,py and more information regarding security headers can be found at the* `OWASP Secure Headers Project <https://www.owasp.org/index.php/OWASP_Secure_Headers_Project>`__ *.* Server ^^^^^^^^^^^^^^ | Contain information about server software | **Default Value:** ``NULL`` *(obfuscate server information, not included by default)* Strict-Transport-Security (HSTS) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | Ensure application communication is sent over HTTPS | **Default Value:** ``max-age=63072000; includeSubdomains`` X-Frame-Options (XFO) ^^^^^^^^^^^^^^^^^^^^^^ | Disable framing from different origins (clickjacking defense) | **Default Value:** ``SAMEORIGIN`` X-XSS-Protection ^^^^^^^^^^^^^^^^^^ | Enable browser cross-site scripting filters | **Default Value:** ``0`` X-Content-Type-Options ^^^^^^^^^^^^^^^^^^^^^^^ | Prevent MIME-sniffing | **Default Value:** ``nosniff`` Content-Security-Policy (CSP) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | Prevent cross-site injections | **Default Value:** ``script-src 'self'; object-src 'self'`` *(not included by default)*\* Referrer-Policy ^^^^^^^^^^^^^^^^ | Enable full referrer if same origin, remove path for cross origin and disable referrer in unsupported browsers | **Default Value:** ``no-referrer, strict-origin-when-cross-origin`` Cache-control ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | Prevent cacheable HTTPS response | **Default Value:** ``no-cache`` Permissions-Policy ^^^^^^^^^^^^^^^ | Limit browser features and APIs to specific origins. Empty list means that a feature is disabled. | **Default Value:** ``accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), clipboard-read=(), clipboard-write=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), gamepad=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), navigation-override=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), speaker=(), speaker-selection=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()`` *(not included by default)* **Additional information:** - The ``Strict-Transport-Security`` (HSTS) header will tell the browser to **only** utilize secure HTTPS connections for the domain, and in the default configuration, including all subdomains. The HSTS header requires trusted certificates and users will unable to connect to the site if using self-signed or expired certificates. The browser will honor the HSTS header for the time directed in the ``max-age`` attribute *(default = 2 years)*, and setting the ``max-age`` to ``0`` will disable an already set HSTS header. Use the ``hsts=False`` option to not include the HSTS header in Secure Headers. - The ``Content-Security-Policy`` (CSP) header can break functionality and can (and should) be carefully constructed, use the ``csp=secure.ContentSecurityPolicy()`` option to enable default values. Usage ^^^^^^^ .. code:: python secure_headers = secure.Secure() secure_headers.framework.[framework](response) **Default HTTP response headers:** .. code:: http Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: SAMEORIGIN X-XSS-Protection: 0 X-Content-Type-Options: nosniff Referrer-Policy: no-referrer, strict-origin-when-cross-origin Cache-control: no-cache, no-store, must-revalidate, max-age=0 Pragma: no-cache Expires: 0 Options ^^^^^^^^ You can toggle the setting of headers with default and override default values by passing a class to the following options: - ``server`` - set the Server header, ``secure.Secure(server=secure.Server())`` *(default=False)* - ``hsts`` - set the Strict-Transport-Security header ``secure.Secure(hsts=secure.StrictTransportSecurity())`` *(default=True)* - ``xfo`` - set the X-Frame-Options header ``secure.Secure(xfo=secure.XFrameOptions())`` *(default=True)* - ``xxp`` - set the X-XSS-Protection header ``secure.Secure(xxp=secure.XXSSProtection())`` *(default=True)* - ``content`` - set the X-Content-Type-Options header ``secure.Secure(content=secure.XContentTypeOptions())`` *(default=True)* - ``csp`` - set the Content-Security-Policy ``secure.Secure(csp=secure.ContentSecurityPolicy())`` *(default=False)* \* - ``referrer`` - set the Referrer-Policy header ``secure.Secure(referrer=secure.ReferrerPolicy())`` *(default=True)* - ``cache`` - set the Cache-control header ``secure.Secure(cache=secure.CacheControl())`` *(default=True)* - ``permissions`` - set the Permissions-Policy header ``secure.Secure(permissions=secure.PermissionsPolicy())`` *(default=False)* **Example:** .. code:: python import secure csp = secure.ContentSecurityPolicy() xfo = secure.XFrameOptions().deny() secure_headers = secure.Secure(csp=csp, hsts=None, xfo=xfo) . . . secure_headers.framework.[framework](response) **HTTP response headers:** .. code:: http x-frame-options: deny x-xss-protection: 0 x-content-type-options: nosniff content-security-policy: script-src 'self'; object-src 'self' referrer-policy: no-referrer, strict-origin-when-cross-origin cache-control: no-store
38.85
630
0.694873
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
.. secure.py documentation master file, created by sphinx-quickstart on Wed Dec 19 05:31:56 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. secure.py ========== |version| |Python 3| |license| |black| secure.py 🔒 is a lightweight package that adds optional security headers for Python web frameworks. Supported Python web frameworks: -------------------------------- `aiohttp <https://docs.aiohttp.org>`__, `Bottle <https://bottlepy.org>`__, `CherryPy <https://cherrypy.org>`__, `Django <https://www.djangoproject.com>`__, `Falcon <https://falconframework.org>`__, `FastAPI <https://fastapi.tiangolo.com>`__, `Flask <http://flask.pocoo.org>`__, `hug <http://www.hug.rest>`__, `Masonite <https://docs.masoniteproject.com>`__, `Pyramid <https://trypyramid.com>`__, `Quart <https://pgjones.gitlab.io/quart/>`__, `Responder <https://python-responder.org>`__, `Sanic <https://sanicframework.org>`__, `Starlette <https://www.starlette.io/>`__, `Tornado <https://www.tornadoweb.org/>`__ Install ------- **pip**: .. code:: console $ pip install secure **Pipenv**: .. code:: console $ pipenv install secure After installing secure.py: .. code:: python import secure secure_headers = secure.Secure() Documentation ------------- .. toctree:: :maxdepth: 2 :caption: Contents: headers policies frameworks resources .. |version| image:: https://img.shields.io/pypi/v/secure.svg :target: https://pypi.org/project/secure/ .. |Python 3| image:: https://img.shields.io/badge/python-3-blue.svg :target: https://www.python.org/downloads/ .. |license| image:: https://img.shields.io/pypi/l/secure.svg :target: https://pypi.org/project/secure/ .. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
22.795181
99
0.656535
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd
21
75
0.701643
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
secure ====== .. toctree:: :maxdepth: 4 secure
6
15
0.509091
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
Policy Builder ---------------- ContentSecurityPolicy() ^^^^^^^ **Directives:** ``base_uri(sources)``, ``child_src(sources)``, ``connect_src(sources)``, ``default_src(sources)``, ``font_src(sources)``, ``form_action(sources)``, ``frame_ancestors(sources)``, ``frame_src(sources)``, ``img_src(sources)``, ``manifest_src(sources)``, ``media_src(sources)``, ``object_src(sources)``, ``plugin_types(types)``, ``report_to(json_object)``, ``report_uri(uri)``, ``require_sri_for(values)``, ``sandbox(values)``, ``script_src(sources)``, ``style_src(sources)``, ``upgrade_insecure_requests()``, ``worker_src(sources)`` **Example:** .. code:: python csp_policy = ( secure.ContentSecurityPolicy() .default_src("'none'") .base_uri("'self'") .connect_src("'self'", "api.spam.com") .frame_src("'none'") .img_src("'self'", "static.spam.com") ) secure_headers = secure.Secure(csp=csp_policy) # default-src 'none'; base-uri 'self'; connect-src 'self' api.spam.com; frame-src 'none'; img-src 'self' static.spam.com *You can check the effectiveness of your CSP Policy at the* `CSP Evaluator <https://csp-evaluator.withgoogle.com>`__ StrictTransportSecurity() ^^^^^^^ **Directives:** ``include_subDomains()``, ``max_age(seconds)``, ``preload()`` **Example:** .. code:: python hsts_value = ( secure.StrictTransportSecurity() .include_subdomains() .preload() .max_age(2592000) ) secure_headers = secure.Secure(hsts=hsts_value) # includeSubDomains; preload; max-age=2592000 XFrameOptions() ^^^^^^ **Directives:** ``allow_from(uri)``, ``deny()``, ``sameorigin()`` **Example:** .. code:: python xfo_value = secure.XFrameOptions().deny() secure_headers = secure.Secure(xfo=xfo_value) # deny ReferrerPolicy() ^^^^^^^^^^^ **Directives:** ``no_referrer()``, ``no_referrer_when_downgrade()``, ``origin()``, ``origin_when_cross_origin()``, ``same_origin()``, ``strict_origin()``, ``strict_origin_when_cross_origin()``, ``unsafe_url()`` **Example:** .. code:: python referrer = secure.ReferrerPolicy().strict_origin() secure_headers = secure.Secure(referrer=referrer).headers() # strict-origin PermissionsPolicy() ^^^^^^^^^^ **Directives:** ``accelerometer(allowlist)``, ``ambient_light_sensor(allowlist)``, ``autoplay(allowlist)``, ``camera(allowlist)``, ``document_domain(allowlist)``, ``encrypted_media(allowlist)``, ``fullscreen(allowlist)``, ``geolocation(allowlist)``, ``gyroscope(allowlist)``, ``magnetometer(allowlist)``, ``microphone(allowlist)``, ``midi(allowlist)``, ``payment(allowlist)``, ``picture_in_picture(allowlist)``, ``speaker(allowlist)``, ``sync_xhr(allowlist)``, ``usb(allowlist)``, ``Values(allowlist)``, ``vr(allowlist)`` **Example:** .. code:: python permissions = ( secure.PermissionsPolicy().geolocation("self", '"spam.com"').vibrate() ) secure_headers = secure.Secure(permissions=permissions).headers() # geolocation=(self "spam.com"), vibrate=() CacheControl() ^^^^^^^^ **Directives:** ``immutable()``, ``max_age(seconds)``, ``max_stale(seconds)``, ``min_fresh(seconds)``, ``must_revalidate()``, ``no_cache()``, ``no_store()``, ``no_transform()``, ``only_if_cached()``, ``private()``, ``proxy_revalidate()``, ``public()``, ``s_maxage(seconds)``, ``stale_if_error(seconds)``, ``stale_while_revalidate(seconds)``, **Example:** .. code:: python cache = secure.CacheControl().no_cache() secure_headers = secure.Secure(cache=cache).headers() # no-store Usage ^^^^^^ .. _example-1: **Example:** .. code:: python import uvicorn from fastapi import FastAPI import secure app = FastAPI() server = secure.Server().set("Secure") csp = ( secure.ContentSecurityPolicy() .default_src("'none'") .base_uri("'self'") .connect_src("'self'" "api.spam.com") .frame_src("'none'") .img_src("'self'", "static.spam.com") ) hsts = secure.StrictTransportSecurity().include_subdomains().preload().max_age(2592000) referrer = secure.ReferrerPolicy().no_referrer() permissions_value = ( secure.PermissionsPolicy().geolocation("self", "'spam.com'").vibrate() ) cache_value = secure.CacheControl().must_revalidate() secure_headers = secure.Secure( server=server, csp=csp, hsts=hsts, referrer=referrer, permissions=permissions_value, cache=cache_value, ) @app.middleware("http") async def set_secure_headers(request, call_next): response = await call_next(request) secure_headers.framework.fastapi(response) return response @app.get("/") async def root(): return {"message": "Secure"} if __name__ == "__main__": uvicorn.run(app, port=8081, host="localhost") . . . Response Headers: .. code:: http server: Secure strict-transport-security: includeSubDomains; preload; max-age=2592000 x-frame-options: SAMEORIGIN x-xss-protection: 0 x-content-type-options: nosniff content-security-policy: default-src 'none'; base-uri 'self'; connect-src 'self'api.spam.com; frame-src 'none'; img-src 'self' static.spam.com referrer-policy: no-referrer cache-control: must-revalidate permissions-policy: geolocation=(self 'spam.com'), vibrate=()
23.625
145
0.628808
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
.. _resources-1: Resources ================== Frameworks ---------------------- - `aiohttp <https://github.com/aio-libs/aiohttp>`__ - Asynchronous HTTP client/server framework for asyncio and Python - `Bottle <https://github.com/bottlepy/bottle>`__ - A fast and simple micro-framework for python web-applications. - `CherryPy <https://github.com/cherrypy/cherrypy>`__ - A pythonic, object-oriented HTTP framework. - `Django <https://github.com/django/django/>`__ - The Web framework for perfectionists with deadlines. - `Falcon <https://github.com/falconry/falcon>`__ - A bare-metal Python web API framework for building high-performance microservices, app backends, and higher-level frameworks. - `Flask <https://github.com/pallets/flask>`__ - The Python micro framework for building web applications. - `hug <https://github.com/timothycrosley/hug>`__ - Embrace the APIs of the future. Hug aims to make developing APIs as simple as possible, but no simpler. - `Masonite <https://github.com/MasoniteFramework/masonite>`__ - The Modern And Developer Centric Python Web Framework. - `Pyramid <https://github.com/Pylons/pyramid>`__ - A Python web framework - `Quart <https://gitlab.com/pgjones/quart>`__ - A Python ASGI web microframework. - `Responder <https://github.com/kennethreitz/responder>`__ - A familiar HTTP Service Framework - `Sanic <https://github.com/huge-success/sanic>`__ - An Async Python 3.5+ web server that’s written to go fast - `Starlette <https://github.com/encode/starlette>`__ - The little ASGI framework that shines. ✨ - `Tornado <https://github.com/tornadoweb/tornado>`__ - A Python web framework and asynchronous networking library, originally developed at FriendFeed. General ---------------------- - `OWASP - Secure Headers Project <https://www.owasp.org/index.php/OWASP_Secure_Headers_Project>`__ - `OWASP - Session Management Cheat Sheet <https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Cookies>`__ - `Mozilla Web Security <https://infosec.mozilla.org/guidelines/web_security>`__ - `securityheaders.com <https://securityheaders.com>`__ Policies ---------------------- - **CSP:** `CSP Cheat Sheet \| Scott Helme <https://scotthelme.co.uk/csp-cheat-sheet/>`__, `Content-Security-Policy \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy>`__, `Content Security Policy Cheat Sheet \| OWASP <https://www.owasp.org/index.php/Content_Security_Policy_Cheat_Sheet>`__, `Content Security Policy CSP Reference & Examples <https://content-security-policy.com>`__ - **XXP:** `X-XSS-Protection \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection>`__ - **XFO:** `X-Frame-Options \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options>`__ - **HSTS:** `Strict-Transport-Security \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security>`__, `HTTP Strict Transport Security Cheat Sheet \| OWASP <https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet>`__ - **Referrer:** `A new security header: Referrer Policy \| Scott Helme <https://scotthelme.co.uk/a-new-security-header-referrer-policy/>`__, `Referrer-Policy \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>`__ - **Feature:** `A new security header: Feature Policy \| Scott Helme <https://scotthelme.co.uk/a-new-security-header-feature-policy/>`__, `Feature-Policy \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy>`__, `Introduction to Feature Policy \| Google Developers <https://developers.google.com/web/updates/2018/06/feature-policy>`__ - **Cache:** `Cache-Control \| MDN <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control>`__
46.609756
121
0.695619
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
secure package ============== Submodules ---------- secure.headers module --------------------- .. automodule:: secure.headers :members: :undoc-members: :show-inheritance: secure.secure module -------------------- .. automodule:: secure.secure :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: secure :members: :undoc-members: :show-inheritance:
13.133333
30
0.560284
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Misc
0
0
0
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Markdown
# secure.py [![image](https://img.shields.io/pypi/v/secure.svg)](https://pypi.org/project/secure/) [![Python 3](https://img.shields.io/badge/python-3-blue.svg)](https://www.python.org/downloads/) [![image](https://img.shields.io/pypi/l/secure.svg)](https://pypi.org/project/secure/) [![image](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Build Status](https://travis-ci.org/TypeError/secure.svg?branch=master)](https://travis-ci.org/TypeError/secure) secure.py 🔒 is a lightweight package that adds optional security headers for Python web frameworks. ## Supported Python web frameworks [aiohttp](https://docs.aiohttp.org), [Bottle](https://bottlepy.org), [CherryPy](https://cherrypy.org), [Django](https://www.djangoproject.com), [Falcon](https://falconframework.org), [FastAPI](https://fastapi.tiangolo.com), [Flask](http://flask.pocoo.org), [hug](http://www.hug.rest), [Masonite](https://docs.masoniteproject.com), [Pyramid](https://trypyramid.com), [Quart](https://pgjones.gitlab.io/quart/), [Responder](https://python-responder.org), [Sanic](https://sanicframework.org), [Starlette](https://www.starlette.io/), [Tornado](https://www.tornadoweb.org/) ## Install **pip**: ```console pip install secure ``` **Pipenv**: ```console pipenv install secure ``` After installing secure: ```Python import secure secure_headers = secure.Secure() ``` ## Secure Headers ### Example `secure_headers.framework(response)` **Default HTTP response headers:** ```HTTP strict-transport-security: max-age=63072000; includeSubdomains x-frame-options: SAMEORIGIN x-xss-protection: 0 x-content-type-options: nosniff referrer-policy: no-referrer, strict-origin-when-cross-origin cache-control: no-store ``` ## Policy Builders ### Policy Builder Example **Content Security Policy builder:** ```python csp = ( secure.ContentSecurityPolicy() .default_src("'none'") .base_uri("'self'") .connect_src("'self'", "api.spam.com") .frame_src("'none'") .img_src("'self'", "static.spam.com") ) secure_headers = secure.Secure(csp=csp) ``` **HTTP response headers:** ```HTTP strict-transport-security: max-age=63072000; includeSubdomains x-frame-options: SAMEORIGIN x-xss-protection: 0 x-content-type-options: nosniff referrer-policy: no-referrer, strict-origin-when-cross-origin cache-control: no-store content-security-policy: default-src 'none'; base-uri 'self'; connect-src 'self' api.spam.com; frame-src 'none'; img-src 'self' static.spam.com" ``` ## Documentation Please see the full set of documentation at [https://secure.readthedocs.io](https://secure.readthedocs.io) ## FastAPI Example ```python import uvicorn from fastapi import FastAPI import secure app = FastAPI() server = secure.Server().set("Secure") csp = ( secure.ContentSecurityPolicy() .default_src("'none'") .base_uri("'self'") .connect_src("'self'" "api.spam.com") .frame_src("'none'") .img_src("'self'", "static.spam.com") ) hsts = secure.StrictTransportSecurity().include_subdomains().preload().max_age(2592000) referrer = secure.ReferrerPolicy().no_referrer() permissions_value = ( secure.PermissionsPolicy().geolocation("self", "'spam.com'").vibrate() ) cache_value = secure.CacheControl().must_revalidate() secure_headers = secure.Secure( server=server, csp=csp, hsts=hsts, referrer=referrer, permissions=permissions_value, cache=cache_value, ) @app.middleware("http") async def set_secure_headers(request, call_next): response = await call_next(request) secure_headers.framework.fastapi(response) return response @app.get("/") async def root(): return {"message": "Secure"} if __name__ == "__main__": uvicorn.run(app, port=8081, host="localhost") ``` **HTTP response headers:** ```HTTP server: Secure strict-transport-security: includeSubDomains; preload; max-age=2592000 x-frame-options: SAMEORIGIN x-xss-protection: 0 x-content-type-options: nosniff content-security-policy: default-src 'none'; base-uri 'self'; connect-src 'self'api.spam.com; frame-src 'none'; img-src 'self' static.spam.com referrer-policy: no-referrer cache-control: must-revalidate permissions-policy: geolocation=(self 'spam.com'), vibrate=() ``` ## Resources - [kennethreitz/setup.py: 📦 A Human’s Ultimate Guide to setup.py.](https://github.com/kennethreitz/setup.py) - [OWASP - Secure Headers Project](https://www.owasp.org/index.php/OWASP_Secure_Headers_Project) - [Mozilla Web Security](https://infosec.mozilla.org/guidelines/web_security) - [securityheaders.com](https://securityheaders.com) - [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#security) - [web.dev](https://web.dev) - [The World Wide Web Consortium (W3C)](https://www.w3.org)
27.790419
567
0.709382
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Text
pytest
2
6
0.75
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath("..")) # -- Project information ----------------------------------------------------- project = "secure.py" copyright = "2021, Caleb Kinney" author = "Caleb Kinney" # The short X.Y version version = "0.3.0" # The full version, including alpha/beta/rc tags release = "0.3.0" # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "securepydoc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "securepy.tex", "secure.py Documentation", "Caleb Kinney", "manual"), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "securepy", "secure.py Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "securepy", "secure.py Documentation", author, "securepy", "One line description of project.", "Miscellaneous", ), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ["search.html"] # -- Extension configuration -------------------------------------------------
28.52809
86
0.635966
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
0
0
0
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
# Header information and recommendations are adapted from: # - OWASP Secure Headers Project (https://owasp.org/www-project-secure-headers/) # - MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#security) # - web.dev (https://web.dev) # - The World Wide Web Consortium (W3C) (https://www.w3.org) import json from typing import Dict, List, Optional, Union import warnings class Server: """Replace server header""" def __init__(self) -> None: self.header = "Server" self.value = "NULL" def set(self, value: str) -> "Server": """Set custom value for `Server` header :param value: custom header value :type value: str :return: Server class :rtype: Server """ self.value = value return self class XContentTypeOptions: """Prevent MIME-sniffing Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options https://owasp.org/www-project-secure-headers/#x-content-type-options """ def __init__(self) -> None: self.header = "X-Content-Type-Options" self.value = "nosniff" def set(self, value: str) -> "XContentTypeOptions": """Set custom value for `X-Content-Type-Options` header :param value: custom header value :type value: str :return: XContentTypeOptions class :rtype: XContentTypeOptions """ self.value = value return self class ReportTo: """Configure reporting endpoints Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-to https://developers.google.com/web/updates/2018/09/reportingapi :param max_age: endpoint TIL in seconds :type max_age: int :param include_subdomains: enable for subdomains, defaults to False :type include_subdomains: bool, optional :param group: endpoint name, defaults to None :type group: Optional[str], optional :param endpoints: variable number of endpoints :type endpoints: List[Dict[str, Union[str, int]]] """ def __init__( self, max_age: int, include_subdomains: bool = False, group: Optional[str] = None, *endpoints: List[Dict[str, Union[str, int]]], ) -> None: self.header = "Report-To" report_to_endpoints = json.dumps(endpoints) report_to_object: Dict[str, Union[str, int]] = { "max_age": max_age, "endpoints": report_to_endpoints, } if group: report_to_object["group"] = group if include_subdomains: report_to_object["include_subdomains"] = include_subdomains self.value = json.dumps(report_to_object) def set(self, value: str) -> "ReportTo": """Set custom value for `Report-To` header :param value: custom header value :type value: str :return: ReportTo class :rtype: ReportTo """ self.value = value return self class ContentSecurityPolicy: """ Prevent Cross-site injections Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy https://developers.google.com/web/fundamentals/security/csp """ def __init__(self) -> None: self.__policy: List[str] = [] self.header = "Content-Security-Policy" self.value = "script-src 'self'; object-src 'self'" def _build(self, directive: str, *sources: str) -> None: if len(sources) == 0: self.__policy.append(directive) else: self.__policy.append(f"{directive} {' '.join(sources)}") self.value = "; ".join(self.__policy) def set(self, value: str) -> "ContentSecurityPolicy": """Set custom value for `Content-Security-Policy` header :param value: custom header value :type value: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build(value) return self def custom_directive( self, directive: str, *sources: str ) -> "ContentSecurityPolicy": """Set custom directive and sources :param directive: custom directive :type directive: str :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build(directive, *sources) return self def report_only(self) -> None: """Set Content-Security-Policy header to Content-Security-Policy-Report-Only""" self.header = "Content-Security-Policy-Report-Only" def base_uri(self, *sources: str) -> "ContentSecurityPolicy": """Sets valid origins for `<base>` Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/base-uri :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("base-uri", *sources) return self def child_src(self, *sources: str) -> "ContentSecurityPolicy": """Sets valid origins for web workers Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/child-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("child-src", *sources) return self def connect_src(self, *sources: str) -> "ContentSecurityPolicy": """Sets valid origins for script interfaces Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("connect-src", *sources) return self def default_src(self, *sources: str) -> "ContentSecurityPolicy": """Sets fallback valid orgins for other directives Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/default-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("default-src", *sources) return self def font_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for `@font-face` Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/font-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("font-src", *sources) return self def form_action(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for form submissions Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/form-action :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("form-action", *sources) return self def frame_ancestors(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins that can embed the resource Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("frame-ancestors", *sources) return self def frame_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for frames Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("frame-src", *sources) return self def img_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for images Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/img-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("img-src", *sources) return self def manifest_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for manifest files Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/manifest-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("manifest-src", *sources) return self def media_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for media Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/media-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("media-src", *sources) return self def object_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for plugins Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/object-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("object-src", *sources) return self def prefetch_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid resources that may prefetched or prerendered Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/prefetch-src :param sources: variable number of sources :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("prefetch-src", *sources) return self def report_to(self, report_to: ReportTo) -> "ContentSecurityPolicy": """Configure reporting endpoints Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-to :param report_to: ReportTo class :type report_to: ReportTo :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("report-to", report_to.value) return self def report_uri(self, *values: str) -> "ContentSecurityPolicy": """Configure reporting endpoints in an older format **Deprecated** This header has been deprecated in favor of report-to. However, as it is not yet supported in most browsers, it is recommended to set both headers. Browsers that support report-to will ignore report-uri if both headers are set. Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri :param values: variable number of URIs :type values: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("report-uri", *values) return self def sandbox(self, *values: str) -> "ContentSecurityPolicy": """Enables sandbox restrictions Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox :param values: variable number of types :type values: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("sandbox", *values) return self def script_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for JavaScript Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src :param sources: variable number of types :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("script-src", *sources) return self def style_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for styles Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src :param sources: variable number of types :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("style-src", *sources) return self def upgrade_insecure_requests(self) -> "ContentSecurityPolicy": """Upgrade HTTP URLs to HTTPS Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("upgrade-insecure-requests") return self def worker_src(self, *sources: str) -> "ContentSecurityPolicy": """Set valid origins for worker scripts Resouces: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/worker-src :param sources: variable number of types :type sources: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ self._build("worker-src", *sources) return self @staticmethod def nonce(value: str) -> str: """Creates a nonce format :param value: nounce value :type value: str :return: ContentSecurityPolicy class :rtype: ContentSecurityPolicy """ value = "'nonce-<{}>'".format(value) return value class XFrameOptions: """ Disable framing from different origins (clickjacking defense) Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options """ def __init__(self) -> None: self.header = "X-Frame-Options" self.value = "SAMEORIGIN" def set(self, value: str) -> "XFrameOptions": """Set custom value for X-Frame-Options header :param value: custom header value :type value: str :return: XFrameOptions class :rtype: XFrameOptions """ self.value = value return self def deny(self) -> "XFrameOptions": """Disable rending site in a frame :return: XFrameOptions class :rtype: XFrameOptions """ self.value = "deny" return self def sameorigin(self) -> "XFrameOptions": """Disable rending site in a frame if not same origin :return: XFrameOptions class :rtype: XFrameOptions """ self.value = "sameorigin" return self class XXSSProtection: """ Enable browser Cross-Site Scripting filters **Deprecated** Recommended to utilize `Content-Security-Policy` instead of the legacy `X-XSS-Protection` header. Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection https://owasp.org/www-project-secure-headers/#x-xss-protection """ def __init__(self) -> None: self.header = "X-XSS-Protection" self.value = "0" def set(self, value: str) -> "XXSSProtection": """Set custom value for `X-XSS-Protection` header :param value: custom header value :type value: str :return: XXSSProtection class :rtype: XXSSProtection """ warnings.warn( "Recommended to utilize Content-Security-Policy", DeprecationWarning, ) self.value = value return self class ReferrerPolicy: """ Enable full referrer if same origin, remove path for cross origin and disable referrer in unsupported browsers Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy https://owasp.org/www-project-secure-headers/#referrer-policy """ def __init__(self) -> None: self.__policy: List[str] = [] self.header = "Referrer-Policy" self.value = "no-referrer, strict-origin-when-cross-origin" def _build(self, directive: str) -> None: self.__policy.append(directive) self.value = ", ".join(self.__policy) def set(self, value: str) -> "ReferrerPolicy": """Set custom value for `Referrer-Policy` header :param value: custom header value :type value: str :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build(value) return self def no_referrer(self) -> "ReferrerPolicy": """The `Referer` header will not be sent :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("no-referrer") return self def no_referrer_when_downgrade(self) -> "ReferrerPolicy": """The `Referer` header will not be sent if HTTPS -> HTTP :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("no-referrer-when-downgrade") return self def origin(self) -> "ReferrerPolicy": """The `Referer` header will contain only the origin :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("origin") return self def origin_when_cross_origin(self) -> "ReferrerPolicy": """The `Referer` header will contain the full URL but only the origin if cross-origin :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("origin-when-cross-origin") return self def same_origin(self) -> "ReferrerPolicy": """The `Referer` header will be sent with the full URL if same-origin :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("same-origin") return self def strict_origin(self) -> "ReferrerPolicy": """The `Referer` header will be sent only for same-origin :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("strict-origin") return self def strict_origin_when_cross_origin(self) -> "ReferrerPolicy": """The `Referer` header will only contain the origin if HTTPS -> HTTP :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("strict-origin-when-cross-origin") return self def unsafe_url(self) -> "ReferrerPolicy": """The `Referer` header will contain the full URL :return: ReferrerPolicy class :rtype: ReferrerPolicy """ self._build("unsafe-url") return self class StrictTransportSecurity: """ Ensure application communication is sent over HTTPS Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security https://owasp.org/www-project-secure-headers/#http-strict-transport-security """ def __init__(self) -> None: self.__policy: List[str] = [] self.header = "Strict-Transport-Security" self.value = "max-age=63072000; includeSubdomains" def _build(self, directive: str) -> None: self.__policy.append(directive) self.value = "; ".join(self.__policy) def set(self, value: str) -> "StrictTransportSecurity": """Set custom value for `Strict-Transport-Security` header :param value: custom header value :type value: str :return: StrictTransportSecurity class :rtype: StrictTransportSecurity """ self._build(value) return self def include_subdomains(self) -> "StrictTransportSecurity": """Include subdomains to HSTS policy [Optional] :return: [description] :rtype: [type] """ self._build("includeSubDomains") return self def max_age(self, seconds: int) -> "StrictTransportSecurity": """Instruct the browser to remember HTTPS preference until time (seconds) expires. :param seconds: time in seconds :type seconds: str :return: StrictTransportSecurity class :rtype: StrictTransportSecurity """ self._build("max-age={}".format(seconds)) return self def preload(self) -> "StrictTransportSecurity": """Instruct browser to always use HTTPS [Optional] Please see: https://hstspreload.org :return: StrictTransportSecurity class :rtype: StrictTransportSecurity """ self._build("preload") return self class CacheControl: """ Prevent cacheable HTTPS response Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control """ def __init__(self) -> None: self.__policy: List[str] = [] self.header = "Cache-Control" self.value = "no-store" def _build(self, directive: str) -> None: self.__policy.append(directive) self.value = ", ".join(self.__policy) def set(self, value: str) -> "CacheControl": """Set custom value for `Cache-control` header :param value: custom header value :type value: str :return: CacheControl class :rtype: CacheControl """ self._build(value) return self def immutable(self) -> "CacheControl": self._build("immutable") return self def max_age(self, seconds: int) -> "CacheControl": self._build("max-age={}".format(seconds)) return self def max_stale(self, seconds: int) -> "CacheControl": self._build("max-stale={}".format(seconds)) return self def min_fresh(self, seconds: int) -> "CacheControl": self._build("min-fresh={}".format(seconds)) return self def must_revalidate(self) -> "CacheControl": self._build("must-revalidate") return self def no_cache(self) -> "CacheControl": self._build("no-cache") return self def no_store(self) -> "CacheControl": self._build("no-store") return self def no_transform(self) -> "CacheControl": self._build("no-transform") return self def only_if_cached(self) -> "CacheControl": self._build("only-if-cached") return self def private(self) -> "CacheControl": self._build("private") return self def proxy_revalidate(self) -> "CacheControl": self._build("proxy-revalidate") return self def public(self) -> "CacheControl": self._build("public") return self def s_maxage(self, seconds: int) -> "CacheControl": self._build("s-maxage={}".format(seconds)) return self def stale_if_error(self, seconds: int) -> "CacheControl": self._build("stale-if-error={}".format(seconds)) return self def stale_while_revalidate(self, seconds: int) -> "CacheControl": self._build("stale-while-revalidate={}".format(seconds)) return self class PermissionsPolicy: """ Disable browser features and APIs Replaces the `Feature-Policy` header Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy https://github.com/w3c/webappsec-permissions-policy/blob/main/permissions-policy-explainer.md """ def __init__(self) -> None: self.__policy: List[str] = [] self.header = "Permissions-Policy" self.value = ( "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), " "camera=(), clipboard-read=(), clipboard-write=(), cross-origin-isolated=(), " "display-capture=(), document-domain=(), encrypted-media=(), " "execution-while-not-rendered=(), execution-while-out-of-viewport=(), " "fullscreen=(), gamepad=(), geolocation=(), gyroscope=(), magnetometer=(), " "microphone=(), midi=(), navigation-override=(), payment=(), " "picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), " "speaker-selection=(), sync-xhr=(), usb=(), web-share=(), " "xr-spatial-tracking=()" ) def _build(self, directive: str, *sources: str) -> None: self.__policy.append(f"{directive}=({' '.join(sources)})") self.value = ", ".join(self.__policy) def set(self, value: str) -> "PermissionsPolicy": self._build(value) return self def accelerometer(self, *allowlist: str) -> "PermissionsPolicy": self._build("accelerometer", *allowlist) return self def ambient_light_sensor(self, *allowlist: str) -> "PermissionsPolicy": self._build("ambient-light-sensor", *allowlist) return self def autoplay(self, *allowlist: str) -> "PermissionsPolicy": self._build("autoplay", *allowlist) return self def battery(self, *allowlist: str) -> "PermissionsPolicy": self._build("battery", *allowlist) return self def camera(self, *allowlist: str) -> "PermissionsPolicy": self._build("camera", *allowlist) return self def clipboard_read(self, *allowlist: str) -> "PermissionsPolicy": self._build("clipboard-read", *allowlist) return self def clipboard_write(self, *allowlist: str) -> "PermissionsPolicy": self._build("clipboard-write", *allowlist) return self def cross_origin_isolated(self, *allowlist: str) -> "PermissionsPolicy": self._build("cross-origin-isolated", *allowlist) return self def display_capture(self, *allowlist: str) -> "PermissionsPolicy": self._build("display-capture", *allowlist) return self def document_domain(self, *allowlist: str) -> "PermissionsPolicy": self._build("document-domain", *allowlist) return self def encrypted_media(self, *allowlist: str) -> "PermissionsPolicy": self._build("encrypted-media", *allowlist) return self def execution_while_not_rendered(self, *allowlist: str) -> "PermissionsPolicy": self._build("execution-while-not-rendered", *allowlist) return self def execution_while_out_of_viewport(self, *allowlist: str) -> "PermissionsPolicy": self._build("execution-while-out-of-viewport", *allowlist) return self def fullscreen(self, *allowlist: str) -> "PermissionsPolicy": self._build("fullscreen", *allowlist) return self def gamepad(self, *allowlist: str) -> "PermissionsPolicy": self._build("gamepad", *allowlist) return self def geolocation(self, *allowlist: str) -> "PermissionsPolicy": self._build("geolocation", *allowlist) return self def gyroscope(self, *allowlist: str) -> "PermissionsPolicy": self._build("gyroscope", *allowlist) return self def magnetometer(self, *allowlist: str) -> "PermissionsPolicy": self._build("magnetometer", *allowlist) return self def microphone(self, *allowlist: str) -> "PermissionsPolicy": self._build("microphone", *allowlist) return self def midi(self, *allowlist: str) -> "PermissionsPolicy": self._build("midi", *allowlist) return self def navigation_override(self, *allowlist: str) -> "PermissionsPolicy": self._build("navigation-override", *allowlist) return self def payment(self, *allowlist: str) -> "PermissionsPolicy": self._build("payment", *allowlist) return self def picture_in_picture(self, *allowlist: str) -> "PermissionsPolicy": self._build("picture-in-picture", *allowlist) return self def publickey_credentials_get(self, *allowlist: str) -> "PermissionsPolicy": self._build("publickey-credentials-get", *allowlist) return self def screen_wake_lock(self, *allowlist: str) -> "PermissionsPolicy": self._build("screen-wake-lock", *allowlist) return self def speaker(self, *allowlist: str) -> "PermissionsPolicy": warnings.warn( "'speaker' feature was removed in favor of 'speaker_selection'", DeprecationWarning, ) self._build("speaker", *allowlist) return self def speaker_selection(self, *allowlist: str) -> "PermissionsPolicy": self._build("speaker-selection", *allowlist) return self def sync_xhr(self, *allowlist: str) -> "PermissionsPolicy": self._build("sync-xhr", *allowlist) return self def usb(self, *allowlist: str) -> "PermissionsPolicy": self._build("usb", *allowlist) return self def web_share(self, *allowlist: str) -> "PermissionsPolicy": self._build("web-share", *allowlist) return self def vibrate(self, *allowlist: str) -> "PermissionsPolicy": warnings.warn( "'vibrate' feature has been removed without ever actually having been implemented", DeprecationWarning, ) return self def vr(self, *allowlist: str) -> "PermissionsPolicy": warnings.warn( "'vr' feature was renamed to 'xr_spatial_tracking'", DeprecationWarning ) self._build("vr", *allowlist) return self def xr_spatial_tracking(self, *allowlist: str) -> "PermissionsPolicy": self._build("xr-spatial-tracking", *allowlist) return self
30.657321
115
0.621256
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
from typing import Any, Dict, List, Optional, Tuple, Union from .headers import ( CacheControl, ContentSecurityPolicy, PermissionsPolicy, ReferrerPolicy, ReportTo, Server, StrictTransportSecurity, XContentTypeOptions, XFrameOptions, XXSSProtection, ) class Secure: """Set Secure Header options :param server: Server header options :param hsts: Strict-Transport-Security (HSTS) header options :param xfo: X-Frame-Options (XFO) header options :param xxp: X-XSS-Protection (XXP) header options :param content: X-Content-Type-Options header options :param csp: Content-Security-Policy (CSP) header options :param referrer: Referrer-Policy header options :param cache: Cache-control, Pragma and Expires headers options :param feature: Feature-Policy header options """ framework: "Framework" def __init__( self, server: Optional[Server] = None, hsts: Optional[StrictTransportSecurity] = StrictTransportSecurity(), xfo: Optional[XFrameOptions] = XFrameOptions(), xxp: Optional[XXSSProtection] = XXSSProtection(), content: Optional[XContentTypeOptions] = XContentTypeOptions(), csp: Optional[ContentSecurityPolicy] = None, referrer: Optional[ReferrerPolicy] = ReferrerPolicy(), cache: Optional[CacheControl] = CacheControl(), permissions: Optional[PermissionsPolicy] = None, report_to: Optional[ReportTo] = None, ) -> None: self.server = server self.hsts = hsts self.xfo = xfo self.xxp = xxp self.content = content self.csp = csp self.referrer = referrer self.cache = cache self.permissions = permissions self.report_to = report_to self.framework = self.Framework(self) def __repr__(self) -> str: return "\n".join( [f"{header}:{value}" for header, value in self.headers().items()] ) def _header_list( self, ) -> List[ Union[ CacheControl, ContentSecurityPolicy, PermissionsPolicy, ReferrerPolicy, ReportTo, Server, StrictTransportSecurity, XContentTypeOptions, XFrameOptions, XXSSProtection, ] ]: headers = [ self.server, self.hsts, self.xfo, self.xxp, self.content, self.csp, self.referrer, self.cache, self.permissions, self.report_to, ] return [header for header in headers if header is not None] def headers(self) -> Dict[str, str]: """Dictionary of secure headers :return: dictionary containing security headers :rtype: Dict[str, str] """ headers: Dict[str, str] = {} for header in self._header_list(): headers[header.header] = header.value return headers def headers_tuple(self) -> List[Tuple[str, str]]: """List of a tuple containing secure headers :return: list of tuples containing security headers :rtype: List[Tuple[str, str]] """ headers: List[Tuple[str, str]] = [] for header in self._header_list(): headers.append((header.header, header.value)) return headers def _set_header_dict(self, response: Any) -> None: for header in self._header_list(): response.headers[header.header] = header.value def _set_header_tuple(self, response: Any) -> None: for header in self._header_list(): response.set_header(header.header, header.value) class Framework: """ Secure supported frameworks """ def __init__(self, secure: "Secure") -> None: self.secure = secure def aiohttp(self, response: Any) -> None: """Update Secure Headers to aiohttp response object. :param response: aiohttp response object. """ self.secure._set_header_dict(response) def bottle(self, response: Any) -> None: """Update Secure Headers to Bottle response object. :param response: Bottle response object (bottle.response). """ self.secure._set_header_dict(response) def cherrypy(self) -> List[Tuple[str, str]]: """Return tuple of Secure Headers for CherryPy (tools.response_headers.headers). :return: A list with a tuple of Secure Headers. """ return self.secure.headers_tuple() def django(self, response: Any) -> None: """Update Secure Headers to Django response object. :param response: Django response object (django.http.HttpResponse) """ for header, value in self.secure.headers().items(): response[header] = value def falcon(self, response: Any) -> None: """Update Secure Headers to Falcon response object. :param response: Falcon response object (falcon.Response) """ self.secure._set_header_tuple(response) def flask(self, response: Any) -> None: """Update Secure Headers to Flask response object. :param response: Flask response object (flask.Response) """ self.secure._set_header_dict(response) def fastapi(self, response: Any) -> None: """Update Secure Headers to FastAPI response object. :param response: FastAPI response object. """ self.secure._set_header_dict(response) def hug(self, response: Any) -> None: """Update Secure Headers to hug response object. :param response: hug response object """ self.secure._set_header_tuple(response) def masonite(self, request: Any) -> None: """Update Secure Headers to Masonite request object. :param request: Masonite request object (masonite.request.Request) """ request.header(self.secure.headers()) def pyramid(self, response: Any) -> None: """Update Secure Headers to Pyramid response object. :param response: Pyramid response object (pyramid.response). """ self.secure._set_header_dict(response) def quart(self, response: Any) -> None: """Update Secure Headers to Quart response object. :param response: Quart response object (quart.wrappers.response.Response) """ self.secure._set_header_dict(response) def responder(self, response: Any) -> None: """Update Secure Headers to Responder response object. :param response: Responder response object. """ self.secure._set_header_dict(response) def sanic(self, response: Any) -> None: """Update Secure Headers to Sanic response object. :param response: Sanic response object (sanic.response). """ self.secure._set_header_dict(response) def starlette(self, response: Any) -> None: """Update Secure Headers to Starlette response object. :param response: Starlette response object. """ self.secure._set_header_dict(response) def tornado(self, response: Any) -> None: """Update Secure Headers to Tornado RequestHandler object. :param response: Tornado RequestHandler object (tornado.web.RequestHandler). """ self.secure._set_header_tuple(response)
31.354167
92
0.587713
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine # Credits: # https://github.com/kennethreitz/setup.py # Copyright <YEAR> <COPYRIGHT HOLDER> # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = "secure" DESCRIPTION = ( "A lightweight package that adds security headers for Python web frameworks." ) URL = "https://github.com/TypeError/secure" EMAIL = "[email protected]" AUTHOR = "Caleb Kinney" REQUIRES_PYTHON = ">=3.6" VERSION = "0.3.0" # What packages are required for this module to be executed? REQUIRED = [ # 'requests', 'maya', 'records', ] # What packages are optional? EXTRAS = { # 'fancy feature': ['django'], } # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: with io.open(os.path.join(here, "README.md"), encoding="utf-8") as f: long_description = "\n" + f.read() except FileNotFoundError: long_description = DESCRIPTION # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(os.path.join(here, NAME, "__version__.py")) as f: exec(f.read(), about) else: about["__version__"] = VERSION class UploadCommand(Command): """Support setup.py upload.""" description = "Build and publish the package." user_options = [] @staticmethod def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status("Removing previous builds…") rmtree(os.path.join(here, "dist")) except OSError: pass self.status("Building Source and Wheel (universal) distribution…") os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable)) self.status("Uploading the package to PyPI via Twine…") os.system("twine upload dist/*") self.status("Pushing git tags…") os.system("git tag v{0}".format(about["__version__"])) os.system("git push --tags") sys.exit() # Where the magic happens: setup( name=NAME, version=about["__version__"], description=DESCRIPTION, long_description=long_description, long_description_content_type="text/markdown", author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=("tests",)), # If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], # entry_points={ # 'console_scripts': ['mycli=mymodule:cli'], # }, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, package_data={ "secure": ["*.pyi", "py.typed"], }, license="MIT", classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], # $ setup.py publish support. cmdclass={ "upload": UploadCommand, }, )
33.006944
462
0.661969
secure
https://github.com/cak/secure
Secure 🔒 headers for Python web frameworks
667
26
2023-12-12 05:57:53+00:00
2018-11-27 00:59:09+00:00
160
MIT License
Python
import unittest import secure class TestDefaultHeaders(unittest.TestCase): def test_headers(self): secure_headers = secure.Secure().headers() self.assertEqual( secure_headers["Strict-Transport-Security"], "max-age=63072000; includeSubdomains", ) self.assertEqual( secure_headers["X-Frame-Options"], "SAMEORIGIN", ) self.assertEqual( secure_headers["X-XSS-Protection"], "0", ) self.assertEqual( secure_headers["X-Content-Type-Options"], "nosniff", ) self.assertEqual( secure_headers["Referrer-Policy"], "no-referrer, strict-origin-when-cross-origin", ) self.assertEqual( secure_headers["Cache-Control"], "no-store", ) class TestHeaders(unittest.TestCase): def test_header(self): csp = ( secure.ContentSecurityPolicy() .default_src("'none'") .base_uri("'self'") .connect_src("'self'", "api.spam.com") .frame_src("'none'") .img_src("'self'", "static.spam.com") ) secure_headers = secure.Secure(csp=csp).headers() self.assertEqual( secure_headers["Content-Security-Policy"], "default-src 'none'; base-uri 'self'; " "connect-src 'self' api.spam.com; frame-src 'none'; img-src 'self' " "static.spam.com", ) class TestHStSHeader(unittest.TestCase): def test_header(self): hsts = ( secure.StrictTransportSecurity() .include_subdomains() .preload() .max_age(2592000) ) secure_headers = secure.Secure(hsts=hsts).headers() self.assertEqual( secure_headers["Strict-Transport-Security"], "includeSubDomains; preload; max-age=2592000", ) class TestXFOHeader(unittest.TestCase): def test_header(self): xfo = secure.XFrameOptions().deny() secure_headers = secure.Secure(xfo=xfo).headers() self.assertEqual(secure_headers["X-Frame-Options"], "deny") class TestReferrerHeader(unittest.TestCase): def test_header(self): referrer = secure.ReferrerPolicy().strict_origin() secure_headers = secure.Secure(referrer=referrer).headers() self.assertEqual(secure_headers["Referrer-Policy"], "strict-origin") class TestPermissionsHeader(unittest.TestCase): def test_header(self): permissions = ( secure.PermissionsPolicy().geolocation("self", '"spam.com"').fullscreen() ) secure_headers = secure.Secure(permissions=permissions).headers() self.assertEqual( secure_headers["Permissions-Policy"], 'geolocation=(self "spam.com"), fullscreen=()', ) class TestCacheHeader(unittest.TestCase): def test_header(self): cache = secure.CacheControl().no_cache() secure_headers = secure.Secure(cache=cache).headers() self.assertEqual(secure_headers["Cache-Control"], "no-cache")
30.808081
85
0.584816