Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manage CTFd configuration from ctfcli #155

Merged
merged 4 commits into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
Expand Down
5 changes: 5 additions & 0 deletions ctfcli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from ctfcli.cli.challenges import ChallengeCommand
from ctfcli.cli.config import ConfigCommand
from ctfcli.cli.instance import InstanceCommand
from ctfcli.cli.pages import PagesCommand
from ctfcli.cli.plugins import PluginsCommand
from ctfcli.cli.templates import TemplatesCommand
Expand Down Expand Up @@ -101,6 +102,9 @@ def init(
def config(self):
return COMMANDS.get("config")

def instance(self):
return COMMANDS.get("instance")

def challenge(self):
return COMMANDS.get("challenge")

Expand All @@ -120,6 +124,7 @@ def templates(self):
"pages": PagesCommand(),
"plugins": PluginsCommand(),
"templates": TemplatesCommand(),
"instance": InstanceCommand(),
"cli": CTFCLI(),
}

Expand Down
69 changes: 69 additions & 0 deletions ctfcli/cli/instance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import logging

import click

from ctfcli.core.config import Config
from ctfcli.core.instance.config import ServerConfig

log = logging.getLogger("ctfcli.cli.instance")


class ConfigCommand:
def get(self, key):
"""Get the value of a specific remote instance config key"""
log.debug(f"ConfigCommand.get: ({key=})")
return ServerConfig.get(key=key)

def set(self, key, value):
"""Set the value of a specific remote instance config key"""
log.debug(f"ConfigCommand.set: ({key=})")
ServerConfig.set(key=key, value=value)
click.secho(f"Successfully set '{key}' to '{value}'", fg="green")

def pull(self):
"""Copy remote instance configuration values to local config"""
log.debug("ConfigCommand.pull")
server_configs = ServerConfig.getall()

config = Config()
if config.config.has_section("instance") is False:
config.config.add_section("instance")

for k, v in server_configs.items():
# We always store as a string because the CTFd Configs model is a string
if v == "None":
v = "null"
config.config.set("instance", k, str(v))

with open(config.config_path, "w+") as f:
config.write(f)

click.secho("Successfully pulled configuration", fg="green")

def push(self):
"""Save local instance configuration values to remote CTFd instance"""
log.debug("ConfigCommand.push")
config = Config()
if config.config.has_section("instance") is False:
config.config.add_section("instance")

configs = {}
for k in config["instance"]:
v = config["instance"][k]
if v == "null":
v = None
configs[k] = v

failed_configs = ServerConfig.setall(configs=configs)
for f in failed_configs:
click.secho(f"Failed to push config {f}", fg="red")

if not failed_configs:
click.secho("Successfully pushed config", fg="green")
else:
return 1


class InstanceCommand:
def config(self):
return ConfigCommand
4 changes: 4 additions & 0 deletions ctfcli/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,7 @@ class InvalidPageConfiguration(PageException):

class IllegalPageOperation(PageException):
pass


class InstanceConfigException(Exception):
pass
Empty file.
65 changes: 65 additions & 0 deletions ctfcli/core/instance/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from typing import List

from ctfcli.core.api import API
from ctfcli.core.exceptions import InstanceConfigException


class ServerConfig:
@staticmethod
def get(key: str) -> str:
api = API()
resp = api.get(f"/api/v1/configs/{key}")
if resp.ok is False:
raise InstanceConfigException(
f"Could not get config {key=} because '{resp.content}' with {resp.status_code}"
)
resp = resp.json()
return resp["data"]["value"]

@staticmethod
def set(key: str, value: str) -> bool:
api = API()
data = {
"value": value,
}
resp = api.patch(f"/api/v1/configs/{key}", json=data)
if resp.ok is False:
raise InstanceConfigException(
f"Could not get config {key=} because '{resp.content}' with {resp.status_code}"
)
resp = resp.json()

return resp["success"]

@staticmethod
def getall():
api = API()
resp = api.get("/api/v1/configs")
if resp.ok is False:
raise InstanceConfigException(f"Could not get configs because '{resp.content}' with {resp.status_code}")
resp = resp.json()
configs = resp["data"]

config = {}
for c in configs:
# Ignore alembic_version configs as they are managed by plugins
if c["key"].endswith("alembic_version") is False:
config[c["key"]] = c["value"]

# Not much point in saving internal configs
del config["ctf_version"]
del config["version_latest"]
del config["next_update_check"]
del config["setup"]

return config

@staticmethod
def setall(configs) -> List[str]:
failed = []
for k, v in configs.items():
try:
ServerConfig.set(key=k, value=v)
except InstanceConfigException:
failed.append(k)
return failed
Loading