def test_cookie_probe_incorrect(render_template, current_app, app, cookie_kv):
    current_app.config = {
        "DM_COOKIE_PROBE_COOKIE_NAME": "foo",
        "DM_COOKIE_PROBE_COOKIE_VALUE": "bar",
        "DM_COOKIE_PROBE_EXPECT_PRESENT": True,
    }
    render_template.return_value = "<html>Oh dear</html>"

    with app.test_request_context('/',
                                  environ_base=cookie_kv and {
                                      "HTTP_COOKIE": dump_cookie(*cookie_kv),
                                  }):
        app.config['WTF_CSRF_ENABLED'] = True
        app.register_blueprint(external_blueprint)

        response, status_code = csrf_handler(CSRFError())

        assert response == render_template.return_value
        assert status_code == 400
        assert render_template.mock_calls == [
            mock.call(
                "errors/400.html",
                error_message=
                "This feature requires cookies to be enabled for correct operation",
            )
        ]
Beispiel #2
0
def go_to_network(tries=0):

    c = Client(mock=False)
    form = GoToNetworkForm(request.form)
    if not form.validate():
        raise CSRFError()

    curr_loc_query = request.form['curr_loc']

    try:
        if request.form.get('language', None):
            networks = c.get_networks(1,
                                      near_location=curr_loc_query,
                                      language=request.form['language'])
        elif request.form.get('from_loc', None):
            networks = c.get_networks(1,
                                      near_location=curr_loc_query,
                                      from_location=request.form['from_loc'])
        else:
            abort(HTTPStatus.BAD_REQUEST)
    except requests.exceptions.ConnectionError as e:

        # Let's keep trying, but less agressively.
        if tries >= GO_TO_NETWORK_MAX_RETRIES:
            raise e
        time.sleep(GO_TO_NETWORK_WAIT_SECS)
        go_to_network(tries + 1)

    if len(networks) != 1:
        abort(HTTPStatus.INTERNAL_SERVER_ERROR)

    return redirect(url_for('networks.network', id=str(networks[0]['id'])))
Beispiel #3
0
def test_csrf_redirects_to_sign_in_page_if_not_signed_in(client, mocker):
    csrf_err = CSRFError('400 Bad Request: The CSRF tokens do not match.')
    mocker.patch('app.main.views.index.render_template', side_effect=csrf_err)

    response = client.get('/cookies')

    assert response.status_code == 302
    assert response.location == url_for('main.sign_in', next='/cookies', _external=True)
def test_csrf_redirects_to_sign_in_page_if_not_signed_in(client, mocker):
    csrf_err = CSRFError("400 Bad Request: The CSRF tokens do not match.")
    mocker.patch("app.main.views.index.render_template", side_effect=csrf_err)

    response = client.get("/accounts")

    assert response.status_code == 302
    assert response.location == url_for("main.sign_in",
                                        next="/accounts",
                                        _external=True)
Beispiel #5
0
def test_csrf_returns_400(logged_in_client, mocker):
    # we turn off CSRF handling for tests, so fake a CSRF response here.
    csrf_err = CSRFError('400 Bad Request: The CSRF tokens do not match.')
    mocker.patch('app.main.views.index.render_template', side_effect=csrf_err)

    response = logged_in_client.get('/cookies')

    assert response.status_code == 400
    page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
    assert page.h1.string.strip() == 'Something went wrong, please go back and try again.'
def test_csrf_returns_400(logged_in_client, mocker):
    # we turn off CSRF handling for tests, so fake a CSRF response here.
    csrf_err = CSRFError('400 Bad Request: The CSRF tokens do not match.')
    mocker.patch('app.main.views.index.render_template', side_effect=csrf_err)

    response = logged_in_client.get('/cookies')

    assert response.status_code == 400
    page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
    assert page.h1.string.strip(
    ) == 'Sorry, there’s a problem with GOV.UK Notify'
    assert page.title.string.strip(
    ) == 'Sorry, there’s a problem with the service – GOV.UK Notify'
Beispiel #7
0
def test_csrf_returns_400(client, mocker, sample_service):
    # we turn off CSRF handling for tests, so fake a CSRF response here.
    csrf_err = CSRFError('400 Bad Request: The CSRF tokens do not match.')
    mocker.patch('app.service_api_client.get_service',
                 return_value={'data': sample_service})
    mocker.patch('app.main.views.index.render_template', side_effect=csrf_err)
    mocker.patch('app.main.views.index.is_file_available', return_value=True)

    response = client.get(
        url_for('main.landing',
                service_id=uuid.uuid4(),
                document_id=uuid.uuid4(),
                key='1234'))

    assert response.status_code == 400
    page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
    assert page.h1.string.strip() == 'Page not found'
def test_csrf_handler_redirects_to_login(current_app, user_session, app,
                                         cookie_probe_expect_present):
    current_app.config = {
        "DM_COOKIE_PROBE_COOKIE_NAME": "foo",
        "DM_COOKIE_PROBE_COOKIE_VALUE": "bar",
        "DM_COOKIE_PROBE_EXPECT_PRESENT": cookie_probe_expect_present,
    }

    with app.test_request_context(
            '/',
            environ_base={
                "HTTP_COOKIE":
                dump_cookie(
                    current_app.config["DM_COOKIE_PROBE_COOKIE_NAME"],
                    current_app.config["DM_COOKIE_PROBE_COOKIE_VALUE"],
                ),
            }):
        app.config['WTF_CSRF_ENABLED'] = True
        app.register_blueprint(external_blueprint)

        if user_session:
            # Our user is logged in
            session['user_id'] = 1234

        response = csrf_handler(CSRFError())

        assert response.status_code == 302
        assert response.location == '/user/login?next=%2F'

        if user_session:
            assert current_app.logger.info.call_args_list == [
                mock.call(
                    'csrf.invalid_token: Aborting request, user_id: {user_id}',
                    extra={'user_id': 1234})
            ]
        else:
            assert current_app.logger.info.call_args_list == [
                mock.call(
                    'csrf.session_expired: Redirecting user to log in page')
            ]
Beispiel #9
0
    def it_returns_400_for_csrf_error(self, mocker, client, mock_admin_logged_in):
        csrf_err = CSRFError('400 Bad Request: The CSRF tokens do not match.')
        mocker.patch('app.main.views.admin.admin.render_template', side_effect=csrf_err)

        users = [
            {
                'access_area': 'admin'
            },
            {
                'id': 'test id',
                'email': '*****@*****.**',
                'access_area': 'email,event,'
            }
        ]

        mocker.patch('app.api_client.get_users', return_value=users)

        response = client.get(url_for('main.admin_users'))

        assert response.status_code == 400
        page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')
        message = page.select_one('p')

        assert message.text.strip() == 'Something went wrong, please go back and try again.'