Exemplo n.º 1
0
def test_api_user_change_verify_email():
    """Test that users are marked unconfirmed if they change their email and verify_emails is turned on"""
    app = create_ctfd()
    with app.app_context():
        set_config("verify_emails", True)
        register_user(app)
        user = Users.query.filter_by(id=2).first()
        user.verified = True
        app.db.session.commit()
        with login_as_user(app) as client:
            r = client.patch(
                "/api/v1/users/me",
                json={"email": "*****@*****.**", "confirm": "password"},
            )
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["email"] == "*****@*****.**"
            assert resp["success"] is True
            user = Users.query.filter_by(id=2).first()
            assert user.verified is False
    destroy_ctfd(app)
Exemplo n.º 2
0
def test_submitting_correct_regex_case_insensitive_flag():
    """Test that correct regex flags are correct if the regex flag is marked case_insensitive"""
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        client = login_as_user(app)
        chal = gen_challenge(app.db)
        gen_flag(
            app.db,
            challenge_id=chal.id,
            type="regex",
            content="flag",
            data="case_insensitive",
        )
        data = {"submission": "FLAG", "challenge_id": chal.id}
        r = client.post("/api/v1/challenges/attempt", json=data)
        assert r.status_code == 200
        resp = r.get_json()["data"]
        assert resp.get("status") == "correct"
        assert resp.get("message") == "Correct"
    destroy_ctfd(app)
Exemplo n.º 3
0
def test_api_user_patch_admin():
    """Can a user patch /api/v1/users/<user_id> if admin"""
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        with login_as_user(app, "admin") as client:
            r = client.patch(
                "/api/v1/users/2",
                json={
                    "name": "user",
                    "email": "*****@*****.**",
                    "password": "******",
                    "country": "US",
                    "verified": True,
                },
            )
            assert r.status_code == 200
            user_data = r.get_json()["data"][0]
            assert user_data["country"] == "US"
            assert user_data["verified"] is True
    destroy_ctfd(app)
Exemplo n.º 4
0
def test_ratelimit_on_auth():
    """Test that ratelimiting function works properly"""
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        with app.test_client() as client:
            r = client.get('/login')
            with client.session_transaction() as sess:
                data = {
                    "name": "user",
                    "password": "******",
                    "nonce": sess.get('nonce')
                }
            for x in range(10):
                r = client.post('/login', data=data)
                assert r.status_code == 200

            for x in range(5):
                r = client.post('/login', data=data)
                assert r.status_code == 429
    destroy_ctfd(app)
Exemplo n.º 5
0
def test_submitting_invalid_regex_flag():
    """Test that invalid regex flags are errored out to the user"""
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        client = login_as_user(app)
        chal = gen_challenge(app.db)
        gen_flag(
            app.db,
            challenge_id=chal.id,
            type="regex",
            content="**",
            data="case_insensitive",
        )
        data = {"submission": "FLAG", "challenge_id": chal.id}
        r = client.post("/api/v1/challenges/attempt", json=data)
        assert r.status_code == 200
        resp = r.get_json()["data"]
        assert resp.get("status") == "incorrect"
        assert resp.get("message") == "Regex parse error occured"
    destroy_ctfd(app)
Exemplo n.º 6
0
def test_user_get_scoreboard_components():
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        client = login_as_user(app)

        # test_user_get_scoreboard
        """Can a registered user load scoreboard components"""
        r = client.get("/scoreboard")
        assert r.status_code == 200

        # test_user_get_scores
        """Can a registered user load /api/v1/scoreboard"""
        r = client.get("/api/v1/scoreboard")
        assert r.status_code == 200

        # test_user_get_topteams
        """Can a registered user load /api/v1/scoreboard/top/10"""
        r = client.get("/api/v1/scoreboard/top/10")
        assert r.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 7
0
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"))
Exemplo n.º 8
0
def test_api_team_get_solves_after_freze_time():
    """Can a user get /api/v1/teams/<team_id>/solves after freeze time"""
    app = create_ctfd(user_mode="teams")
    with app.app_context():
        register_user(app)
        team = gen_team(
            app.db, name="team1", email="*****@*****.**", member_count=1
        )

        team_member = team.members[0]
        tm_name = team_member.name

        set_config("freeze", "1507262400")
        with freeze_time("2017-10-4"):
            chal = gen_challenge(app.db)
            chal_id = chal.id
            gen_solve(app.db, user_id=3, team_id=1, challenge_id=chal_id)
            chal2 = gen_challenge(app.db)
            chal2_id = chal2.id

        with freeze_time("2017-10-8"):
            gen_solve(app.db, user_id=3, team_id=1, challenge_id=chal2_id)

            assert Solves.query.count() == 2

            with login_as_user(app) as client:
                r = client.get("/api/v1/teams/1/solves")
                data = r.get_json()["data"]
                assert len(data) == 1

            with login_as_user(app, name=tm_name) as client:
                r = client.get("/api/v1/teams/me/solves")
                data = r.get_json()["data"]
                assert len(data) == 2

            with login_as_user(app, name="admin") as client:
                r = client.get("/api/v1/teams/1/solves")
                data = r.get_json()["data"]
                assert len(data) == 2
    destroy_ctfd(app)
Exemplo n.º 9
0
def test_user_can_unlock_hint():
    """Test that a user can unlock a hint if they have enough points"""
    app = create_ctfd()
    with app.app_context():
        with app.test_client():
            register_user(app, name="user1", email="*****@*****.**")

            chal = gen_challenge(app.db, value=100)
            chal_id = chal.id

            gen_flag(app.db, challenge_id=chal.id, content='flag')

            hint = gen_hint(app.db, chal_id, cost=10)
            hint_id = hint.id

            gen_award(app.db, user_id=2, value=15)

            client = login_as_user(app, name="user1", password="******")

            user = Users.query.filter_by(name="user1").first()
            assert user.score == 15

            with client.session_transaction():
                r = client.get('/api/v1/hints/{}'.format(hint_id))
                resp = r.get_json()
                assert resp['data'].get('content') is None

                params = {"target": hint_id, "type": "hints"}

                r = client.post('/api/v1/unlocks', json=params)
                resp = r.get_json()
                assert resp['success'] is True

                r = client.get('/api/v1/hints/{}'.format(hint_id))
                resp = r.get_json()
                assert resp['data'].get('content') == "This is a hint"

                user = Users.query.filter_by(name="user1").first()
                assert user.score == 5
    destroy_ctfd(app)
Exemplo n.º 10
0
def test_unlocking_hints_with_cost_before_ctf():
    """Test that hints are not unlocked if the CTF hasn't begun"""
    app = create_ctfd()
    with app.app_context():
        register_user(app)
        chal = gen_challenge(app.db)
        chal_id = chal.id
        gen_hint(app.db, chal_id)
        gen_award(app.db, user_id=2)

        set_config('start', '1507089600'
                   )  # Wednesday, October 4, 2017 12:00:00 AM GMT-04:00 DST
        set_config(
            'end',
            '1507262400')  # Friday, October 6, 2017 12:00:00 AM GMT-04:00 DST

        with freeze_time("2017-10-1"):
            client = login_as_user(app)

            r = client.get('/api/v1/hints/1')
            assert r.status_code == 403
            assert r.get_json().get('data') is None

            r = client.post('/api/v1/unlocks',
                            json={
                                'target': 1,
                                'type': 'hints'
                            })
            assert r.status_code == 403
            assert r.get_json().get('data') is None

            r = client.get('/api/v1/hints/1')
            assert r.get_json().get('data') is None
            assert r.status_code == 403

            user = Users.query.filter_by(id=2).first()

            assert user.score == 100
            assert Unlocks.query.count() == 0
    destroy_ctfd(app)
Exemplo n.º 11
0
def test_boolean_checkbox_field():
    app = create_ctfd()
    with app.app_context():
        gen_field(app.db, name="CustomField1", field_type="boolean", required=False)

        with app.test_client() as client:
            r = client.get("/register")
            resp = r.get_data(as_text=True)

            # We should have rendered a checkbox input
            assert "checkbox" in resp

            with client.session_transaction() as sess:
                data = {
                    "name": "user",
                    "email": "*****@*****.**",
                    "password": "******",
                    "nonce": sess.get("nonce"),
                    "fields[1]": "y",
                }
            client.post("/register", data=data)
            with client.session_transaction() as sess:
                assert sess["id"]

        assert UserFieldEntries.query.count() == 1
        assert UserFieldEntries.query.filter_by(id=1).first().value is True

        with login_as_user(app) as client:
            r = client.get("/settings")
            resp = r.get_data(as_text=True)
            assert "CustomField1" in resp
            assert "checkbox" in resp

            r = client.patch(
                "/api/v1/users/me", json={"fields": [{"field_id": 1, "value": False}]}
            )
            assert r.status_code == 200
            assert UserFieldEntries.query.count() == 1
            assert UserFieldEntries.query.filter_by(id=1).first().value is False
    destroy_ctfd(app)
Exemplo n.º 12
0
def test_sendmail_with_mailgun_from_config_file(fake_post_request):
    """Does sendmail work properly with Mailgun using file configuration"""
    app = create_ctfd()
    with app.app_context():
        app.config["MAILGUN_API_KEY"] = "key-1234567890-file-config"
        app.config["MAILGUN_BASE_URL"] = "https://api.mailgun.net/v3/file.faked.com"

        from_addr = get_config("mailfrom_addr") or app.config.get("MAILFROM_ADDR")
        to_addr = "*****@*****.**"
        msg = "this is a test"

        sendmail(to_addr, msg)

        ctf_name = get_config("ctf_name")
        email_msg = MIMEText(msg)
        email_msg["Subject"] = "Message from {0}".format(ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        fake_response = Mock()
        fake_post_request.return_value = fake_response
        fake_response.status_code = 200

        status, message = sendmail(to_addr, msg)

        args, kwargs = fake_post_request.call_args
        assert args[0] == "https://api.mailgun.net/v3/file.faked.com/messages"
        assert kwargs["auth"] == ("api", u"key-1234567890-file-config")
        assert kwargs["timeout"] == 1.0
        assert kwargs["data"] == {
            "to": ["*****@*****.**"],
            "text": "this is a test",
            "from": "CTFd Admin <*****@*****.**>",
            "subject": "Message from CTFd",
        }

        assert fake_response.status_code == 200
        assert status is True
        assert message == "Email sent"
    destroy_ctfd(app)
Exemplo n.º 13
0
def test_invalid_requirements_are_rejected():
    """Test that invalid requirements JSON blobs are rejected by the API"""
    app = create_ctfd()
    with app.app_context():
        gen_challenge(app.db)
        gen_challenge(app.db)
        with login_as_user(app, "admin") as client:
            # Test None/null values
            r = client.patch("/api/v1/challenges/1",
                             json={"requirements": {
                                 "prerequisites": [None]
                             }})
            assert r.status_code == 400
            assert r.get_json() == {
                "success": False,
                "errors": {
                    "requirements":
                    ["Challenge requirements cannot have a null prerequisite"]
                },
            }
            # Test empty strings
            r = client.patch("/api/v1/challenges/1",
                             json={"requirements": {
                                 "prerequisites": [""]
                             }})
            assert r.status_code == 400
            assert r.get_json() == {
                "success": False,
                "errors": {
                    "requirements":
                    ["Challenge requirements cannot have a null prerequisite"]
                },
            }
            # Test a valid integer
            r = client.patch("/api/v1/challenges/1",
                             json={"requirements": {
                                 "prerequisites": [2]
                             }})
            assert r.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 14
0
def test_successful_registration_email(mock_smtp):
    """Does successful_registration_notification send emails"""
    app = create_ctfd()
    with app.app_context():
        set_config("mail_server", "localhost")
        set_config("mail_port", 25)
        set_config("mail_useauth", True)
        set_config("mail_username", "username")
        set_config("mail_password", "password")
        set_config("verify_emails", True)

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"

        successful_registration_notification(to_addr)

        msg = "You've successfully registered for CTFd!"

        if six.PY2:
            email_msg = MIMEText(msg)
        else:
            email_msg = EmailMessage()
            email_msg.set_content(msg)
        email_msg["Subject"] = "Successfully registered for {ctf_name}".format(
            ctf_name=ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        if six.PY2:
            mock_smtp.return_value.sendmail.assert_called_with(
                from_addr, [to_addr], email_msg.as_string())
        else:
            mock_smtp.return_value.send_message.assert_called()
            assert str(mock_smtp.return_value.send_message.call_args[0]
                       [0]) == str(email_msg)
    destroy_ctfd(app)
def test_verify_email(mock_smtp):
    """Does verify_email send emails"""
    app = create_ctfd()
    with app.app_context():
        set_config("mail_server", "localhost")
        set_config("mail_port", 25)
        set_config("mail_useauth", True)
        set_config("mail_username", "username")
        set_config("mail_password", "password")
        set_config("verify_emails", True)

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"

        with freeze_time("2012-01-14 03:21:34"):
            verify_email_address(to_addr)

        # This is currently not actually validated
        msg = (
            "Please click the following link to confirm"
            " your email address for CTFd:"
            " http://localhost/confirm/InVzZXJAdXNlci5jb20i.TxD0vg.28dY_Gzqb1TH9nrcE_H7W8YFM-U"
        )

        ctf_name = get_config("ctf_name")
        email_msg = EmailMessage()
        email_msg.set_content(msg)
        email_msg["Subject"] = "Confirm your account for {ctf_name}".format(
            ctf_name=ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        mock_smtp.return_value.send_message.assert_called()
        assert str(mock_smtp.return_value.send_message.call_args[0][0]) == str(
            email_msg)
    destroy_ctfd(app)
Exemplo n.º 16
0
def test_verify_email(mock_smtp):
    """Does verify_email send emails"""
    app = create_ctfd()
    with app.app_context():
        set_config("mail_server", "localhost")
        set_config("mail_port", 25)
        set_config("mail_useauth", True)
        set_config("mail_username", "username")
        set_config("mail_password", "password")
        set_config("verify_emails", True)

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"

        with freeze_time("2012-01-14 03:21:34"):
            verify_email_address(to_addr)

        # This is currently not actually validated
        msg = (
            "Please click the following link to confirm"
            " your email address for CTFd:"
            " http://localhost/confirm/InVzZXJAdXNlci5jb20i.TxD0vg.28dY_Gzqb1TH9nrcE_H7W8YFM-U"
        )

        ctf_name = get_config("ctf_name")
        email_msg = MIMEText(msg)
        email_msg["Subject"] = "Confirm your account for {ctf_name}".format(
            ctf_name=ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        # Need to freeze time to predict the value of the itsdangerous token.
        # For now just assert that sendmail was called.
        mock_smtp.return_value.sendmail.assert_called_with(
            from_addr, [to_addr], email_msg.as_string())
    destroy_ctfd(app)
Exemplo n.º 17
0
def test_api_users_post_admin():
    """Can a user post /api/v1/users if admin"""
    app = create_ctfd()
    with app.app_context():
        with login_as_user(app, "admin") as client:
            # Create user
            r = client.post(
                "/api/v1/users",
                json={"name": "user", "email": "*****@*****.**", "password": "******"},
            )
            assert r.status_code == 200

            # Make sure password was hashed properly
            user = Users.query.filter_by(email="*****@*****.**").first()
            assert user
            assert verify_password("password", user.password)

            # Make sure user can login with the creds
            client = login_as_user(app)
            r = client.get("/profile")
            assert r.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 18
0
def test_api_accessing_banned_users():
    """Banned users should not be visible to normal users, only to admins"""
    app = create_ctfd()
    with app.app_context():
        register_user(app, name="visible_user", email="*****@*****.**")
        register_user(app, name="banned_user", email="*****@*****.**")  # ID 3
        user = Users.query.filter_by(name="banned_user").first()
        user.banned = True
        app.db.session.commit()

        with login_as_user(app, name="visible_user") as client:
            assert client.get("/api/v1/users/3").status_code == 404
            assert client.get("/api/v1/users/3/solves").status_code == 404
            assert client.get("/api/v1/users/3/fails").status_code == 404
            assert client.get("/api/v1/users/3/awards").status_code == 404

        with login_as_user(app, name="admin") as client:
            assert client.get("/api/v1/users/3").status_code == 200
            assert client.get("/api/v1/users/3/solves").status_code == 200
            assert client.get("/api/v1/users/3/fails").status_code == 200
            assert client.get("/api/v1/users/3/awards").status_code == 200
    destroy_ctfd(app)
Exemplo n.º 19
0
def test_api_admin_user_patch_me_logged_in():
    """Can an admin patch /api/v1/users/me"""
    app = create_ctfd()
    with app.app_context():
        with login_as_user(app, name="admin") as client:
            r = client.patch(
                "/api/v1/users/me",
                json={
                    "name": "user",
                    "email": "*****@*****.**",
                    "password": "******",
                    "confirm": "password",
                    "country": "US",
                },
            )
            assert r.status_code == 200
            assert r.get_json()["data"]["country"] == "US"

            user = Users.query.filter_by(id=1).first()
            assert user.name == "user"
            assert user.email == "*****@*****.**"
    destroy_ctfd(app)
Exemplo n.º 20
0
def test_teams_join_post():
    """Can a user post /teams/join"""
    app = create_ctfd(user_mode="teams")
    with app.app_context():
        gen_user(app.db, name="user")
        gen_team(app.db, name="team")
        with login_as_user(app) as client:
            r = client.get("/teams/join")
            assert r.status_code == 200
            with client.session_transaction() as sess:
                data = {
                    "name": "team",
                    "password": "******",
                    "nonce": sess.get("nonce"),
                }
            r = client.post("/teams/join", data=data)
            assert r.status_code == 302
            incorrect_data = data
            incorrect_data["password"] = ""
            r = client.post("/teams/join", data=incorrect_data)
            assert r.status_code == 200
    destroy_ctfd(app)
def test_sendmail_with_mailgun_from_db_config(fake_post_request):
    """Does sendmail work properly with Mailgun using database configuration"""
    app = create_ctfd()
    with app.app_context():
        app.config["MAILGUN_API_KEY"] = "key-1234567890-file-config"
        app.config[
            "MAILGUN_BASE_URL"] = "https://api.mailgun.net/v3/file.faked.com"

        # db values should take precedence over file values
        set_config("mailgun_api_key", "key-1234567890-db-config")
        set_config("mailgun_base_url",
                   "https://api.mailgun.net/v3/db.faked.com")

        to_addr = "*****@*****.**"
        msg = "this is a test"

        sendmail(to_addr, msg)

        fake_response = Mock()
        fake_post_request.return_value = fake_response
        fake_response.status_code = 200

        status, message = sendmail(to_addr, msg)

        args, kwargs = fake_post_request.call_args
        assert args[0] == "https://api.mailgun.net/v3/db.faked.com/messages"
        assert kwargs["auth"] == ("api", u"key-1234567890-db-config")
        assert kwargs["timeout"] == 1.0
        assert kwargs["data"] == {
            "to": ["*****@*****.**"],
            "text": "this is a test",
            "from": "CTFd <*****@*****.**>",
            "subject": "Message from CTFd",
        }

        assert fake_response.status_code == 200
        assert status is True
        assert message == "Email sent"
    destroy_ctfd(app)
Exemplo n.º 22
0
def test_team_fields_required_on_creation():
    app = create_ctfd(user_mode="teams")
    with app.app_context():
        register_user(app)
        gen_field(app.db, type="team")

        with app.app_context():
            with login_as_user(app) as client:
                assert Teams.query.count() == 0
                r = client.get("/teams/new")
                resp = r.get_data(as_text=True)
                assert "CustomField" in resp
                assert "CustomFieldDescription" in resp

                with client.session_transaction() as sess:
                    data = {
                        "name": "team",
                        "password": "******",
                        "nonce": sess.get("nonce"),
                    }
                r = client.post("/teams/new", data=data)
                assert "Please provide all required fields" in r.get_data(as_text=True)
                assert Teams.query.count() == 0

                with client.session_transaction() as sess:
                    data = {
                        "name": "team",
                        "password": "******",
                        "fields[1]": "CustomFieldEntry",
                        "nonce": sess.get("nonce"),
                    }
                r = client.post("/teams/new", data=data)
                assert r.status_code == 302
                assert Teams.query.count() == 1

                entry = TeamFieldEntries.query.filter_by(id=1).first()
                assert entry.team_id == 1
                assert entry.value == "CustomFieldEntry"
    destroy_ctfd(app)
Exemplo n.º 23
0
def test_api_tag_list_get():
    """Can a user get /api/v1/tokens"""
    app = create_ctfd()
    with app.app_context():
        user = gen_user(app.db, name="user")
        generate_user_token(user)

        user2 = gen_user(app.db, name="user2", email="*****@*****.**")
        generate_user_token(user2)
        generate_user_token(user2)
        with login_as_user(app) as client:
            r = client.get("/api/v1/tokens", json="")
            assert r.status_code == 200
            resp = r.get_json()
            len(resp["data"]) == 1

        with login_as_user(app, name="user2") as client:
            r = client.get("/api/v1/tokens", json="")
            assert r.status_code == 200
            resp = r.get_json()
            len(resp["data"]) == 2
    destroy_ctfd(app)
Exemplo n.º 24
0
def test_s3_uploader():
    conn = boto3.resource("s3", region_name="us-east-1")
    conn.create_bucket(Bucket="bucket")

    app = create_ctfd()
    with app.app_context():
        app.config["UPLOAD_PROVIDER"] = "s3"
        app.config["AWS_ACCESS_KEY_ID"] = "AKIAIOSFODNN7EXAMPLE"
        app.config[
            "AWS_SECRET_ACCESS_KEY"] = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        app.config["AWS_S3_BUCKET"] = "bucket"

        uploader = S3Uploader()

        assert uploader.s3
        assert uploader.bucket == "bucket"

        fake_file = BytesIO("fakedfile".encode())
        path = uploader.upload(fake_file, "fake_file.txt")

        assert "fake_file.txt" in uploader.download(path).location
    destroy_ctfd(app)
Exemplo n.º 25
0
def test_sendmail_with_smtp_from_config_file(mock_smtp):
    """Does sendmail work properly with simple SMTP mail servers using file configuration"""
    app = create_ctfd()
    with app.app_context():
        app.config["MAIL_SERVER"] = "localhost"
        app.config["MAIL_PORT"] = "25"
        app.config["MAIL_USEAUTH"] = "True"
        app.config["MAIL_USERNAME"] = "******"
        app.config["MAIL_PASSWORD"] = "******"

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"
        msg = "this is a test"

        sendmail(to_addr, msg)

        ctf_name = get_config("ctf_name")
        if six.PY2:
            email_msg = MIMEText(msg)
        else:
            email_msg = EmailMessage()
            email_msg.set_content(msg)

        email_msg["Subject"] = "Message from {0}".format(ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        if six.PY2:
            mock_smtp.return_value.sendmail.assert_called_with(
                from_addr, [to_addr], email_msg.as_string())
        else:
            mock_smtp.return_value.send_message.assert_called()
            assert str(mock_smtp.return_value.send_message.call_args[0]
                       [0]) == str(email_msg)
    destroy_ctfd(app)
Exemplo n.º 26
0
def test_api_hint_admin_access():
    """Can the users patch/delete /api/v1/hint/<hint_id> if not admin"""
    app = create_ctfd()
    with app.app_context():
        chal = gen_challenge(app.db)
        gen_hint(app.db,
                 chal.id,
                 content="This is a hint",
                 cost=1,
                 type="standard")
        admin = login_as_user(app, "admin")
        register_user(app)
        client = login_as_user(app)
        r = client.patch("/api/v1/hints/1", json="")
        assert r.status_code == 403
        r = client.delete("/api/v1/hints/1", json="")
        assert r.status_code == 403
        r_admin = admin.patch("/api/v1/hints/1", json={"cost": 2})
        assert r_admin.status_code == 200
        r_admin = admin.delete("/api/v1/hints/1", json="")
        assert r_admin.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 27
0
def test_api_team_disbanding_disabled():
    """Test that team disbanding can be disabled"""
    app = create_ctfd(user_mode="teams")
    with app.app_context():
        set_config("team_disbanding", "disabled")
        team = gen_team(app.db)
        captain = Users.query.filter_by(id=team.captain_id).first()
        app.db.session.commit()
        with login_as_user(app, name=captain.name) as client:
            r = client.delete("/api/v1/teams/me", json="")
            assert r.status_code == 403
            assert r.get_json() == {
                "success": False,
                "errors": {
                    "": ["Team disbanding is currently disabled"]
                },
            }
        set_config("team_disbanding", "inactive_only")
        with login_as_user(app, name=captain.name) as client:
            r = client.delete("/api/v1/teams/me", json="")
            assert r.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 28
0
def test_api_page_patch_admin():
    """Can a user patch /api/v1/pages/<page_id> if admin"""
    app = create_ctfd()
    with app.app_context():
        gen_page(app.db, title="title", route="/route", content="content")
        with login_as_user(app, "admin") as client:
            with client.session_transaction() as sess:
                nonce = sess.get("nonce")
            r = client.patch(
                "/api/v1/pages/2",
                json={
                    "title": "Title",
                    "route": "/route",
                    "content": "content_edit",
                    "id": "2",
                    "nonce": nonce,
                    "auth_required": False,
                },
            )
            assert r.status_code == 200
            assert r.get_json()["data"]["content"] == "content_edit"
    destroy_ctfd(app)
Exemplo n.º 29
0
def test_page_requiring_auth():
    """Test that pages properly require authentication"""
    app = create_ctfd()
    with app.app_context():
        gen_page(
            app.db,
            title="Title",
            route="this-is-a-route",
            content="This is some HTML",
            auth_required=True,
        )

        with app.test_client() as client:
            r = client.get("/this-is-a-route")
            assert r.status_code == 302
            assert r.location == "http://localhost/login?next=%2Fthis-is-a-route%3F"

        register_user(app)
        client = login_as_user(app)
        r = client.get("/this-is-a-route")
        assert r.status_code == 200
    destroy_ctfd(app)
Exemplo n.º 30
0
def test_register_user_page_menu_bar():
    """
    Test that the register_user_page_menu_bar() properly inserts into HTML and get_user_page_menu_bar() returns the
    proper list.
    """
    app = create_ctfd()
    with app.app_context():
        register_user_page_menu_bar(
            title="test_user_menu_link", route="/test_user_href"
        )

        with app.test_client() as client:
            r = client.get("/")

        output = r.get_data(as_text=True)
        assert "/test_user_href" in output
        assert "test_user_menu_link" in output

        menu_item = get_user_page_menu_bar()[0]
        assert menu_item.title == "test_user_menu_link"
        assert menu_item.route == "/test_user_href"
    destroy_ctfd(app)