Files
CTFd/tests/test_themes.py
Kevin Chung 8de9819bd4 3.3.0 (#1833)
# 3.3.0 / UNRELEASED

**General**

- Don't require a team for viewing challenges if Challenge visibility is set to public
- Add a `THEME_FALLBACK` config to help develop themes. See **Themes** section for details.

**API**

- Implement a faster `/api/v1/scoreboard` endpoint in Teams Mode
- Add the `solves` item to both `/api/v1/challenges` and `/api/v1/challenges/[challenge_id]` to more easily determine how many solves a challenge has
- Add the `solved_by_me` item to both `/api/v1/challenges` and `/api/v1/challenges/[challenge_id]` to more easily determine if the current account has solved the challenge
- Prevent admins from deleting themselves through `DELETE /api/v1/users/[user_id]`
- Add length checking to some sensitive fields in the Pages and Challenges schemas
- Fix issue where `PATCH /api/v1/users[user_id]` returned a list instead of a dict
- Fix exception that occured on demoting admins through `PATCH /api/v1/users[user_id]`
- Add `team_id` to `GET /api/v1/users` to determine if a user is already in a team

**Themes**

- Add a `THEME_FALLBACK` config to help develop themes.
  - `THEME_FALLBACK` will configure CTFd to try to find missing theme files in the default built-in `core` theme.
  - This makes it easier to develop themes or use incomplete themes.
- Allow for one theme to reference and inherit from another theme through approaches like `{% extends "core/page.html" %}`
- Allow for the automatic date rendering format to be overridden by specifying a `data-time-format` attribute.
- Add styling for the `<blockquote>` element.
- Fix scoreboard table identifier to switch between User/Team depending on configured user mode
- Switch to using Bootstrap's scss in `core/main.scss` to allow using Bootstrap variables
- Consolidate Jinja error handlers into a single function and better handle issues where error templates can't be found

**Plugins**

- Set plugin migration version after successful migrations
- Fix issue where Page URLs injected into the navbar were relative instead of absolute

**Admin Panel**

- Add User standings as well as Teams standings to the admin scoreboard when in Teams Mode
- Add a UI for adding members to a team from the team's admin page
- Add ability for admins to disable public team creation
- Link directly to users who submitted something in the submissions page if the CTF is in Teams Mode
- Fix Challenge Requirements interface in Admin Panel to not allow empty/null requirements to be added
- Fixed an issue where config times (start, end, freeze times) could not be removed
- Fix an exception that occurred when demoting an Admin user
- Adds a temporary hack for re-enabling Javascript snippets in Flag editor templates. (See #1779)

**Deployment**

- Install `python3-dev` instead of `python-dev` in apt
- Bump lxml to 4.6.2
- Bump pip-compile to 5.4.0

**Miscellaneous**

- Cache Docker builds more by copying and installing Python dependencies before copying CTFd
- Change the default emails slightly and rework confirmation email page to make some recommendations clearer
- Use `examplectf.com` as testing/development domain instead of `ctfd.io`
- Fixes issue where user's name and email would not appear in logs properly
- Add more linting by also linting with `flake8-comprehensions` and `flake8-bugbear`
2021-03-18 18:08:46 -04:00

224 lines
7.9 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import pytest
from flask import render_template, render_template_string, request
from jinja2.exceptions import TemplateNotFound
from jinja2.sandbox import SecurityError
from werkzeug.test import Client
from CTFd.config import TestingConfig
from CTFd.utils import get_config, set_config
from tests.helpers import create_ctfd, destroy_ctfd, gen_user, login_as_user
def test_themes_run_in_sandbox():
"""Does get_config and set_config work properly"""
app = create_ctfd()
with app.app_context():
try:
app.jinja_env.from_string(
"{{ ().__class__.__bases__[0].__subclasses__()[40]('./test_utils.py').read() }}"
).render()
except SecurityError:
pass
except Exception as e:
raise e
destroy_ctfd(app)
def test_themes_cant_access_configpy_attributes():
"""Themes should not be able to access config.py attributes"""
app = create_ctfd()
with app.app_context():
assert app.config["SECRET_KEY"] == "AAAAAAAAAAAAAAAAAAAA"
assert (
app.jinja_env.from_string("{{ get_config('SECRET_KEY') }}").render()
!= app.config["SECRET_KEY"]
)
destroy_ctfd(app)
def test_themes_escape_html():
"""Themes should escape XSS properly"""
app = create_ctfd()
with app.app_context():
user = gen_user(app.db, name="<script>alert(1)</script>")
user.affiliation = "<script>alert(1)</script>"
user.website = "<script>alert(1)</script>"
user.country = "<script>alert(1)</script>"
with app.test_client() as client:
r = client.get("/users")
assert r.status_code == 200
assert "<script>alert(1)</script>" not in r.get_data(as_text=True)
destroy_ctfd(app)
def test_theme_header():
"""Config should be able to properly set CSS in theme header"""
app = create_ctfd()
with app.app_context():
with login_as_user(app, "admin") as admin:
css_value = """.test{}"""
css_value2 = """.test2{}"""
r = admin.patch("/api/v1/configs", json={"theme_header": css_value})
assert r.status_code == 200
assert get_config("theme_header") == css_value
r = admin.get("/")
assert css_value in r.get_data(as_text=True)
r = admin.patch("/api/v1/configs", json={"theme_header": css_value2})
r = admin.get("/")
assert css_value2 in r.get_data(as_text=True)
destroy_ctfd(app)
def test_that_ctfd_can_be_deployed_in_subdir():
"""Test that CTFd can be deployed in a subdirectory"""
# This test is quite complicated. I do not suggest modifying it haphazardly.
# Flask is automatically inserting the APPLICATION_ROOT into the
# test urls which means when we hit /setup we hit /ctf/setup.
# You can use the raw Werkzeug client to bypass this as we do below.
app = create_ctfd(setup=False, application_root="/ctf")
with app.app_context():
with app.test_client() as client:
r = client.get("/")
assert r.status_code == 302
assert r.location == "http://localhost/ctf/setup"
r = client.get("/setup")
with client.session_transaction() as sess:
data = {
"ctf_name": "CTFd",
"ctf_description": "CTF description",
"name": "admin",
"email": "admin@examplectf.com",
"password": "password",
"user_mode": "users",
"nonce": sess.get("nonce"),
}
r = client.post("/setup", data=data)
assert r.status_code == 302
assert r.location == "http://localhost/ctf/"
c = Client(app)
app_iter, status, headers = c.get("/")
headers = dict(headers)
assert status == "302 FOUND"
assert headers["Location"] == "http://localhost/ctf/"
r = client.get("/challenges")
assert r.status_code == 200
assert "Challenges" in r.get_data(as_text=True)
r = client.get("/scoreboard")
assert r.status_code == 200
assert "Scoreboard" in r.get_data(as_text=True)
destroy_ctfd(app)
def test_that_request_path_hijacking_works_properly():
"""Test that the CTFdRequest subclass correctly mimics the Flask Request when it should"""
app = create_ctfd(setup=False, application_root="/ctf")
assert app.request_class.__name__ == "CTFdRequest"
with app.app_context():
# Despite loading /challenges request.path should actually be /ctf/challenges because we are
# preprending script_root and the test context already accounts for the application_root
with app.test_request_context("/challenges"):
assert request.path == "/ctf/challenges"
destroy_ctfd(app)
app = create_ctfd()
assert app.request_class.__name__ == "CTFdRequest"
with app.app_context():
# Under normal circumstances we should be an exact clone of BaseRequest
with app.test_request_context("/challenges"):
assert request.path == "/challenges"
from flask import Flask
test_app = Flask("test")
assert test_app.request_class.__name__ == "Request"
with test_app.test_request_context("/challenges"):
assert request.path == "/challenges"
destroy_ctfd(app)
def test_theme_fallback_config():
"""Test that the `THEME_FALLBACK` config properly falls themes back to the core theme"""
app = create_ctfd()
# Make an empty theme
try:
os.mkdir(os.path.join(app.root_path, "themes", "foo"))
except OSError:
pass
# Without theme fallback, missing themes should disappear
with app.app_context():
set_config("ctf_theme", "foo")
assert app.config["THEME_FALLBACK"] == False
with app.test_client() as client:
try:
r = client.get("/")
except TemplateNotFound:
pass
try:
r = client.get("/themes/foo/static/js/pages/main.dev.js")
except TemplateNotFound:
pass
destroy_ctfd(app)
class ThemeFallbackConfig(TestingConfig):
THEME_FALLBACK = True
app = create_ctfd(config=ThemeFallbackConfig)
with app.app_context():
set_config("ctf_theme", "foo")
assert app.config["THEME_FALLBACK"] == True
with app.test_client() as client:
r = client.get("/")
assert r.status_code == 200
r = client.get("/themes/foo/static/js/pages/main.dev.js")
assert r.status_code == 200
destroy_ctfd(app)
# Remove empty theme
os.rmdir(os.path.join(app.root_path, "themes", "foo"))
def test_theme_template_loading_by_prefix():
"""Test that we can load theme files by their folder prefix"""
app = create_ctfd()
with app.test_request_context():
tpl1 = render_template_string("{% extends 'core/page.html' %}", content="test")
tpl2 = render_template("page.html", content="test")
assert tpl1 == tpl2
def test_theme_template_disallow_loading_admin_templates():
"""Test that admin files in a theme will not be loaded"""
app = create_ctfd()
with app.app_context():
try:
# Make an empty malicious theme
filename = os.path.join(
app.root_path, "themes", "foo", "admin", "malicious.html"
)
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("malicious")
with pytest.raises(TemplateNotFound):
render_template_string("{% include 'admin/malicious.html' %}")
finally:
# Remove empty theme
shutil.rmtree(
os.path.join(app.root_path, "themes", "foo"), ignore_errors=True
)