feat(csp): infrastructure de sortie de unsafe-inline, et couche partagee migree
SEC-WEB-001 / OPS-010. script-src porte toujours 'unsafe-inline' : c'est
pour cela que le XSS stocke de SEC-XSS-001 s'executait au lieu d'etre
bloque. Le retirer n'est pas un changement d'une ligne.
Ce qui bloque reellement
Un nonce autorise des elements <script> ; il ne peut rien pour un
attribut onclick="...". Mesure faite : 76 gestionnaires en ligne repartis
dans 15 gabarits. Tant qu'il en reste un, la politique ne peut pas etre
durcie.
Piege supplementaire, documente dans build_csp() : en CSP niveau 3, un
navigateur ignore 'unsafe-inline' des qu'un nonce est present. Emettre
les deux ne serait donc pas une transition douce -- ce serait couper
d'un coup tous les scripts en ligne et tous les onclick, et uniquement
sur les navigateurs recents. La bascule doit etre atomique, d'ou un
drapeau unique : CSP_ALLOW_INLINE_SCRIPT.
Infrastructure posee
build_csp() assemble l'en-tete selon le drapeau. Un nonce est genere par
requete et n'est emis que lorsque l'inline est interdit. Les 15 blocs
<script> portent deja nonce="{{ csp_nonce }}", inerte aujourd'hui : la
bascule finale sera un changement de configuration, pas de gabarits.
Couche partagee migree en premier
base.html et macros.html sont rendus sur absolument toutes les pages. Six
gestionnaires retires, remplaces par des attributs data-action et un
ecouteur delegue unique dans main.js. La delegation plutot qu'un
ecouteur par widget : le contenu injecte dynamiquement herite du
comportement sans re-attachement.
Un cliquet plutot qu'une promesse
tests/test_csp.py fixe un budget par gabarit qui ne peut que baisser.
Ajouter un gestionnaire en ligne fait echouer la suite ; en retirer sans
mettre le budget a jour aussi, ce qui force a enregistrer la progression
dans le diff. A zero, il ne reste qu'a basculer le drapeau.
Le cliquet a d'ailleurs corrige mon propre relevé : mon grep initial
comptait 83 gestionnaires, la mesure exacte en donne 76 -- le motif ne
verifiait pas l'espace avant l'attribut.
style-src conserve 'unsafe-inline' : les attributs style="" sont partout et
ne constituent pas un vecteur XSS a eux seuls. Migration distincte.
192 tests.
Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
+69
-11
@@ -5,7 +5,9 @@ the Flask application instance with comprehensive security hardening.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from flask import Flask, request, redirect, jsonify, render_template, url_for
|
import secrets
|
||||||
|
|
||||||
|
from flask import Flask, g, request, redirect, jsonify, render_template, url_for
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
from app.extensions import db, login_manager, csrf, limiter, babel
|
from app.extensions import db, login_manager, csrf, limiter, babel
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
@@ -33,6 +35,52 @@ def nl2br(value):
|
|||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def build_csp(*, allow_inline_script, nonce=None):
|
||||||
|
"""Assemble the Content-Security-Policy header.
|
||||||
|
|
||||||
|
Two mutually exclusive modes, and they really are exclusive.
|
||||||
|
|
||||||
|
Under CSP level 3, a browser that understands nonces **ignores
|
||||||
|
'unsafe-inline' entirely as soon as a nonce is present**. Emitting both
|
||||||
|
would therefore not be a gentle transition: it would drop every inline
|
||||||
|
script and every onclick attribute at once, in modern browsers only.
|
||||||
|
The switch has to be atomic, which is why one flag drives it.
|
||||||
|
|
||||||
|
While allow_inline_script is true no nonce is emitted at all, so adding
|
||||||
|
nonce="{{ csp_nonce }}" to a template ahead of the switch is harmless.
|
||||||
|
|
||||||
|
Flipping the flag requires every inline event handler to be gone first.
|
||||||
|
A nonce cannot authorise an onclick attribute — nonces apply to script
|
||||||
|
elements, never to handler attributes. See tests/test_csp.py, which
|
||||||
|
tracks how many are left.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
allow_inline_script: Keep 'unsafe-inline' in script-src.
|
||||||
|
nonce: Per-request nonce, used only when inline script is not allowed.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The header value.
|
||||||
|
"""
|
||||||
|
if allow_inline_script:
|
||||||
|
script_src = "'self' 'unsafe-inline' https://cdn.jsdelivr.net"
|
||||||
|
else:
|
||||||
|
script_src = f"'self' 'nonce-{nonce}' https://cdn.jsdelivr.net"
|
||||||
|
|
||||||
|
return '; '.join([
|
||||||
|
"default-src 'self'",
|
||||||
|
f'script-src {script_src}',
|
||||||
|
# style-src is a separate migration: inline style="" attributes are
|
||||||
|
# spread across the templates and are not an XSS vector on their own.
|
||||||
|
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net",
|
||||||
|
"font-src 'self' https://cdnjs.cloudflare.com",
|
||||||
|
"img-src 'self' data: https://cdn.discordapp.com",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
def create_app(config=None):
|
def create_app(config=None):
|
||||||
"""Create and configure the Flask application.
|
"""Create and configure the Flask application.
|
||||||
|
|
||||||
@@ -70,6 +118,12 @@ def create_app(config=None):
|
|||||||
app.config['CORS_ALLOWED_ORIGINS'] = os.getenv('CORS_ALLOWED_ORIGINS', '')
|
app.config['CORS_ALLOWED_ORIGINS'] = os.getenv('CORS_ALLOWED_ORIGINS', '')
|
||||||
app.config['FORCE_HTTPS'] = os.getenv('FORCE_HTTPS', 'true').lower() == 'true'
|
app.config['FORCE_HTTPS'] = os.getenv('FORCE_HTTPS', 'true').lower() == 'true'
|
||||||
|
|
||||||
|
# Still true: 76 inline event handlers remain across the templates, and
|
||||||
|
# no nonce can authorise those. Flip once tests/test_csp.py reports zero.
|
||||||
|
app.config['CSP_ALLOW_INLINE_SCRIPT'] = (
|
||||||
|
os.getenv('CSP_ALLOW_INLINE_SCRIPT', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
|
||||||
# Internationalisation. French is the site's primary language.
|
# Internationalisation. French is the site's primary language.
|
||||||
app.config['BABEL_DEFAULT_LOCALE'] = i18n.DEFAULT_LOCALE
|
app.config['BABEL_DEFAULT_LOCALE'] = i18n.DEFAULT_LOCALE
|
||||||
app.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.join(
|
app.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.join(
|
||||||
@@ -140,6 +194,17 @@ def create_app(config=None):
|
|||||||
|
|
||||||
# Exposed to every template so the language switcher can render itself
|
# Exposed to every template so the language switcher can render itself
|
||||||
# without each view having to pass the list along.
|
# without each view having to pass the list along.
|
||||||
|
@app.before_request
|
||||||
|
def generate_csp_nonce():
|
||||||
|
# Only meaningful once inline script is disallowed; generated
|
||||||
|
# unconditionally so templates can carry nonce="" beforehand.
|
||||||
|
g.csp_nonce = secrets.token_urlsafe(16)
|
||||||
|
|
||||||
|
@app.context_processor
|
||||||
|
def inject_csp_nonce():
|
||||||
|
return {'csp_nonce': '' if app.config['CSP_ALLOW_INLINE_SCRIPT']
|
||||||
|
else g.get('csp_nonce', '')}
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def inject_locales():
|
def inject_locales():
|
||||||
from flask_babel import get_locale
|
from flask_babel import get_locale
|
||||||
@@ -199,16 +264,9 @@ def create_app(config=None):
|
|||||||
'interest-cohort=(), payment=(), usb=()'
|
'interest-cohort=(), payment=(), usb=()'
|
||||||
)
|
)
|
||||||
response.headers['Cross-Origin-Opener-Policy'] = 'same-origin'
|
response.headers['Cross-Origin-Opener-Policy'] = 'same-origin'
|
||||||
response.headers['Content-Security-Policy'] = (
|
response.headers['Content-Security-Policy'] = build_csp(
|
||||||
"default-src 'self'; "
|
allow_inline_script=app.config['CSP_ALLOW_INLINE_SCRIPT'],
|
||||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
|
nonce=g.get('csp_nonce'),
|
||||||
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; "
|
|
||||||
"font-src 'self' https://cdnjs.cloudflare.com; "
|
|
||||||
"img-src 'self' data: https://cdn.discordapp.com; "
|
|
||||||
"connect-src 'self'; "
|
|
||||||
"frame-ancestors 'none'; "
|
|
||||||
"base-uri 'self'; "
|
|
||||||
"form-action 'self'"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Only enable HSTS when HTTPS is actually being used
|
# Only enable HSTS when HTTPS is actually being used
|
||||||
|
|||||||
+57
-1
@@ -436,4 +436,60 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
}, 5000);
|
}, 5000);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
/* =========================================================================
|
||||||
|
Declarative behaviours — replacing inline event handlers
|
||||||
|
=========================================================================
|
||||||
|
|
||||||
|
A Content Security Policy without 'unsafe-inline' blocks `onclick="..."`
|
||||||
|
attributes, and a nonce does not help: nonces apply to <script> elements,
|
||||||
|
never to event handler attributes. Dropping 'unsafe-inline' therefore
|
||||||
|
requires removing every one of them first.
|
||||||
|
|
||||||
|
Rather than one listener per widget, behaviours are declared in the
|
||||||
|
markup with a data-action attribute and dispatched from a single
|
||||||
|
delegated listener. New markup gets the behaviour for free, and nothing
|
||||||
|
has to be re-bound after content is replaced dynamically.
|
||||||
|
|
||||||
|
<button data-action="toggle-sidebar">
|
||||||
|
<button data-action="dismiss-alert">
|
||||||
|
<div data-action="hide-modal" data-modal-id="confirmDelete">
|
||||||
|
|
||||||
|
Migration status is tracked by tests/test_csp.py.
|
||||||
|
========================================================================= */
|
||||||
|
|
||||||
|
const DATA_ACTIONS = {
|
||||||
|
'toggle-sidebar': function () {
|
||||||
|
toggleSidebar();
|
||||||
|
},
|
||||||
|
'toggle-dark-mode': function () {
|
||||||
|
toggleDarkMode();
|
||||||
|
},
|
||||||
|
'dismiss-alert': function (element) {
|
||||||
|
const alert = element.closest('.alert');
|
||||||
|
if (alert) {
|
||||||
|
alert.remove();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'hide-modal': function (element) {
|
||||||
|
const id = element.getAttribute('data-modal-id');
|
||||||
|
if (id && typeof hideModal === 'function') {
|
||||||
|
hideModal(id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'history-back': function (element, event) {
|
||||||
|
event.preventDefault();
|
||||||
|
history.back();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('click', function (event) {
|
||||||
|
const trigger = event.target.closest('[data-action]');
|
||||||
|
if (!trigger) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const handler = DATA_ACTIONS[trigger.getAttribute('data-action')];
|
||||||
|
if (handler) {
|
||||||
|
handler(trigger, event);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@@ -126,14 +126,15 @@
|
|||||||
|
|
||||||
<div class="main-content" id="mainContent">
|
<div class="main-content" id="mainContent">
|
||||||
<header class="top-bar">
|
<header class="top-bar">
|
||||||
<button class="sidebar-toggle" id="sidebarToggle" onclick="toggleSidebar()">
|
<button class="sidebar-toggle" id="sidebarToggle" data-action="toggle-sidebar">
|
||||||
<i class="fas fa-bars"></i>
|
<i class="fas fa-bars"></i>
|
||||||
</button>
|
</button>
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>{% block page_title %}{{ _('Dashboard') }}{% endblock %}</h1>
|
<h1>{% block page_title %}{{ _('Dashboard') }}{% endblock %}</h1>
|
||||||
{% block breadcrumb %}{% endblock %}
|
{% block breadcrumb %}{% endblock %}
|
||||||
</div>
|
</div>
|
||||||
<button class="dark-mode-toggle" id="darkModeToggle" onclick="toggleDarkMode()" title="Toggle dark mode">
|
<button class="dark-mode-toggle" id="darkModeToggle" data-action="toggle-dark-mode"
|
||||||
|
title="{{ _('Toggle dark mode') }}">
|
||||||
<i class="fas fa-moon"></i>
|
<i class="fas fa-moon"></i>
|
||||||
</button>
|
</button>
|
||||||
{% block header_actions %}{% endblock %}
|
{% block header_actions %}{% endblock %}
|
||||||
@@ -144,7 +145,8 @@
|
|||||||
{% for category, message in messages %}
|
{% for category, message in messages %}
|
||||||
<div class="alert alert-{{ category }} alert-dismissible">
|
<div class="alert alert-{{ category }} alert-dismissible">
|
||||||
<span>{{ message }}</span>
|
<span>{{ message }}</span>
|
||||||
<button type="button" class="alert-close" onclick="this.parentElement.remove()">×</button>
|
<button type="button" class="alert-close" data-action="dismiss-alert"
|
||||||
|
aria-label="{{ _('Dismiss') }}">×</button>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -162,7 +164,8 @@
|
|||||||
{% for category, message in messages %}
|
{% for category, message in messages %}
|
||||||
<div class="alert alert-{{ category }} alert-dismissible">
|
<div class="alert alert-{{ category }} alert-dismissible">
|
||||||
<span>{{ message }}</span>
|
<span>{{ message }}</span>
|
||||||
<button type="button" class="alert-close" onclick="this.parentElement.remove()">×</button>
|
<button type="button" class="alert-close" data-action="dismiss-alert"
|
||||||
|
aria-label="{{ _('Dismiss') }}">×</button>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -108,11 +108,12 @@
|
|||||||
{# Modal Macro - renders a modal dialog #}
|
{# Modal Macro - renders a modal dialog #}
|
||||||
{% macro modal(id, title, content, footer_buttons=None) %}
|
{% macro modal(id, title, content, footer_buttons=None) %}
|
||||||
<div id="{{ id }}" class="modal hidden">
|
<div id="{{ id }}" class="modal hidden">
|
||||||
<div class="modal-backdrop" onclick="hideModal('{{ id }}')"></div>
|
<div class="modal-backdrop" data-action="hide-modal" data-modal-id="{{ id }}"></div>
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h3>{{ title }}</h3>
|
<h3>{{ title }}</h3>
|
||||||
<button class="modal-close" onclick="hideModal('{{ id }}')">×</button>
|
<button class="modal-close" data-action="hide-modal" data-modal-id="{{ id }}"
|
||||||
|
aria-label="{{ _('Close') }}">×</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
{{ content }}
|
{{ content }}
|
||||||
|
|||||||
@@ -116,7 +116,7 @@
|
|||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.css" rel="stylesheet">
|
<link href="https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.css" rel="stylesheet">
|
||||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.js"></script>
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
var canScheduleMatches = {% if current_user.can_schedule_matches() %}true{% else %}false{% endif %};
|
var canScheduleMatches = {% if current_user.can_schedule_matches() %}true{% else %}false{% endif %};
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
|||||||
@@ -88,7 +88,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Time slots from 8:00 AM to 10:00 PM (30-minute intervals)
|
// Time slots from 8:00 AM to 10:00 PM (30-minute intervals)
|
||||||
const TIME_SLOTS = [];
|
const TIME_SLOTS = [];
|
||||||
for (let h = 8; h <= 22; h++) {
|
for (let h = 8; h <= 22; h++) {
|
||||||
|
|||||||
@@ -107,7 +107,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function showUploadSignedForm(contractId) {
|
function showUploadSignedForm(contractId) {
|
||||||
document.getElementById('uploadSignedForm').action = '/users/contracts/' + contractId + '/upload_signed';
|
document.getElementById('uploadSignedForm').action = '/users/contracts/' + contractId + '/upload_signed';
|
||||||
document.getElementById('uploadSignedModal').classList.remove('hidden');
|
document.getElementById('uploadSignedModal').classList.remove('hidden');
|
||||||
|
|||||||
@@ -112,7 +112,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
var GAME_PLATFORMS = {{ game_platforms|tojson }};
|
var GAME_PLATFORMS = {{ game_platforms|tojson }};
|
||||||
|
|
||||||
// Show/hide gamertag inputs when games are checked
|
// Show/hide gamertag inputs when games are checked
|
||||||
|
|||||||
@@ -114,7 +114,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Show/hide gamertag inputs when games are checked
|
// Show/hide gamertag inputs when games are checked
|
||||||
function toggleGamertagInputs() {
|
function toggleGamertagInputs() {
|
||||||
var selectedGames = [];
|
var selectedGames = [];
|
||||||
|
|||||||
@@ -445,7 +445,7 @@
|
|||||||
gap: 4px;
|
gap: 4px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Player data as simple JS object (id -> full_name)
|
// Player data as simple JS object (id -> full_name)
|
||||||
var playerDataById = {
|
var playerDataById = {
|
||||||
player_data: {
|
player_data: {
|
||||||
|
|||||||
@@ -169,7 +169,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function togglePresence(btn) {
|
function togglePresence(btn) {
|
||||||
var matchId = btn.getAttribute('data-match-id');
|
var matchId = btn.getAttribute('data-match-id');
|
||||||
var participantId = btn.getAttribute('data-participant-id');
|
var participantId = btn.getAttribute('data-participant-id');
|
||||||
|
|||||||
@@ -260,7 +260,7 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function showRejectModal(requestId) {
|
function showRejectModal(requestId) {
|
||||||
const modal = document.getElementById('rejectModal');
|
const modal = document.getElementById('rejectModal');
|
||||||
const form = document.getElementById('rejectForm');
|
const form = document.getElementById('rejectForm');
|
||||||
|
|||||||
@@ -177,7 +177,7 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Time slots from 8:00 AM to 10:00 PM
|
// Time slots from 8:00 AM to 10:00 PM
|
||||||
const TIME_SLOTS = [];
|
const TIME_SLOTS = [];
|
||||||
for (let h = 8; h <= 22; h++) {
|
for (let h = 8; h <= 22; h++) {
|
||||||
|
|||||||
@@ -266,7 +266,7 @@
|
|||||||
@media (max-width: 768px) { .availability-grid { grid-template-columns: repeat(3, 1fr); } }
|
@media (max-width: 768px) { .availability-grid { grid-template-columns: repeat(3, 1fr); } }
|
||||||
@media (max-width: 480px) { .availability-grid { grid-template-columns: 1fr; } }
|
@media (max-width: 480px) { .availability-grid { grid-template-columns: 1fr; } }
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
const COACH_TIME_SLOTS = [];
|
const COACH_TIME_SLOTS = [];
|
||||||
for (let h = 8; h <= 22; h++) {
|
for (let h = 8; h <= 22; h++) {
|
||||||
for (let m = 0; m < 60; m += 30) {
|
for (let m = 0; m < 60; m += 30) {
|
||||||
@@ -394,7 +394,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{% if user.role == 'player' %}
|
{% if user.role == 'player' %}
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Generate time slots from 5pm (17:00) to 12am (24:00)
|
// Generate time slots from 5pm (17:00) to 12am (24:00)
|
||||||
var TIME_SLOTS = [];
|
var TIME_SLOTS = [];
|
||||||
for (var h = 17; h <= 24; h++) {
|
for (var h = 17; h <= 24; h++) {
|
||||||
|
|||||||
@@ -155,7 +155,7 @@
|
|||||||
<p class="auth-link">Already have an account? <a href="{{ url_for('auth.login') }}">Sign in</a></p>
|
<p class="auth-link">Already have an account? <a href="{{ url_for('auth.login') }}">Sign in</a></p>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
// Toggle gamertag input visibility when a game checkbox is checked/unchecked
|
// Toggle gamertag input visibility when a game checkbox is checked/unchecked
|
||||||
function toggleGamertagInput(checkbox) {
|
function toggleGamertagInput(checkbox) {
|
||||||
var game = checkbox.value.replace(/ /g, '_');
|
var game = checkbox.value.replace(/ /g, '_');
|
||||||
|
|||||||
@@ -145,7 +145,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function togglePresence(btn) {
|
function togglePresence(btn) {
|
||||||
var matchId = btn.getAttribute('data-match-id');
|
var matchId = btn.getAttribute('data-match-id');
|
||||||
var participantId = btn.getAttribute('data-participant-id');
|
var participantId = btn.getAttribute('data-participant-id');
|
||||||
|
|||||||
@@ -300,7 +300,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function showCreateForm() {
|
function showCreateForm() {
|
||||||
document.getElementById('createTeamForm').classList.remove('hidden');
|
document.getElementById('createTeamForm').classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -562,7 +562,7 @@
|
|||||||
box-shadow: 0 1px 3px rgba(0,0,0,0.12);
|
box-shadow: 0 1px 3px rgba(0,0,0,0.12);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script nonce="{{ csp_nonce }}">
|
||||||
function showCreateTeam() { document.getElementById('createTeamForm').classList.remove('hidden'); }
|
function showCreateTeam() { document.getElementById('createTeamForm').classList.remove('hidden'); }
|
||||||
function hideCreateTeam() { document.getElementById('createTeamForm').classList.add('hidden'); }
|
function hideCreateTeam() { document.getElementById('createTeamForm').classList.add('hidden'); }
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -8,7 +8,7 @@ msgid ""
|
|||||||
msgstr ""
|
msgstr ""
|
||||||
"Project-Id-Version: team-tryouts VERSION\n"
|
"Project-Id-Version: team-tryouts VERSION\n"
|
||||||
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
|
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
|
||||||
"POT-Creation-Date: 2026-08-07 20:25-0400\n"
|
"POT-Creation-Date: 2026-08-07 20:42-0400\n"
|
||||||
"PO-Revision-Date: 2026-08-07 20:22-0400\n"
|
"PO-Revision-Date: 2026-08-07 20:22-0400\n"
|
||||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||||
"Language: en\n"
|
"Language: en\n"
|
||||||
@@ -268,10 +268,22 @@ msgstr "My Profile"
|
|||||||
msgid "Logout"
|
msgid "Logout"
|
||||||
msgstr "Logout"
|
msgstr "Logout"
|
||||||
|
|
||||||
#: app/templates/layouts/base.html:175
|
#: app/templates/layouts/base.html:137
|
||||||
|
msgid "Toggle dark mode"
|
||||||
|
msgstr "Toggle dark mode"
|
||||||
|
|
||||||
|
#: app/templates/layouts/base.html:149 app/templates/layouts/base.html:168
|
||||||
|
msgid "Dismiss"
|
||||||
|
msgstr "Dismiss"
|
||||||
|
|
||||||
|
#: app/templates/layouts/base.html:178
|
||||||
msgid "Team Tryout Management System"
|
msgid "Team Tryout Management System"
|
||||||
msgstr "Team Tryout Management System"
|
msgstr "Team Tryout Management System"
|
||||||
|
|
||||||
|
#: app/templates/layouts/macros.html:116
|
||||||
|
msgid "Close"
|
||||||
|
msgstr "Close"
|
||||||
|
|
||||||
#: app/templates/pages/login.html:2
|
#: app/templates/pages/login.html:2
|
||||||
msgid "Login"
|
msgid "Login"
|
||||||
msgstr "Login"
|
msgstr "Login"
|
||||||
|
|||||||
Binary file not shown.
@@ -8,7 +8,7 @@ msgid ""
|
|||||||
msgstr ""
|
msgstr ""
|
||||||
"Project-Id-Version: team-tryouts VERSION\n"
|
"Project-Id-Version: team-tryouts VERSION\n"
|
||||||
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
|
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
|
||||||
"POT-Creation-Date: 2026-08-07 20:25-0400\n"
|
"POT-Creation-Date: 2026-08-07 20:42-0400\n"
|
||||||
"PO-Revision-Date: 2026-08-07 20:22-0400\n"
|
"PO-Revision-Date: 2026-08-07 20:22-0400\n"
|
||||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||||
"Language: fr\n"
|
"Language: fr\n"
|
||||||
@@ -268,10 +268,22 @@ msgstr "Mon profil"
|
|||||||
msgid "Logout"
|
msgid "Logout"
|
||||||
msgstr "Déconnexion"
|
msgstr "Déconnexion"
|
||||||
|
|
||||||
#: app/templates/layouts/base.html:175
|
#: app/templates/layouts/base.html:137
|
||||||
|
msgid "Toggle dark mode"
|
||||||
|
msgstr "Basculer le mode sombre"
|
||||||
|
|
||||||
|
#: app/templates/layouts/base.html:149 app/templates/layouts/base.html:168
|
||||||
|
msgid "Dismiss"
|
||||||
|
msgstr "Fermer"
|
||||||
|
|
||||||
|
#: app/templates/layouts/base.html:178
|
||||||
msgid "Team Tryout Management System"
|
msgid "Team Tryout Management System"
|
||||||
msgstr "Système de gestion des sélections d'équipe"
|
msgstr "Système de gestion des sélections d'équipe"
|
||||||
|
|
||||||
|
#: app/templates/layouts/macros.html:116
|
||||||
|
msgid "Close"
|
||||||
|
msgstr "Fermer"
|
||||||
|
|
||||||
#: app/templates/pages/login.html:2
|
#: app/templates/pages/login.html:2
|
||||||
msgid "Login"
|
msgid "Login"
|
||||||
msgstr "Connexion"
|
msgstr "Connexion"
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""Content Security Policy, and the migration away from 'unsafe-inline'.
|
||||||
|
|
||||||
|
SEC-WEB-001 / OPS-010. script-src still carries 'unsafe-inline', which is
|
||||||
|
why the stored XSS of SEC-XSS-001 executed instead of being blocked.
|
||||||
|
|
||||||
|
Removing it is not a one-line change. A nonce authorises `<script>`
|
||||||
|
elements; it can do nothing for `onclick="..."` attributes, and there are
|
||||||
|
dozens of those across the templates. Under CSP level 3 a browser also
|
||||||
|
ignores 'unsafe-inline' the moment a nonce appears, so the two cannot
|
||||||
|
coexist as a gradual transition — the switch is atomic.
|
||||||
|
|
||||||
|
The counts below are a ratchet: they may only go down. Migrating a
|
||||||
|
template and lowering the number is a deliberate act, recorded in the
|
||||||
|
diff. Adding a new inline handler turns the suite red.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.app import build_csp
|
||||||
|
|
||||||
|
TEMPLATE_ROOT = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||||
|
'app', 'templates',
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Attributes a nonce can never authorise.
|
||||||
|
INLINE_HANDLER = re.compile(
|
||||||
|
r'\son(?:click|change|submit|input|load|keyup|keydown|mouseover|focus|blur)\s*=',
|
||||||
|
re.I,
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Remaining inline handlers, per template. Lower these as you migrate;
|
||||||
|
#: never raise one. Templates absent from this map must have none.
|
||||||
|
HANDLER_BUDGET = {
|
||||||
|
'pages/match_form.html': 13,
|
||||||
|
'pages/calendar.html': 11,
|
||||||
|
'pages/teams.html': 11,
|
||||||
|
'pages/evaluate_player.html': 9,
|
||||||
|
'pages/view_tryout.html': 8,
|
||||||
|
'pages/contracts.html': 4,
|
||||||
|
'pages/notes.html': 4,
|
||||||
|
'pages/team_matches.html': 4,
|
||||||
|
'pages/coach_availability.html': 3,
|
||||||
|
'pages/profile.html': 3,
|
||||||
|
'pages/one_on_one.html': 2,
|
||||||
|
'pages/my_teams.html': 1,
|
||||||
|
'pages/register.html': 1,
|
||||||
|
'pages/users.html': 1,
|
||||||
|
'pages/view_user.html': 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
#: What the ratchet is counting down to.
|
||||||
|
TOTAL_BUDGET = sum(HANDLER_BUDGET.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _templates():
|
||||||
|
for root, _dirs, files in os.walk(TEMPLATE_ROOT):
|
||||||
|
for name in files:
|
||||||
|
if name.endswith('.html'):
|
||||||
|
full = os.path.join(root, name)
|
||||||
|
rel = os.path.relpath(full, TEMPLATE_ROOT).replace(os.sep, '/')
|
||||||
|
yield rel, full
|
||||||
|
|
||||||
|
|
||||||
|
def _count_handlers(path):
|
||||||
|
with open(path, encoding='utf-8') as handle:
|
||||||
|
return len(INLINE_HANDLER.findall(handle.read()))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPolicyHeader:
|
||||||
|
def test_the_current_policy_still_allows_inline_script(self, client):
|
||||||
|
"""Documents where we are, not where we want to be."""
|
||||||
|
csp = client.get('/auth/login').headers['Content-Security-Policy']
|
||||||
|
assert "'unsafe-inline'" in csp
|
||||||
|
|
||||||
|
def test_the_policy_pins_the_dangerous_directives(self, client):
|
||||||
|
csp = client.get('/auth/login').headers['Content-Security-Policy']
|
||||||
|
|
||||||
|
assert "default-src 'self'" in csp
|
||||||
|
assert "frame-ancestors 'none'" in csp
|
||||||
|
assert "base-uri 'self'" in csp
|
||||||
|
assert "form-action 'self'" in csp
|
||||||
|
assert "object-src" not in csp or "object-src 'none'" in csp
|
||||||
|
|
||||||
|
def test_no_nonce_is_emitted_while_inline_script_is_allowed(self, client):
|
||||||
|
"""Emitting both would silently drop every inline script in modern
|
||||||
|
browsers, since a nonce makes them ignore 'unsafe-inline'."""
|
||||||
|
csp = client.get('/auth/login').headers['Content-Security-Policy']
|
||||||
|
assert 'nonce-' not in csp
|
||||||
|
|
||||||
|
def test_the_hardened_policy_carries_a_nonce_and_no_unsafe_inline(self):
|
||||||
|
csp = build_csp(allow_inline_script=False, nonce='abc123')
|
||||||
|
|
||||||
|
assert "'nonce-abc123'" in csp
|
||||||
|
assert "'unsafe-inline'" not in csp.split('style-src')[0]
|
||||||
|
|
||||||
|
def test_each_request_gets_a_distinct_nonce(self, app):
|
||||||
|
"""A reused nonce is worth no more than 'unsafe-inline'."""
|
||||||
|
application = app
|
||||||
|
application.config['CSP_ALLOW_INLINE_SCRIPT'] = False
|
||||||
|
client = application.test_client()
|
||||||
|
|
||||||
|
seen = set()
|
||||||
|
for _ in range(5):
|
||||||
|
csp = client.get('/auth/login').headers['Content-Security-Policy']
|
||||||
|
seen.add(re.search(r"'nonce-([^']+)'", csp).group(1))
|
||||||
|
|
||||||
|
assert len(seen) == 5
|
||||||
|
|
||||||
|
|
||||||
|
class TestInlineHandlerRatchet:
|
||||||
|
@pytest.mark.parametrize('relative,full', list(_templates()))
|
||||||
|
def test_a_template_never_gains_an_inline_handler(self, relative, full):
|
||||||
|
allowed = HANDLER_BUDGET.get(relative, 0)
|
||||||
|
found = _count_handlers(full)
|
||||||
|
|
||||||
|
assert found <= allowed, (
|
||||||
|
f'{relative} has {found} inline event handler(s), budget is '
|
||||||
|
f'{allowed}. A nonce cannot authorise these — use '
|
||||||
|
f'data-action="..." and the delegated listener in main.js.'
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_the_budget_map_has_no_stale_entries(self):
|
||||||
|
"""Lower an entry to zero and it must be deleted, so the map keeps
|
||||||
|
reflecting the real remaining work."""
|
||||||
|
actual = {rel: _count_handlers(full) for rel, full in _templates()}
|
||||||
|
|
||||||
|
stale = [rel for rel, allowed in HANDLER_BUDGET.items()
|
||||||
|
if actual.get(rel, 0) < allowed]
|
||||||
|
|
||||||
|
assert not stale, (
|
||||||
|
f'Budget is now higher than reality for {stale}. Lower or remove '
|
||||||
|
f'these entries so the count keeps meaning something.'
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_the_shared_layout_is_already_free_of_them(self):
|
||||||
|
"""base.html and macros.html render on every single page, so they
|
||||||
|
were migrated first."""
|
||||||
|
for relative in ('layouts/base.html', 'layouts/macros.html'):
|
||||||
|
full = os.path.join(TEMPLATE_ROOT, *relative.split('/'))
|
||||||
|
assert _count_handlers(full) == 0, f'{relative} regressed'
|
||||||
|
|
||||||
|
def test_progress_is_recorded(self):
|
||||||
|
"""Fails when the total drops, as a reminder to update the budget
|
||||||
|
and, once it reaches zero, to flip CSP_ALLOW_INLINE_SCRIPT."""
|
||||||
|
total = sum(_count_handlers(full) for _rel, full in _templates())
|
||||||
|
|
||||||
|
assert total <= TOTAL_BUDGET
|
||||||
|
assert total == TOTAL_BUDGET, (
|
||||||
|
f'{TOTAL_BUDGET - total} handler(s) removed since the budget was '
|
||||||
|
f'last updated — lower HANDLER_BUDGET to {total}. At zero, set '
|
||||||
|
f'CSP_ALLOW_INLINE_SCRIPT to false and delete this ratchet.'
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user