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: 2 additions & 0 deletions docs/reference/matrix-updates/0.11.0-activation.tsv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
inactivity:log-texts adapted BootUI 2.6.0 (BootUiShellGuardAutoConfiguration.java:66-76) logs fixed inactivity texts. sharpit logs the same texts and levels with BootUI replaced by sharpit, the bootui.* properties replaced by the SHARPIT_* variables and Spring Boot DevTools replaced by a reloading development server, because sharpit has no Spring properties and detects reload through the development server.
inactivity:warnings-count adapted BootUI logs neither the configuration warnings nor their number while it is inactive. While sharpit is inactive it logs one WARNING with the number of configuration warnings (omitted when there are none) instead of the warnings themselves, because the count keeps an invalid setting visible without printing its value. The count leaves out the invalid SHARPIT_ENABLED warning, which the fixed text already reports, so an invalid SHARPIT_ENABLED logs one record as in BootUI.
2 changes: 1 addition & 1 deletion docs/superpowers/plans/2026-10-30-sharpit-mvp.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ scripts/sanitize_golden.py
**Interfaces:**
- Consumes: Tasks 2–5.
- Produces:
- `install(app, *, settings: Sequence[object] = (), **options) -> SharpitHandle` — reads `load_settings(options, os.environ)`, `decide(...)`, inserts a `SharpitMount(path, app=sub_app, name="sharpit")` at `app.router.routes[0]`. `SharpitMount` subclasses Starlette `Mount` and overrides its compiled path regex to `^{path}(?:/(?P<path>.*))?$` so the **bare** `{path}` (any method) also reaches the sub-app and its guard (a plain `Mount` never receives it; the host router would redirect or a host catch-all would answer). It registers a lifespan-start hook by wrapping `app.router.lifespan_context` (the original is kept as `handle.original_lifespan` for Task 10) that records startup ms; logs one INFO line `sharpit inactive: <reason>` when inactive; when active and `show_banner`, prints the banner to stderr, including the generated token if any; when `expose_values` is FULL, logs a WARNING.
- `install(app, *, settings: Sequence[object] = (), **options) -> SharpitHandle` — reads `load_settings(options, os.environ)`, `decide(...)`, inserts a `SharpitMount(path, app=sub_app, name="sharpit")` at `app.router.routes[0]`. `SharpitMount` subclasses Starlette `Mount` and overrides its compiled path regex to `^{path}(?:/(?P<path>.*))?$` so the **bare** `{path}` (any method) also reaches the sub-app and its guard (a plain `Mount` never receives it; the host router would redirect or a host catch-all would answer). It registers a lifespan-start hook by wrapping `app.router.lifespan_context` (the original is kept as `handle.original_lifespan` for Task 10) that records startup ms; logs one fixed text when inactive (INFO for AUTO mode, DEBUG for OFF and a disabled profile, WARNING for an invalid `SHARPIT_ENABLED`; never the reason), plus one WARNING with the number of configuration warnings when there are any; when active and `show_banner`, prints the banner to stderr, including the generated token if any; when `expose_values` is FULL, logs a WARNING.
- Inactive response: 404 with the host framework's not-found shape (`{"detail":"Not Found"}` JSON for a FastAPI host), no sharpit headers, for every method and every path including the bare `{path}`.
- Host middleware (e.g. `TrustedHostMiddleware`, auth middleware) wraps the mount and stays authoritative; README documents adding `localhost` to the host's allowed hosts. sharpit does not try to bypass it.
- `class SharpitHandle: settings; activation: ActivationStatus; context: SharpitContext; original_lifespan` (for tests).
Expand Down
44 changes: 37 additions & 7 deletions src/sharpit/engine/activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@

from __future__ import annotations

import logging
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from typing import Any, Literal

from sharpit.engine.guard import remote_access_configured
from sharpit.settings import SharpitSettings, parse_mode

Inactivity = Literal["auto", "off", "disabled-profile", "invalid"]


@dataclass(frozen=True)
class ActivationStatus:
enabled: bool
localhost_only: bool
reason: str
warnings: tuple[str, ...]
inactivity: Inactivity | None = None

def to_dto(self) -> dict[str, Any]:
return {
Expand All @@ -26,6 +30,28 @@ def to_dto(self) -> dict[str, Any]:
}


# Fixed texts and levels (port of BootUI 2.6.0 ``BootUiShellGuardAutoConfiguration.bootUiInactiveStartupDiagnostic``).
# They never carry the decision's reason or warnings: those can hold configured values, which stay out of the log.
_INACTIVITY_MESSAGES: dict[Inactivity, tuple[int, str]] = {
"auto": (
logging.INFO,
"sharpit is inactive in AUTO mode: no enabled profile is active and no reloading development server was"
" detected. For local development, activate a SHARPIT_ENABLED_PROFILES profile or set SHARPIT_ENABLED=ON.",
),
"off": (logging.DEBUG, "sharpit is inactive: SHARPIT_ENABLED=OFF."),
"disabled-profile": (logging.DEBUG, "sharpit is inactive: an active profile matches SHARPIT_DISABLED_PROFILES."),
"invalid": (
logging.WARNING,
"sharpit is inactive: invalid SHARPIT_ENABLED configuration (fail-closed). Use AUTO, ON, or OFF.",
),
}


def inactivity_message(status: ActivationStatus) -> tuple[int, str] | None:
"""The log level and fixed text for an inactive status; ``None`` when sharpit is enabled."""
return None if status.inactivity is None else _INACTIVITY_MESSAGES[status.inactivity]


def active_profiles(settings: SharpitSettings, environ: Mapping[str, str]) -> list[str]:
"""Union of the ``profile_vars`` env vars: comma-split, trimmed, lower-cased, de-duplicated in order."""
seen: dict[str, None] = {}
Expand All @@ -40,12 +66,12 @@ def decide(settings: SharpitSettings, profiles: Sequence[str], dev_signal: str |
warnings = list(settings.warnings)
localhost_only = not remote_access_configured(settings) # sharpit: trusted proxies and gateway trust count too

def result(enabled: bool, reason: str) -> ActivationStatus:
return ActivationStatus(enabled, localhost_only, reason, tuple(warnings))
def result(enabled: bool, reason: str, inactivity: Inactivity | None = None) -> ActivationStatus:
return ActivationStatus(enabled, localhost_only, reason, tuple(warnings), inactivity)

mode = parse_mode(settings.enabled)
if mode is None:
return result(False, f"Disabled: invalid SHARPIT_ENABLED value '{settings.enabled}'")
return result(False, f"Disabled: invalid SHARPIT_ENABLED value '{settings.enabled}'", "invalid")

active = {p.strip().lower() for p in profiles}
for profile in settings.disabled_profiles:
Expand All @@ -55,15 +81,19 @@ def result(enabled: bool, reason: str) -> ActivationStatus:
f"Profile '{profile}' is in SHARPIT_DISABLED_PROFILES but SHARPIT_ENABLED=ON forces it on."
)
return result(True, f"Explicitly enabled (SHARPIT_ENABLED=ON) despite disabled profile '{profile}'")
return result(False, f"Disabled because active profile '{profile}' is in SHARPIT_DISABLED_PROFILES")
return result(
False,
f"Disabled because active profile '{profile}' is in SHARPIT_DISABLED_PROFILES",
"disabled-profile",
)

if mode == "OFF":
return result(False, "Disabled by SHARPIT_ENABLED=OFF")
return result(False, "Disabled by SHARPIT_ENABLED=OFF", "off")
if mode == "ON":
return result(True, "Enabled by SHARPIT_ENABLED=ON")
for profile in settings.enabled_profiles:
if profile in active:
return result(True, f"Enabled by active profile '{profile}'")
if dev_signal:
return result(True, f"Enabled because a reloading development server was detected ({dev_signal})")
return result(False, "Disabled: no enabled profile and no reloading development server detected")
return result(False, "Disabled: no enabled profile and no reloading development server detected", "auto")
34 changes: 17 additions & 17 deletions src/sharpit/fastapi/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from starlette.middleware import Middleware

from sharpit.engine import guard, sqla
from sharpit.engine.activation import ActivationStatus, active_profiles, decide
from sharpit.engine.activation import ActivationStatus, active_profiles, decide, inactivity_message
from sharpit.engine.capture import route_path
from sharpit.engine.capture.exceptions import ExceptionStore
from sharpit.engine.capture.exchanges import HttpExchangeBuffer
Expand All @@ -40,7 +40,7 @@
from sharpit.fastapi.handle import SharpitHandle # not from adapter: it imports this module at its end
from sharpit.fastapi.introspector import FastApiIntrospector
from sharpit.fastapi.signals import dev_server_signal
from sharpit.settings import SharpitSettings, load_settings, parse_mode
from sharpit.settings import INVALID_ENABLED_WARNING_PREFIX, SharpitSettings, load_settings

__all__ = ["install", "_configure_capture"]

Expand Down Expand Up @@ -185,20 +185,11 @@ def _models(models: object) -> tuple[object, ...]: # NOSONAR - one element per
return tuple(cast("Iterable[object]", models))


def _requested(settings: SharpitSettings, profiles: tuple[str, ...]) -> bool:
"""sharpit was asked for (an unusable SHARPIT_ENABLED, or an enabled profile is active) yet ended up inactive."""
return parse_mode(settings.enabled) is None or any(p in profiles for p in settings.enabled_profiles)


def _existing_handle(router: Any, mount_type: type) -> Any:
"""An earlier install's handle on this router, with its warning logged; ``None`` on a first install."""
existing = next((r.sharpit_handle for r in router.routes if isinstance(r, mount_type) and r.sharpit_handle), None)
if existing is not None:
first = (
""
if existing.activation.enabled
else f" (that install left sharpit inactive: {existing.activation.reason})"
)
first = "" if existing.activation.enabled else " (that install left sharpit inactive)"
logger.warning("sharpit.install() was already called on this app; ignoring this call%s", first)
return existing

Expand Down Expand Up @@ -276,6 +267,16 @@ def _apply_runtime_overrides(
)


def _log_inactivity(activation: ActivationStatus) -> None:
"""BootUI's levels and fixed texts: neither the reason nor a settings warning (both may hold a configured value)."""
if (inactive := inactivity_message(activation)) is not None:
logger.log(*inactive)
# The invalid SHARPIT_ENABLED warning is left out: the fixed text above already reports it.
count = sum(not warning.startswith(INVALID_ENABLED_WARNING_PREFIX) for warning in activation.warnings)
if count:
logger.warning("sharpit is inactive; %d configuration warning(s) are not shown while it is inactive.", count)


def install(
app: Any,
*,
Expand Down Expand Up @@ -319,18 +320,17 @@ def install(
)
handle = sharpit_handle_type(sharpit_settings, activation, ctx, original)
idle_tracker: IdleTracker | None = None
for warning in activation.warnings: # the overview panel shows them too, but not while sharpit is inactive
logger.warning("%s", warning)

if not activation.enabled:
mount = sharpit_mount_type(sharpit_settings.path, app=_not_found, name="sharpit")
mount.sharpit_handle = handle
router.routes.insert(0, mount)
# asked for but still off is a WARNING (uvicorn drops INFO from unconfigured loggers); an explicit OFF is INFO
level = logging.WARNING if _requested(sharpit_settings, profiles) else logging.INFO
logger.log(level, "sharpit inactive: %s", activation.reason)
_log_inactivity(activation)
return handle

for warning in activation.warnings: # the overview panel shows them too
logger.warning("%s", warning)

ctx.masker.identity_key = _identity_key(sharpit_settings)
if ctx.masker.identity_key is None:
logger.warning("SQLite statement identities are unavailable because sharpit could not load a state key")
Expand Down
6 changes: 5 additions & 1 deletion src/sharpit/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
from sharpit.engine.panels import PANELS

_NEVER_ECHOED = _registry.NEVER_ECHOED

# The invalid SHARPIT_ENABLED warning: the inactive log reports it with a fixed text, so it is not counted.
INVALID_ENABLED_WARNING_PREFIX = "Ignoring invalid SHARPIT_ENABLED value"
_JOURNAL_SOURCES = _registry.JOURNAL_SOURCES
_SPECS = _registry.SPECS
_UNSET = _registry.UNSET
Expand Down Expand Up @@ -274,7 +277,8 @@ def load_settings(kwargs: Mapping[str, object], environ: Mapping[str, str]) -> S
except ValueError:
# install() logs warnings: never echo a token, however malformed, or a URI that can carry credentials
shown = "" if name in _NEVER_ECHOED else f" '{raw}'"
warnings.append(f"Ignoring invalid {env} value{shown}")
prefix = INVALID_ENABLED_WARNING_PREFIX if name == "enabled" else f"Ignoring invalid {env} value"
warnings.append(f"{prefix}{shown}")
# `enabled` keeps the raw text so decide() reports it; other fields take their fail-safe (or default).
if name == "enabled":
values[name] = str(raw).strip()
Expand Down
77 changes: 76 additions & 1 deletion tests/engine/test_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@

from __future__ import annotations

import logging

import pytest

from sharpit.engine.activation import ActivationStatus, active_profiles, decide
from inactivity_texts import AUTO_TEXT, DISABLED_PROFILE_TEXT, INVALID_TEXT, OFF_TEXT
from sharpit.engine.activation import ActivationStatus, active_profiles, decide, inactivity_message
from sharpit.settings import SharpitSettings, load_settings

SIGNAL = "uvicorn --reload"
Expand Down Expand Up @@ -299,3 +302,75 @@ def test_to_dto_shape():

def test_decide_accepts_unnormalised_profiles():
assert decide(SharpitSettings(), [" PROD "], None).enabled is False


# ---- inactivity category and fixed log texts (BootUI 2.6.0) ---------------------------------------------------------


@pytest.mark.parametrize(
("environ", "expected"),
[
pytest.param(
{"APP_ENV": "dev", "SHARPIT_ENABLED": "maybe"}, "invalid", id="invalid"
), # ported: BootUiActivationConditionTests.invalidEnabledModeFailsClosedEvenWithEnabledProfile
pytest.param(
{"APP_ENV": "prod,dev"}, "disabled-profile", id="disabled-profile"
), # ported: BootUiActivationConditionTests.disabledProfileForcesOffByDefault
pytest.param(
{"APP_ENV": "dev", "SHARPIT_ENABLED": "OFF"}, "off", id="off"
), # ported: BootUiActivationConditionTests.enabledOffForcesDisabled
pytest.param(
{"APP_ENV": "staging"}, "auto", id="auto"
), # ported: BootUiActivationConditionTests.autoDisablesWithoutEnabledProfileAndWithoutDevtools
],
)
def test_inactivity_category_per_branch(environ: dict[str, str], expected: str):
assert run(environ).inactivity == expected


@pytest.mark.parametrize(
("environ", "dev_signal"),
[
pytest.param({"SHARPIT_ENABLED": "ON"}, None, id="on"),
pytest.param(
{"APP_ENV": "dev"}, None, id="enabled-profile"
), # ported: BootUiActivationConditionTests.autoEnablesOnEnabledProfile
pytest.param(
{}, SIGNAL, id="dev-signal"
), # ported: BootUiActivationConditionTests.autoEnablesWhenDevtoolsIsPresent
pytest.param(
{"APP_ENV": "prod", "SHARPIT_ENABLED": "ON"}, None, id="on-despite-disabled-profile"
), # ported: BootUiActivationConditionTests.enabledOnOverridesDisabledProfileButRecordsWarning
],
)
def test_inactivity_is_none_when_enabled(environ: dict[str, str], dev_signal: str | None):
# ported: BootUiInactiveStartupDiagnosticTests.enabledInstallationDoesNotRegisterAnInactiveDiagnostic
status = run(environ, dev_signal=dev_signal)
assert status.enabled is True
assert status.inactivity is None


def test_activation_dto_has_no_inactivity_key():
status = run({"APP_ENV": "dev", "SHARPIT_ENABLED": "OFF"})
assert "inactivity" not in status.to_dto()


@pytest.mark.parametrize(
("environ", "level", "text"),
[
pytest.param({"APP_ENV": "staging"}, logging.INFO, AUTO_TEXT, id="auto"),
pytest.param({"SHARPIT_ENABLED": "OFF"}, logging.DEBUG, OFF_TEXT, id="off"),
pytest.param({"APP_ENV": "prod"}, logging.DEBUG, DISABLED_PROFILE_TEXT, id="disabled-profile"),
pytest.param({"SHARPIT_ENABLED": "maybe"}, logging.WARNING, INVALID_TEXT, id="invalid"),
],
)
def test_inactivity_message_levels_and_texts(environ: dict[str, str], level: int, text: str):
# ported: BootUiInactiveStartupDiagnosticTests.ordinaryAutoInactivityLogsOnceWithALocalDevelopmentAction
# ported: BootUiInactiveStartupDiagnosticTests.explicitOffOnlyLogsAtDebug
# ported: BootUiInactiveStartupDiagnosticTests.disabledProfileOnlyLogsAtDebugWithoutEchoingTheProfile
# ported: BootUiInactiveStartupDiagnosticTests.invalidConfigurationStaysClosedAndLogsOnlyAFixedSafeWarning
assert inactivity_message(run(environ)) == (level, text)


def test_inactivity_message_is_none_when_enabled():
assert inactivity_message(run({"SHARPIT_ENABLED": "ON"})) is None
Loading