<commit_before># Copyright 2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import collections

import flask
from sqlalchemy import event

from scoreboard.app import app
from scoreboard import models
from scoreboard import utils


DEFAULT_CSP_POLICY = {
        'default-src': ["'self'"],
        'script-src': [
            "'self'",
            "'unsafe-eval'",  # Needed for Charts.js
        ],
        'frame-ancestors': ["'none'"],
        'img-src': [
            "'self'",
            'data:',
        ],
        'object-src': ["'none'"],
        'reflected-xss': ['block'],
        'font-src': [
            "'self'",
            'fonts.gstatic.com',
        ],
        'style-src': [
            "'self'",
            'fonts.googleapis.com',
            "'unsafe-inline'",  # Needed for Charts.js
        ],
        }

_CSP_POLICY_STRING = None


def get_csp_policy():
    global _CSP_POLICY_STRING
    if _CSP_POLICY_STRING is not None:
        return _CSP_POLICY_STRING
    if app.config.get('CSP_POLICY'):
        policy = app.config.get('CSP_POLICY')
    elif app.config.get('EXTEND_CSP_POLICY'):
        policy = collections.defaultdict(list)
        for k, v in DEFAULT_CSP_POLICY.iteritems():
            policy[k] = v
        for k, v in app.config.get('EXTEND_CSP_POLICY').iteritems():
            policy[k].extend(v)
    else:
        policy = DEFAULT_CSP_POLICY
    components = []
    for k, v in policy.iteritems():
        sources = ' '.join(v)
        components.append(k + ' ' + sources)
    _CSP_POLICY_STRING = '; '.join(components)
    return _CSP_POLICY_STRING


# Setup flask.g
@app.before_request
def load_globals():
    """Prepopulate flask.g.* with properties."""
    flask.g.uid = flask.session.get('user')
    flask.g.tid = flask.session.get('team')
    flask.g.admin = flask.session.get('admin') or False


# Add headers to responses
@app.after_request
def add_headers(response):
    """Add security-related headers to all outgoing responses."""
    h = response.headers
    h.add('Content-Security-Policy', get_csp_policy())
    h.add('X-Frame-Options', 'DENY')
    h.add('X-XSS-Protection', '1', mode='block')<commit_msg>Ensure flask.g.{user,team} are clear on each request.<commit_after># Copyright 2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import collections

import flask
from sqlalchemy import event

from scoreboard.app import app
from scoreboard import models
from scoreboard import utils


DEFAULT_CSP_POLICY = {
        'default-src': ["'self'"],
        'script-src': [
            "'self'",
            "'unsafe-eval'",  # Needed for Charts.js
        ],
        'frame-ancestors': ["'none'"],
        'img-src': [
            "'self'",
            'data:',
        ],
        'object-src': ["'none'"],
        'reflected-xss': ['block'],
        'font-src': [
            "'self'",
            'fonts.gstatic.com',
        ],
        'style-src': [
            "'self'",
            'fonts.googleapis.com',
            "'unsafe-inline'",  # Needed for Charts.js
        ],
        }

_CSP_POLICY_STRING = None


def get_csp_policy():
    global _CSP_POLICY_STRING
    if _CSP_POLICY_STRING is not None:
        return _CSP_POLICY_STRING
    if app.config.get('CSP_POLICY'):
        policy = app.config.get('CSP_POLICY')
    elif app.config.get('EXTEND_CSP_POLICY'):
        policy = collections.defaultdict(list)
        for k, v in DEFAULT_CSP_POLICY.iteritems():
            policy[k] = v
        for k, v in app.config.get('EXTEND_CSP_POLICY').iteritems():
            policy[k].extend(v)
    else:
        policy = DEFAULT_CSP_POLICY
    components = []
    for k, v in policy.iteritems():
        sources = ' '.join(v)
        components.append(k + ' ' + sources)
    _CSP_POLICY_STRING = '; '.join(components)
    return _CSP_POLICY_STRING


# Setup flask.g
@app.before_request
def load_globals():
    """Prepopulate flask.g.* with properties."""
    flask.g.uid = flask.session.get('user')
    flask.g.tid = flask.session.get('team')
    flask.g.admin = flask.session.get('admin') or False
    try:
        del flask.g.user
    except AttributeError:
        pass
    try:
        del flask.g.team
    except AttributeError:
        pass


# Add headers to responses
@app.after_request
def add_headers(response):
    """Add security-related headers to all outgoing responses."""
    h = response.headers
    h.add('Content-Security-Policy', get_csp_policy())
    h.add('X-Frame-Options', 'DENY')
    h.add('X-XSS-Protection', '1', mode='block')
{'fraction_non_alphanumeric': 0.12797404470079307, 'fraction_numerical': 0.0032444124008651765, 'mean_word_length': 2.607932379713914, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1838091', 'n_tokens_mistral': 1773, 'n_tokens_neox': 1738, 'n_words': 461}