pyquocca 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ FROM ghcr.io/astral-sh/uv:python3.12-alpine
2
+
3
+ WORKDIR /app
4
+ COPY . .
5
+
6
+ RUN uv sync --all-extras
7
+
8
+ ENTRYPOINT []
9
+ # CMD sleep 5 && .venv/bin/python3 src/test_app/main.py
10
+ CMD sleep 5 && .venv/bin/gunicorn -c python:pyquocca.gunicorn test_app.main:app
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquocca
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Challenge utilities for SecEDU CTFs (primarily UNSW's COMP6[48]43).
5
5
  Author-email: Hamish Cox <hamish.cox@unsw.edu.au>
6
6
  Maintainer-email: Hamish Cox <hamish.cox@unsw.edu.au>
@@ -4,7 +4,7 @@ services:
4
4
  volumes:
5
5
  - ./src:/app/src
6
6
  ports:
7
- - "8000:5000"
7
+ - "8000:8000"
8
8
  environment:
9
9
  - POSTGRES_HOST=pgsql
10
10
  - POSTGRES_USER=user
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyquocca"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "Challenge utilities for SecEDU CTFs (primarily UNSW's COMP6[48]43)."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.9"
@@ -0,0 +1,7 @@
1
+ import re
2
+
3
+ _NAME_TO_ENV = re.compile(r"[^A-Z0-9_]")
4
+
5
+
6
+ def to_env_var(s: str):
7
+ return _NAME_TO_ENV.sub("", s.upper().replace("-", "_"))
@@ -54,6 +54,11 @@ def get_flag(key: str, username: Optional[str] = None) -> str:
54
54
  },
55
55
  )
56
56
  if r.status_code == 200:
57
+ logger = logging.getLogger("pyquocca.flags")
58
+ logger.info(
59
+ "Generated flag `%(flag)s` for user `%(username)s`",
60
+ {"flag": key, "username": username},
61
+ )
57
62
  return r.json().get("flag")
58
63
  else:
59
64
  raise FlaganizerException(r.json().get("msg"))
@@ -17,37 +17,43 @@ if reload and os.getenv("PYQUOCCA_RELOAD_GLOBS", "") != "":
17
17
  reload_extra_files.extend(glob(g, recursive=True))
18
18
 
19
19
 
20
- class GunicornJsonAccessLogger(JsonFormatter):
20
+ class JsonArgsFormatter(JsonFormatter):
21
+ def __init__(self, *args, require_rename: bool = False, **kwargs):
22
+ self.require_rename = require_rename
23
+ super().__init__(*args, **kwargs)
24
+
21
25
  def add_fields(self, log_record, record, message_dict):
22
- super(GunicornJsonAccessLogger, self).add_fields(
23
- log_record, record, message_dict
24
- )
26
+ super().add_fields(log_record, record, message_dict)
25
27
 
26
28
  if isinstance(record.args, dict):
27
29
  for key, value in record.args.items():
28
30
  if (
29
31
  key not in self.reserved_attrs
30
32
  and not (hasattr(key, "startswith") and key.startswith("_"))
31
- and key in self.rename_fields
33
+ and (not self.require_rename or key in self.rename_fields)
32
34
  ):
33
- log_record[self.rename_fields[key]] = value
35
+ log_record[self.rename_fields.get(key, key)] = value
34
36
 
35
37
 
36
38
  def make_access_formatter():
37
39
  try:
38
- return GunicornJsonAccessLogger(
39
- fmt="%(M)s %(t)s %(r)s %(s)s %(p)s %(a)s %({host}i)s %({x-mtls-full-name}i)s %({x-forwarded-for}i)s %({x-mtls-username}i)s %({x-mtls-staff}i)s %({x-mtls-impersonated-by}i)s",
40
+ return JsonArgsFormatter(
41
+ fmt="%(asctime)s %(process)d %(levelname)s %(name)s %(D)s %(U)s %(q)s %(H)s %(m)s %(B)s %(r)s %(s)s %(a)s %({host}i)s %({x-mtls-full-name}i)s %({x-forwarded-for}i)s %({x-mtls-username}i)s %({x-mtls-staff}i)s %({x-mtls-impersonated-by}i)s",
40
42
  datefmt="%Y-%m-%dT%H:%M:%S%z",
41
43
  style="%",
44
+ require_rename=True,
42
45
  rename_fields={
43
- "M": "duration",
46
+ "D": "duration_us",
47
+ "m": "method",
48
+ "U": "path",
49
+ "q": "query_string",
50
+ "H": "protocol",
44
51
  "a": "user_agent",
45
- "t": "time",
46
52
  "{host}i": "host",
47
53
  "{x-forwarded-for}i": "ip",
48
54
  "s": "status",
49
55
  "r": "request",
50
- "p": "process_id",
56
+ "B": "response_length",
51
57
  "{x-mtls-full-name}i": "full_name",
52
58
  "{x-mtls-username}i": "user",
53
59
  "{x-mtls-staff}i": "is_staff",
@@ -62,7 +68,7 @@ def make_access_formatter():
62
68
  logconfig_dict = {
63
69
  "version": 1,
64
70
  "disable_existing_loggers": False,
65
- "root": {"level": "INFO", "handlers": ["console"]},
71
+ "root": {"level": "INFO", "handlers": ["console", "readable_console_error"]},
66
72
  "loggers": {
67
73
  "gunicorn.access": {
68
74
  "level": "INFO",
@@ -71,14 +77,19 @@ logconfig_dict = {
71
77
  },
72
78
  "gunicorn.error": {
73
79
  "level": "INFO",
74
- "handlers": ["error_console"],
80
+ "handlers": ["console_error"],
75
81
  "qualname": "gunicorn.error",
76
82
  },
83
+ "pyquocca.pgsql": {
84
+ "level": "DEBUG",
85
+ "handlers": ["console"],
86
+ "qualname": "pyquocca.pgsql",
87
+ },
77
88
  },
78
89
  "handlers": {
79
90
  "console": {
80
91
  "class": "logging.StreamHandler",
81
- "formatter": "generic",
92
+ "formatter": "json",
82
93
  "stream": "ext://sys.stdout",
83
94
  },
84
95
  "console_access": {
@@ -86,18 +97,30 @@ logconfig_dict = {
86
97
  "formatter": "json_access",
87
98
  "stream": "ext://sys.stdout",
88
99
  },
89
- "error_console": {
100
+ "console_error": {
90
101
  "class": "logging.StreamHandler",
102
+ "formatter": "json",
103
+ "stream": "ext://sys.stderr",
104
+ },
105
+ "readable_console_error": {
106
+ "class": "logging.StreamHandler",
107
+ "level": "ERROR",
91
108
  "formatter": "generic",
92
109
  "stream": "ext://sys.stderr",
93
110
  },
94
111
  },
95
112
  "formatters": {
96
113
  "generic": {
97
- "format": "%(asctime)s [%(process)d] [%(levelname)s] %(message)s",
114
+ "format": "%(asctime)s [%(process)d] [%(levelname)s] [%(name)s] %(message)s",
98
115
  "datefmt": "[%Y-%m-%d %H:%M:%S %z]",
99
116
  "class": "logging.Formatter",
100
117
  },
118
+ "json": {
119
+ "class": "pyquocca.gunicorn.JsonArgsFormatter",
120
+ "format": "%(asctime)s %(process)d %(levelname)s %(name)s %(message)s %(pathname)s %(lineno)s %(funcName)s %(module)s",
121
+ "datefmt": "%Y-%m-%dT%H:%M:%S%z",
122
+ "style": "%",
123
+ },
101
124
  "json_access": {
102
125
  "()": "pyquocca.gunicorn.make_access_formatter",
103
126
  },
@@ -0,0 +1,15 @@
1
+ import logging
2
+
3
+ from flask.logging import default_handler
4
+
5
+
6
+ def setup_dev_server_logging():
7
+ # Log messages from everything (including pyquocca).
8
+ root = logging.getLogger()
9
+ root.addHandler(default_handler)
10
+ root.setLevel("INFO")
11
+ # Don't overwrite the format of the dev server.
12
+ logging.getLogger("werkzeug").propagate = False
13
+ # Log debugging for SQL.
14
+ logging.getLogger("pyquocca.pgsql").setLevel("DEBUG")
15
+ logging.getLogger("pyquocca.mysql").setLevel("DEBUG")
@@ -1,22 +1,48 @@
1
+ import logging
1
2
  import os
2
- import re
3
- from typing import Optional, Union, cast
3
+ import time
4
+ from typing import Any, Optional, Union
4
5
 
5
6
  from flask import Flask, g
6
7
  from pymysql import Connection
7
8
  from pymysql.cursors import DictCursor
8
9
 
9
- _NAME_TO_ENV = re.compile(r"[^A-Z0-9_]")
10
+ from pyquocca.envvars import to_env_var
11
+
12
+
13
+ class LoggingDictCursor(DictCursor):
14
+ def execute(
15
+ self,
16
+ query,
17
+ args=None,
18
+ ):
19
+ logger = logging.getLogger("pyquocca.mysql")
20
+
21
+ start = time.monotonic_ns()
22
+ try:
23
+ result = super().execute(query, args)
24
+ duration_ns = time.monotonic_ns() - start
25
+ except Exception as exc:
26
+ logger.error(
27
+ "`%(query)s` with params `%(params)s` caused an error",
28
+ {"query": query, "params": args},
29
+ )
30
+ raise exc
31
+
32
+ logger.debug(
33
+ "`%(query)s` with params `%(params)s` ran in %(duration_us).3f us",
34
+ {"query": query, "params": args, "duration_us": duration_ns / 1000},
35
+ )
36
+
37
+ return result
10
38
 
11
39
 
12
40
  def connect(name: str = "mysql"):
13
41
  """Connects to a MySQL database resource using provided environment variables
14
- (e.g. `MYSQL_{name}_HOST`, note that `MYSQL_MYSQL_HOST` will be abbreviated to `MYSQL_HOST`).
42
+ (e.g. `{name}_HOST`).
15
43
  """
16
44
 
17
- env_prefix = f"MYSQL_{name}" if name != "mysql" else "MYSQL"
18
- env_prefix = _NAME_TO_ENV.sub("", env_prefix.upper().replace("-", "_"))
19
-
45
+ env_prefix = to_env_var(name)
20
46
  host = os.getenv(f"{env_prefix}_HOST")
21
47
  database = os.getenv(f"{env_prefix}_DB") or os.getenv(f"{env_prefix}_DATABASE")
22
48
  user = os.getenv(f"{env_prefix}_USER")
@@ -36,29 +62,29 @@ def connect(name: str = "mysql"):
36
62
  database=database,
37
63
  user=user,
38
64
  password=password,
39
- cursorclass=DictCursor,
65
+ cursorclass=LoggingDictCursor,
40
66
  )
41
67
 
42
68
 
43
69
  def execute(
44
- connection: Connection[DictCursor],
70
+ connection: Connection,
45
71
  sql: str,
46
72
  values: Optional[Union[tuple, list]] = None,
47
- ):
73
+ ) -> LoggingDictCursor:
48
74
  """Executes an SQL query against a database connection."""
49
75
  cursor = connection.cursor()
50
76
  cursor.execute(sql, values)
51
77
  return cursor
52
78
 
53
79
 
54
- def fetch_one(connection: Connection[DictCursor], sql: str, values=None):
80
+ def fetch_one(connection: Connection, sql: str, values=None) -> dict[str, Any] | None:
55
81
  """Executes an SQL query and calls `cursor.fetchone()` automatically."""
56
82
  with connection.cursor() as cursor:
57
83
  cursor.execute(sql, values)
58
84
  return cursor.fetchone()
59
85
 
60
86
 
61
- def fetch_all(connection: Connection[DictCursor], sql: str, values=None):
87
+ def fetch_all(connection: Connection, sql: str, values=None) -> list[dict[str, Any]]:
62
88
  """Executes an SQL query and calls `cursor.fetchall()` automatically."""
63
89
  with connection.cursor() as cursor:
64
90
  cursor.execute(sql, values)
@@ -89,16 +115,13 @@ class FlaskMySQL:
89
115
  g._mysql_connections = {}
90
116
  return g._mysql_connections
91
117
 
92
- def _get_connection(self):
118
+ def _get_connection(self) -> Connection | None:
93
119
  connections = self._get_connections_dict()
94
120
  if self.name not in connections:
95
121
  return None
96
- return cast(
97
- Connection[DictCursor],
98
- connections[self.name],
99
- )
122
+ return connections[self.name]
100
123
 
101
- def _get_or_create_connection(self):
124
+ def _get_or_create_connection(self) -> Connection:
102
125
  db = self._get_connection()
103
126
  if db is None:
104
127
  db = connect(self.name)
@@ -121,19 +144,19 @@ class FlaskMySQL:
121
144
  self,
122
145
  sql: str,
123
146
  values=None,
124
- ):
147
+ ) -> LoggingDictCursor:
125
148
  """Executes an SQL query."""
126
149
  cursor = self._get_or_create_connection().cursor()
127
150
  cursor.execute(sql, values)
128
151
  return cursor
129
152
 
130
- def fetch_one(self, sql: str, values=None):
153
+ def fetch_one(self, sql: str, values=None) -> dict[str, Any]:
131
154
  """Executes an SQL query and calls `cursor.fetchone()` automatically."""
132
155
  with self._get_or_create_connection().cursor() as cursor:
133
156
  cursor.execute(sql, values)
134
157
  return cursor.fetchone()
135
158
 
136
- def fetch_all(self, sql: str, values=None):
159
+ def fetch_all(self, sql: str, values=None) -> list[dict[str, Any]]:
137
160
  """Executes an SQL query and calls `cursor.fetchall()` automatically."""
138
161
  with self._get_or_create_connection().cursor() as cursor:
139
162
  cursor.execute(sql, values)
@@ -1,15 +1,46 @@
1
1
  import atexit
2
+ import logging
2
3
  import os
3
- import re
4
+ import time
4
5
  from typing import Generic, Optional, TypeVar, cast
5
6
 
6
7
  from flask import Flask, g
7
- from psycopg import Connection
8
+ from psycopg import Connection, Cursor
8
9
  from psycopg.abc import Params, Query
9
10
  from psycopg.rows import RowFactory, dict_row
10
11
  from psycopg_pool import ConnectionPool, NullConnectionPool
11
12
 
12
- _NAME_TO_ENV = re.compile(r"[^A-Z0-9_]")
13
+ from pyquocca.envvars import to_env_var
14
+
15
+
16
+ class LoggingCursor(Cursor):
17
+ def execute(
18
+ self,
19
+ query: Query,
20
+ params: Optional[Params] = None,
21
+ *,
22
+ prepare: Optional[bool] = None,
23
+ binary: Optional[bool] = None,
24
+ ):
25
+ logger = logging.getLogger("pyquocca.pgsql")
26
+
27
+ start = time.monotonic_ns()
28
+ try:
29
+ super().execute(query, params, prepare=prepare, binary=binary)
30
+ duration_ns = time.monotonic_ns() - start
31
+ except Exception as exc:
32
+ logger.error(
33
+ "`%(query)s` with params `%(params)s` caused an error",
34
+ {"query": query, "params": params},
35
+ )
36
+ raise exc
37
+
38
+ logger.debug(
39
+ "`%(query)s` with params `%(params)s` ran in %(duration_us).3f us",
40
+ {"query": query, "params": params, "duration_us": duration_ns / 1000},
41
+ )
42
+
43
+ return self
13
44
 
14
45
 
15
46
  T = TypeVar("T")
@@ -21,12 +52,10 @@ def connect(
21
52
  pool: Optional[bool] = None,
22
53
  ) -> ConnectionPool[Connection[T]] | NullConnectionPool[Connection[T]]:
23
54
  """Connects to a PostgreSQL database resource using provided environment variables
24
- (e.g. `POSTGRES_{name}_HOST`, note that `POSTGRES_POSTGRES_HOST` will be abbreviated to `POSTGRES_HOST`).
55
+ (e.g. `{name}_HOST`).
25
56
  """
26
57
 
27
- env_prefix = f"POSTGRES_{name}" if name != "postgres" else "POSTGRES"
28
- env_prefix = _NAME_TO_ENV.sub("", env_prefix.upper().replace("-", "_"))
29
-
58
+ env_prefix = to_env_var(name)
30
59
  host = os.getenv(f"{env_prefix}_HOST")
31
60
  database = os.getenv(f"{env_prefix}_DB") or os.getenv(f"{env_prefix}_DATABASE")
32
61
  user = os.getenv(f"{env_prefix}_USER")
@@ -50,11 +79,12 @@ def connect(
50
79
  return PoolClass(
51
80
  connection_class=Connection[T],
52
81
  kwargs={
53
- "row_factory": row_factory,
54
82
  "host": host,
55
83
  "dbname": database,
56
84
  "user": user,
57
85
  "password": password,
86
+ "row_factory": row_factory,
87
+ "cursor_factory": LoggingCursor,
58
88
  },
59
89
  )
60
90
 
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import os
2
3
  from typing import Any, Literal, Optional
3
4
 
@@ -94,6 +95,12 @@ def visit(
94
95
  )
95
96
 
96
97
  if r.status_code == 204:
98
+ logger = logging.getLogger("pyquocca.xssbot")
99
+ logger.info(
100
+ "Sent request to XSSBot to visit `%(url)s` for user `%(username)s`",
101
+ {"url": url, "username": username},
102
+ extra={"options": data},
103
+ )
97
104
  return
98
105
  elif r.status_code == 400:
99
106
  raise BadRequestError(r.json())
@@ -0,0 +1,24 @@
1
+ from flask import Flask, jsonify
2
+ from pyquocca.logging import setup_dev_server_logging
3
+ from pyquocca.mysql import FlaskMySQL
4
+
5
+ app = Flask(__name__)
6
+
7
+ # db = FlaskPostgres()
8
+ db = FlaskMySQL()
9
+
10
+
11
+ @app.route("/")
12
+ def index():
13
+ app.logger.info("Did a thing!")
14
+ return jsonify(db.fetch_all("SELECT * FROM posts;"))
15
+
16
+
17
+ @app.route("/500")
18
+ def error():
19
+ raise Exception("Oops!")
20
+
21
+
22
+ if __name__ == "__main__":
23
+ setup_dev_server_logging()
24
+ app.run(debug=True, host="0.0.0.0", port=8000)
pyquocca-0.2.0/Dockerfile DELETED
@@ -1,9 +0,0 @@
1
- FROM ghcr.io/astral-sh/uv:python3.12-alpine
2
-
3
- WORKDIR /app
4
- COPY . .
5
-
6
- RUN uv sync --all-extras
7
-
8
- ENTRYPOINT []
9
- CMD sleep 5 && .venv/bin/python3 src/test_app/main.py
@@ -1,23 +0,0 @@
1
- import logging
2
-
3
- from flask import Flask, jsonify
4
- from pyquocca.pgsql import FlaskPostgres
5
-
6
- app = Flask(__name__)
7
-
8
- db = FlaskPostgres()
9
-
10
-
11
- @app.route("/")
12
- def index():
13
- logging.info("Did a thing!")
14
- return jsonify(db.fetch_all("SELECT * FROM posts;"))
15
-
16
-
17
- @app.route("/500")
18
- def error():
19
- raise Exception("Oops!")
20
-
21
-
22
- if __name__ == "__main__":
23
- app.run(debug=True, host="0.0.0.0")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes