Fix/review findings #1

Merged
Matte23 merged 4 commits from fix/review-findings into main 2026-11-18 20:51:39 +00:00
7 changed files with 307 additions and 0 deletions
Showing only changes of commit e54d98498c - Show all commits

No files matched your search

+3
View File
@@ -174,3 +174,6 @@ cython_debug/
# PyPI configuration file # PyPI configuration file
.pypirc .pypirc
# written by CTFd's test app (make test)
.ctfd_secret_key
+25
View File
@@ -0,0 +1,25 @@
# Same lint tools and rules as CTFd 3.8.9 (see CTFd's Makefile and linting.txt).
# Setup: make venv (needs uv; Python 3.11 like CTFd's Docker image)
VENV ?= .venv/bin
CTFD_PATH ?= ../CTFd
PYTHON ?= 3.11
venv:
uv venv --python $(PYTHON) .venv
uv pip install --python .venv/bin/python -r $(CTFD_PATH)/requirements.txt -r dev-requirements.txt
lint:
$(VENV)/ruff check --select E,F,W,B,C4,I --ignore E402,E501,E712,B904,B905,I001 --exclude=.venv .
$(VENV)/isort --profile=black --check-only --skip=.venv .
$(VENV)/black --check --diff --exclude=.venv .
format:
$(VENV)/isort --profile=black --skip=.venv .
$(VENV)/black --exclude=.venv .
# Runs inside CTFd's own test app, with the plugin loaded from this
# checkout; CTFD_PATH must be a checkout of the CTFd version it targets.
test:
CTFD_PATH=$(CTFD_PATH) $(VENV)/pytest -c plugin_tests/pytest.ini plugin_tests
.PHONY: venv lint format test
+3
View File
@@ -0,0 +1,3 @@
-r linting.txt
# same version as CTFd 3.8.9 (development.txt)
pytest==8.4.2
+3
View File
@@ -0,0 +1,3 @@
black==26.10.1
isort==5.13.2
ruff==0.0.260
+77
View File
@@ -0,0 +1,77 @@
"""Test harness: CTFd's own test app with ctfd-cheaters loaded from this repo.
CTFd is imported from CTFD_PATH (default: ../CTFd). The test app runs in
CTFd's safe mode (no plugins loaded from CTFd/plugins), and this checkout is
loaded as CTFd.plugins.ctfd_cheaters, the name other plugins import.
"""
import importlib.util
import os
import sys
from pathlib import Path
import pytest
REPO = Path(__file__).resolve().parent.parent
CTFD_PATH = Path(os.environ.get("CTFD_PATH", REPO.parent / "CTFd")).resolve()
PLUGIN_MODULE = "CTFd.plugins.ctfd_cheaters"
if not (CTFD_PATH / "CTFd" / "__init__.py").exists():
raise RuntimeError(f"CTFd not found at {CTFD_PATH}: set CTFD_PATH")
sys.path.insert(0, str(CTFD_PATH))
import CTFd.plugins # noqa: E402,F401 (parent package of the plugin module)
from tests.helpers import create_ctfd, destroy_ctfd, setup_ctfd # noqa: E402
def _import_plugin():
"""Import the plugin (once). Like CTFd, only inside an app context."""
if PLUGIN_MODULE in sys.modules:
return sys.modules[PLUGIN_MODULE]
spec = importlib.util.spec_from_file_location(
PLUGIN_MODULE, REPO / "__init__.py", submodule_search_locations=[str(REPO)]
)
module = importlib.util.module_from_spec(spec)
sys.modules[PLUGIN_MODULE] = module
spec.loader.exec_module(module)
return module
def plugin(submodule=None):
return sys.modules[PLUGIN_MODULE + (f".{submodule}" if submodule else "")]
def _make_app(user_mode):
app = create_ctfd(setup=False, user_mode=user_mode)
with app.app_context():
_import_plugin().load(app)
return setup_ctfd(app, user_mode=user_mode)
@pytest.fixture
def app():
app = _make_app("users")
yield app
destroy_ctfd(app)
@pytest.fixture
def teams_app():
app = _make_app("teams")
yield app
destroy_ctfd(app)
def submit(client, challenge_id, submission, preview=False):
url = "/api/v1/challenges/attempt" + ("?preview=true" if preview else "")
r = client.post(url, json={"challenge_id": challenge_id, "submission": submission})
assert r.status_code == 200, r.get_json()
return r.get_json()["data"]["status"]
def reports(app):
with app.app_context():
return [
(r.cheater_id, r.owner_id, r.flag_id)
for r in plugin("models").CheatReport.query.all()
]
+13
View File
@@ -0,0 +1,13 @@
[pytest]
# This directory is the rootdir on purpose: the repo root is the plugin
# package itself (it has an __init__.py), which pytest would otherwise import
# as a test package before any CTFd app exists. The folder isn't called
# "tests" because CTFd's own tests package, whose helpers the suite uses,
# needs that name. Run with: make test
addopts = -p no:cacheprovider
filterwarnings =
ignore::DeprecationWarning
# CTFd's test client uses the "localhost" cookie domain
ignore:'localhost' is not a valid cookie domain:UserWarning
# CTFd's Flags model maps no subclasses: every flag type warns
ignore:Flushing object .* with incompatible polymorphic identity
+183
View File
@@ -0,0 +1,183 @@
from conftest import plugin, reports, submit
from CTFd.models import Flags, Users, db
from tests.helpers import (
gen_challenge,
gen_flag,
gen_team,
login_as_user,
register_user,
)
def _challenge_with_flags(app, *owners):
"""A challenge with one personal flag per owner id; returns (id, {owner: flag})."""
with app.app_context():
challenge = gen_challenge(db)
flags = {
owner: gen_flag(
db,
challenge.id,
content=f"flag{{{owner}}}",
type="personal",
data=str(owner),
).id
for owner in owners
}
return challenge.id, flags
def _users(app, *names):
for name in names:
register_user(app, name=name, email=f"{name}@examplectf.com")
with app.app_context():
return [Users.query.filter_by(name=name).one().id for name in names]
def test_own_flag_is_correct_and_not_reported(app):
alice, bob = _users(app, "alice", "bob")
challenge_id, _ = _challenge_with_flags(app, alice, bob)
with login_as_user(app, name="alice") as client:
assert submit(client, challenge_id, f"flag{{{alice}}}") == "correct"
assert reports(app) == []
def test_shared_flag_is_accepted_and_reported_once(app):
alice, bob = _users(app, "alice", "bob")
challenge_id, flags = _challenge_with_flags(app, alice, bob)
with login_as_user(app, name="alice") as client:
assert submit(client, challenge_id, "wrong") == "incorrect"
assert submit(client, challenge_id, f"flag{{{bob}}}") == "correct"
assert reports(app) == [(alice, bob, flags[bob])]
# reporting the same cheat again (e.g. "all" logic re-checks) adds nothing
with app.test_request_context(), login_as_user(app, name="alice"):
cheater = Users.query.get(alice)
owner = Users.query.get(bob)
plugin("flags").report_cheater(challenge_id, cheater, owner, flags[bob])
assert len(reports(app)) == 1
def test_admins_are_not_reported(app):
(alice,) = _users(app, "alice")
challenge_id, _ = _challenge_with_flags(app, alice)
with login_as_user(app, name="admin") as admin:
assert (
submit(admin, challenge_id, f"flag{{{alice}}}", preview=True) == "correct"
)
assert reports(app) == []
def test_invalid_owner_and_empty_flags(app):
(alice,) = _users(app, "alice")
with app.app_context():
challenge_id = gen_challenge(db).id
db.session.add(
Flags(challenge_id=challenge_id, type="personal", content="flag{x}")
)
db.session.add(
Flags(
challenge_id=challenge_id,
type="personal",
content="flag{y}",
data="bob",
)
)
db.session.add(Flags(challenge_id=challenge_id, type="personal", content=""))
db.session.commit()
with login_as_user(app, name="alice") as client:
# no crash for a flag without (or with an invalid) owner, and no report
assert submit(client, challenge_id, "flag{x}") == "correct"
with login_as_user(app, name="alice") as client:
assert submit(client, challenge_id, "") in ("incorrect", "already_solved")
assert reports(app) == []
def test_teams_mode_only_reports_other_teams(teams_app):
app = teams_app
with app.app_context():
red = gen_team(db, name="red", email="red@examplectf.com", member_count=2)
blue = gen_team(db, name="blue", email="blue@examplectf.com", member_count=1)
red_a, red_b = (m.id for m in red.members)
blue_a = blue.members[0].id
names = {u.id: u.name for u in Users.query.all()}
challenge_id, flags = _challenge_with_flags(app, red_a, red_b, blue_a)
with login_as_user(app, name=names[red_b]) as client:
# a teammate's flag: shared within the team, not a cheat
assert submit(client, challenge_id, f"flag{{{red_a}}}") == "correct"
assert reports(app) == []
second = _challenge_with_flags(app, red_a, blue_a)[0]
with login_as_user(app, name=names[blue_a]) as client:
assert submit(client, second, f"flag{{{red_a}}}") == "correct"
with app.app_context():
assert [
(r.cheater_id, r.owner_id) for r in plugin("models").CheatReport.query
] == [(blue_a, red_a)]
def test_create_flag_if_missing(app):
alice, bob = _users(app, "alice", "bob")
create = plugin().create_flag_if_missing
with app.app_context():
challenge_id = gen_challenge(db).id
# a non-personal flag with the same data is never picked up
gen_flag(db, challenge_id, content="static", data=str(alice))
first = create(challenge_id, alice, "flag{one}")
again = create(challenge_id, alice, "flag{two}")
other = create(challenge_id, bob, "flag{bob}")
assert first == again != other
flag = Flags.query.get(first)
assert (flag.type, flag.content, flag.data) == (
"personal",
"flag{one}",
str(alice),
)
def test_admin_flag_form_sets_the_owner(app):
(alice,) = _users(app, "alice")
with app.app_context():
challenge_id = gen_challenge(db).id
with login_as_user(app, name="admin") as admin:
# what the admin form posts (its fields: content, data, type)
r = admin.post(
"/api/v1/flags",
json={
"challenge": challenge_id,
"content": "flag{a}",
"data": str(alice),
"type": "personal",
},
)
assert r.status_code == 200, r.get_json()
assert r.get_json()["data"]["data"] == str(alice)
r = admin.get("/api/v1/flags/types/personal")
templates = r.get_json()["data"]["templates"]
assert templates["create"] == "/plugins/ctfd_cheaters/assets/create.html"
assert admin.get(templates["create"]).status_code == 200
def test_admin_page_and_dismiss(app):
alice, bob = _users(app, "alice", "bob")
challenge_id, _ = _challenge_with_flags(app, alice, bob)
with login_as_user(app, name="alice") as client:
assert submit(client, challenge_id, f"flag{{{bob}}}") == "correct"
[report_id] = _report_ids(app)
with login_as_user(app, name="admin") as admin:
page = admin.get("/admin/cheaters").get_data(as_text=True)
assert "alice" in page and "bob" in page and f"flag{{{bob}}}" in page
with admin.session_transaction() as sess:
nonce = sess["nonce"]
r = admin.post(f"/admin/cheaters/{report_id}/dismiss", data={"nonce": nonce})
assert r.status_code == 302
assert "No reports" in admin.get("/admin/cheaters").get_data(as_text=True)
assert reports(app) == []
def test_players_cannot_see_the_admin_page(app):
_users(app, "alice")
with login_as_user(app, name="alice") as client:
assert client.get("/admin/cheaters").status_code in (302, 403)
def _report_ids(app):
with app.app_context():
return [r.id for r in plugin("models").CheatReport.query.all()]