Skip to content
Draft
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
2 changes: 1 addition & 1 deletion src/sharpit/engine/advisors/retention.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

DEFAULT_PAGE_LIMIT = 100
MAX_PAGE_LIMIT = 1000
_INTEGER = re.compile(r"-?[0-9]+")
_INTEGER = re.compile(r"-?[0-9]+") # NOSONAR - \d also matches non-ASCII digits; the paging values are ASCII


class AdvisorViolationError(Exception):
Expand Down
114 changes: 72 additions & 42 deletions src/sharpit/engine/collectors/alembic.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import sys
import time
import tomllib
from collections.abc import Callable
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol, cast
Expand Down Expand Up @@ -48,7 +48,9 @@
MAX_REVISION_BYTES = 1024 * 1024
MAX_ERROR_BYTES = 4096
DEFAULT_VERSION_TABLE = "alembic_version"
_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,62}")
_IDENTIFIER = re.compile(
r"[A-Za-z_][A-Za-z0-9_]{0,62}"
) # NOSONAR - \w also matches non-ASCII letters; a plain identifier is ASCII
_DRIVE = re.compile(r"^[A-Za-z]:[\\/]")
_SEPARATORS = {"os": os.pathsep, ":": ":", ";": ";", "space": " ", "newline": "\n"}
_VARIABLES = ("revision", "down_revision", "branch_labels", "depends_on")
Expand All @@ -64,7 +66,7 @@

@dataclass(frozen=True)
class Revision:
revision: str
revision: str # NOSONAR - the Alembic revision id, named as in the migration scripts
down_revisions: tuple[str, ...]
description: str | None
script: str # relative to the config file's directory, with forward slashes
Expand Down Expand Up @@ -157,7 +159,7 @@ def _split(raw: object, separator: object) -> list[str]:
text = str(raw)
if isinstance(separator, str) and separator in _SEPARATORS:
return [part.strip() for part in text.split(_SEPARATORS[separator]) if part.strip()]
return [part for part in re.split(r", *|(?: +)", text.strip()) if part] # Alembic's legacy split
return [part for part in re.split(r", *| +", text.strip()) if part] # Alembic's legacy split


def _relative(path: Path, base: Path) -> str:
Expand All @@ -171,40 +173,52 @@ def _literal(value: ast.expr) -> object:
return ast.literal_eval(value)


def _parse_revision(path: Path, base: Path, masker: Masker) -> Revision | str | None:
"""The revision in ``path``, a reason it was skipped, or None when the file declares no ``revision``."""
try:
if path.stat().st_size > MAX_REVISION_BYTES:
return "larger than 1 MB"
tree = ast.parse(path.read_bytes(), filename=path.name)
except (OSError, SyntaxError, ValueError, MemoryError, RecursionError) as exc:
return masker.mask_text(f"cannot be parsed: {type(exc).__name__}: {exc}") or "cannot be parsed"
values: dict[str, object] = {}
def _assignments(tree: ast.Module) -> Iterator[tuple[list[ast.expr], ast.expr]]:
for node in tree.body:
if isinstance(node, ast.Assign):
targets, value = node.targets, node.value
yield node.targets, node.value
elif isinstance(node, ast.AnnAssign) and node.value is not None: # revision: str = "abc" (Alembic >= 1.12)
targets, value = [node.target], node.value
else:
continue
yield [node.target], node.value


def _variables(tree: ast.Module) -> dict[str, object] | str:
"""The literal values of the revision variables, or why one of them is not a literal."""
values: dict[str, object] = {}
for targets, value in _assignments(tree):
for target in targets:
if isinstance(target, ast.Name) and target.id in _VARIABLES:
try:
values[target.id] = _literal(value)
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
return f"{target.id} is not a literal value"
return values


def _down_revisions(down: object) -> tuple[str, ...]:
if isinstance(down, str):
return (down,)
if isinstance(down, tuple | list):
return tuple(d for d in cast("tuple[object, ...]", tuple(cast("Any", down))) if isinstance(d, str))
return ()


def _parse_revision(path: Path, base: Path, masker: Masker) -> Revision | str | None:
"""The revision in ``path``, a reason it was skipped, or None when the file declares no ``revision``."""
try:
if path.stat().st_size > MAX_REVISION_BYTES:
return "larger than 1 MB"
tree = ast.parse(path.read_bytes(), filename=path.name)
except (OSError, SyntaxError, ValueError, MemoryError, RecursionError) as exc:
return masker.mask_text(f"cannot be parsed: {type(exc).__name__}: {exc}") or "cannot be parsed"
values = _variables(tree)
if isinstance(values, str):
return values
if "revision" not in values:
return None
revision = values["revision"]
if not isinstance(revision, str) or not revision:
return "revision is not a non-empty string"
down = values.get("down_revision")
if isinstance(down, str):
downs: tuple[str, ...] = (down,)
elif isinstance(down, tuple | list):
downs = tuple(d for d in cast("tuple[object, ...]", tuple(cast("Any", down))) if isinstance(d, str))
else:
downs = ()
downs = _down_revisions(values.get("down_revision"))
doc = ast.get_docstring(tree)
first = doc.strip().splitlines()[0] if doc and doc.strip() else None
return Revision(revision, downs, masker.mask_text(first), _relative(path, base))
Expand Down Expand Up @@ -233,26 +247,17 @@ def _order(revisions: dict[str, Revision]) -> list[Revision]:
return ordered + sorted((r for r in revisions.values() if r.revision not in seen), key=lambda r: r.script)


def read_alembic_files(ini_path: Path, masker: Masker) -> AlembicFiles:
"""The history in the files next to ``ini_path``; never imports Alembic or the revision modules."""
files, options, here = _config(ini_path, masker)
if files.reason is not None:
return files
files.version_table = str(options.get("version_table") or DEFAULT_VERSION_TABLE)
schema = options.get("version_table_schema")
files.version_table_schema = str(schema) if schema else None
def _table_error(files: AlembicFiles, masker: Masker) -> str | None:
"""The refusal for the last hostile ``version_table`` / ``version_table_schema`` (the later one wins)."""
error = None
for label, value in (("version_table", files.version_table), ("version_table_schema", files.version_table_schema)):
if value is not None and not _IDENTIFIER.fullmatch(value):
shown = masker.mask_text(value) or ""
files.table_error = f"Refused to read the database: {label} {shown!r} is not a plain identifier"
script_location = options.get("script_location")
if not script_location:
files.reason = f"{files.config_path} sets no script_location"
return files
script_dir = _location(str(script_location))
if isinstance(script_dir, str):
files.reason = script_dir
return files
error = f"Refused to read the database: {label} {shown!r} is not a plain identifier"
return error


def _collect_version_dirs(files: AlembicFiles, options: dict[str, Any], script_dir: Path) -> None:
raw = options.get("version_locations")
separator = options.get("path_separator") or options.get("version_path_separator")
for item in _split(raw, separator) if raw else []:
Expand All @@ -263,6 +268,9 @@ def read_alembic_files(ini_path: Path, masker: Masker) -> AlembicFiles:
files.version_dirs.append(location)
if not raw:
files.version_dirs.append(script_dir / "versions")


def _collect_revisions(files: AlembicFiles, here: Path, masker: Masker) -> dict[str, Revision]:
found: dict[str, Revision] = {}
for directory in files.version_dirs:
for path in sorted(directory.glob("*.py")) if directory.is_dir() else []:
Expand All @@ -273,6 +281,28 @@ def read_alembic_files(ini_path: Path, masker: Masker) -> AlembicFiles:
files.skipped.append((parsed.script, f"duplicate revision {parsed.revision!r}"))
elif parsed is not None:
found[parsed.revision] = parsed
return found


def read_alembic_files(ini_path: Path, masker: Masker) -> AlembicFiles:
"""The history in the files next to ``ini_path``; never imports Alembic or the revision modules."""
files, options, here = _config(ini_path, masker)
if files.reason is not None:
return files
files.version_table = str(options.get("version_table") or DEFAULT_VERSION_TABLE)
schema = options.get("version_table_schema")
files.version_table_schema = str(schema) if schema else None
files.table_error = _table_error(files, masker)
script_location = options.get("script_location")
if not script_location:
files.reason = f"{files.config_path} sets no script_location"
return files
script_dir = _location(str(script_location))
if isinstance(script_dir, str):
files.reason = script_dir
return files
_collect_version_dirs(files, options, script_dir)
found = _collect_revisions(files, here, masker)
files.revisions = _order(found)
parents = {p for r in found.values() for p in r.down_revisions}
files.heads = sorted(r for r in found if r not in parents)
Expand Down Expand Up @@ -421,7 +451,7 @@ async def _read(
return DatabaseRead(name, None, f"Reading the database version timed out after {timeout:g}s", checked)
except sqla.ReadOnlyUnavailable as exc:
return DatabaseRead(name, None, exc.reason, checked)
except Exception as exc: # noqa: BLE001 - a failed read is reported for that database, never raised
except Exception as exc: # noqa: BLE001 # a failed read is reported for that database, never raised
dialect = dialect_of_name(getattr(getattr(engine, "dialect", None), "name", None)) or Dialect.UNSUPPORTED
reason = error_text(ctx.masker, exc, dialect) or type(exc).__name__
return DatabaseRead(name, None, reason, checked)
Expand Down
2 changes: 1 addition & 1 deletion src/sharpit/engine/collectors/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ async def _ping(self, name: str, engine: Any, flight: Flight, executor: DaemonEx
status, details["error"] = "DOWN", self._timed_out()
except sqla.ReadOnlyUnavailable as exc: # skipped: nothing is known about the database, so never DOWN
status, details["error"] = "UNKNOWN", exc.reason
except Exception as exc: # noqa: BLE001 - a failed ping is this engine's DOWN, never the request's 500
except Exception as exc: # noqa: BLE001 # a failed ping is this engine's DOWN, never the request's 500
status, details["error"] = "DOWN", self._failure(exc)
return node(name, status, {**details, "checkedAt": _now_ms()})

Expand Down
7 changes: 5 additions & 2 deletions src/sharpit/engine/collectors/loggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def loggers_report(q: str | None, offset: int | None, limit: int | None) -> dict
# Read the registry directly: getLogger() on a name would create it, and PlaceHolders are not loggers.
registry = logging.root.manager.loggerDict
entries = [
_dto(name, lg) for name, lg in list(registry.items()) if isinstance(lg, logging.Logger) and not _is_own(name)
_dto(name, lg)
for name, lg in list(registry.items()) # NOSONAR - another thread can register a logger mid-iteration
if isinstance(lg, logging.Logger) and not _is_own(name)
]
entries.append(_dto(_ROOT, logging.root))
entries.sort(key=lambda e: e["name"])
Expand All @@ -48,6 +50,7 @@ def set_level(name: str, level: str | None) -> dict[str, Any]:
raise BadRequest(f"Unknown level '{level}'")
is_root = name in (_ROOT, "root")
logger = logging.root if is_root else logging.getLogger(name)
number = logging.getLevelNamesMapping()[wanted] if wanted else logging.WARNING if is_root else logging.NOTSET
unset = logging.WARNING if is_root else logging.NOTSET
number = logging.getLevelNamesMapping()[wanted] if wanted else unset
logger.setLevel(number)
return _dto(_ROOT if is_root else name, logger)
8 changes: 6 additions & 2 deletions src/sharpit/engine/collectors/threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ def task_info(ctx: SharpitContext, task: Any, max_frames: int, *, names_only: bo


def _task_state(task: Any) -> str:
return "CANCELLED" if task.cancelled() else "DONE" if task.done() else "PENDING" # cancelled() first: also done
if task.cancelled(): # first: a cancelled task is also done
return "CANCELLED"
return "DONE" if task.done() else "PENDING"


def _collect(ctx: SharpitContext, max_frames: int, cap: int, names_only: bool) -> tuple[list[dict[str, Any]], int]:
Expand Down Expand Up @@ -185,7 +187,9 @@ async def collect() -> tuple[list[dict[str, Any]], int]: # NOSONAR - all_tasks(
def _thread_name(ctx: SharpitContext, name: str) -> str:
"""BootUI ``maskName``: a secret-looking name is masked; under ``METADATA_ONLY`` too (a name is metadata)."""
shown = ctx.masker.mask_text(name)
return shown if shown is not None else MASK if ctx.settings.mask_secrets and is_secret_value(name) else name
if shown is not None:
return shown
return MASK if ctx.settings.mask_secrets and is_secret_value(name) else name


def _thread_rows(
Expand Down
2 changes: 1 addition & 1 deletion src/sharpit/engine/collectors/vulns/epss.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

CVE_PARAMETER_MAX_LENGTH = 2000 # FIRST.org's documented limit on the comma-joined cve parameter
EPSS_MAX_BYTES = 1024 * 1024
_CVE_ID = re.compile(r"CVE-[0-9]{4}-[0-9]{4,}")
_CVE_ID = re.compile(r"CVE-[0-9]{4}-[0-9]{4,}") # NOSONAR - \d also matches non-ASCII digits; CVE ids are ASCII


class _EpssError(Exception):
Expand Down
Loading
Loading