feat(datasource): 完成 M03 数据源配置与熔断巡检

交付三种引擎登记、草稿/已保存连接测试、可逆启用、每源熔断与 Cron 巡检,以及控制台页面;用户确认收尾后标 DONE_LOCAL。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-18 12:50:46 +08:00
1 parent f17bf19709
commit e6d37d176d
98 files changed
+9097 -91

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ from sqlalchemy import engine_from_config, pool
from watchman.core.config import get_settings
from watchman.models.base import Base
from watchman.models import AuthSession, AuditEvent, RunRecord # noqa: F401
from watchman.models import AuthSession, AuditEvent, DataSource, RunRecord # noqa: F401
config = context.config
if config.config_file_name is not None:
@@ -0,0 +1,68 @@
"""Create data_sources with forced RLS.
Revision ID: 20261117_0004
Revises: 20261117_0003
Create Date: 2026-11-17
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261117_0004"
down_revision: Union[str, None] = "20261117_0003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
TABLE = "data_sources"
def upgrade() -> None:
op.create_table(
TABLE,
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("kind", sa.String(length=32), nullable=False),
sa.Column("engine", sa.String(length=32), nullable=False),
sa.Column("host", sa.String(length=255), nullable=False),
sa.Column("port", sa.Integer(), nullable=False),
sa.Column("database_name", sa.String(length=128), nullable=False),
sa.Column("username", sa.String(length=128), nullable=False),
sa.Column("secret_ciphertext", sa.Text(), nullable=False),
sa.Column("read_only_intent", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("last_test_category", sa.String(length=32), nullable=True),
sa.Column("last_test_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_test_message", sa.String(length=255), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.UniqueConstraint("tenant_id", "name", name="uq_data_sources_tenant_name"),
sa.CheckConstraint("kind = 'database'", name="ck_data_sources_kind"),
sa.CheckConstraint("engine IN ('postgresql','mysql','sqlserver')", name="ck_data_sources_engine"),
sa.CheckConstraint("port BETWEEN 1 AND 65535", name="ck_data_sources_port"),
)
op.execute(f"ALTER TABLE {TABLE} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {TABLE} FORCE ROW LEVEL SECURITY")
op.execute(
f"""
CREATE POLICY tenant_isolation ON {TABLE}
FOR ALL
TO {APP_ROLE}
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
"""
)
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {TABLE} TO {APP_ROLE}")
def downgrade() -> None:
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {TABLE}")
op.drop_table(TABLE)
@@ -0,0 +1,103 @@
"""Add per-datasource circuit breaker configuration and runtime state.
Revision ID: 20261118_0005
Revises: 20261117_0004
Create Date: 2026-11-18
The circuit is independent of data_sources.enabled: an open circuit never flips enabled.
Existing rows get the defaults (window 300s, threshold 3, cooldown 600s, closed).
The table keeps its RLS policy and grants from revision 20261117_0004.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0005"
down_revision: Union[str, None] = "20261117_0004"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
TABLE = "data_sources"
_CHECKS = (
("ck_data_sources_circuit_window", "circuit_failure_window_seconds BETWEEN 1 AND 86400"),
("ck_data_sources_circuit_threshold", "circuit_failure_threshold BETWEEN 1 AND 100"),
("ck_data_sources_circuit_cooldown", "circuit_open_cooldown_seconds BETWEEN 1 AND 86400"),
("ck_data_sources_circuit_state", "circuit_state IN ('closed','open')"),
("ck_data_sources_circuit_count", "circuit_failure_count >= 0"),
)
def upgrade() -> None:
op.add_column(
TABLE,
sa.Column(
"circuit_failure_window_seconds",
sa.Integer(),
server_default=sa.text("300"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_failure_threshold",
sa.Integer(),
server_default=sa.text("3"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_open_cooldown_seconds",
sa.Integer(),
server_default=sa.text("600"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_state",
sa.String(length=16),
server_default=sa.text("'closed'"),
nullable=False,
),
)
op.add_column(
TABLE, sa.Column("circuit_opened_at", sa.DateTime(timezone=True), nullable=True)
)
op.add_column(
TABLE,
sa.Column(
"circuit_failure_count",
sa.Integer(),
server_default=sa.text("0"),
nullable=False,
),
)
op.add_column(
TABLE, sa.Column("circuit_window_started_at", sa.DateTime(timezone=True), nullable=True)
)
for name, condition in _CHECKS:
op.create_check_constraint(name, TABLE, condition)
def downgrade() -> None:
for name, _condition in reversed(_CHECKS):
op.drop_constraint(name, TABLE, type_="check")
for column in (
"circuit_window_started_at",
"circuit_failure_count",
"circuit_opened_at",
"circuit_state",
"circuit_open_cooldown_seconds",
"circuit_failure_threshold",
"circuit_failure_window_seconds",
):
op.drop_column(TABLE, column)
+4
View File
@@ -14,6 +14,10 @@ dependencies = [
"celery>=5.4,<6",
"python-dotenv>=1.0,<2",
"pyjwt[crypto]>=2.10,<3",
"cryptography>=43,<51",
"pymysql>=1.1,<2",
"pymssql>=2.3,<3",
"croniter>=3,<7",
]
[build-system]
@@ -0,0 +1,129 @@
"""Create the isolated probe-test databases for PostgreSQL, MySQL and SQL Server.
Why: connector tests must never touch the platform database, so each engine gets its own
empty database plus one harmless table. This is the only place CREATE DATABASE runs; the
probe function itself stays read-only.
Boundary: creates a database only if missing and never drops anything. Prints engine names
and ok/failed words only -- no hosts, users, passwords or driver error text.
Depends on .env.local through watchman.core.config.merge_layered_env.
Usage (from services/watchman): uv run python scripts/setup_probe_test_sources.py [engine ...]
"""
from __future__ import annotations
import re
import sys
import psycopg
import pymssql
import pymysql
from psycopg import sql
from watchman.core.config import merge_layered_env
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_TIMEOUT = 10
def _env(prefix: str) -> dict[str, str]:
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
missing = [f"{prefix}_{k}" for k in keys if not env.get(f"{prefix}_{k}")]
if missing:
raise RuntimeError("missing env: " + ", ".join(missing))
values = {k.lower(): env[f"{prefix}_{k}"] for k in keys}
if not _IDENT.match(values["database"]):
# Identifier is interpolated into CREATE DATABASE; keep it to a safe charset.
raise RuntimeError(f"{prefix}_DATABASE is not a plain identifier")
return values
def _setup_postgresql() -> None:
cfg = _env("WATCHMAN_TEST_PG")
common = dict(
host=cfg["host"],
port=int(cfg["port"]),
user=cfg["user"],
password=cfg["password"],
connect_timeout=_TIMEOUT,
autocommit=True,
)
with psycopg.connect(dbname="postgres", **common) as conn:
exists = conn.execute(
"SELECT 1 FROM pg_database WHERE datname = %s", (cfg["database"],)
).fetchone()
if not exists:
conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(cfg["database"])))
with psycopg.connect(dbname=cfg["database"], **common) as conn:
conn.execute("CREATE TABLE IF NOT EXISTS probe (id int)")
def _setup_mysql() -> None:
cfg = _env("WATCHMAN_TEST_MYSQL")
conn = pymysql.connect(
host=cfg["host"],
port=int(cfg["port"]),
user=cfg["user"],
password=cfg["password"],
connect_timeout=_TIMEOUT,
autocommit=True,
)
try:
with conn.cursor() as cur:
cur.execute(f"CREATE DATABASE IF NOT EXISTS `{cfg['database']}`")
cur.execute(f"CREATE TABLE IF NOT EXISTS `{cfg['database']}`.probe (id int)")
finally:
conn.close()
def _setup_sqlserver() -> None:
cfg = _env("WATCHMAN_TEST_SQLSERVER")
conn = pymssql.connect(
server=cfg["host"],
port=cfg["port"],
user=cfg["user"],
password=cfg["password"],
database="master",
login_timeout=_TIMEOUT,
timeout=60,
autocommit=True,
)
try:
cur = conn.cursor()
db = cfg["database"]
cur.execute(f"IF DB_ID(N'{db}') IS NULL CREATE DATABASE [{db}]")
cur.execute(
f"USE [{db}]; IF OBJECT_ID(N'dbo.probe', N'U') IS NULL CREATE TABLE dbo.probe (id int)"
)
finally:
conn.close()
_ENGINES = {
"postgresql": _setup_postgresql,
"mysql": _setup_mysql,
"sqlserver": _setup_sqlserver,
}
def main(argv: list[str]) -> int:
wanted = argv or list(_ENGINES)
unknown = [e for e in wanted if e not in _ENGINES]
if unknown:
print("unknown engine name(s); choose from: " + ", ".join(_ENGINES))
return 2
failed = 0
for name in wanted:
try:
_ENGINES[name]()
print(f"{name}: ok")
except Exception as exc: # noqa: BLE001
# Class name only: driver messages can embed user, host or password hints.
print(f"{name}: failed ({type(exc).__name__})")
failed += 1
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+2 -1
View File
@@ -43,7 +43,8 @@ def main() -> None:
if role == "beat":
from watchman.jobs.celery_app import celery_app
# M01 registers no business schedules; beat must still be startable.
# beat_schedule comes from celery_app (empty unless the datasource health check is
# enabled with a valid cron), so beat stays startable with no business schedule.
celery_app.start(argv=["beat", "--loglevel=INFO"])
return
raise SystemExit(f"unknown role: {role}")
+10 -2
View File
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from watchman.api.routes import auth, health, platform
from watchman.api.routes import auth, datasources, health, platform
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
from watchman.core.errors import AppError, ValidationError
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
@@ -77,6 +77,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
app.include_router(health.router)
app.include_router(auth.router)
app.include_router(platform.router)
app.include_router(datasources.router)
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
@@ -97,7 +98,14 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
status_code=400,
code=40000,
message="Validation failed",
details={"errors": exc.errors()},
# GUARD: drop "input" and "ctx"; they can echo a submitted password or hold
# non-JSON exception objects. Location, type and message are enough.
details={
"errors": [
{key: err[key] for key in ("type", "loc", "msg") if key in err}
for err in exc.errors()
]
},
)
@app.exception_handler(Exception)
@@ -0,0 +1,244 @@
"""Datasource configuration routes under /datasources.
Why: lets the console list, save, disable and test source-database connections.
Boundary: request models forbid unknown fields, so a caller can never send tenant_id, a
connection URL or a test target; responses never carry a password or ciphertext. Business
rules live in watchman.services.datasources.
Depends on the datasource service and the three datasource permission dependencies.
"""
from __future__ import annotations
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
from sqlalchemy.orm import Session
from watchman.auth.principal import (
require_datasource_reader,
require_datasource_tester,
require_datasource_writer,
)
from watchman.core.db import get_db_session
from watchman.core.response import success_body
from watchman.datasources import ProbeCategory
from watchman.services import datasources as service
router = APIRouter(prefix="/datasources", tags=["datasources"])
Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
Text128 = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
# D23: host is only required (non-blank, bounded); no format check, the probe decides.
Host = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=255)]
Port = Annotated[int, Field(ge=1, le=65535)]
# Not stripped: a password may legitimately start or end with a space.
PasswordText = Annotated[str, StringConstraints(max_length=1024)]
CircuitSeconds = Annotated[int, Field(ge=1, le=86400, strict=True)]
CircuitThreshold = Annotated[int, Field(ge=1, le=100, strict=True)]
class DatasourceCreate(BaseModel):
"""Create body. Unknown fields such as tenant_id are rejected with 40000."""
model_config = ConfigDict(extra="forbid")
name: Name
description: Annotated[str, StringConstraints(max_length=2000)] | None = None
kind: str = "database"
engine: str
host: Host
port: Port
database_name: Text128
username: Text128
password: PasswordText = Field(repr=False)
read_only_intent: bool = True
class DatasourceUpdate(BaseModel):
"""Partial update body. Omit password, or send it blank, to keep the stored one."""
model_config = ConfigDict(extra="forbid")
name: Name | None = None
description: Annotated[str, StringConstraints(max_length=2000)] | None = None
kind: str | None = None
engine: str | None = None
host: Host | None = None
port: Port | None = None
database_name: Text128 | None = None
username: Text128 | None = None
password: PasswordText | None = Field(default=None, repr=False)
read_only_intent: bool | None = None
circuit_failure_window_seconds: CircuitSeconds | None = None
circuit_failure_threshold: CircuitThreshold | None = None
circuit_open_cooldown_seconds: CircuitSeconds | None = None
class DraftTestBody(BaseModel):
"""Form values to probe without saving. Blank password + datasource_id = stored secret."""
model_config = ConfigDict(extra="forbid")
datasource_id: str | None = None
kind: str = "database"
engine: str
host: Host
port: Port
database_name: Text128
username: Text128
password: PasswordText | None = Field(default=None, repr=False)
class EmptyBody(BaseModel):
"""Optional body for disable and test; it has no fields, so no target can be sent."""
model_config = ConfigDict(extra="forbid")
def _ok(request: Request, data: Any) -> JSONResponse:
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
@router.get("")
def list_datasources(
request: Request,
usable: bool = False,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List the server tenant's datasources; usable=true keeps enabled, circuit-closed ones."""
rows = service.list_datasources(session, usable_only=usable)
data = {"items": [service.to_public(row) for row in rows]}
# An elapsed cooldown closes the circuit while listing; persist that.
session.commit()
return _ok(request, data)
@router.post("/test-draft")
def test_draft_connection(
request: Request,
body: DraftTestBody,
_: None = Depends(require_datasource_tester),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Probe the form's values. Writes no last_test and does not count toward the circuit.
Declared before the /{datasource_id} routes so the static path always wins.
"""
fields = body.model_dump(exclude={"datasource_id"})
result = service.run_draft_connection_test(session, fields, datasource_id=body.datasource_id)
session.commit()
if result.category is not ProbeCategory.SUCCESS:
raise service.ConnectionTestFailedError(result)
return _ok(request, {"category": result.category.value, "message": result.message})
@router.post("")
def create_datasource(
request: Request,
body: DatasourceCreate,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Create a datasource; the password is encrypted and never returned."""
row = service.create_datasource(session, **body.model_dump())
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{datasource_id}")
def get_datasource(
request: Request,
datasource_id: str,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one datasource."""
data = service.to_public(service.get_datasource(session, datasource_id))
# An elapsed cooldown closes the circuit while reading; persist that.
session.commit()
return _ok(request, data)
@router.patch("/{datasource_id}")
def update_datasource(
request: Request,
datasource_id: str,
body: DatasourceUpdate,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Update the fields that were sent; a blank or missing password keeps the old one."""
row = service.update_datasource(session, datasource_id, body.model_dump(exclude_unset=True))
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/disable")
def disable_datasource(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Disable a datasource. The record stays readable and is never deleted."""
row = service.disable_datasource(session, datasource_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/enable")
def enable_datasource(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Enable a datasource again. Does not touch the circuit state."""
row = service.enable_datasource(session, datasource_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/test")
def test_datasource_connection(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_tester),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Probe the saved connection. The body cannot name a different target."""
row, result = service.run_connection_test(session, datasource_id)
# The outcome is stored for success and failure alike, so commit before replying.
session.commit()
if result.category is not ProbeCategory.SUCCESS:
raise service.ConnectionTestFailedError(result)
return _ok(
request,
{
"id": str(row.id),
"category": result.category.value,
"message": result.message,
"last_test_at": row.last_test_at.isoformat() if row.last_test_at else None,
},
)
@router.get("/{datasource_id}/references")
def get_datasource_references(
request: Request,
datasource_id: str,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return what references this datasource. Nothing does yet, so items is empty."""
return _ok(request, service.list_references(session, datasource_id))
+29 -2
View File
@@ -1,6 +1,7 @@
"""Role checks for the three Watchman permission nodes.
"""Role checks for the Watchman permission nodes.
Decides enter, platform write, and object read from Casdoor role names.
Decides enter, platform write, object read, and the three datasource nodes (read,
write, test) from Casdoor role names.
Depends on semantic errors only; it does not call Casdoor or open a session.
"""
@@ -12,6 +13,10 @@ ENTER_NODE = "perm:app:emp:watchman.enter"
PLATFORM_WRITE_NODE = "perm:data:emp:watchman.platform.write"
OBJECT_READ_NODE = "perm:data:emp:watchman.object.read"
DATASOURCE_READ_NODE = "perm:data:emp:watchman.datasource.read"
DATASOURCE_WRITE_NODE = "perm:data:emp:watchman.datasource.write"
DATASOURCE_TEST_NODE = "perm:data:emp:watchman.datasource.test"
ROLE_ADMIN = "watchman-admin"
ROLE_OPERATOR = "watchman-operator"
ROLE_VIEWER = "watchman-viewer"
@@ -38,6 +43,28 @@ def require_platform_write(role_names: list[str]) -> None:
raise ForbiddenError(permission_node=PLATFORM_WRITE_NODE)
def require_datasource_read(role_names: list[str]) -> None:
"""Allow datasource list, detail and references only for watchman-admin.
Operator, viewer, and an empty or unknown role list are denied with the
datasource read node.
"""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_READ_NODE)
def require_datasource_write(role_names: list[str]) -> None:
"""Allow datasource create, update and disable only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_WRITE_NODE)
def require_datasource_test(role_names: list[str]) -> None:
"""Allow a datasource connection test only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_TEST_NODE)
def require_object_access(role_names: list[str], object_id: str) -> None:
"""Reject every object id until a later module grants row access.
@@ -14,7 +14,12 @@ from urllib.parse import quote
from fastapi import Cookie, Depends, Request
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
from watchman.auth.access import require_platform_write
from watchman.auth.access import (
require_datasource_read,
require_datasource_test,
require_datasource_write,
require_platform_write,
)
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
SessionStore,
@@ -117,3 +122,58 @@ def require_platform_writer(
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
require_platform_write(roles)
def _load_session_roles(
request: Request,
session_token: str | None,
sessions: SessionStore,
directory: RoleDirectory,
) -> list[str]:
"""Return fresh role names for the caller's session, or raise 41000 / 503.
Same session and freshness rules as require_platform_writer: a stale snapshot is
reloaded from Casdoor and, if that fails, the old roles are not used.
"""
token = read_session_token(request, session_token)
if token is None:
raise UnauthorizedError()
now = utc_now()
row = sessions.get(token_hash=hash_cookie_token(token), now=now)
if row is None:
raise UnauthorizedError()
roles = list(row.role_snapshot)
if now - row.role_checked_at >= ROLE_FRESHNESS:
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
return roles
def require_datasource_reader(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject datasource reads unless the session is watchman-admin."""
require_datasource_read(_load_session_roles(request, session_token, sessions, directory))
def require_datasource_writer(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject datasource create, update and disable unless the session is watchman-admin."""
require_datasource_write(_load_session_roles(request, session_token, sessions, directory))
def require_datasource_tester(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject a connection test unless the session is watchman-admin."""
require_datasource_test(_load_session_roles(request, session_token, sessions, directory))
@@ -111,6 +111,37 @@ class Settings(BaseSettings):
hxops_sso_issuer: str = Field(default="", alias="HXOPS_SSO_ISSUER")
hxops_sso_audience: str = Field(default="", alias="HXOPS_SSO_AUDIENCE")
hxops_sso_public_key: str = Field(default="", alias="HXOPS_SSO_PUBLIC_KEY")
# Fernet key for datasource passwords. Deliberately not in REQUIRED_RUNTIME_KEYS:
# only datasource code needs it, so a missing key must not stop unrelated boot.
datasource_key: str = Field(default="", alias="WATCHMAN_DATASOURCE_KEY", repr=False)
# Per-attempt connect timeout and attempt cap for datasource probes. Only timeout and
# unreachable outcomes are retried; the cap keeps a dead source from stalling a request.
datasource_probe_timeout_seconds: float = Field(
default=5.0, gt=0, le=60, alias="WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS"
)
datasource_probe_max_attempts: int = Field(
default=2, ge=1, le=2, alias="WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS"
)
# Scheduled datasource health check (M03 S7). Off by default; the cron string is a
# 5-field Unix expression validated by jobs/ and services/ (invalid means no schedule).
datasource_healthcheck_enabled: bool = Field(
default=False, alias="WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED"
)
datasource_healthcheck_cron: str = Field(
default="", alias="WATCHMAN_DATASOURCE_HEALTHCHECK_CRON"
)
def _env_bool(value: str | None, default: bool = False) -> bool:
"""Parse a boolean env value; unknown text falls back to the (safe) default."""
if value is None or not value.strip():
return default
text = value.strip().lower()
if text in {"1", "true", "yes", "on"}:
return True
if text in {"0", "false", "no", "off"}:
return False
return default
def _settings_from_env_map(env: dict[str, str]) -> Settings:
@@ -141,6 +172,17 @@ def _settings_from_env_map(env: dict[str, str]) -> Settings:
hxops_sso_issuer=env.get("HXOPS_SSO_ISSUER", ""),
hxops_sso_audience=env.get("HXOPS_SSO_AUDIENCE", ""),
hxops_sso_public_key=env.get("HXOPS_SSO_PUBLIC_KEY", ""),
datasource_key=env.get("WATCHMAN_DATASOURCE_KEY", ""),
datasource_probe_timeout_seconds=float(
env.get("WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS", "5") or "5"
),
datasource_probe_max_attempts=int(
env.get("WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS", "2") or "2"
),
datasource_healthcheck_enabled=_env_bool(
env.get("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED")
),
datasource_healthcheck_cron=env.get("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", "").strip(),
)
@@ -0,0 +1,47 @@
"""Symmetric encryption for datasource passwords stored in platform Postgres.
Boundary: only turns plaintext into an opaque token and back; it never logs, caches or
persists either side. Callers decide when decryption is allowed (connection test only).
Depends on the cryptography Fernet recipe and WATCHMAN_DATASOURCE_KEY from Settings.
"""
from __future__ import annotations
from cryptography.fernet import Fernet, InvalidToken
from watchman.core.config import get_settings
KEY_ENV_NAME = "WATCHMAN_DATASOURCE_KEY"
class SecretKeyError(RuntimeError):
"""The datasource key is missing or malformed. Message never carries key material."""
class SecretDecryptError(RuntimeError):
"""Ciphertext cannot be decrypted with the configured key."""
def _load_cipher() -> Fernet:
raw = get_settings().datasource_key.strip()
if not raw or "CHANGE-ME" in raw:
raise SecretKeyError(f"{KEY_ENV_NAME} is not configured")
try:
return Fernet(raw.encode("ascii"))
except (ValueError, UnicodeEncodeError):
# Do not chain: the original error text may echo part of the key.
raise SecretKeyError(f"{KEY_ENV_NAME} is not a valid Fernet key") from None
def encrypt_secret(plaintext: str) -> str:
"""Encrypt a password into a urlsafe-base64 Fernet token."""
return _load_cipher().encrypt(plaintext.encode("utf-8")).decode("ascii")
def decrypt_secret(ciphertext: str) -> str:
"""Decrypt a token produced by encrypt_secret with the current key."""
cipher = _load_cipher()
try:
return cipher.decrypt(ciphertext.encode("ascii")).decode("utf-8")
except (InvalidToken, ValueError):
raise SecretDecryptError("datasource secret cannot be decrypted with the configured key") from None
@@ -0,0 +1,22 @@
"""Datasource connectors: connectivity probes against external source databases.
Boundary: probing only (SELECT 1 / driver ping, bounded by a connect timeout); no
persistence, no API, no query execution. Callers pass a decrypted password in memory.
Depends on the psycopg, PyMySQL and pymssql drivers.
"""
from watchman.datasources.probe import (
ProbeCategory,
ProbeResult,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
__all__ = [
"ProbeCategory",
"ProbeResult",
"ProbeTarget",
"UnsupportedDataSourceError",
"probe_datasource",
]
@@ -0,0 +1,307 @@
"""Connectivity probe for PostgreSQL, MySQL and SQL Server source databases.
Why: users need to know whether a saved datasource works, and why not, without the
platform ever running DDL/DML on a customer database or leaking credentials through
driver error text. Every outcome collapses into five categories with fixed messages.
Boundary: opens one short-lived connection and runs only SELECT 1; it does not decrypt
secrets, persist results, or run user queries. Unknown kind/engine raises before any
socket is opened.
Depends on psycopg, PyMySQL and pymssql; the timeout is the drivers' own connect timeout.
"""
from __future__ import annotations
import logging
import math
import socket
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Callable
import psycopg
import pymssql
import pymysql
logger = logging.getLogger("watchman.datasources.probe")
DEFAULT_TIMEOUT_SECONDS = 5.0
# MySQL: only 1044/1045 (access denied) are positive auth evidence. Other server-side
# errors (<2000, e.g. 1049 unknown database, 1130 host not allowed) are "rejected";
# 2xxx are client/network errors.
_MYSQL_AUTH_CODES = frozenset({1044, 1045})
_MYSQL_SERVER_ERROR_LIMIT = 2000
# Positive auth evidence for PostgreSQL. The Chinese phrase is the server's own message
# when lc_messages is zh_CN; it only survives decoding with a GB-family client_encoding.
_PG_AUTH_KEYWORDS = ("password authentication failed", "authentication failed", "认证失败", "no pg_hba.conf entry")
_PG_MISSING_KEYWORDS = ("does not exist", "不存在")
_REPLACEMENT_CHAR = "\ufffd"
class ProbeCategory(StrEnum):
SUCCESS = "success"
AUTH_FAILED = "auth_failed"
TIMEOUT = "timeout"
UNREACHABLE = "unreachable"
# Server reached and answered, but not with evidence of a credential problem
# (e.g. database missing): never report this as auth_failed.
REJECTED = "rejected"
# Fixed texts: driver messages often embed host, user or parts of the connection string.
_MESSAGES: dict[ProbeCategory, str] = {
ProbeCategory.SUCCESS: "connection succeeded",
ProbeCategory.AUTH_FAILED: "authentication failed",
ProbeCategory.TIMEOUT: "connection timed out",
ProbeCategory.UNREACHABLE: "data source unreachable",
ProbeCategory.REJECTED: "data source rejected the connection",
}
@dataclass(frozen=True)
class ProbeResult:
category: ProbeCategory
message: str
class UnsupportedDataSourceError(ValueError):
"""Kind or engine has no connector. The message is fixed and carries no input values."""
def __init__(self) -> None:
super().__init__("unsupported datasource kind or engine")
@dataclass(frozen=True)
class ProbeTarget:
"""Connection parameters for one probe. The password is excluded from repr."""
engine: str
host: str
port: int
database: str
username: str
password: str = field(repr=False)
kind: str = "database"
def _result(category: ProbeCategory) -> ProbeResult:
return ProbeResult(category=category, message=_MESSAGES[category])
def _whole_seconds(timeout: float) -> int:
# libpq and FreeTDS only take whole seconds; round up so the bound is never exceeded
# in the shorter direction, and never pass 0 (which means "wait forever").
return max(1, math.ceil(timeout))
def _chain_has_timeout(exc: BaseException) -> bool:
"""True if the exception or any chained cause is a socket-level timeout."""
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
seen.add(id(current))
if isinstance(current, TimeoutError):
return True
current = current.__cause__ or current.__context__
return False
def _tcp_reachability(host: str, port: int, timeout: float) -> str:
"""Return "open", "refused" or "timeout" for a bare TCP connect; sends no payload."""
try:
with socket.create_connection((host, port), timeout=timeout):
return "open"
except TimeoutError:
return "timeout"
except OSError:
# Refused, no route, DNS failure: all mean nothing is listening there for us.
return "refused"
def _classify_after_failure(
target: ProbeTarget,
timeout: float,
driver_timed_out: bool,
is_auth_failure: Callable[[], bool],
) -> ProbeCategory:
"""Classify a driver connect failure that carries no trustworthy error code.
libpq and FreeTDS (pymssql) both lose the distinction between refused, blackholed and
rejected-login: PG has no SQLSTATE on connect failures and localizes the server text,
pymssql reuses the previous call's error number, and on Windows both wait out the whole
connect timeout on a refused port. A bare TCP connect with the same bound is
language-independent, so it decides reachability; a failed probe costs at most 2x timeout.
"""
reach = _tcp_reachability(target.host, target.port, timeout)
if reach == "refused":
return ProbeCategory.UNREACHABLE
if reach == "timeout":
return ProbeCategory.TIMEOUT
# Port is open: a driver-level stall is a genuine timeout. Otherwise the server answered;
# call it auth_failed only on positive evidence, else rejected (never guess).
if driver_timed_out:
return ProbeCategory.TIMEOUT
return ProbeCategory.AUTH_FAILED if is_auth_failure() else ProbeCategory.REJECTED
def _pg_connect(target: ProbeTarget, timeout: float, client_encoding: str):
return psycopg.connect(
host=target.host,
port=target.port,
dbname=target.database,
user=target.username,
password=target.password,
connect_timeout=_whole_seconds(timeout),
client_encoding=client_encoding,
autocommit=True,
)
def _pg_is_auth_failure(exc: psycopg.Error, target: ProbeTarget, timeout: float) -> bool:
"""Decide from the server's failure text; the text is inspected, never stored or logged.
A UTF8 client turns a non-UTF8 server message (here GB18030 Chinese) into U+FFFD, which
hides every keyword. When UTF8 text is undecided, reconnect once with GB18030 purely to
read it. Absence of positive evidence means "not auth".
"""
text = str(exc).lower()
if any(k in text for k in _PG_AUTH_KEYWORDS):
return True
if _REPLACEMENT_CHAR not in text and any(k in text for k in _PG_MISSING_KEYWORDS):
return False
try:
_pg_connect(target, timeout, "GB18030").close()
return False
except psycopg.Error as retry_exc:
retry_text = str(retry_exc).lower()
return any(k in retry_text for k in _PG_AUTH_KEYWORDS)
except Exception: # noqa: BLE001
return False
def _probe_postgresql(target: ProbeTarget, timeout: float) -> ProbeCategory:
try:
with _pg_connect(target, timeout, "UTF8") as conn:
conn.execute("SELECT 1")
return ProbeCategory.SUCCESS
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if sqlstate.startswith("28"):
return ProbeCategory.AUTH_FAILED
timed_out = isinstance(exc, psycopg.errors.ConnectionTimeout) or _chain_has_timeout(exc)
return _classify_after_failure(
target, timeout, timed_out, lambda: _pg_is_auth_failure(exc, target, timeout)
)
def _probe_mysql(target: ProbeTarget, timeout: float) -> ProbeCategory:
try:
conn = pymysql.connect(
host=target.host,
port=target.port,
user=target.username,
password=target.password,
database=target.database,
connect_timeout=timeout,
read_timeout=timeout,
write_timeout=timeout,
)
try:
with conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
finally:
conn.close()
return ProbeCategory.SUCCESS
except pymysql.err.MySQLError as exc:
code = exc.args[0] if exc.args and isinstance(exc.args[0], int) else None
if code in _MYSQL_AUTH_CODES:
return ProbeCategory.AUTH_FAILED
if _chain_has_timeout(exc):
return ProbeCategory.TIMEOUT
if code is not None and code < _MYSQL_SERVER_ERROR_LIMIT:
# The server answered (e.g. 1049 unknown database): reachable, not an auth problem.
return ProbeCategory.REJECTED
return ProbeCategory.UNREACHABLE
except OSError as exc:
return ProbeCategory.TIMEOUT if _chain_has_timeout(exc) else ProbeCategory.UNREACHABLE
def _probe_sqlserver(target: ProbeTarget, timeout: float) -> ProbeCategory:
seconds = _whole_seconds(timeout)
try:
conn = pymssql.connect(
server=target.host,
port=str(target.port),
user=target.username,
password=target.password,
database=target.database,
login_timeout=seconds,
timeout=seconds,
)
try:
cur = conn.cursor()
cur.execute("SELECT 1")
cur.fetchone()
finally:
conn.close()
return ProbeCategory.SUCCESS
except pymssql.Error as exc:
# DB-Lib 20009 = cannot reach server, 20003 = connection timed out. The numeric
# error code is deliberately ignored: pymssql can report a stale one.
parts = exc.args[0] if len(exc.args) == 1 and isinstance(exc.args[0], tuple) else exc.args
text = " ".join(
a.decode("utf-8", "replace") if isinstance(a, bytes) else str(a) for a in parts
).lower()
stalled = "timed out" in text or "unable to connect" in text or _chain_has_timeout(exc)
# 4060 ("Cannot open database ... The login failed.") means the database is missing
# or inaccessible, not that the credentials were wrong, so it is not auth evidence.
is_auth = "login failed" in text and "cannot open database" not in text
return _classify_after_failure(target, timeout, stalled, lambda: is_auth)
_RETRYABLE = frozenset({ProbeCategory.TIMEOUT, ProbeCategory.UNREACHABLE})
_CONNECTORS: dict[str, Callable[[ProbeTarget, float], ProbeCategory]] = {
"postgresql": _probe_postgresql,
"mysql": _probe_mysql,
"sqlserver": _probe_sqlserver,
}
def probe_datasource(
target: ProbeTarget,
*,
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
max_attempts: int = 1,
) -> ProbeResult:
"""Probe one database target and classify the outcome.
Raises UnsupportedDataSourceError for a non-database kind or unknown engine, without
opening a socket. Never raises for connection failures. With max_attempts > 1 only
timeout and unreachable outcomes are retried; auth_failed and rejected need a config
change, so they return at once.
"""
connector = _CONNECTORS.get(target.engine) if target.kind == "database" else None
if connector is None:
raise UnsupportedDataSourceError()
category = ProbeCategory.UNREACHABLE
for _attempt in range(max(1, max_attempts)):
try:
category = connector(target, timeout_seconds)
except Exception: # noqa: BLE001
# Unexpected driver failure: do not surface its text (may include user or host).
category = ProbeCategory.UNREACHABLE
if category not in _RETRYABLE:
break
# Log only non-secret identifiers; username is omitted because it can be ambiguous.
logger.info(
"datasource probe engine=%s host=%s port=%s database=%s category=%s",
target.engine,
target.host,
target.port,
target.database,
category.value,
)
return _result(category)
@@ -6,9 +6,14 @@ Probe tasks must not write platform audit or business occurrence facts.
from __future__ import annotations
from typing import Any
from celery import Celery
from watchman.core.config import get_settings
from watchman.core.db import session_scope
from watchman.jobs.schedule import DATASOURCE_HEALTHCHECK_TASK, build_beat_schedule
from watchman.services.datasource_healthcheck import run_datasource_healthcheck
def create_celery_app() -> Celery:
@@ -25,6 +30,8 @@ def create_celery_app() -> Celery:
timezone="UTC",
enable_utc=True,
worker_hijack_root_logger=False,
# Empty unless the health check is enabled with a valid cron.
beat_schedule=build_beat_schedule(settings),
)
return app
@@ -32,6 +39,16 @@ def create_celery_app() -> Celery:
celery_app = create_celery_app()
@celery_app.task(name=DATASOURCE_HEALTHCHECK_TASK)
def datasource_healthcheck() -> dict[str, Any]:
"""Run the scheduled datasource health check for the server tenant.
The body re-checks the enabled flag and cron, so a stale schedule is a no-op.
"""
with session_scope() as session:
return run_datasource_healthcheck(session).as_dict()
@celery_app.task(name="watchman.probe.ping")
def probe_ping() -> dict[str, str]:
"""Return a static probe payload with no database side effects."""
@@ -0,0 +1,31 @@
"""Beat schedule entries for business jobs (thin adapter over Celery Beat).
Why: the health check must be scheduled only when it is switched on and its cron is
valid, and bad configuration must leave beat startable with no entry.
Boundary: no scheduler of our own; this only builds the beat_schedule dict. Cron
validation and the crontab mapping live in services.cron.
Depends on core.config and services.cron.
"""
from __future__ import annotations
from typing import Any
from watchman.core.config import Settings
from watchman.services.cron import parse_unix_cron, to_celery_crontab
DATASOURCE_HEALTHCHECK_TASK = "watchman.datasources.healthcheck"
DATASOURCE_HEALTHCHECK_ENTRY = "datasource-healthcheck"
def build_beat_schedule(settings: Settings) -> dict[str, dict[str, Any]]:
"""Return beat entries for the given settings; empty when nothing should run."""
schedule: dict[str, dict[str, Any]] = {}
if settings.datasource_healthcheck_enabled:
fields = parse_unix_cron(settings.datasource_healthcheck_cron)
if fields is not None:
schedule[DATASOURCE_HEALTHCHECK_ENTRY] = {
"task": DATASOURCE_HEALTHCHECK_TASK,
"schedule": to_celery_crontab(fields),
}
return schedule
@@ -1,6 +1,7 @@
"""SQLAlchemy models for the Watchman service package."""
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent, RunRecord
__all__ = ["AuthSession", "AuditEvent", "RunRecord"]
__all__ = ["AuthSession", "AuditEvent", "DataSource", "RunRecord"]
@@ -0,0 +1,135 @@
"""Tenant-scoped datasource metadata with an encrypted password.
Boundary: persistence and the kind/engine whitelist only; no connection logic and no
plaintext secrets. Kind and engine stay free-form strings in the table so later phases
can widen them by relaxing the CHECK constraints instead of changing the column type.
Depends on SQLAlchemy and the shared Watchman declarative base.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
Integer,
String,
Text,
UniqueConstraint,
func,
text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from watchman.models.base import Base
ALLOWED_KINDS = frozenset({"database"})
ALLOWED_ENGINES = frozenset({"postgresql", "mysql", "sqlserver"})
def validate_kind_engine(kind: str, engine: str) -> None:
"""Reject unsupported kind or engine before touching the database.
The CHECK constraints remain the backstop; this gives callers a readable error first.
"""
if kind not in ALLOWED_KINDS:
raise ValueError(f"unsupported datasource kind: {kind!r}")
if engine not in ALLOWED_ENGINES:
raise ValueError(f"unsupported datasource engine: {engine!r}")
class DataSource(Base):
"""A configured source database; the password is stored only as Fernet ciphertext."""
__tablename__ = "data_sources"
__table_args__ = (
UniqueConstraint("tenant_id", "name", name="uq_data_sources_tenant_name"),
CheckConstraint("kind = 'database'", name="ck_data_sources_kind"),
CheckConstraint(
"engine IN ('postgresql','mysql','sqlserver')",
name="ck_data_sources_engine",
),
CheckConstraint("port BETWEEN 1 AND 65535", name="ck_data_sources_port"),
CheckConstraint(
"circuit_failure_window_seconds BETWEEN 1 AND 86400",
name="ck_data_sources_circuit_window",
),
CheckConstraint(
"circuit_failure_threshold BETWEEN 1 AND 100",
name="ck_data_sources_circuit_threshold",
),
CheckConstraint(
"circuit_open_cooldown_seconds BETWEEN 1 AND 86400",
name="ck_data_sources_circuit_cooldown",
),
CheckConstraint(
"circuit_state IN ('closed','open')", name="ck_data_sources_circuit_state"
),
CheckConstraint("circuit_failure_count >= 0", name="ck_data_sources_circuit_count"),
)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
kind: Mapped[str] = mapped_column(String(32), nullable=False)
engine: Mapped[str] = mapped_column(String(32), nullable=False)
host: Mapped[str] = mapped_column(String(255), nullable=False)
port: Mapped[int] = mapped_column(Integer, nullable=False)
database_name: Mapped[str] = mapped_column(String(128), nullable=False)
username: Mapped[str] = mapped_column(String(128), nullable=False)
secret_ciphertext: Mapped[str] = mapped_column(Text, nullable=False)
read_only_intent: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("true")
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
last_test_category: Mapped[str | None] = mapped_column(String(32), nullable=True)
last_test_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_test_message: Mapped[str | None] = mapped_column(String(255), nullable=True)
# Circuit breaker: independent of `enabled`; an open circuit never flips it.
circuit_failure_window_seconds: Mapped[int] = mapped_column(
Integer, nullable=False, default=300, server_default=text("300")
)
circuit_failure_threshold: Mapped[int] = mapped_column(
Integer, nullable=False, default=3, server_default=text("3")
)
circuit_open_cooldown_seconds: Mapped[int] = mapped_column(
Integer, nullable=False, default=600, server_default=text("600")
)
circuit_state: Mapped[str] = mapped_column(
String(16), nullable=False, default="closed", server_default=text("'closed'")
)
circuit_opened_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
circuit_failure_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default=text("0")
)
circuit_window_started_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
)
def __repr__(self) -> str:
# GUARD: never include secret_ciphertext, even though it is encrypted.
return (
f"DataSource(id={self.id!s}, tenant_id={self.tenant_id!r}, name={self.name!r}, "
f"engine={self.engine!r})"
)
@@ -0,0 +1,70 @@
"""Thin Cron validation shared by the scheduler adapter and job bodies.
Why: a configured schedule string must mean the same thing to the validator and to
Celery Beat, and a bad string must degrade to "no schedule" instead of breaking boot.
Boundary: croniter validates and Celery's crontab executes; nothing here parses cron
itself. Only a conservative subset is accepted (5 fields, digits and * / , - only) and
day-of-month plus day-of-week may not both be restricted, because croniter ORs them while
Celery ANDs them (docs/cron-reuse.md section 5).
Depends on croniter and celery.schedules.
"""
from __future__ import annotations
import re
from typing import NamedTuple
from celery.schedules import crontab
from croniter import croniter
_FIELD_PATTERN = re.compile(r"^[0-9*/,\-]+$")
_MAX_LENGTH = 100
class CronFields(NamedTuple):
"""The five validated Unix cron fields."""
minute: str
hour: str
day_of_month: str
month_of_year: str
day_of_week: str
def parse_unix_cron(expression: str | None) -> CronFields | None:
"""Return the cron fields, or None when the expression is not an accepted 5-field cron."""
if not isinstance(expression, str):
return None
text = expression.strip()
if not text or len(text) > _MAX_LENGTH:
return None
parts = text.split()
if len(parts) != 5 or not all(_FIELD_PATTERN.match(part) for part in parts):
return None
fields = CronFields(*parts)
# Semantics differ when both day fields are restricted (OR vs AND): refuse, not guess.
if fields.day_of_month != "*" and fields.day_of_week != "*":
return None
try:
if not croniter.is_valid(" ".join(parts)):
return None
# The executing side must accept the same fields.
to_celery_crontab(fields)
except Exception: # noqa: BLE001 - any library rejection means "invalid"
return None
return fields
def is_valid_unix_cron(expression: str | None) -> bool:
return parse_unix_cron(expression) is not None
def to_celery_crontab(fields: CronFields) -> crontab:
"""Map validated fields onto a Celery crontab schedule."""
return crontab(
minute=fields.minute,
hour=fields.hour,
day_of_month=fields.day_of_month,
month_of_year=fields.month_of_year,
day_of_week=fields.day_of_week,
)
@@ -0,0 +1,94 @@
"""Scheduled datasource health check orchestration (M03 S7, D23).
Why: a source that quietly broke should show a failed last_test (and open its circuit
after repeated failures) before someone runs a query against it.
Boundary: only enabled, circuit-closed sources of the server tenant are probed, one at a
time, through the same probe path as the saved connection test; enabled is never
changed and nothing is sent to WeCom. Each source commits on its own so no transaction
stays open during a network probe. Callers (the Celery task) own the session.
Depends on services.datasources, services.cron and core.config.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any
from sqlalchemy.orm import Session
from watchman.core.config import Settings, get_settings
from watchman.core.errors import AppError
from watchman.datasources import ProbeCategory
from watchman.services.cron import is_valid_unix_cron
from watchman.services.datasources import list_datasources, run_healthcheck_probe
logger = logging.getLogger(__name__)
SKIP_DISABLED = "healthcheck_disabled"
SKIP_INVALID_CRON = "invalid_cron"
@dataclass
class HealthcheckSummary:
"""Counts only; never hosts, names or error text."""
skipped_reason: str | None = None
checked: int = 0
succeeded: int = 0
failed: int = 0
skipped: int = 0
errors: int = 0
categories: dict[str, int] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
return {
"skipped_reason": self.skipped_reason,
"checked": self.checked,
"succeeded": self.succeeded,
"failed": self.failed,
"skipped": self.skipped,
"errors": self.errors,
"categories": dict(self.categories),
}
def run_datasource_healthcheck(
session: Session, *, settings: Settings | None = None
) -> HealthcheckSummary:
"""Probe every enabled, circuit-closed datasource and record the outcomes."""
current = settings or get_settings()
summary = HealthcheckSummary()
if not current.datasource_healthcheck_enabled:
summary.skipped_reason = SKIP_DISABLED
return summary
if not is_valid_unix_cron(current.datasource_healthcheck_cron):
summary.skipped_reason = SKIP_INVALID_CRON
return summary
# Listing closes elapsed cooldowns; commit persists that and ends the read transaction.
candidate_ids = [str(row.id) for row in list_datasources(session, usable_only=True)]
session.commit()
for datasource_id in candidate_ids:
try:
result = run_healthcheck_probe(session, datasource_id)
session.commit()
except AppError:
# One broken source (unsupported engine, unusable secret) must not stop the rest.
session.rollback()
summary.errors += 1
logger.warning("datasource healthcheck error id=%s", datasource_id)
continue
if result is None:
summary.skipped += 1
continue
summary.checked += 1
summary.categories[result.category.value] = (
summary.categories.get(result.category.value, 0) + 1
)
if result.category is ProbeCategory.SUCCESS:
summary.succeeded += 1
else:
summary.failed += 1
return summary
@@ -0,0 +1,600 @@
"""Datasource configuration service: CRUD, disable, connection test and audit.
Why: the console needs to save source-database connections without the API layer ever
touching plaintext passwords or deciding tenant scope.
Boundary: tenant comes only from server settings; the password is encrypted on write and
decrypted only inside test_datasource; no public dict carries a password, ciphertext or
connection string. Callers (routes) own the final commit, except test_datasource, which
commits once before the network call so no transaction stays open during the probe.
Depends on the DataSource model, core.secrets, datasources.probe and create_audit_event.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from watchman.core.secrets import SecretDecryptError, SecretKeyError, decrypt_secret, encrypt_secret
from watchman.datasources import (
ProbeCategory,
ProbeResult,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.models.datasource import DataSource, validate_kind_engine
from watchman.services.platform_records import create_audit_event
# Only these probe categories are worth retrying; the others need a config change.
RETRYABLE_CATEGORIES = frozenset({ProbeCategory.TIMEOUT, ProbeCategory.UNREACHABLE})
CIRCUIT_CLOSED = "closed"
CIRCUIT_OPEN = "open"
# Allowed ranges for the per-source circuit parameters (mirrored by CHECK constraints).
_CIRCUIT_RANGES: dict[str, tuple[int, int]] = {
"circuit_failure_window_seconds": (1, 86400),
"circuit_failure_threshold": (1, 100),
"circuit_open_cooldown_seconds": (1, 86400),
}
# Plain columns a PATCH may change. The password is handled separately and enabled is
# only changed by enable_datasource / disable_datasource.
_UPDATABLE_FIELDS = (
"name",
"description",
"kind",
"engine",
"host",
"port",
"database_name",
"username",
"read_only_intent",
"circuit_failure_window_seconds",
"circuit_failure_threshold",
"circuit_open_cooldown_seconds",
)
# Fields (besides the password) whose change invalidates the stored test result.
_CONNECTION_FIELDS = ("engine", "host", "port", "database_name", "username")
class DatasourceSecretUnavailableError(AppError):
"""The stored password cannot be used (key missing or changed). Message is fixed."""
def __init__(self) -> None:
super().__init__(
"Datasource secret is unavailable",
code=50000,
http_status=500,
details={"reason": "secret_unavailable"},
)
class ConnectionTestFailedError(AppError):
"""A connection test ran and did not succeed.
The message is the fixed probe text; details carry only the category, never driver text.
"""
def __init__(self, result: ProbeResult) -> None:
super().__init__(
result.message,
code=40000,
http_status=400,
details={"category": result.category.value},
retryable=result.category in RETRYABLE_CATEGORIES,
)
def _now() -> datetime:
return datetime.now(timezone.utc)
def _tenant_id() -> str:
# GUARD: tenant is never taken from a request.
return get_settings().tenant_id
def _isoformat(value: datetime | None) -> str | None:
return value.isoformat() if value is not None else None
def _circuit_open_until(row: DataSource) -> datetime | None:
if row.circuit_state != CIRCUIT_OPEN or row.circuit_opened_at is None:
return None
return row.circuit_opened_at + timedelta(seconds=row.circuit_open_cooldown_seconds)
def to_public(row: DataSource) -> dict[str, Any]:
"""Serialize a datasource for API responses.
Exposes only whether a password is stored; the ciphertext and any connection
string are never included. circuit_state is the stored state; circuit_open_until is
set only while it is open (an elapsed value means the next usability check closes it).
"""
return {
"id": str(row.id),
"name": row.name,
"description": row.description,
"kind": row.kind,
"engine": row.engine,
"host": row.host,
"port": row.port,
"database_name": row.database_name,
"username": row.username,
"secret_configured": bool(row.secret_ciphertext),
"read_only_intent": row.read_only_intent,
"enabled": row.enabled,
"last_test_category": row.last_test_category,
"last_test_at": _isoformat(row.last_test_at),
"last_test_message": row.last_test_message,
"circuit_state": row.circuit_state,
"circuit_opened_at": _isoformat(row.circuit_opened_at),
"circuit_open_until": _isoformat(_circuit_open_until(row)),
"circuit_failure_window_seconds": row.circuit_failure_window_seconds,
"circuit_failure_threshold": row.circuit_failure_threshold,
"circuit_open_cooldown_seconds": row.circuit_open_cooldown_seconds,
"created_at": _isoformat(row.created_at),
"updated_at": _isoformat(row.updated_at),
}
def _parse_id(datasource_id: str) -> uuid.UUID:
try:
return uuid.UUID(datasource_id)
except ValueError:
# An id that cannot exist is the same as an unknown id.
raise NotFoundError("Datasource not found") from None
def _get_row(
session: Session, datasource_id: str, *, refresh: bool = False, lock: bool = False
) -> DataSource:
"""Load one datasource of the server tenant or raise 404 (also for other tenants).
lock=True takes a row lock (and refreshes) so circuit counters are not lost to a race.
"""
statement = select(DataSource).where(
DataSource.id == _parse_id(datasource_id),
DataSource.tenant_id == _tenant_id(),
)
if refresh or lock:
statement = statement.execution_options(populate_existing=True)
if lock:
statement = statement.with_for_update()
row = session.scalar(statement)
if row is None:
raise NotFoundError("Datasource not found")
return row
def _check_kind_engine(kind: str, engine: str) -> None:
try:
validate_kind_engine(kind, engine)
except ValueError:
# Fixed text: do not echo the caller's value.
raise ValidationError(
"Unsupported datasource kind or engine",
details={"fields": ["kind", "engine"]},
) from None
def _check_circuit_params(values: dict[str, Any]) -> None:
bad = [
field
for field, (low, high) in _CIRCUIT_RANGES.items()
if values.get(field) is not None
and (
isinstance(values[field], bool)
or not isinstance(values[field], int)
or not low <= values[field] <= high
)
]
if bad:
raise ValidationError("Circuit parameter out of range", details={"fields": bad})
def _ensure_name_free(session: Session, name: str, *, exclude_id: uuid.UUID | None = None) -> None:
statement = select(DataSource.id).where(
DataSource.tenant_id == _tenant_id(),
DataSource.name == name,
)
if exclude_id is not None:
statement = statement.where(DataSource.id != exclude_id)
if session.scalar(statement) is not None:
raise ConflictError("Datasource name already exists", details={"reason": "duplicate_name"})
def _flush_unique(session: Session) -> None:
"""Flush, turning a racing duplicate-name insert or update into the same 409."""
try:
with session.begin_nested():
session.flush()
except IntegrityError:
raise ConflictError(
"Datasource name already exists", details={"reason": "duplicate_name"}
) from None
def _audit(session: Session, action: str, row: DataSource, **extra: Any) -> None:
"""Write an audit event with a server-generated key and a credential-free payload."""
payload = {"id": str(row.id), "name": row.name, "engine": row.engine, **extra}
create_audit_event(
session,
action=action,
payload=payload,
idempotency_key=f"{action}:{uuid.uuid4().hex}",
)
def list_datasources(session: Session, *, usable_only: bool = False) -> list[DataSource]:
"""Return datasources of the server tenant, oldest first.
Every returned row first has an elapsed circuit cooldown closed (time only, no probe),
so the exposed circuit state is never stale; the caller commits to persist that.
usable_only then keeps rows that are enabled and whose circuit is closed.
"""
rows = list(
session.scalars(
select(DataSource)
.where(DataSource.tenant_id == _tenant_id())
.order_by(DataSource.created_at, DataSource.name)
)
)
now = _now()
for row in rows:
_close_if_cooled_down(row, now)
if not usable_only:
return rows
return [row for row in rows if row.enabled and row.circuit_state != CIRCUIT_OPEN]
def get_datasource(session: Session, datasource_id: str) -> DataSource:
"""Return one datasource or raise 404.
An elapsed circuit cooldown is closed first (the caller commits to persist it), so
the exposed circuit state matches what assert_usable would decide.
"""
row = _get_row(session, datasource_id)
_close_if_cooled_down(row, _now())
return row
def create_datasource(
session: Session,
*,
name: str,
description: str | None,
kind: str,
engine: str,
host: str,
port: int,
database_name: str,
username: str,
password: str,
read_only_intent: bool,
) -> DataSource:
"""Create an enabled datasource with an encrypted password and write the audit event."""
_check_kind_engine(kind, engine)
if not password.strip():
raise ValidationError("Password is required", details={"fields": ["password"]})
_ensure_name_free(session, name)
now = _now()
row = DataSource(
tenant_id=_tenant_id(),
name=name,
description=description,
kind=kind,
engine=engine,
host=host,
port=port,
database_name=database_name,
username=username,
secret_ciphertext=encrypt_secret(password),
read_only_intent=read_only_intent,
enabled=True,
circuit_failure_window_seconds=300,
circuit_failure_threshold=3,
circuit_open_cooldown_seconds=600,
circuit_state=CIRCUIT_CLOSED,
circuit_failure_count=0,
created_at=now,
updated_at=now,
)
session.add(row)
_flush_unique(session)
_audit(session, "datasource.create", row)
return row
def update_datasource(session: Session, datasource_id: str, changes: dict[str, Any]) -> DataSource:
"""Apply a partial update. A missing or blank password keeps the stored ciphertext."""
row = _get_row(session, datasource_id)
# Only description may be cleared; an explicit null elsewhere is a caller mistake.
nulled = [f for f in _UPDATABLE_FIELDS if f != "description" and f in changes and changes[f] is None]
if nulled:
raise ValidationError("Fields cannot be null", details={"fields": nulled})
_check_circuit_params(changes)
password = changes.get("password")
new_kind = changes.get("kind", row.kind)
new_engine = changes.get("engine", row.engine)
_check_kind_engine(new_kind, new_engine)
if "name" in changes and changes["name"] != row.name:
_ensure_name_free(session, changes["name"], exclude_id=row.id)
# A changed connection target or credential makes the last test result describe an
# old configuration, so it is cleared; name or description edits keep it.
connection_changed = any(
field in changes and changes[field] != getattr(row, field) for field in _CONNECTION_FIELDS
)
for field in _UPDATABLE_FIELDS:
if field in changes:
setattr(row, field, changes[field])
if isinstance(password, str) and password.strip():
row.secret_ciphertext = encrypt_secret(password)
connection_changed = True
if connection_changed:
row.last_test_category = None
row.last_test_at = None
row.last_test_message = None
row.updated_at = _now()
_flush_unique(session)
_audit(session, "datasource.update", row)
return row
def disable_datasource(session: Session, datasource_id: str) -> DataSource:
"""Mark a datasource disabled. The row stays readable; it is never deleted."""
row = _get_row(session, datasource_id)
row.enabled = False
row.updated_at = _now()
session.flush()
_audit(session, "datasource.disable", row)
return row
def enable_datasource(session: Session, datasource_id: str) -> DataSource:
"""Mark a datasource enabled again. The circuit state is left untouched."""
row = _get_row(session, datasource_id)
row.enabled = True
row.updated_at = _now()
session.flush()
_audit(session, "datasource.enable", row)
return row
def _close_circuit(row: DataSource) -> None:
row.circuit_state = CIRCUIT_CLOSED
row.circuit_opened_at = None
row.circuit_failure_count = 0
row.circuit_window_started_at = None
def _close_if_cooled_down(row: DataSource, now: datetime) -> bool:
"""Close an open circuit whose cooldown has elapsed (time only, no probe). True if closed."""
until = _circuit_open_until(row)
if row.circuit_state == CIRCUIT_OPEN and (until is None or now >= until):
_close_circuit(row)
return True
return False
def assert_usable(session: Session, target: DataSource | str) -> DataSource:
"""Raise 409 unless the datasource is enabled and its circuit lets traffic through.
reason=disabled for a disabled source, reason=circuit_open while the cooldown runs.
An elapsed cooldown closes the circuit (the caller commits) and the call passes.
"""
row = _get_row(session, target) if isinstance(target, str) else target
if not row.enabled:
raise ConflictError("Datasource is disabled", details={"reason": "disabled"})
now = _now()
_close_if_cooled_down(row, now)
if row.circuit_state == CIRCUIT_OPEN:
until = _circuit_open_until(row)
raise ConflictError(
"Datasource circuit is open",
details={"reason": "circuit_open", "circuit_open_until": _isoformat(until)},
)
return row
def record_probe_outcome(
session: Session,
row: DataSource,
result: ProbeResult,
*,
update_last_test: bool = True,
) -> bool:
"""Account one persisted probe against the circuit. Returns True if it opened it.
Only saved-connection tests and health checks call this; draft tests never do. Any
non-success category (auth_failed included) is a failure. Failures are counted from
the start of a window of circuit_failure_window_seconds; a success while closed
resets the count. The caller holds a locked, fresh row and commits.
"""
now = _now()
if update_last_test:
row.last_test_category = result.category.value
row.last_test_at = now
row.last_test_message = result.message
row.updated_at = now
opened = False
if row.circuit_state == CIRCUIT_CLOSED:
if result.category is ProbeCategory.SUCCESS:
row.circuit_failure_count = 0
row.circuit_window_started_at = None
else:
started = row.circuit_window_started_at
window = timedelta(seconds=row.circuit_failure_window_seconds)
if started is None or now - started > window:
started = now
row.circuit_failure_count = 0
row.circuit_window_started_at = started
row.circuit_failure_count += 1
if row.circuit_failure_count >= row.circuit_failure_threshold:
row.circuit_state = CIRCUIT_OPEN
row.circuit_opened_at = now
opened = True
session.flush()
if opened:
_audit(
session,
"datasource.circuit_open",
row,
category=result.category.value,
failure_count=row.circuit_failure_count,
)
return opened
def list_references(session: Session, datasource_id: str) -> dict[str, Any]:
"""Return the references to a datasource. No module references datasources yet."""
row = _get_row(session, datasource_id)
return {"id": str(row.id), "items": []}
def _probe(target: ProbeTarget) -> ProbeResult:
"""Run one probe with the configured timeout and attempt cap."""
settings = get_settings()
try:
return probe_datasource(
target,
timeout_seconds=settings.datasource_probe_timeout_seconds,
max_attempts=settings.datasource_probe_max_attempts,
)
except UnsupportedDataSourceError:
raise ValidationError(
"Unsupported datasource kind or engine",
details={"fields": ["kind", "engine"]},
) from None
def _decrypt_stored(row: DataSource) -> str:
try:
return decrypt_secret(row.secret_ciphertext)
except (SecretKeyError, SecretDecryptError):
raise DatasourceSecretUnavailableError() from None
def run_connection_test(session: Session, datasource_id: str) -> tuple[DataSource, ProbeResult]:
"""Probe the saved connection, record last_test and circuit accounting; the caller commits.
The target is built only from the stored row and its decrypted password. A disabled
or circuit-open datasource is refused with 409 before the password is decrypted or any
socket opens. The outcome (including a circuit that opens because of it) is persisted
for success and failure alike.
"""
row = assert_usable(session, _get_row(session, datasource_id))
password = _decrypt_stored(row)
target = ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=password,
)
# End the read transaction first (this also persists an auto-closed circuit) so no
# connection is held open during the probe.
session.commit()
result = _probe(target)
row = _get_row(session, datasource_id, lock=True)
record_probe_outcome(session, row, result)
_audit(session, "datasource.test", row, category=result.category.value)
return row, result
def run_healthcheck_probe(session: Session, datasource_id: str) -> ProbeResult | None:
"""Probe one saved datasource for the scheduled health check; the caller commits.
Returns None (no probe, nothing recorded) when the source is gone, disabled or its
circuit is open. Otherwise the target is built from the stored row exactly like
run_connection_test, the outcome feeds last_test and the circuit, and a non-success
writes a credential-free audit event (id, name, engine, category). enabled is never
changed. No transaction stays open during the probe.
"""
try:
row = _get_row(session, datasource_id, refresh=True)
assert_usable(session, row)
except (NotFoundError, ConflictError):
# Persist an auto-closed circuit, then release the read transaction.
session.commit()
return None
password = _decrypt_stored(row)
target = ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=password,
)
session.commit()
result = _probe(target)
try:
row = _get_row(session, datasource_id, lock=True)
except NotFoundError:
session.rollback()
return None
record_probe_outcome(session, row, result)
if result.category is not ProbeCategory.SUCCESS:
_audit(session, "datasource.healthcheck_failed", row, category=result.category.value)
return result
def run_draft_connection_test(
session: Session,
fields: dict[str, Any],
*,
datasource_id: str | None = None,
) -> ProbeResult:
"""Probe a form-only target. Never writes last_test_* and never feeds the circuit.
A blank password falls back to the stored secret of datasource_id (same tenant); with
no datasource_id a password is required. The saved row's enabled flag and circuit are
deliberately ignored: a draft is only a check of what the form holds. The caller commits.
"""
kind = fields.get("kind") or "database"
engine = fields.get("engine") or ""
_check_kind_engine(kind, engine)
password = fields.get("password")
stored: DataSource | None = None
if datasource_id is not None:
stored = _get_row(session, datasource_id)
if not isinstance(password, str) or not password.strip():
if stored is None:
raise ValidationError("Password is required", details={"fields": ["password"]})
password = _decrypt_stored(stored)
target = ProbeTarget(
engine=engine,
kind=kind,
host=fields["host"],
port=fields["port"],
database=fields["database_name"],
username=fields["username"],
password=password,
)
audit_id = str(stored.id) if stored is not None else None
# No transaction may stay open during the network call.
session.commit()
result = _probe(target)
# GUARD: payload has no host, user or password; the target is not recorded.
create_audit_event(
session,
action="datasource.test_draft",
payload={"engine": engine, "category": result.category.value, "id": audit_id},
idempotency_key=f"datasource.test_draft:{uuid.uuid4().hex}",
)
return result
@@ -0,0 +1,686 @@
"""Datasource API tests: permission matrix, secret hygiene, disable, test endpoint, audit.
Why: the datasource routes are the only place a password enters and the only place a
saved connection can be probed, so roles, redaction and the no-target rule need proof.
Boundary: uses the local platform Postgres and seeded sessions like test_platform_access;
probes are replaced by fakes except one live PostgreSQL test taken from WATCHMAN_TEST_PG_*.
All rows created here are removed afterwards (audit events are append-only and kept).
Depends on watchman.api.app, the session store and the datasource service.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from cryptography.fernet import Fernet
from fastapi.testclient import TestClient
from sqlalchemy import delete, select
from watchman.api.app import create_app
from watchman.auth.access import (
DATASOURCE_READ_NODE,
DATASOURCE_TEST_NODE,
DATASOURCE_WRITE_NODE,
require_datasource_read,
require_datasource_test,
require_datasource_write,
)
from watchman.auth.principal import get_role_directory
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
from watchman.core.config import get_settings, merge_layered_env, reload_settings
from watchman.core.db import get_session_factory, reset_engine, set_tenant
from watchman.core.errors import ForbiddenError
from watchman.core.secrets import KEY_ENV_NAME, decrypt_secret
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget, probe_datasource
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent
from watchman.services import datasources as service
# Unique marker: any appearance in a response or audit payload is a leak. Not a credential.
SENTINEL = "Zq9-api-sentinel-pw-4c1e7a"
OTHER_SENTINEL = "Zq9-api-replacement-pw-8d2b6f"
NAME_PREFIX = f"apitest-{uuid.uuid4().hex[:8]}-"
ADMIN = ["watchman-admin"]
OPERATOR = ["watchman-operator"]
VIEWER = ["watchman-viewer"]
@pytest.fixture(autouse=True)
def datasource_key(monkeypatch: pytest.MonkeyPatch):
"""Use a throwaway Fernet key so these tests never depend on the real one."""
monkeypatch.setenv(KEY_ENV_NAME, Fernet.generate_key().decode("ascii"))
reload_settings()
yield
monkeypatch.undo()
reload_settings()
@pytest.fixture(autouse=True)
def cleanup():
"""Delete seeded sessions and every datasource whose name carries this run's prefix."""
tokens: list[str] = []
yield tokens
reload_settings()
reset_engine()
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
session.execute(delete(DataSource).where(DataSource.name.like(f"{NAME_PREFIX}%")))
if tokens:
session.execute(
delete(AuthSession).where(
AuthSession.token_hash.in_([hash_cookie_token(t) for t in tokens])
)
)
session.commit()
finally:
session.close()
reset_engine()
def _seed(tokens: list[str], roles: list[str]) -> str:
token = issue_cookie_token()
now = datetime.now(timezone.utc)
settings = get_settings()
session = get_session_factory()()
try:
set_tenant(session, settings.tenant_id)
session.add(
AuthSession(
token_hash=hash_cookie_token(token),
subject=f"subject-{uuid.uuid4().hex}",
issuer="https://casdoor.test",
display_name="Worker",
login_name="worker",
role_snapshot=list(roles),
role_checked_at=now,
expires_at=now + timedelta(hours=1),
tenant_id=settings.tenant_id,
)
)
session.commit()
finally:
session.close()
tokens.append(token)
return token
def _client(cleanup: list[str], roles: list[str] | None) -> TestClient:
"""A client with a fresh seeded session; roles=None means no cookie at all."""
reload_settings()
reset_engine()
app = create_app()
class _NoDirectory:
def lookup_roles(self, *, login_name: str) -> list[str]:
raise AssertionError("a fresh session must not trigger a role reload")
app.dependency_overrides[get_role_directory] = lambda: _NoDirectory()
client = TestClient(app)
if roles is not None:
client.cookies.set(SESSION_COOKIE_NAME, _seed(cleanup, roles))
return client
def _body(**overrides) -> dict:
values = {
"name": f"{NAME_PREFIX}{uuid.uuid4().hex[:8]}",
"description": "synthetic",
"kind": "database",
"engine": "postgresql",
"host": "db.synthetic.invalid",
"port": 5432,
"database_name": "synthetic_db",
"username": "synthetic_user",
"password": SENTINEL,
}
values.update(overrides)
return values
def _create(client: TestClient, **overrides) -> dict:
response = client.post("/datasources", json=_body(**overrides))
assert response.status_code == 200, response.text
return response.json()["data"]
def _stored(datasource_id: str) -> DataSource:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(datasource_id)))
assert row is not None
return row
finally:
session.close()
def _audit_events(datasource_id: str, action: str) -> list[AuditEvent]:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
return list(
session.scalars(
select(AuditEvent).where(
AuditEvent.tenant_id == get_settings().tenant_id,
AuditEvent.action == action,
AuditEvent.payload["id"].as_string() == datasource_id,
)
)
)
finally:
session.close()
@pytest.fixture
def no_network(monkeypatch: pytest.MonkeyPatch):
"""Fail loudly if any code path tries to probe or open a socket."""
def _boom(*_args, **_kwargs):
raise AssertionError("network must not be used")
monkeypatch.setattr(service, "probe_datasource", _boom)
monkeypatch.setattr("watchman.datasources.probe.probe_datasource", _boom)
monkeypatch.setattr("socket.create_connection", _boom)
# --- permission nodes and role rules ---------------------------------------------------
def test_node_strings_and_role_rules() -> None:
assert DATASOURCE_READ_NODE == "perm:data:emp:watchman.datasource.read"
assert DATASOURCE_WRITE_NODE == "perm:data:emp:watchman.datasource.write"
assert DATASOURCE_TEST_NODE == "perm:data:emp:watchman.datasource.test"
# The confirmed console allows only watchman-admin into datasources.
require_datasource_read(ADMIN)
require_datasource_write(ADMIN)
require_datasource_test(ADMIN)
cases = [
(require_datasource_read, OPERATOR, DATASOURCE_READ_NODE),
(require_datasource_read, VIEWER, DATASOURCE_READ_NODE),
(require_datasource_read, [], DATASOURCE_READ_NODE),
(require_datasource_read, ["someone-else"], DATASOURCE_READ_NODE),
(require_datasource_write, OPERATOR, DATASOURCE_WRITE_NODE),
(require_datasource_write, VIEWER, DATASOURCE_WRITE_NODE),
(require_datasource_write, [], DATASOURCE_WRITE_NODE),
(require_datasource_test, OPERATOR, DATASOURCE_TEST_NODE),
(require_datasource_test, VIEWER, DATASOURCE_TEST_NODE),
(require_datasource_test, [], DATASOURCE_TEST_NODE),
]
for check, roles, node in cases:
with pytest.raises(ForbiddenError) as raised:
check(roles)
assert raised.value.permission_node == node
ANY_ID = str(uuid.uuid4())
ROUTES = [
("GET", "/datasources", None),
("POST", "/datasources", _body()),
("GET", f"/datasources/{ANY_ID}", None),
("PATCH", f"/datasources/{ANY_ID}", {"description": "x"}),
("POST", f"/datasources/{ANY_ID}/disable", None),
("POST", f"/datasources/{ANY_ID}/enable", None),
("POST", "/datasources/test-draft", {"engine": "postgresql", "host": "h", "port": 5432, "database_name": "d", "username": "u", "password": "x"}),
("POST", f"/datasources/{ANY_ID}/test", None),
("GET", f"/datasources/{ANY_ID}/references", None),
]
@pytest.mark.parametrize(("method", "path", "payload"), ROUTES)
def test_anonymous_is_41000_without_permission_node(cleanup, method, path, payload) -> None:
response = _client(cleanup, None).request(method, path, json=payload)
assert response.status_code == 401
error = response.json()["error"]
assert error["code"] == 41000
assert "permission_node" not in error
@pytest.mark.parametrize(
("roles", "method", "path_kind", "node"),
[
(VIEWER, "POST", "create", DATASOURCE_WRITE_NODE),
(VIEWER, "PATCH", "item", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "disable", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "test", DATASOURCE_TEST_NODE),
(VIEWER, "POST", "enable", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "draft", DATASOURCE_TEST_NODE),
(OPERATOR, "POST", "enable", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "draft", DATASOURCE_TEST_NODE),
(VIEWER, "GET", "list", DATASOURCE_READ_NODE),
(VIEWER, "GET", "item", DATASOURCE_READ_NODE),
(VIEWER, "GET", "references", DATASOURCE_READ_NODE),
(OPERATOR, "POST", "create", DATASOURCE_WRITE_NODE),
(OPERATOR, "PATCH", "item", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "disable", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "test", DATASOURCE_TEST_NODE),
(OPERATOR, "GET", "list", DATASOURCE_READ_NODE),
(OPERATOR, "GET", "item", DATASOURCE_READ_NODE),
(OPERATOR, "GET", "references", DATASOURCE_READ_NODE),
([], "GET", "list", DATASOURCE_READ_NODE),
([], "GET", "references", DATASOURCE_READ_NODE),
([], "GET", "item", DATASOURCE_READ_NODE),
],
)
def test_wrong_role_is_42000_with_node(cleanup, no_network, roles, method, path_kind, node) -> None:
created = _create(_client(cleanup, ADMIN))
ds_id = created["id"]
paths = {
"create": "/datasources",
"list": "/datasources",
"item": f"/datasources/{ds_id}",
"disable": f"/datasources/{ds_id}/disable",
"test": f"/datasources/{ds_id}/test",
"enable": f"/datasources/{ds_id}/enable",
"draft": "/datasources/test-draft",
"references": f"/datasources/{ds_id}/references",
}
payload = _body() if path_kind in ("create", "draft") else ({"description": "x"} if method == "PATCH" else None)
response = _client(cleanup, roles).request(method, paths[path_kind], json=payload)
assert response.status_code == 403
error = response.json()["error"]
assert error["code"] == 42000
assert error["permission_node"] == node
# A denied write must not have changed anything.
assert _stored(ds_id).enabled is True and _stored(ds_id).description == "synthetic"
def test_admin_can_read(cleanup) -> None:
created = _create(_client(cleanup, ADMIN))
client = _client(cleanup, ADMIN)
listing = client.get("/datasources")
assert listing.status_code == 200
assert created["id"] in [item["id"] for item in listing.json()["data"]["items"]]
assert client.get(f"/datasources/{created['id']}").status_code == 200
# --- create, redaction, audit --------------------------------------------------------------
def test_admin_create_redacts_secret_and_audits_cleanly(cleanup) -> None:
client = _client(cleanup, ADMIN)
response = client.post("/datasources", json=_body())
assert response.status_code == 200
data = response.json()["data"]
row = _stored(data["id"])
ciphertext = row.secret_ciphertext
assert SENTINEL not in ciphertext and decrypt_secret(ciphertext) == SENTINEL
assert data["secret_configured"] is True
assert set(data) == {
"id", "name", "description", "kind", "engine", "host", "port", "database_name",
"username", "secret_configured", "read_only_intent", "enabled", "last_test_category",
"last_test_at", "last_test_message", "created_at", "updated_at", "circuit_state",
"circuit_opened_at", "circuit_open_until", "circuit_failure_window_seconds",
"circuit_failure_threshold", "circuit_open_cooldown_seconds",
} # fmt: skip
assert data["enabled"] is True and data["read_only_intent"] is True
for surface in (response.text, client.get(f"/datasources/{data['id']}").text, client.get("/datasources").text):
assert SENTINEL not in surface
assert ciphertext not in surface
assert "secret_ciphertext" not in surface and "password" not in surface
events = _audit_events(data["id"], "datasource.create")
assert len(events) == 1
payload = events[0].payload
assert payload == {"id": data["id"], "name": data["name"], "engine": "postgresql"}
dumped = json.dumps(payload) + events[0].idempotency_key
assert SENTINEL not in dumped and ciphertext not in dumped and "synthetic_user" not in dumped
def test_create_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
bad_bodies = [
_body(kind="api"),
_body(engine="oracle"),
_body(password=""),
_body(password=" "),
_body(port=0),
_body(port=70000),
_body(host=" "),
_body(host=""),
_body(tenant_id="other-tenant"),
_body(enabled=False),
{k: v for k, v in _body().items() if k != "password"},
]
for body in bad_bodies:
response = client.post("/datasources", json=body)
assert response.status_code == 400, body.get("name")
assert response.json()["error"]["code"] == 40000
assert SENTINEL not in response.text
listing = client.get("/datasources").json()["data"]["items"]
assert not [i for i in listing if i["name"].startswith(NAME_PREFIX)]
def test_duplicate_name_is_409(cleanup) -> None:
client = _client(cleanup, ADMIN)
first = _create(client)
response = client.post("/datasources", json=_body(name=first["name"]))
assert response.status_code == 409
assert response.json()["error"]["details"]["reason"] == "duplicate_name"
def test_unknown_and_foreign_tenant_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
foreign_name = f"{NAME_PREFIX}foreign"
session = get_session_factory()()
try:
set_tenant(session, "other-tenant-api-test")
row = DataSource(
tenant_id="other-tenant-api-test",
name=foreign_name,
kind="database",
engine="postgresql",
host="h.invalid",
port=5432,
database_name="d",
username="u",
secret_ciphertext="opaque",
)
session.add(row)
session.commit()
foreign_id = str(row.id)
finally:
session.close()
try:
for path in (
f"/datasources/{uuid.uuid4()}",
f"/datasources/{foreign_id}",
f"/datasources/{foreign_id}/references",
"/datasources/not-a-uuid",
):
response = client.get(path)
assert response.status_code == 404, path
assert client.patch(f"/datasources/{foreign_id}", json={"description": "x"}).status_code == 404
assert client.post(f"/datasources/{foreign_id}/disable").status_code == 404
assert client.post(f"/datasources/{foreign_id}/test").status_code == 404
assert foreign_id not in [i["id"] for i in client.get("/datasources").json()["data"]["items"]]
finally:
cleaner = get_session_factory()()
try:
set_tenant(cleaner, "other-tenant-api-test")
cleaner.execute(delete(DataSource).where(DataSource.name == foreign_name))
cleaner.commit()
finally:
cleaner.close()
# --- update ------------------------------------------------------------------------------
def test_patch_keeps_or_replaces_password(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
before = _stored(ds_id)
kept = client.patch(f"/datasources/{ds_id}", json={"description": "changed", "port": 5433})
assert kept.status_code == 200
assert kept.json()["data"]["description"] == "changed"
after = _stored(ds_id)
assert after.secret_ciphertext == before.secret_ciphertext
assert after.updated_at > before.updated_at
blank = client.patch(f"/datasources/{ds_id}", json={"password": "", "host": "other.invalid"})
assert blank.status_code == 200
assert _stored(ds_id).secret_ciphertext == before.secret_ciphertext
replaced = client.patch(f"/datasources/{ds_id}", json={"password": OTHER_SENTINEL})
assert replaced.status_code == 200
new_cipher = _stored(ds_id).secret_ciphertext
assert new_cipher != before.secret_ciphertext
assert decrypt_secret(new_cipher) == OTHER_SENTINEL
for surface in (kept.text, blank.text, replaced.text):
assert SENTINEL not in surface and OTHER_SENTINEL not in surface and new_cipher not in surface
events = _audit_events(ds_id, "datasource.update")
assert len(events) == 3
dumped = json.dumps([e.payload for e in events])
assert OTHER_SENTINEL not in dumped and new_cipher not in dumped and "synthetic_user" not in dumped
@pytest.mark.parametrize(
"change",
[
{"host": "changed.invalid"},
{"port": 5439},
{"database_name": "other_db"},
{"username": "other_user"},
{"engine": "mysql"},
{"password": OTHER_SENTINEL},
],
)
def test_patch_connection_change_clears_last_test(cleanup, monkeypatch, change) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
_fake_probe(monkeypatch, ProbeCategory.AUTH_FAILED)
client.post(f"/datasources/{ds_id}/test")
tested = _stored(ds_id)
assert tested.last_test_category == "auth_failed" and tested.last_test_at is not None
response = client.patch(f"/datasources/{ds_id}", json=change)
assert response.status_code == 200
data = response.json()["data"]
assert data["last_test_category"] is None
assert data["last_test_at"] is None
assert data["last_test_message"] is None
stored = _stored(ds_id)
assert stored.last_test_category is None
assert stored.last_test_at is None
assert stored.last_test_message is None
assert stored.updated_at > tested.updated_at
def test_patch_without_connection_change_keeps_last_test(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
_fake_probe(monkeypatch, ProbeCategory.AUTH_FAILED)
client.post(f"/datasources/{ds_id}/test")
tested = _stored(ds_id)
new_name = f"{NAME_PREFIX}renamed"
for body in (
{"name": new_name},
{"description": "edited", "read_only_intent": False},
{"password": " "}, # blank keeps the stored password and the test result
{"host": created["host"], "port": created["port"]}, # same values: not a change
):
response = client.patch(f"/datasources/{ds_id}", json=body)
assert response.status_code == 200
assert response.json()["data"]["last_test_category"] == "auth_failed"
stored = _stored(ds_id)
assert stored.last_test_category == "auth_failed"
assert stored.last_test_message == tested.last_test_message
assert stored.last_test_at == tested.last_test_at
def test_patch_rejections(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
other = _create(client)
ds_id = created["id"]
for body in (
{"kind": "api"},
{"engine": "oracle"},
{"tenant_id": "other"},
{"enabled": False},
{"name": None},
{"port": 0},
):
response = client.patch(f"/datasources/{ds_id}", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
clash = client.patch(f"/datasources/{ds_id}", json={"name": other["name"]})
assert clash.status_code == 409
assert client.patch(f"/datasources/{ds_id}", json={"engine": "mysql"}).json()["data"]["engine"] == "mysql"
# --- disable, references -----------------------------------------------------------------
def test_disable_blocks_test_without_network_and_stays_readable(cleanup, no_network) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
before = _stored(ds_id)
disabled = client.post(f"/datasources/{ds_id}/disable")
assert disabled.status_code == 200 and disabled.json()["data"]["enabled"] is False
assert _stored(ds_id).updated_at > before.updated_at
assert client.get(f"/datasources/{ds_id}").json()["data"]["enabled"] is False
assert client.delete(f"/datasources/{ds_id}").status_code == 405
response = client.post(f"/datasources/{ds_id}/test")
assert response.status_code == 409
error = response.json()["error"]
assert error["details"]["reason"] == "disabled"
assert _stored(ds_id).last_test_category is None
operator = _client(cleanup, OPERATOR).post(f"/datasources/{ds_id}/test")
assert operator.status_code == 403
events = _audit_events(ds_id, "datasource.disable")
assert len(events) == 1 and events[0].payload["id"] == ds_id
def test_references_are_empty(cleanup) -> None:
created = _create(_client(cleanup, ADMIN))
response = _client(cleanup, ADMIN).get(f"/datasources/{created['id']}/references")
assert response.status_code == 200
assert response.json()["data"] == {"id": created["id"], "items": []}
# --- connection test -------------------------------------------------------------------------
def _fake_probe(monkeypatch: pytest.MonkeyPatch, category: ProbeCategory) -> list[ProbeTarget]:
seen: list[ProbeTarget] = []
def _probe(target: ProbeTarget, **_kwargs) -> ProbeResult:
seen.append(target)
return ProbeResult(category=category, message=f"fixed text for {category.value}")
monkeypatch.setattr(service, "probe_datasource", _probe)
return seen
def test_connection_test_success_uses_saved_target_only(cleanup, monkeypatch) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
seen = _fake_probe(monkeypatch, ProbeCategory.SUCCESS)
before = _stored(created["id"])
# Only admin may test. The probe sees the saved target and the decrypted password.
response = _client(cleanup, ADMIN).post(f"/datasources/{created['id']}/test")
assert response.status_code == 200
data = response.json()["data"]
assert response.json()["success"] is True
assert data["category"] == "success" and data["message"] == "fixed text for success"
assert [(t.host, t.port, t.database, t.username, t.engine) for t in seen] == [
("db.synthetic.invalid", 5432, "synthetic_db", "synthetic_user", "postgresql")
]
assert seen[0].password == SENTINEL
assert SENTINEL not in response.text
after = _stored(created["id"])
assert after.last_test_category == "success"
assert after.last_test_message == "fixed text for success"
assert after.last_test_at is not None and after.updated_at > before.updated_at
events = _audit_events(created["id"], "datasource.test")
assert len(events) == 1
assert events[0].payload == {
"id": created["id"], "name": created["name"], "engine": "postgresql", "category": "success"
} # fmt: skip
def test_connection_test_rejects_any_target_in_body(cleanup, monkeypatch) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
seen = _fake_probe(monkeypatch, ProbeCategory.SUCCESS)
for body in ({"host": "evil.invalid"}, {"url": "postgresql://u:p@h/db"}, {"tenant_id": "x"}, {"port": 1}):
response = admin.post(f"/datasources/{created['id']}/test", json=body)
assert response.status_code == 400 and response.json()["error"]["code"] == 40000
assert seen == []
@pytest.mark.parametrize(
("category", "retryable"),
[
(ProbeCategory.AUTH_FAILED, False),
(ProbeCategory.TIMEOUT, True),
(ProbeCategory.UNREACHABLE, True),
(ProbeCategory.REJECTED, False),
],
)
def test_connection_test_failure_envelope(cleanup, monkeypatch, category, retryable) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
_fake_probe(monkeypatch, category)
response = admin.post(f"/datasources/{created['id']}/test")
assert response.status_code == 400
body = response.json()
assert body["success"] is False
error = body["error"]
assert error["code"] == 40000
assert error["message"] == f"fixed text for {category.value}"
assert error["details"] == {"category": category.value}
assert error["retryable"] is retryable
assert SENTINEL not in response.text
stored = _stored(created["id"])
assert stored.last_test_category == category.value
assert stored.last_test_message == f"fixed text for {category.value}"
assert stored.last_test_at is not None
events = _audit_events(created["id"], "datasource.test")
assert [e.payload["category"] for e in events] == [category.value]
# --- live PostgreSQL through the API --------------------------------------------------------------
def test_live_postgres_success_and_wrong_password(cleanup) -> None:
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
if any(not env.get(f"WATCHMAN_TEST_PG_{k}") for k in keys):
pytest.skip("WATCHMAN_TEST_PG_* env not configured")
live = dict(
host=env["WATCHMAN_TEST_PG_HOST"],
port=int(env["WATCHMAN_TEST_PG_PORT"]),
database_name=env["WATCHMAN_TEST_PG_DATABASE"],
username=env["WATCHMAN_TEST_PG_USER"],
)
precheck = probe_datasource(
ProbeTarget(
engine="postgresql",
host=live["host"],
port=live["port"],
database=live["database_name"],
username=live["username"],
password=env["WATCHMAN_TEST_PG_PASSWORD"],
)
)
if precheck.category is not ProbeCategory.SUCCESS:
pytest.skip(f"live postgres not available ({precheck.category.value})")
admin = _client(cleanup, ADMIN)
good = _create(admin, password=env["WATCHMAN_TEST_PG_PASSWORD"], **live)
ok = admin.post(f"/datasources/{good['id']}/test")
assert ok.status_code == 200
assert ok.json()["data"]["category"] == "success"
assert _stored(good["id"]).last_test_category == "success"
bad = _create(admin, password=SENTINEL, **live)
failed = admin.post(f"/datasources/{bad['id']}/test")
assert failed.status_code == 400
error = failed.json()["error"]
assert error["details"]["category"] == "auth_failed"
assert error["retryable"] is False
assert env["WATCHMAN_TEST_PG_PASSWORD"] not in ok.text + failed.text
assert SENTINEL not in failed.text
assert _stored(bad["id"]).last_test_category == "auth_failed"
@@ -0,0 +1,677 @@
"""Datasource enable, draft test and circuit breaker tests (M03 S6, D23).
Why: the circuit decides whether a saved source may be probed at all, so open/close
timing, which probes count, and the draft-test isolation need executable proof.
Boundary: real platform Postgres through the API like test_datasource_api; probes are
fakes and time is frozen by replacing the service clock. Rows created here are removed
by the shared cleanup fixture (audit events are append-only and kept).
Depends on test_datasource_api helpers, the datasource service and the probe module.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from fastapi.testclient import TestClient
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
OPERATOR,
SENTINEL,
_audit_events,
_body,
_client,
_create,
_stored,
cleanup,
datasource_key,
)
from watchman.core.config import get_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget, probe_datasource
from watchman.datasources import probe as probe_module
from watchman.services import datasources as service
T0 = datetime(2030, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
class Clock:
"""A controllable replacement for service._now."""
def __init__(self) -> None:
self.now = T0
def advance(self, seconds: float) -> None:
self.now += timedelta(seconds=seconds)
def __call__(self) -> datetime:
return self.now
@pytest.fixture
def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
fake = Clock()
monkeypatch.setattr(service, "_now", fake)
return fake
class FakeProbe:
"""Records targets; returns the queued category (the last one repeats)."""
def __init__(self, *categories: ProbeCategory) -> None:
self.categories = list(categories) or [ProbeCategory.SUCCESS]
self.targets: list[ProbeTarget] = []
def __call__(self, target: ProbeTarget, **_kwargs) -> ProbeResult:
self.targets.append(target)
category = self.categories.pop(0) if len(self.categories) > 1 else self.categories[0]
return ProbeResult(category=category, message=f"fixed text for {category.value}")
def _install(monkeypatch: pytest.MonkeyPatch, *categories: ProbeCategory) -> FakeProbe:
fake = FakeProbe(*categories)
monkeypatch.setattr(service, "probe_datasource", fake)
return fake
def _draft_body(**overrides) -> dict:
values = {
"engine": "postgresql",
"host": "draft.synthetic.invalid",
"port": 5432,
"database_name": "draft_db",
"username": "draft_user",
"password": "draft-pw-not-a-credential",
}
values.update(overrides)
return values
def _test(client: TestClient, ds_id: str):
return client.post(f"/datasources/{ds_id}/test")
# --- enable --------------------------------------------------------------------------------
def test_enable_after_disable_restores_testing(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
assert client.post(f"/datasources/{ds_id}/disable").json()["data"]["enabled"] is False
refused = _test(client, ds_id)
assert refused.status_code == 409
assert refused.json()["error"]["details"]["reason"] == "disabled"
assert fake.targets == []
enabled = client.post(f"/datasources/{ds_id}/enable")
assert enabled.status_code == 200
assert enabled.json()["data"]["enabled"] is True
assert _stored(ds_id).enabled is True
assert _test(client, ds_id).status_code == 200
assert len(fake.targets) == 1
assert len(_audit_events(ds_id, "datasource.enable")) == 1
def test_enable_does_not_clear_open_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
assert _stored(ds_id).circuit_state == "open"
client.post(f"/datasources/{ds_id}/disable")
data = client.post(f"/datasources/{ds_id}/enable").json()["data"]
assert data["enabled"] is True and data["circuit_state"] == "open"
assert _test(client, ds_id).json()["error"]["details"]["reason"] == "circuit_open"
# --- draft test ----------------------------------------------------------------------------
def test_draft_test_writes_no_last_test_and_no_circuit_accounting(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.AUTH_FAILED)
before = _stored(ds_id)
for _ in range(5): # more than the threshold of 3
response = client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id))
assert response.status_code == 400
assert response.json()["error"]["details"] == {"category": "auth_failed"}
after = _stored(ds_id)
assert after.last_test_category is None and after.last_test_at is None
assert after.last_test_message is None
assert after.circuit_state == "closed" and after.circuit_failure_count == 0
assert after.circuit_window_started_at is None and after.circuit_opened_at is None
assert after.updated_at == before.updated_at
assert len(fake.targets) == 5
# The draft values are what was probed, not the saved row.
assert fake.targets[0].host == "draft.synthetic.invalid"
assert _audit_events(ds_id, "datasource.test") == []
def test_draft_test_success_and_stored_password_fallback(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
explicit = client.post("/datasources/test-draft", json=_draft_body())
assert explicit.status_code == 200
assert explicit.json()["data"]["category"] == "success"
assert fake.targets[-1].password == "draft-pw-not-a-credential"
for blank in (None, "", " "):
body = _draft_body(datasource_id=ds_id)
if blank is None:
del body["password"]
else:
body["password"] = blank
response = client.post("/datasources/test-draft", json=body)
assert response.status_code == 200, body
assert fake.targets[-1].password == SENTINEL
assert SENTINEL not in response.text
assert _stored(ds_id).last_test_at is None
def test_draft_test_validation_and_tenant_scope(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
for body in (
_draft_body(password=""), # create-style, no stored secret to fall back on
{k: v for k, v in _draft_body().items() if k != "password"},
_draft_body(engine="oracle"),
_draft_body(kind="api"),
_draft_body(host=" "),
_draft_body(tenant_id="other"),
_draft_body(password="x", url="postgresql://u:p@h/db"),
):
response = client.post("/datasources/test-draft", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
assert fake.targets == []
for missing in (str(uuid.uuid4()), "not-a-uuid"):
response = client.post(
"/datasources/test-draft", json=_draft_body(password="", datasource_id=missing)
)
assert response.status_code == 404
assert ds_id # the real row is untouched by the failed lookups
def test_draft_test_ignores_disabled_and_open_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
assert _stored(ds_id).circuit_state == "open"
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
response = client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password=""))
assert response.status_code == 200
assert len(fake.targets) == 1
def test_draft_audit_has_no_target_or_secret(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.SUCCESS)
client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password=""))
events = _audit_events(ds_id, "datasource.test_draft")
assert len(events) == 1
assert events[0].payload == {"engine": "postgresql", "category": "success", "id": ds_id}
dumped = json.dumps(events[0].payload) + events[0].idempotency_key
assert SENTINEL not in dumped and "draft.synthetic.invalid" not in dumped
# --- circuit breaker ----------------------------------------------------------------------------
def test_failures_open_circuit_then_reject_then_auto_close(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.TIMEOUT)
for attempt in (1, 2, 3):
response = _test(client, ds_id)
assert response.status_code == 400
stored = _stored(ds_id)
# last_test is persisted on every saved test, including the one that opens the circuit.
assert stored.last_test_category == "timeout"
assert stored.last_test_at == clock.now
assert stored.circuit_failure_count == attempt
assert stored.circuit_state == ("open" if attempt == 3 else "closed")
clock.advance(1)
assert len(fake.targets) == 3
opened = _stored(ds_id)
assert opened.enabled is True # never auto-disabled
assert opened.circuit_opened_at == T0 + timedelta(seconds=2)
assert len(_audit_events(ds_id, "datasource.circuit_open")) == 1
data = client.get(f"/datasources/{ds_id}").json()["data"]
assert data["circuit_state"] == "open"
assert data["circuit_open_until"] == (opened.circuit_opened_at + timedelta(seconds=600)).isoformat()
rejected = _test(client, ds_id)
assert rejected.status_code == 409
assert rejected.json()["error"]["details"]["reason"] == "circuit_open"
assert len(fake.targets) == 3 # refused before any probe
# Still inside the cooldown: refused. Past it: assert_usable closes the circuit.
clock.advance(590)
assert _test(client, ds_id).status_code == 409
clock.advance(20)
fake_ok = _install(monkeypatch, ProbeCategory.SUCCESS)
assert _test(client, ds_id).status_code == 200
assert len(fake_ok.targets) == 1
closed = _stored(ds_id)
assert closed.circuit_state == "closed" and closed.circuit_opened_at is None
assert closed.circuit_failure_count == 0 and closed.circuit_window_started_at is None
assert closed.last_test_category == "success"
data = client.get(f"/datasources/{ds_id}").json()["data"]
assert data["circuit_state"] == "closed" and data["circuit_open_until"] is None
def test_auth_failed_counts_toward_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
for _ in range(3):
assert _test(client, ds_id).status_code == 400
assert _stored(ds_id).circuit_state == "open"
assert _test(client, ds_id).status_code == 409
def test_rejected_and_unreachable_also_count(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.REJECTED, ProbeCategory.UNREACHABLE, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
assert _stored(ds_id).circuit_state == "open"
def test_success_resets_failure_count(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT, ProbeCategory.TIMEOUT, ProbeCategory.SUCCESS, ProbeCategory.TIMEOUT)
for _ in range(2):
_test(client, ds_id)
assert _stored(ds_id).circuit_failure_count == 2
_test(client, ds_id) # success
reset = _stored(ds_id)
assert reset.circuit_failure_count == 0 and reset.circuit_window_started_at is None
_test(client, ds_id) # one failure again
final = _stored(ds_id)
assert final.circuit_failure_count == 1 and final.circuit_state == "closed"
def test_failures_outside_window_do_not_accumulate(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
assert client.patch(
f"/datasources/{ds_id}", json={"circuit_failure_window_seconds": 60}
).status_code == 200
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
_test(client, ds_id)
clock.advance(61) # first window expired
_test(client, ds_id)
stored = _stored(ds_id)
assert stored.circuit_failure_count == 1 and stored.circuit_state == "closed"
assert stored.circuit_window_started_at == clock.now
def test_circuit_parameters_persist_and_apply(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
assert created["circuit_failure_window_seconds"] == 300
assert created["circuit_failure_threshold"] == 3
assert created["circuit_open_cooldown_seconds"] == 600
assert created["circuit_state"] == "closed"
response = client.patch(
f"/datasources/{ds_id}",
json={
"circuit_failure_window_seconds": 120,
"circuit_failure_threshold": 2,
"circuit_open_cooldown_seconds": 30,
},
)
assert response.status_code == 200
data = response.json()["data"]
assert (
data["circuit_failure_window_seconds"],
data["circuit_failure_threshold"],
data["circuit_open_cooldown_seconds"],
) == (120, 2, 30)
stored = _stored(ds_id)
assert (stored.circuit_failure_window_seconds, stored.circuit_failure_threshold) == (120, 2)
assert stored.circuit_open_cooldown_seconds == 30
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
_test(client, ds_id) # threshold 2 opens it
assert _stored(ds_id).circuit_state == "open"
clock.advance(31) # custom cooldown of 30 s has passed
_install(monkeypatch, ProbeCategory.SUCCESS)
assert _test(client, ds_id).status_code == 200
@pytest.mark.parametrize(
"change",
[
{"circuit_failure_window_seconds": 0},
{"circuit_failure_window_seconds": 86401},
{"circuit_failure_threshold": 0},
{"circuit_failure_threshold": 101},
{"circuit_open_cooldown_seconds": 0},
{"circuit_open_cooldown_seconds": 86401},
{"circuit_open_cooldown_seconds": "10"},
{"circuit_failure_threshold": 2.5},
{"circuit_failure_threshold": None},
{"circuit_state": "closed"},
{"circuit_failure_count": 0},
],
)
def test_circuit_parameter_validation(cleanup, change) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
response = client.patch(f"/datasources/{ds_id}", json=change)
assert response.status_code == 400, change
assert response.json()["error"]["code"] == 40000
stored = _stored(ds_id)
assert (stored.circuit_failure_window_seconds, stored.circuit_failure_threshold) == (300, 3)
assert stored.circuit_open_cooldown_seconds == 600
def test_circuit_parameter_boundaries_accepted(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
for change in (
{"circuit_failure_window_seconds": 1, "circuit_failure_threshold": 1, "circuit_open_cooldown_seconds": 1},
{"circuit_failure_window_seconds": 86400, "circuit_failure_threshold": 100, "circuit_open_cooldown_seconds": 86400},
):
assert client.patch(f"/datasources/{ds_id}", json=change).status_code == 200
def test_circuit_config_change_keeps_last_test_and_state(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
client.patch(f"/datasources/{ds_id}", json={"circuit_failure_threshold": 5})
stored = _stored(ds_id)
assert stored.last_test_category == "timeout" and stored.circuit_failure_count == 1
def test_disable_is_decoupled_from_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
stored = _stored(ds_id)
assert stored.enabled is False
assert stored.circuit_failure_count == 1 and stored.circuit_state == "closed"
def test_disabled_check_wins_over_circuit_reason(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
refused = _test(client, ds_id)
assert refused.status_code == 409
assert refused.json()["error"]["details"]["reason"] == "disabled"
# --- assert_usable and the usable list -----------------------------------------------------------
def test_assert_usable_service_contract(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
with pytest.raises(service.ConflictError) as raised:
service.assert_usable(session, ds_id) # by id
assert raised.value.details["reason"] == "circuit_open"
row = service.get_datasource(session, ds_id)
with pytest.raises(service.ConflictError):
service.assert_usable(session, row) # by row
clock.advance(601)
assert service.assert_usable(session, row) is row
assert row.circuit_state == "closed" and row.circuit_opened_at is None
assert row.circuit_failure_count == 0
row.enabled = False
with pytest.raises(service.ConflictError) as disabled:
service.assert_usable(session, row)
assert disabled.value.details["reason"] == "disabled"
session.rollback()
finally:
session.close()
def test_record_probe_outcome_can_skip_last_test(cleanup, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = service.get_datasource(session, ds_id)
failure = ProbeResult(ProbeCategory.AUTH_FAILED, "authentication failed")
assert service.record_probe_outcome(session, row, failure, update_last_test=False) is False
assert row.last_test_category is None and row.circuit_failure_count == 1
service.record_probe_outcome(session, row, failure)
assert row.last_test_category == "auth_failed"
assert service.record_probe_outcome(session, row, failure) is True
assert row.circuit_state == "open"
session.rollback()
finally:
session.close()
def test_usable_list_filters_disabled_and_open_sources(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
good = _create(client)["id"]
disabled = _create(client)["id"]
tripped = _create(client)["id"]
client.post(f"/datasources/{disabled}/disable")
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, tripped)
def ids(path: str) -> set[str]:
response = client.get(path)
assert response.status_code == 200
return {item["id"] for item in response.json()["data"]["items"]}
everything = ids("/datasources")
assert {good, disabled, tripped} <= everything
usable = ids("/datasources?usable=true")
assert good in usable and disabled not in usable and tripped not in usable
assert ids("/datasources?usable=false") == everything
clock.advance(601) # cooldown over: usable again, and the circuit is persisted closed
assert tripped in ids("/datasources?usable=true")
assert _stored(tripped).circuit_state == "closed"
def test_detail_get_closes_elapsed_cooldown(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
still_open = client.get(f"/datasources/{ds_id}").json()["data"]
assert still_open["circuit_state"] == "open"
assert still_open["circuit_open_until"] is not None
clock.advance(601) # default cooldown is 600s
detail = client.get(f"/datasources/{ds_id}")
assert detail.status_code == 200
data = detail.json()["data"]
assert data["circuit_state"] == "closed"
assert data["circuit_opened_at"] is None and data["circuit_open_until"] is None
stored = _stored(ds_id)
assert stored.circuit_state == "closed" and stored.circuit_opened_at is None
assert stored.circuit_failure_count == 0
def test_plain_list_closes_elapsed_cooldown(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable") # disabled rows are normalized too
clock.advance(601)
items = client.get("/datasources").json()["data"]["items"]
item = next(entry for entry in items if entry["id"] == ds_id)
assert item["circuit_state"] == "closed"
assert item["circuit_opened_at"] is None and item["circuit_open_until"] is None
assert _stored(ds_id).circuit_state == "closed"
# --- secrecy and validation ---------------------------------------------------------------------
def test_public_json_never_contains_password_or_ciphertext(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
ciphertext = _stored(ds_id).secret_ciphertext
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
surfaces = [json.dumps(created)]
for _ in range(3):
surfaces.append(_test(client, ds_id).text)
surfaces.append(_test(client, ds_id).text) # circuit_open conflict
surfaces.append(client.get(f"/datasources/{ds_id}").text)
surfaces.append(client.get("/datasources").text)
surfaces.append(client.get("/datasources?usable=true").text)
surfaces.append(client.post(f"/datasources/{ds_id}/disable").text)
surfaces.append(client.post(f"/datasources/{ds_id}/enable").text)
surfaces.append(client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password="")).text)
for surface in surfaces:
assert SENTINEL not in surface and ciphertext not in surface
assert "secret_ciphertext" not in surface and '"password"' not in surface
for event in _audit_events(ds_id, "datasource.circuit_open"):
dumped = json.dumps(event.payload) + event.idempotency_key
assert SENTINEL not in dumped and ciphertext not in dumped and "synthetic_user" not in dumped
def test_host_is_required_only(cleanup) -> None:
client = _client(cleanup, ADMIN)
for blank in ("", " ", "\t "):
response = client.post("/datasources", json=_body(host=blank))
assert response.status_code == 400, repr(blank)
assert response.json()["error"]["code"] == 40000
# No format check any more: non-empty unusual strings are accepted and stored trimmed.
for index, host in enumerate(("my host.example", "postgres://u:p@h/db", " padded.example ", "db_01/√")):
created = _create(client, host=host, name=f"{NAME_PREFIX}host-{index}")
assert created["host"] == host.strip()
too_long = client.post("/datasources", json=_body(host="h" * 256))
assert too_long.status_code == 400
ds_id = _create(client)["id"]
assert client.patch(f"/datasources/{ds_id}", json={"host": "weird host!"}).status_code == 200
assert client.patch(f"/datasources/{ds_id}", json={"host": " "}).status_code == 400
def test_enable_unknown_and_foreign_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
assert client.post(f"/datasources/{uuid.uuid4()}/enable").status_code == 404
assert client.post("/datasources/not-a-uuid/enable").status_code == 404
assert _client(cleanup, OPERATOR).post(f"/datasources/{uuid.uuid4()}/enable").status_code == 403
# --- probe retry ----------------------------------------------------------------------------------
def _target() -> ProbeTarget:
return ProbeTarget(
engine="postgresql", host="h.invalid", port=5432, database="d", username="u", password="p"
)
@pytest.mark.parametrize(
("first", "second", "calls", "expected"),
[
(ProbeCategory.TIMEOUT, ProbeCategory.SUCCESS, 2, ProbeCategory.SUCCESS),
(ProbeCategory.UNREACHABLE, ProbeCategory.SUCCESS, 2, ProbeCategory.SUCCESS),
(ProbeCategory.TIMEOUT, ProbeCategory.TIMEOUT, 2, ProbeCategory.TIMEOUT),
(ProbeCategory.AUTH_FAILED, ProbeCategory.SUCCESS, 1, ProbeCategory.AUTH_FAILED),
(ProbeCategory.REJECTED, ProbeCategory.SUCCESS, 1, ProbeCategory.REJECTED),
(ProbeCategory.SUCCESS, ProbeCategory.TIMEOUT, 1, ProbeCategory.SUCCESS),
],
)
def test_probe_retries_only_timeout_and_unreachable_once(monkeypatch, first, second, calls, expected) -> None:
queue = [first, second]
seen: list[int] = []
def _connector(_target, _timeout):
seen.append(1)
return queue.pop(0)
monkeypatch.setitem(probe_module._CONNECTORS, "postgresql", _connector)
result = probe_datasource(_target(), max_attempts=2)
assert result.category is expected
assert len(seen) == calls
def test_probe_default_is_single_attempt_and_cap_is_respected(monkeypatch) -> None:
seen: list[int] = []
def _connector(_target, _timeout):
seen.append(1)
return ProbeCategory.TIMEOUT
monkeypatch.setitem(probe_module._CONNECTORS, "postgresql", _connector)
probe_datasource(_target())
assert len(seen) == 1
seen.clear()
probe_datasource(_target(), max_attempts=5)
assert len(seen) == 5 # callers (settings) cap attempts at 2; the function obeys its argument
def test_service_passes_configured_timeout_and_attempts(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
captured: dict = {}
def _probe(target, **kwargs):
captured.update(kwargs)
return ProbeResult(ProbeCategory.SUCCESS, "ok")
monkeypatch.setattr(service, "probe_datasource", _probe)
monkeypatch.setenv("WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS", "2.5")
monkeypatch.setenv("WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS", "1")
from watchman.core.config import reload_settings
reload_settings()
assert _test(client, ds_id).status_code == 200
assert captured == {"timeout_seconds": 2.5, "max_attempts": 1}
@@ -0,0 +1,328 @@
"""Scheduled datasource health check tests (M03 S7, D23).
Why: the health check probes saved sources unattended, so the switch, the cron guard, the
skip rules, the secret hygiene of its audit events and the beat wiring need executable proof.
Boundary: real platform Postgres like test_datasource_circuit; probes are fakes (no network)
and the candidate list is restricted to this run's rows so other dev rows are never touched.
Depends on test_datasource_api helpers, the health check service and the jobs adapter.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
SENTINEL,
_audit_events,
_client,
_create,
_stored,
cleanup,
datasource_key,
)
from watchman.core.config import _settings_from_env_map, get_settings, reload_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget
from watchman.jobs.schedule import (
DATASOURCE_HEALTHCHECK_ENTRY,
DATASOURCE_HEALTHCHECK_TASK,
build_beat_schedule,
)
from watchman.models.datasource import DataSource
from watchman.services import datasource_healthcheck as healthcheck
from watchman.services import datasources as service
from watchman.services.cron import is_valid_unix_cron
VALID_CRON = "*/5 * * * *"
class FakeProbe:
"""Records targets; returns the queued category (the last one repeats)."""
def __init__(self, *categories: ProbeCategory) -> None:
self.categories = list(categories) or [ProbeCategory.SUCCESS]
self.targets: list[ProbeTarget] = []
def __call__(self, target: ProbeTarget, **_kwargs) -> ProbeResult:
self.targets.append(target)
category = self.categories.pop(0) if len(self.categories) > 1 else self.categories[0]
return ProbeResult(category=category, message=f"fixed text for {category.value}")
@pytest.fixture(autouse=True)
def only_test_rows(monkeypatch: pytest.MonkeyPatch):
"""Limit the candidate list to rows created by this test run."""
real = healthcheck.list_datasources
def _filtered(session, **kwargs):
return [row for row in real(session, **kwargs) if row.name.startswith(NAME_PREFIX)]
monkeypatch.setattr(healthcheck, "list_datasources", _filtered)
def _install(monkeypatch: pytest.MonkeyPatch, *categories: ProbeCategory) -> FakeProbe:
fake = FakeProbe(*categories)
monkeypatch.setattr(service, "probe_datasource", fake)
return fake
def _settings(*, enabled: bool = True, cron: str = VALID_CRON):
return get_settings().model_copy(
update={"datasource_healthcheck_enabled": enabled, "datasource_healthcheck_cron": cron}
)
def _run(settings=None) -> healthcheck.HealthcheckSummary:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
summary = healthcheck.run_datasource_healthcheck(session, settings=settings or _settings())
session.commit()
return summary
finally:
session.close()
def _create_source(client, label: str) -> str:
return _create(client, host=f"{label}.synthetic.invalid")["id"]
def _open_circuit(ds_id: str) -> None:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(ds_id)))
row.circuit_state = "open"
row.circuit_opened_at = datetime.now(timezone.utc) - timedelta(seconds=5)
session.commit()
finally:
session.close()
# --- switch and cron guard -----------------------------------------------------------------
def test_disabled_flag_probes_nothing(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "off")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run(_settings(enabled=False))
assert summary.skipped_reason == healthcheck.SKIP_DISABLED
assert fake.targets == []
stored = _stored(ds_id)
assert stored.last_test_category is None and stored.last_test_at is None
@pytest.mark.parametrize("cron", ["", "not a cron", "* * * *", "* * * * * *", "*/5 * * * ?", "61 * * * *"])
def test_invalid_cron_is_a_noop(cleanup, monkeypatch, cron) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "badcron")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run(_settings(cron=cron))
assert summary.skipped_reason == healthcheck.SKIP_INVALID_CRON
assert fake.targets == []
assert _stored(ds_id).last_test_category is None
# --- skip rules ----------------------------------------------------------------------------
def test_disabled_and_open_circuit_sources_are_skipped(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
live = _create_source(client, "live")
disabled = _create_source(client, "disabled")
opened = _create_source(client, "opened")
assert client.post(f"/datasources/{disabled}/disable").status_code == 200
_open_circuit(opened)
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run()
assert [t.host for t in fake.targets] == ["live.synthetic.invalid"]
assert summary.checked == 1 and summary.succeeded == 1
assert _stored(live).last_test_category == "success"
for skipped in (disabled, opened):
assert _stored(skipped).last_test_category is None
# The health check never changes enabled.
assert _stored(disabled).enabled is False and _stored(live).enabled is True
def test_source_disabled_mid_loop_is_skipped(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
first = _create_source(client, "first")
second = _create_source(client, "second")
fake = FakeProbe(ProbeCategory.SUCCESS)
def _probe_then_disable_other(target, **kwargs):
result = fake(target, **kwargs)
# While the first source is probed, the other one gets disabled.
other = second if target.host.startswith("first.") else first
client.post(f"/datasources/{other}/disable")
return result
monkeypatch.setattr(service, "probe_datasource", _probe_then_disable_other)
summary = _run()
assert len(fake.targets) == 1
assert summary.checked == 1 and summary.skipped == 1
# --- outcomes ------------------------------------------------------------------------------
def test_success_updates_last_test(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "ok")
_install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run()
stored = _stored(ds_id)
assert stored.last_test_category == "success"
assert stored.last_test_at is not None
assert stored.circuit_state == "closed"
assert summary.categories == {"success": 1}
assert _audit_events(ds_id, "datasource.healthcheck_failed") == []
def test_failure_updates_last_test_and_audits_without_secrets(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "bad")
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
summary = _run()
stored = _stored(ds_id)
assert stored.last_test_category == "auth_failed"
assert stored.last_test_at is not None
assert stored.enabled is True
assert stored.circuit_failure_count == 1
assert summary.failed == 1 and summary.categories == {"auth_failed": 1}
events = _audit_events(ds_id, "datasource.healthcheck_failed")
assert len(events) == 1
payload = events[0].payload
assert set(payload) == {"id", "name", "engine", "category"}
assert payload["category"] == "auth_failed"
dumped = json.dumps(payload)
for secret in (SENTINEL, "bad.synthetic.invalid", "synthetic_user", "synthetic_db"):
assert secret not in dumped
def test_repeated_failures_open_the_circuit(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "flaky")
fake = _install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(4):
_run()
assert len(fake.targets) == 3 # the fourth run skips the now-open source
assert _stored(ds_id).circuit_state == "open"
assert len(_audit_events(ds_id, "datasource.circuit_open")) == 1
# --- cron validation and beat wiring -------------------------------------------------------
@pytest.mark.parametrize(
"expression",
["*/5 * * * *", "0 3 * * *", "15,45 8-18 * * 1-5", "0 0 1 * *", " 30 2 * * 0 "],
)
def test_valid_cron_accepted(expression) -> None:
assert is_valid_unix_cron(expression)
@pytest.mark.parametrize(
"expression",
[None, "", " ", "* * * *", "* * * * * *", "@daily", "0 0 L * *", "0 0 * * mon", "0 0 1 * 1"],
)
def test_invalid_cron_rejected(expression) -> None:
# The last case restricts both day fields; croniter ORs them and Celery ANDs them.
assert not is_valid_unix_cron(expression)
def test_beat_schedule_only_when_enabled_and_valid() -> None:
base = get_settings()
def schedule(enabled: bool, cron: str):
return build_beat_schedule(
base.model_copy(
update={"datasource_healthcheck_enabled": enabled, "datasource_healthcheck_cron": cron}
)
)
assert schedule(False, VALID_CRON) == {}
assert schedule(True, "") == {}
assert schedule(True, "nonsense") == {}
entry = schedule(True, "*/5 * * * *")[DATASOURCE_HEALTHCHECK_ENTRY]
assert entry["task"] == DATASOURCE_HEALTHCHECK_TASK
assert entry["schedule"].minute == {m for m in range(0, 60, 5)}
def test_settings_from_env_map_defaults_and_values() -> None:
off = _settings_from_env_map({})
assert off.datasource_healthcheck_enabled is False
assert off.datasource_healthcheck_cron == ""
on = _settings_from_env_map(
{
"WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED": "true",
"WATCHMAN_DATASOURCE_HEALTHCHECK_CRON": " */10 * * * * ",
}
)
assert on.datasource_healthcheck_enabled is True
assert on.datasource_healthcheck_cron == "*/10 * * * *"
# Unknown boolean text stays off.
assert _settings_from_env_map(
{"WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED": "maybe"}
).datasource_healthcheck_enabled is False
def test_celery_app_registers_task_and_schedule_from_env(monkeypatch) -> None:
from watchman.jobs import celery_app as module
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "true")
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", "*/5 * * * *")
reload_settings()
app = module.create_celery_app()
assert DATASOURCE_HEALTHCHECK_ENTRY in app.conf.beat_schedule
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "false")
reload_settings()
assert module.create_celery_app().conf.beat_schedule == {}
assert DATASOURCE_HEALTHCHECK_TASK in module.celery_app.tasks
assert "watchman.probe.ping" in module.celery_app.tasks
def test_celery_task_runs_check_when_enabled(cleanup, monkeypatch) -> None:
from watchman.jobs.celery_app import datasource_healthcheck
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "task")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "false")
reload_settings()
assert datasource_healthcheck()["skipped_reason"] == healthcheck.SKIP_DISABLED
assert fake.targets == []
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "true")
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", VALID_CRON)
reload_settings()
result = datasource_healthcheck()
assert result["skipped_reason"] is None and result["checked"] >= 1
assert _stored(ds_id).last_test_category == "success"
@@ -0,0 +1,338 @@
"""Connector probe tests: category mapping, secret hygiene and live per-engine checks.
Why: the probe is the only code that talks to customer databases, so classification and
"no secret in message/log" must be proven per engine, not assumed from one driver.
Boundary: live tests use isolated databases from .env.local and skip (with a reason)
when an engine is not reachable; they never write to the platform database.
Depends on watchman.datasources and watchman.core.config.merge_layered_env.
"""
from __future__ import annotations
import logging
import socket
import time
import psycopg
import pymssql
import pymysql
import pytest
from watchman.core.config import merge_layered_env
from watchman.datasources import (
ProbeCategory,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.datasources import probe as probe_module
SENTINEL = "Zq9-sentinel-pw-7f3a1c"
NON_ROUTABLE_HOST = "10.255.255.1"
ENGINES = {
"postgresql": "WATCHMAN_TEST_PG",
"mysql": "WATCHMAN_TEST_MYSQL",
"sqlserver": "WATCHMAN_TEST_SQLSERVER",
}
def _closed_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _target(engine: str, **overrides) -> ProbeTarget:
p = ENGINES[engine]
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
if any(not env.get(f"{p}_{k}") for k in keys):
pytest.skip(f"{p}_* env not configured")
base = dict(
engine=engine,
host=env[f"{p}_HOST"],
port=int(env[f"{p}_PORT"]),
database=env[f"{p}_DATABASE"],
username=env[f"{p}_USER"],
password=env[f"{p}_PASSWORD"],
)
base.update(overrides)
return ProbeTarget(**base)
@pytest.fixture(params=sorted(ENGINES))
def engine(request) -> str:
return request.param
@pytest.fixture
def live_engine(engine: str) -> str:
"""Skip (not pass) when the engine cannot be reached with the correct password."""
result = probe_datasource(_target(engine), timeout_seconds=5)
if result.category is not ProbeCategory.SUCCESS:
pytest.skip(f"{engine} live instance not available ({result.category.value})")
return engine
# --- unit: mapping and fixed messages (no network) -----------------------------------
def _raise(exc: BaseException):
def _inner(*_a, **_k):
raise exc
return _inner
def _mysql_timeout() -> BaseException:
err = pymysql.err.OperationalError(2003, "Can't connect to MySQL server (timed out)")
err.__cause__ = TimeoutError("timed out")
return err
@pytest.mark.parametrize(
("engine", "patch_target", "exc", "expected"),
[
("mysql", (pymysql, "connect"), _mysql_timeout(), ProbeCategory.TIMEOUT),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1045, "denied"), ProbeCategory.AUTH_FAILED),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(2003, "refused"), ProbeCategory.UNREACHABLE),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1044, "denied to db"), ProbeCategory.AUTH_FAILED),
# Unknown database / host not allowed: server answered, no credential evidence.
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1049, "unknown db"), ProbeCategory.REJECTED),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1130, "host not allowed"), ProbeCategory.REJECTED),
],
)
def test_driver_exception_mapping(monkeypatch, engine, patch_target, exc, expected):
monkeypatch.setattr(patch_target[0], patch_target[1], _raise(exc))
target = ProbeTarget(engine=engine, host="h.invalid", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
# Message is fixed text, never the driver's exception text.
assert str(exc) not in result.message
assert SENTINEL not in result.message
@pytest.mark.parametrize(
("exc", "tcp", "expected"),
[
# SQLSTATE 28xxx is trusted when libpq supplies it, whatever the TCP check says.
(psycopg.errors.InvalidPassword("bad"), "open", ProbeCategory.AUTH_FAILED),
# No SQLSTATE and port open: only positive text evidence counts as auth_failed.
(psycopg.OperationalError('FATAL: password authentication failed for user "u"'), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError("FATAL: Authentication failed"), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError("致命错误: 用户 u Password 认证失败"), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError('FATAL: no pg_hba.conf entry for host'), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError('FATAL: database "d" does not exist'), "open", ProbeCategory.REJECTED),
(psycopg.OperationalError('致命错误: 数据库 "d" 不存在'), "open", ProbeCategory.REJECTED),
# Unclassifiable text must not be guessed into auth_failed.
(psycopg.OperationalError("connection failed: <unrecognised FATAL>"), "open", ProbeCategory.REJECTED),
# Port open but libpq's own connect timeout fired: a genuine stall.
(psycopg.errors.ConnectionTimeout("connection timeout expired"), "open", ProbeCategory.TIMEOUT),
# Windows libpq waits out the timeout on a refused port; TCP check corrects it.
(psycopg.errors.ConnectionTimeout("connection timeout expired"), "refused", ProbeCategory.UNREACHABLE),
(psycopg.OperationalError("connection failed"), "refused", ProbeCategory.UNREACHABLE),
(psycopg.OperationalError("connection failed"), "timeout", ProbeCategory.TIMEOUT),
],
)
def test_postgresql_exception_mapping(monkeypatch, exc, tcp, expected):
monkeypatch.setattr(psycopg, "connect", _raise(exc))
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: tcp)
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
assert str(exc) not in result.message
@pytest.mark.parametrize(
("exc", "tcp", "expected"),
[
# Login rejected: only the "login failed" text is positive evidence; the code is ignored.
(pymssql.OperationalError((18456, b"Login failed for user")), "open", ProbeCategory.AUTH_FAILED),
(pymssql.OperationalError((18456, b"Cannot open database requested by the login. The login failed.")), "open", ProbeCategory.REJECTED),
(pymssql.OperationalError((18456, b"something else entirely")), "open", ProbeCategory.REJECTED),
# pymssql can carry a stale 18456 on a network failure; TCP evidence must win.
(pymssql.OperationalError((18456, b"Unable to connect: TDS server is unavailable")), "refused", ProbeCategory.UNREACHABLE),
(pymssql.OperationalError((18456, b"TDS server connection timed out")), "timeout", ProbeCategory.TIMEOUT),
# Port accepts TCP but login stalls.
(pymssql.OperationalError(20003, b"TDS server connection timed out"), "open", ProbeCategory.TIMEOUT),
],
)
def test_sqlserver_exception_mapping(monkeypatch, exc, tcp, expected):
monkeypatch.setattr(pymssql, "connect", _raise(exc))
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: tcp)
target = ProbeTarget(engine="sqlserver", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
assert "Login failed" not in result.message
def test_postgresql_replacement_chars_trigger_gb18030_reclassification(monkeypatch):
"""A UTF8 client mangles zh_CN server text; the GB18030 retry restores the keywords."""
encodings: list[str] = []
def _fake_connect(*_a, **kwargs):
encodings.append(kwargs["client_encoding"])
if kwargs["client_encoding"] == "UTF8":
raise psycopg.OperationalError("\ufffd\ufffd\ufffd: \ufffd\ufffd \ufffd\ufffd\ufffd\ufffd")
raise psycopg.OperationalError("致命错误: 用户 u Password 认证失败")
monkeypatch.setattr(psycopg, "connect", _fake_connect)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "open")
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert probe_datasource(target).category is ProbeCategory.AUTH_FAILED
assert encodings == ["UTF8", "GB18030"]
def test_postgresql_no_retry_when_utf8_text_is_already_classified(monkeypatch):
encodings: list[str] = []
def _fake_connect(*_a, **kwargs):
encodings.append(kwargs["client_encoding"])
raise psycopg.OperationalError('FATAL: database "d" does not exist')
monkeypatch.setattr(psycopg, "connect", _fake_connect)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "open")
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert probe_datasource(target).category is ProbeCategory.REJECTED
assert encodings == ["UTF8"]
def test_rejected_message_is_fixed():
from watchman.datasources.probe import _result
assert _result(ProbeCategory.REJECTED).message == "data source rejected the connection"
def test_unexpected_driver_error_is_unreachable_without_leaking(monkeypatch):
monkeypatch.setattr(psycopg, "connect", _raise(RuntimeError(f"boom {SENTINEL}")))
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is ProbeCategory.UNREACHABLE
assert SENTINEL not in result.message
@pytest.mark.parametrize(
("kind", "engine"),
[("database", "oracle"), ("api", "postgresql"), ("file", "mysql"), ("database", "")],
)
def test_unsupported_kind_or_engine_opens_no_socket(monkeypatch, kind, engine):
def _forbidden(*_a, **_k):
raise AssertionError("driver must not be called for unsupported targets")
monkeypatch.setattr(psycopg, "connect", _forbidden)
monkeypatch.setattr(pymysql, "connect", _forbidden)
monkeypatch.setattr(pymssql, "connect", _forbidden)
monkeypatch.setattr(socket, "create_connection", _forbidden)
target = ProbeTarget(kind=kind, engine=engine, host="h", port=1, database="d", username="u", password=SENTINEL)
with pytest.raises(UnsupportedDataSourceError) as info:
probe_datasource(target)
assert SENTINEL not in str(info.value)
assert engine not in str(info.value) or engine == ""
def test_probe_target_repr_hides_password():
target = ProbeTarget(engine="mysql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert SENTINEL not in repr(target)
def test_timeout_is_passed_to_driver_connect(monkeypatch):
seen: dict[str, object] = {}
def _capture(*_a, **kwargs):
seen.update(kwargs)
raise psycopg.OperationalError("x")
monkeypatch.setattr(psycopg, "connect", _capture)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "refused")
probe_datasource(
ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["connect_timeout"] == 3
seen.clear()
monkeypatch.setattr(pymysql, "connect", _capture)
probe_datasource(
ProbeTarget(engine="mysql", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["connect_timeout"] == 2.5
seen.clear()
monkeypatch.setattr(pymssql, "connect", _capture)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "refused")
probe_datasource(
ProbeTarget(engine="sqlserver", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["login_timeout"] == 3
# --- live: one engine at a time -------------------------------------------------------
def test_live_success(live_engine, caplog):
caplog.set_level(logging.DEBUG)
target = _target(live_engine)
result = probe_datasource(target, timeout_seconds=5)
assert result.category is ProbeCategory.SUCCESS
# Exact log shape instead of a substring check: dev passwords can be short words that
# legitimately appear in engine names, so "not in" would be both flaky and weak.
assert [r.getMessage() for r in caplog.records if r.name == probe_module.logger.name] == [
f"datasource probe engine={target.engine} host={target.host} port={target.port} "
f"database={target.database} category=success"
]
assert result.message == "connection succeeded"
def test_live_wrong_password(live_engine, caplog):
caplog.set_level(logging.DEBUG)
result = probe_datasource(_target(live_engine, password=SENTINEL), timeout_seconds=5)
assert result.category is ProbeCategory.AUTH_FAILED
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
def test_live_missing_database_is_rejected_not_auth_failed(live_engine, caplog):
"""Regression: valid credentials + nonexistent database must not read as bad password."""
caplog.set_level(logging.DEBUG)
target = _target(live_engine, database="watchman_no_such_db_s2")
result = probe_datasource(target, timeout_seconds=5)
assert result.category is ProbeCategory.REJECTED
assert result.message == "data source rejected the connection"
assert target.password not in result.message
assert "category=rejected" in caplog.text
assert "\ufffd" not in caplog.text
def test_live_connection_refused_on_closed_port(engine, caplog):
caplog.set_level(logging.DEBUG)
result = probe_datasource(
_target(engine, host="127.0.0.1", port=_closed_port(), password=SENTINEL), timeout_seconds=5
)
assert result.category is ProbeCategory.UNREACHABLE
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
def test_live_timeout_on_non_routable_address(engine, caplog):
caplog.set_level(logging.DEBUG)
started = time.monotonic()
result = probe_datasource(
_target(engine, host=NON_ROUTABLE_HOST, port=5432, password=SENTINEL), timeout_seconds=2
)
elapsed = time.monotonic() - started
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
assert elapsed < 15, "probe exceeded the driver timeout bound"
if result.category is not ProbeCategory.TIMEOUT:
# The OS may fail fast (no route) instead of dropping packets; do not call that a pass.
pytest.skip(
f"live timeout not reproducible for {engine}: OS returned "
f"{result.category.value} in {elapsed:.1f}s"
)
assert result.category is ProbeCategory.TIMEOUT
def test_module_logger_name_is_stable():
assert probe_module.logger.name == "watchman.datasources.probe"
@@ -0,0 +1,197 @@
"""RLS and constraint tests for data_sources against local Postgres."""
from __future__ import annotations
import uuid
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.orm import Session, sessionmaker
from watchman.core.config import get_settings, reload_settings
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
from watchman.models.datasource import DataSource
# Opaque stand-in; the table stores whatever text it is given, so no real key is needed.
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
@pytest.fixture()
def ds_factory():
reload_settings()
reset_engine()
_ensure_after_begin_listener()
settings = get_settings()
engine = create_engine(settings.database_url, pool_pre_ping=True)
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
created: list[tuple[str, str]] = [] # (tenant_id, name)
yield factory, created, settings
cleanup = factory()
try:
for tenant, name in created:
set_tenant(cleanup, tenant)
cleanup.execute(
text("DELETE FROM data_sources WHERE tenant_id = :t AND name = :n"),
{"t": tenant, "n": name},
)
cleanup.commit()
finally:
cleanup.close()
engine.dispose()
reset_engine()
def _row(tenant_id: str, name: str, **overrides) -> DataSource: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant_id,
name=name,
kind="database",
engine="postgresql",
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
secret_ciphertext=FAKE_CIPHERTEXT,
)
values.update(overrides)
return DataSource(**values)
def test_data_sources_owner_is_not_app_role() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
owner = conn.execute(
text(
"SELECT tableowner FROM pg_tables "
"WHERE schemaname = 'public' AND tablename = 'data_sources'"
)
).scalar_one()
forced = conn.execute(
text(
"SELECT relrowsecurity, relforcerowsecurity FROM pg_class "
"WHERE relname = 'data_sources'"
)
).one()
engine.dispose()
assert owner != "watchman_app"
assert forced.relrowsecurity is True
assert forced.relforcerowsecurity is True
def test_insert_under_configured_tenant_and_defaults(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-rls-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
row = _row(settings.tenant_id, name)
session.add(row)
session.commit()
stored = session.execute(
text(
"SELECT enabled, read_only_intent, created_at IS NOT NULL AS has_created "
"FROM data_sources WHERE name = :n"
),
{"n": name},
).one()
assert stored.enabled is True
assert stored.read_only_intent is True
assert stored.has_created is True
finally:
session.close()
def test_other_tenant_cannot_see_row(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-iso-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name))
session.commit()
finally:
session.close()
other: Session = factory()
try:
set_tenant(other, "other-tenant")
assert other.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 0
finally:
other.close()
bare: Session = factory()
try:
assert bare.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 0
finally:
bare.close()
same: Session = factory()
try:
set_tenant(same, settings.tenant_id)
assert same.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 1
finally:
same.close()
def test_write_for_foreign_tenant_is_rejected(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, _created, settings = ds_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row("other-tenant", f"ds-foreign-{uuid.uuid4().hex[:12]}"))
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
finally:
session.close()
def test_duplicate_name_in_tenant_is_rejected(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-dup-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name))
session.commit()
session.add(_row(settings.tenant_id, name))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[
{"kind": "api"},
{"engine": "oracle"},
{"port": 0},
{"port": 65536},
],
)
def test_check_constraints_backstop(ds_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-chk-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@@ -0,0 +1,138 @@
"""Unit tests for datasource password encryption and kind/engine validation."""
from __future__ import annotations
import pytest
from cryptography.fernet import Fernet
from watchman.core.config import get_settings, reload_settings, settings_as_public_dict
from watchman.core.secrets import (
KEY_ENV_NAME,
SecretDecryptError,
SecretKeyError,
decrypt_secret,
encrypt_secret,
)
from watchman.models.datasource import DataSource, validate_kind_engine
# Unique marker so a leak into messages or repr is detectable; not a real credential.
SENTINEL = "sentinel-7f3a91c2-not-a-real-password"
@pytest.fixture()
def with_key(monkeypatch: pytest.MonkeyPatch):
key = Fernet.generate_key().decode("ascii")
monkeypatch.setenv(KEY_ENV_NAME, key)
reload_settings()
yield key
monkeypatch.undo()
reload_settings()
def test_roundtrip(with_key: str) -> None:
token = encrypt_secret(SENTINEL)
assert SENTINEL not in token
assert decrypt_secret(token) == SENTINEL
def test_encrypt_is_not_deterministic(with_key: str) -> None:
assert encrypt_secret(SENTINEL) != encrypt_secret(SENTINEL)
def test_wrong_key_fails_without_leak(monkeypatch: pytest.MonkeyPatch, with_key: str) -> None:
token = encrypt_secret(SENTINEL)
other_key = Fernet.generate_key().decode("ascii")
monkeypatch.setenv(KEY_ENV_NAME, other_key)
reload_settings()
with pytest.raises(SecretDecryptError) as exc:
decrypt_secret(token)
message = str(exc.value)
assert SENTINEL not in message
assert other_key not in message
assert with_key not in message
def test_garbage_ciphertext_fails(with_key: str) -> None:
with pytest.raises(SecretDecryptError):
decrypt_secret("not-a-fernet-token")
@pytest.mark.parametrize("value", ["", " ", "CHANGE-ME"])
def test_missing_key_names_env_var(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
monkeypatch.setenv(KEY_ENV_NAME, value)
reload_settings()
try:
with pytest.raises(SecretKeyError) as exc:
encrypt_secret(SENTINEL)
assert KEY_ENV_NAME in str(exc.value)
assert SENTINEL not in str(exc.value)
finally:
monkeypatch.undo()
reload_settings()
def test_malformed_key_does_not_echo_key(monkeypatch: pytest.MonkeyPatch) -> None:
bad = "short-bad-key-value"
monkeypatch.setenv(KEY_ENV_NAME, bad)
reload_settings()
try:
with pytest.raises(SecretKeyError) as exc:
encrypt_secret(SENTINEL)
assert bad not in str(exc.value)
assert SENTINEL not in str(exc.value)
assert exc.value.__cause__ is None
assert exc.value.__suppress_context__ is True
finally:
monkeypatch.undo()
reload_settings()
def test_public_settings_exclude_key(with_key: str) -> None:
public = settings_as_public_dict(get_settings())
assert with_key not in repr(public)
assert all("key" not in name for name in public)
assert with_key not in repr(get_settings())
def test_datasource_key_not_required_at_boot() -> None:
from watchman.core.config import REQUIRED_RUNTIME_KEYS
assert KEY_ENV_NAME not in REQUIRED_RUNTIME_KEYS
def test_validate_accepts_supported_values() -> None:
for engine in ("postgresql", "mysql", "sqlserver"):
validate_kind_engine("database", engine)
@pytest.mark.parametrize(
("kind", "engine"),
[
("api", "postgresql"),
("", "postgresql"),
("database", "oracle"),
("database", "PostgreSQL"),
("database", ""),
],
)
def test_validate_rejects_unsupported(kind: str, engine: str) -> None:
with pytest.raises(ValueError):
validate_kind_engine(kind, engine)
def test_model_repr_hides_secret() -> None:
ciphertext = f"gAAAA-{SENTINEL}"
row = DataSource(
tenant_id="t1",
name="src",
kind="database",
engine="postgresql",
host="h",
port=5432,
database_name="d",
username="u",
secret_ciphertext=ciphertext,
)
text = repr(row)
assert SENTINEL not in text
assert "secret" not in text