feat(queries): 完成 M04 查询定义与版本激活

交付不可变查询版本、保存即生效与激活(D26),并带控制台列表筛选排序与试跑预览;补 RLS 下 current_version_no 回填迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-18 18:32:24 +08:00
1 parent 8c0335040f
commit 21cc721fcc
97 files changed
+13354 -153

No files matched your search

@@ -0,0 +1,136 @@
"""Create query_definitions and query_versions with forced RLS.
Revision ID: 20261118_0006
Revises: 20261118_0005
Create Date: 2026-11-18
query_versions rows are immutable by contract. watchman_app still gets UPDATE so the ORM
and edge-case maintenance keep working; the service layer refuses content updates.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261118_0006"
down_revision: Union[str, None] = "20261118_0005"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def _enable_rls(table: str) -> None:
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 upgrade() -> None:
op.create_table(
DEFINITIONS,
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(
"datasource_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("data_sources.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("draft_sql_template", sa.Text(), nullable=False),
sa.Column(
"draft_param_schema",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column(
"draft_output_schema",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column(
"draft_allowed_identifiers",
postgresql.JSONB(),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column("draft_timeout_ms", sa.Integer(), server_default=sa.text("10000"), nullable=False),
sa.Column("draft_max_rows", sa.Integer(), server_default=sa.text("100"), nullable=False),
sa.Column("latest_published_version_no", sa.Integer(), 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_query_definitions_tenant_name"),
sa.CheckConstraint("draft_timeout_ms BETWEEN 1 AND 300000", name="ck_query_definitions_timeout"),
sa.CheckConstraint("draft_max_rows BETWEEN 1 AND 10000", name="ck_query_definitions_max_rows"),
sa.CheckConstraint(
"latest_published_version_no IS NULL OR latest_published_version_no >= 1",
name="ck_query_definitions_latest_version",
),
)
op.create_index("ix_query_definitions_datasource_id", DEFINITIONS, ["datasource_id"])
op.create_table(
VERSIONS,
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(
"definition_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("query_definitions.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("version_no", sa.Integer(), nullable=False),
sa.Column("sql_template", sa.Text(), nullable=False),
sa.Column("param_schema", postgresql.JSONB(), nullable=False),
sa.Column("output_schema", postgresql.JSONB(), nullable=False),
sa.Column("allowed_identifiers", postgresql.JSONB(), nullable=False),
sa.Column("timeout_ms", sa.Integer(), nullable=False),
sa.Column("max_rows", sa.Integer(), nullable=False),
sa.Column("published_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.Column("published_by", sa.String(length=128), nullable=True),
sa.UniqueConstraint("definition_id", "version_no", name="uq_query_versions_def_version"),
sa.CheckConstraint("version_no >= 1", name="ck_query_versions_version_no"),
sa.CheckConstraint("timeout_ms BETWEEN 1 AND 300000", name="ck_query_versions_timeout"),
sa.CheckConstraint("max_rows BETWEEN 1 AND 10000", name="ck_query_versions_max_rows"),
)
_enable_rls(DEFINITIONS)
_enable_rls(VERSIONS)
def downgrade() -> None:
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {VERSIONS}")
op.drop_table(VERSIONS)
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {DEFINITIONS}")
op.drop_index("ix_query_definitions_datasource_id", table_name=DEFINITIONS)
op.drop_table(DEFINITIONS)
@@ -0,0 +1,63 @@
"""Make query_versions append-only at the database boundary.
Revision ID: 20261118_0007
Revises: 20261118_0006
Create Date: 2026-11-18
Published versions are immutable (D24). 0006 still granted UPDATE/DELETE to watchman_app and
relied on a Python helper nobody calls on a write path. Two independent layers now enforce it:
1. privileges: watchman_app keeps SELECT and INSERT only (UPDATE/DELETE revoked);
2. a statement-level BEFORE UPDATE/DELETE/TRUNCATE trigger that always raises, so even the
table owner or a future GRANT cannot change or remove a version. Statement level on
purpose: it fires even when forced RLS hides every row from the caller.
There is no application maintenance path. A superuser who must purge rows (test cleanup,
data-retention work) has to opt out explicitly with `SET LOCAL session_replication_role =
replica`, which is not available to the application or migrator roles.
"""
from __future__ import annotations
from typing import Sequence, Union
from alembic import op
revision: str = "20261118_0007"
down_revision: Union[str, None] = "20261118_0006"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
VERSIONS = "query_versions"
FUNCTION = "query_versions_reject_mutation"
TRIGGER = "trg_query_versions_append_only"
def upgrade() -> None:
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
op.execute(
f"""
CREATE OR REPLACE FUNCTION {FUNCTION}() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'query_versions is append-only: published versions are immutable'
USING ERRCODE = 'restrict_violation';
END;
$$
"""
)
op.execute(
f"""
CREATE TRIGGER {TRIGGER}
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
"""
)
def downgrade() -> None:
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {VERSIONS} TO {APP_ROLE}")
@@ -0,0 +1,108 @@
"""Add current_version_no and backfill from drafts / latest published.
Revision ID: 20261118_0008
Revises: 20261118_0007
Create Date: 2026-11-18
D26: definitions point at the active version. Rows with no versions yet get v1 from draft_*.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0008"
down_revision: Union[str, None] = "20261118_0007"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def upgrade() -> None:
op.add_column(
DEFINITIONS,
sa.Column("current_version_no", sa.Integer(), nullable=True),
)
op.create_check_constraint(
"ck_query_definitions_current_version",
DEFINITIONS,
"current_version_no IS NULL OR current_version_no >= 1",
)
# FORCE RLS would hide / block migrator writes; lift it for backfill only.
op.execute(f"ALTER TABLE {DEFINITIONS} NO FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {VERSIONS} NO FORCE ROW LEVEL SECURITY")
try:
# Definitions that already have published versions: current = latest pointer.
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = latest_published_version_no
WHERE latest_published_version_no IS NOT NULL
AND current_version_no IS NULL
"""
)
# Definitions with no version rows: freeze draft_* as v1 and point current at it.
op.execute(
f"""
INSERT INTO {VERSIONS} (
id, tenant_id, definition_id, version_no,
sql_template, param_schema, output_schema, allowed_identifiers,
timeout_ms, max_rows, published_at, published_by
)
SELECT
gen_random_uuid(),
d.tenant_id,
d.id,
1,
d.draft_sql_template,
d.draft_param_schema,
d.draft_output_schema,
d.draft_allowed_identifiers,
d.draft_timeout_ms,
d.draft_max_rows,
COALESCE(d.updated_at, d.created_at, now()),
'migration:20261118_0008'
FROM {DEFINITIONS} d
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id
)
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS} d
SET latest_published_version_no = 1,
current_version_no = 1
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v
WHERE v.definition_id = d.id AND v.version_no > 1
)
AND EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id AND v.version_no = 1
)
AND (d.latest_published_version_no IS NULL OR d.current_version_no IS NULL)
"""
)
# Any remaining gaps (e.g. latest set but current still null after inserts).
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = COALESCE(current_version_no, latest_published_version_no, 1)
WHERE current_version_no IS NULL
"""
)
finally:
op.execute(f"ALTER TABLE {VERSIONS} FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {DEFINITIONS} FORCE ROW LEVEL SECURITY")
def downgrade() -> None:
op.drop_constraint("ck_query_definitions_current_version", DEFINITIONS, type_="check")
op.drop_column(DEFINITIONS, "current_version_no")
@@ -0,0 +1,90 @@
"""Re-backfill current_version_no under FORCE ROW LEVEL SECURITY.
Revision ID: 20261118_0009
Revises: 20261118_0008
Create Date: 2026-11-18
0008 added the column but migrator updates/inserts saw zero rows or were
blocked because query_definitions / query_versions use FORCE ROW LEVEL
SECURITY. Temporarily lift FORCE on both, backfill, then restore.
"""
from __future__ import annotations
from typing import Sequence, Union
from alembic import op
revision: str = "20261118_0009"
down_revision: Union[str, None] = "20261118_0008"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
DEFINITIONS = "query_definitions"
VERSIONS = "query_versions"
def upgrade() -> None:
op.execute(f"ALTER TABLE {DEFINITIONS} NO FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {VERSIONS} NO FORCE ROW LEVEL SECURITY")
try:
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = latest_published_version_no
WHERE latest_published_version_no IS NOT NULL
AND current_version_no IS NULL
"""
)
op.execute(
f"""
INSERT INTO {VERSIONS} (
id, tenant_id, definition_id, version_no,
sql_template, param_schema, output_schema, allowed_identifiers,
timeout_ms, max_rows, published_at, published_by
)
SELECT
gen_random_uuid(),
d.tenant_id,
d.id,
1,
d.draft_sql_template,
d.draft_param_schema,
d.draft_output_schema,
d.draft_allowed_identifiers,
d.draft_timeout_ms,
d.draft_max_rows,
COALESCE(d.updated_at, d.created_at, now()),
'migration:20261118_0009'
FROM {DEFINITIONS} d
WHERE NOT EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id
)
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS} d
SET latest_published_version_no = COALESCE(latest_published_version_no, 1),
current_version_no = COALESCE(current_version_no, 1)
WHERE EXISTS (
SELECT 1 FROM {VERSIONS} v WHERE v.definition_id = d.id AND v.version_no = 1
)
AND current_version_no IS NULL
"""
)
op.execute(
f"""
UPDATE {DEFINITIONS}
SET current_version_no = COALESCE(current_version_no, latest_published_version_no, 1)
WHERE current_version_no IS NULL
"""
)
finally:
op.execute(f"ALTER TABLE {VERSIONS} FORCE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {DEFINITIONS} FORCE ROW LEVEL SECURITY")
def downgrade() -> None:
# Data backfill only; nothing to reverse safely.
pass
+244
View File
@@ -0,0 +1,244 @@
"""Seed a local M04 demo: source table + datasource + parameterized query.
Loads secrets only from the layered env (.env.local). Safe to re-run: replaces the
demo table rows and reuses the named datasource / query when they already exist.
Does not print passwords or connection strings.
"""
from __future__ import annotations
import sys
import psycopg
from watchman.core.config import get_settings, merge_layered_env, reload_settings
from watchman.core.db import session_scope
from watchman.services import datasources as ds_service
from watchman.services import queries as q_service
DS_NAME = "演示工艺库"
QUERY_NAME = "按产线查工艺读数"
QUERY_OPTIONAL_NAME = "工艺读数(产线可选)"
TABLE = "wm_demo_process_readings"
SQL = f"""\
SELECT line_code, lot_no, metric, reading_value, sampled_at
FROM {TABLE}
WHERE line_code = :line_code
ORDER BY sampled_at DESC
"""
# Optional filter: omit line_code → all rows; supply it → filter that line.
# Cast is required on PostgreSQL so a NULL bind still has a known type (avoids SQLSTATE 42P08).
SQL_OPTIONAL = f"""\
SELECT line_code, lot_no, metric, reading_value, sampled_at
FROM {TABLE}
WHERE (CAST(:line_code AS text) IS NULL OR line_code = CAST(:line_code AS text))
ORDER BY line_code, sampled_at DESC
"""
PARAM_SCHEMA = [
{"name": "line_code", "type": "string", "required": True},
]
PARAM_SCHEMA_OPTIONAL = [
{"name": "line_code", "type": "string", "required": False},
]
OUTPUT_SCHEMA = [
{"name": "line_code", "type": "string"},
{"name": "lot_no", "type": "string"},
{"name": "metric", "type": "string"},
{"name": "reading_value", "type": "number"},
{"name": "sampled_at", "type": "datetime"},
]
def _require_pg(env: dict[str, str]) -> dict[str, str]:
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
missing = [k for k in keys if not env.get(f"WATCHMAN_TEST_PG_{k}")]
if missing:
raise SystemExit(f"missing WATCHMAN_TEST_PG_* keys: {', '.join(missing)}")
return {k: env[f"WATCHMAN_TEST_PG_{k}"] for k in keys}
def seed_source_table(pg: dict[str, str]) -> None:
conn = psycopg.connect(
host=pg["HOST"],
port=int(pg["PORT"]),
user=pg["USER"],
password=pg["PASSWORD"],
dbname=pg["DATABASE"],
connect_timeout=5,
)
try:
with conn.cursor() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {TABLE} (
id bigserial PRIMARY KEY,
line_code text NOT NULL,
lot_no text NOT NULL,
metric text NOT NULL,
reading_value double precision NOT NULL,
sampled_at timestamptz NOT NULL
)
"""
)
cur.execute(f"DELETE FROM {TABLE}")
cur.execute(
f"""
INSERT INTO {TABLE} (line_code, lot_no, metric, reading_value, sampled_at)
VALUES
('L1', 'LOT-1001', 'temp_c', 86.5, '2026-11-18T02:00:00+00'),
('L1', 'LOT-1001', 'pressure_kpa', 101.2, '2026-11-18T02:01:00+00'),
('L1', 'LOT-1002', 'temp_c', 91.0, '2026-11-18T02:05:00+00'),
('L2', 'LOT-2001', 'temp_c', 72.3, '2026-11-18T02:10:00+00'),
('L2', 'LOT-2001', 'pressure_kpa', 98.0, '2026-11-18T02:11:00+00'),
('L3', 'LOT-3001', 'temp_c', 65.0, '2026-11-18T02:20:00+00')
"""
)
conn.commit()
finally:
conn.close()
print(f"source table ready: {TABLE} (6 rows)")
def ensure_datasource(pg: dict[str, str]) -> str:
with session_scope() as session:
existing = next((r for r in ds_service.list_datasources(session) if r.name == DS_NAME), None)
if existing is None:
row = ds_service.create_datasource(
session,
name=DS_NAME,
description="M04 本地演示源:工艺读数表(合成数据)",
kind="database",
engine="postgresql",
host=pg["HOST"],
port=int(pg["PORT"]),
database_name=pg["DATABASE"],
username=pg["USER"],
password=pg["PASSWORD"],
read_only_intent=True,
)
session.commit()
print(f"datasource created: {DS_NAME} id={row.id}")
return str(row.id)
ds_service.update_datasource(
session,
str(existing.id),
{
"description": "M04 本地演示源:工艺读数表(合成数据)",
"kind": "database",
"engine": "postgresql",
"host": pg["HOST"],
"port": int(pg["PORT"]),
"database_name": pg["DATABASE"],
"username": pg["USER"],
"password": pg["PASSWORD"],
},
)
if not existing.enabled:
ds_service.enable_datasource(session, str(existing.id))
session.commit()
print(f"datasource updated: {DS_NAME} id={existing.id}")
return str(existing.id)
def ensure_query(
datasource_id: str,
*,
name: str,
description: str,
sql_template: str,
param_schema: list[dict],
) -> str:
with session_scope() as session:
existing = next((r for r in q_service.list_queries(session) if r.name == name), None)
fields = {
"description": description,
"datasource_id": datasource_id,
"sql_template": sql_template,
"param_schema": param_schema,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 10000,
"max_rows": 100,
}
if existing is None:
row = q_service.create_query(
session, name=name, published_by="seed_m04_demo", **fields
)
session.commit()
qid = str(row.id)
print(f"query created: {name} id={qid} current=v{row.current_version_no}")
else:
meta = {
"description": fields["description"],
"datasource_id": fields["datasource_id"],
}
q_service.update_query(session, str(existing.id), meta)
version = q_service.save_as_version(
session,
str(existing.id),
{
"sql_template": fields["sql_template"],
"param_schema": fields["param_schema"],
"output_schema": fields["output_schema"],
"allowed_identifiers": fields["allowed_identifiers"],
"timeout_ms": fields["timeout_ms"],
"max_rows": fields["max_rows"],
},
published_by="seed_m04_demo",
)
if not existing.enabled:
q_service.enable_query(session, str(existing.id))
session.commit()
qid = str(existing.id)
print(f"query updated: {name} id={qid} current=v{version.version_no}")
return qid
def preview(query_id: str, params: dict) -> None:
with session_scope() as session:
result = q_service.preview_current(session, query_id, params)
session.commit()
status = result.get("status")
rows = result.get("rows") or []
print(f"preview params={params!r} status={status} row_count={result.get('row_count', len(rows))}")
for row in rows[:5]:
print(f" {row}")
def main() -> int:
reload_settings()
env = merge_layered_env()
pg = _require_pg(env)
settings = get_settings()
print(f"tenant={settings.tenant_id} source_db={pg['DATABASE']}@{pg['HOST']}:{pg['PORT']}")
seed_source_table(pg)
ds_id = ensure_datasource(pg)
qid = ensure_query(
ds_id,
name=QUERY_NAME,
description="按产线过滤工艺读数;试跑时传入 line_code=L1 / L2 / L3(必填)",
sql_template=SQL,
param_schema=PARAM_SCHEMA,
)
qid_opt = ensure_query(
ds_id,
name=QUERY_OPTIONAL_NAME,
description="line_code 非必填:留空查全部产线;填写则只查该产线(L1 / L2 / L3)",
sql_template=SQL_OPTIONAL,
param_schema=PARAM_SCHEMA_OPTIONAL,
)
preview(qid, {"line_code": "L1"})
preview(qid_opt, {})
preview(qid_opt, {"line_code": "L2"})
print(f"open required: http://127.0.0.1:5173/#/queries/{qid}")
print(f"open optional: http://127.0.0.1:5173/#/queries/{qid_opt}")
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -1
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, datasources, health, platform
from watchman.api.routes import auth, datasources, health, platform, queries
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
@@ -78,6 +78,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
app.include_router(auth.router)
app.include_router(platform.router)
app.include_router(datasources.router)
app.include_router(queries.router)
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
@@ -105,12 +105,46 @@ def _ok(request: Request, data: Any) -> JSONResponse:
def list_datasources(
request: Request,
usable: bool = False,
name: str | None = None,
engine: str | None = None,
enabled: bool | None = None,
sort_by: str = "created_at",
sort_order: str = "asc",
page: int = 1,
page_size: int = 20,
_: 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]}
"""List datasources.
usable=true returns the complete option list (enabled + circuit closed) for dropdowns.
Otherwise filters, sorts and pages in SQL for the console table.
"""
if usable:
rows = service.list_datasources(session, usable_only=True)
data = {
"items": [service.to_public(row) for row in rows],
"total": len(rows),
"page": 1,
"page_size": len(rows) or page_size,
}
else:
result = service.search_datasources(
session,
name=name,
engine=engine,
enabled=enabled,
sort_by=sort_by,
sort_order=sort_order,
page=page,
page_size=page_size,
)
data = {
"items": [service.to_public(row) for row in result["items"]],
"total": result["total"],
"page": result["page"],
"page_size": result["page_size"],
}
# An elapsed cooldown closes the circuit while listing; persist that.
session.commit()
return _ok(request, data)
@@ -240,5 +274,5 @@ def get_datasource_references(
_: 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 what references this datasource: the query definitions bound to it."""
return _ok(request, service.list_references(session, datasource_id))
@@ -0,0 +1,301 @@
"""Query definition routes under /queries.
Why: lets the console create definitions with immutable v1, save further versions, activate
a current version, and trial-run current or a chosen version (D26).
Boundary: request models forbid unknown fields, so a caller can never send tenant_id,
version_no, published_by or current_version_no; there is deliberately no route that updates
or deletes a version. Business rules live in watchman.services.queries.
Depends on the query service and the four query 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_query_previewer,
require_query_publisher,
require_query_reader,
require_query_writer,
)
from watchman.core.db import get_db_session
from watchman.core.response import success_body
from watchman.models.query import DEFAULT_MAX_ROWS, DEFAULT_TIMEOUT_MS
from watchman.services import queries as service
router = APIRouter(prefix="/queries", tags=["queries"])
Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
Description = Annotated[str, StringConstraints(max_length=2000)]
# Not stripped: whitespace inside SQL is content. Blank templates are refused by the service.
SqlTemplate = Annotated[str, StringConstraints(max_length=100000)]
# A value above the server cap is capped by the service; below 1 or a non-int is a 40000.
Limit = Annotated[int, Field(ge=1, strict=True)]
class QueryCreate(BaseModel):
"""Create body. Unknown fields such as tenant_id or enabled are rejected with 40000."""
model_config = ConfigDict(extra="forbid")
name: Name
description: Description | None = None
datasource_id: str
sql_template: SqlTemplate
param_schema: list[dict[str, Any]] = Field(default_factory=list)
output_schema: list[dict[str, Any]] = Field(default_factory=list)
allowed_identifiers: list[str] = Field(default_factory=list)
timeout_ms: Limit = DEFAULT_TIMEOUT_MS
max_rows: Limit = DEFAULT_MAX_ROWS
class QueryUpdate(BaseModel):
"""Metadata-only PATCH. Content must be saved as a new version (D26)."""
model_config = ConfigDict(extra="forbid")
name: Name | None = None
description: Description | None = None
datasource_id: str | None = None
class VersionCreate(BaseModel):
"""Body for saving a new immutable version that becomes current."""
model_config = ConfigDict(extra="forbid")
sql_template: SqlTemplate
param_schema: list[dict[str, Any]] = Field(default_factory=list)
output_schema: list[dict[str, Any]] = Field(default_factory=list)
allowed_identifiers: list[str] = Field(default_factory=list)
timeout_ms: Limit = DEFAULT_TIMEOUT_MS
max_rows: Limit = DEFAULT_MAX_ROWS
class EmptyBody(BaseModel):
"""Optional body for enable / disable / activate; it has no fields."""
model_config = ConfigDict(extra="forbid")
class PreviewBody(BaseModel):
"""Parameter values for a trial run. Nothing else (no SQL, no datasource) can be sent."""
model_config = ConfigDict(extra="forbid")
params: dict[str, Any] = Field(default_factory=dict)
def _ok(request: Request, data: Any) -> JSONResponse:
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
@router.get("")
def list_queries(
request: Request,
enabled: bool | None = None,
name: str | None = None,
datasource_id: str | None = None,
sort_by: str = "updated_at",
sort_order: str = "desc",
page: int = 1,
page_size: int = 20,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List query definitions with optional filters; sort and page in SQL."""
result = service.search_queries(
session,
enabled=enabled,
name=name,
datasource_id=datasource_id,
sort_by=sort_by,
sort_order=sort_order,
page=page,
page_size=page_size,
)
return _ok(
request,
{
"items": [service.summary_public(row) for row in result["items"]],
"total": result["total"],
"page": result["page"],
"page_size": result["page_size"],
},
)
@router.post("")
def create_query(
request: Request,
body: QueryCreate,
login_name: str = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Create an enabled definition with immutable v1 as current."""
# Creating v1 is a publish-class write (D26); publisher dependency also yields login_name.
row = service.create_query(session, published_by=login_name, **body.model_dump())
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{query_id}")
def get_query(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one definition with current content and version pointers."""
return _ok(request, service.to_public(service.get_query(session, query_id)))
@router.patch("/{query_id}")
def update_query(
request: Request,
query_id: str,
body: QueryUpdate,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Update metadata only. SQL content is saved via POST .../versions."""
row = service.update_query(session, query_id, body.model_dump(exclude_unset=True))
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/disable")
def disable_query(
request: Request,
query_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Disable a definition. It stays readable and cannot be previewed."""
row = service.disable_query(session, query_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/enable")
def enable_query(
request: Request,
query_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_query_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Enable a definition again."""
row = service.enable_query(session, query_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/versions")
def list_query_versions(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List version summaries, newest first."""
rows = service.list_versions(session, query_id)
return _ok(
request,
{"id": query_id, "items": [service.version_summary(row) for row in rows]},
)
@router.post("/{query_id}/versions")
def save_query_version(
request: Request,
query_id: str,
body: VersionCreate,
login_name: str = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Save content as the next immutable version and make it current (D26)."""
version = service.save_as_version(
session, query_id, body.model_dump(), published_by=login_name
)
data = service.version_public(version)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/versions/{version_no}")
def get_query_version(
request: Request,
query_id: str,
version_no: int,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one frozen version. Read-only: no route can change it."""
return _ok(request, service.version_public(service.get_version(session, query_id, version_no)))
@router.post("/{query_id}/versions/{version_no}/activate")
def activate_query_version(
request: Request,
query_id: str,
version_no: int,
body: EmptyBody | None = None,
_: None = Depends(require_query_publisher),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Set an existing version as the current active version."""
row = service.activate_version(session, query_id, version_no)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/preview")
def preview_query_current(
request: Request,
query_id: str,
body: PreviewBody | None = None,
_: None = Depends(require_query_previewer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Trial-run the current active version. Outcome is only in the response."""
data = service.preview_current(session, query_id, (body or PreviewBody()).params)
session.commit()
return _ok(request, data)
@router.post("/{query_id}/versions/{version_no}/preview")
def preview_query_version(
request: Request,
query_id: str,
version_no: int,
body: PreviewBody | None = None,
_: None = Depends(require_query_previewer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Trial-run a frozen version. The outcome is only in the response; nothing is stored."""
data = service.preview_version(session, query_id, version_no, (body or PreviewBody()).params)
session.commit()
return _ok(request, data)
@router.get("/{query_id}/references")
def get_query_references(
request: Request,
query_id: str,
_: None = Depends(require_query_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return what references this query. No scenario exists yet, so items is empty."""
return _ok(request, service.list_references(session, query_id))
+30 -1
View File
@@ -1,7 +1,7 @@
"""Role checks for the Watchman permission nodes.
Decides enter, platform write, object read, and the three datasource nodes (read,
write, test) from Casdoor role names.
write, test) and the four query nodes (read, write, publish, preview) from Casdoor role names.
Depends on semantic errors only; it does not call Casdoor or open a session.
"""
@@ -17,6 +17,11 @@ 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"
QUERY_READ_NODE = "perm:data:emp:watchman.query.read"
QUERY_WRITE_NODE = "perm:data:emp:watchman.query.write"
QUERY_PUBLISH_NODE = "perm:data:emp:watchman.query.publish"
QUERY_PREVIEW_NODE = "perm:data:emp:watchman.query.preview"
ROLE_ADMIN = "watchman-admin"
ROLE_OPERATOR = "watchman-operator"
ROLE_VIEWER = "watchman-viewer"
@@ -65,6 +70,30 @@ def require_datasource_test(role_names: list[str]) -> None:
raise ForbiddenError(permission_node=DATASOURCE_TEST_NODE)
def require_query_read(role_names: list[str]) -> None:
"""Allow query list, detail, versions and references only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_READ_NODE)
def require_query_write(role_names: list[str]) -> None:
"""Allow query create, update, enable and disable only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_WRITE_NODE)
def require_query_publish(role_names: list[str]) -> None:
"""Allow publishing an immutable query version only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_PUBLISH_NODE)
def require_query_preview(role_names: list[str]) -> None:
"""Allow a draft or version preview run only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=QUERY_PREVIEW_NODE)
def require_object_access(role_names: list[str], object_id: str) -> None:
"""Reject every object id until a later module grants row access.
@@ -19,6 +19,10 @@ from watchman.auth.access import (
require_datasource_test,
require_datasource_write,
require_platform_write,
require_query_preview,
require_query_publish,
require_query_read,
require_query_write,
)
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
@@ -124,13 +128,13 @@ def require_platform_writer(
require_platform_write(roles)
def _load_session_roles(
def _load_session(
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.
) -> tuple[str, list[str]]:
"""Return (login_name, 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.
@@ -146,7 +150,17 @@ def _load_session_roles(
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
return row.login_name, 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."""
return _load_session(request, session_token, sessions, directory)[1]
def require_datasource_reader(
@@ -177,3 +191,45 @@ def require_datasource_tester(
) -> None:
"""Reject a connection test unless the session is watchman-admin."""
require_datasource_test(_load_session_roles(request, session_token, sessions, directory))
def require_query_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 query list, detail, version and reference reads unless the session is admin."""
require_query_read(_load_session_roles(request, session_token, sessions, directory))
def require_query_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 query create, update, enable and disable unless the session is admin."""
require_query_write(_load_session_roles(request, session_token, sessions, directory))
def require_query_publisher(
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),
) -> str:
"""Reject a publish unless the session is admin; return the login name to record."""
login_name, roles = _load_session(request, session_token, sessions, directory)
require_query_publish(roles)
return login_name
def require_query_previewer(
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 draft or version preview unless the session is admin."""
require_query_preview(_load_session_roles(request, session_token, sessions, directory))
@@ -3,5 +3,13 @@
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent, RunRecord
from watchman.models.query import QueryDefinition, QueryVersion
__all__ = ["AuthSession", "AuditEvent", "DataSource", "RunRecord"]
__all__ = [
"AuthSession",
"AuditEvent",
"DataSource",
"QueryDefinition",
"QueryVersion",
"RunRecord",
]
@@ -0,0 +1,170 @@
"""Tenant-scoped query drafts and immutable published query versions.
Boundary: persistence only. A QueryDefinition holds the mutable draft; a QueryVersion is a
frozen snapshot that must never be edited in place (enforced by the service helper in
`watchman.services.query_versions`, not by this module). No SQL execution and no datasource
connection logic live here.
Depends on SQLAlchemy, the shared Watchman declarative base, and the data_sources table.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Integer,
String,
Text,
UniqueConstraint,
func,
text,
)
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column
from watchman.models.base import Base
DEFAULT_TIMEOUT_MS = 10000
DEFAULT_MAX_ROWS = 100
MAX_TIMEOUT_MS = 300000
MAX_ROWS_LIMIT = 10000
# Columns that make up a published version's content; frozen once the row exists.
VERSION_CONTENT_COLUMNS = frozenset(
{
"sql_template",
"param_schema",
"output_schema",
"allowed_identifiers",
"timeout_ms",
"max_rows",
}
)
class QueryDefinition(Base):
"""A query definition with mirrored draft_* columns and current/latest version pointers.
D26: callers treat versions as the source of truth; draft_* mirrors the current version
for transitional internals and is not exposed as an editable draft API.
"""
__tablename__ = "query_definitions"
__table_args__ = (
UniqueConstraint("tenant_id", "name", name="uq_query_definitions_tenant_name"),
CheckConstraint(
"draft_timeout_ms BETWEEN 1 AND 300000", name="ck_query_definitions_timeout"
),
CheckConstraint(
"draft_max_rows BETWEEN 1 AND 10000", name="ck_query_definitions_max_rows"
),
CheckConstraint(
"latest_published_version_no IS NULL OR latest_published_version_no >= 1",
name="ck_query_definitions_latest_version",
),
CheckConstraint(
"current_version_no IS NULL OR current_version_no >= 1",
name="ck_query_definitions_current_version",
),
)
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)
# RESTRICT: a datasource referenced by a query cannot be deleted out from under it.
datasource_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("data_sources.id", ondelete="RESTRICT"),
nullable=False,
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
draft_sql_template: Mapped[str] = mapped_column(Text, nullable=False)
draft_param_schema: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
draft_output_schema: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
# Whitelist for identifiers that cannot be bound as parameters (tables, columns).
draft_allowed_identifiers: Mapped[list[Any]] = mapped_column(
JSONB, nullable=False, default=list, server_default=text("'[]'::jsonb")
)
draft_timeout_ms: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=DEFAULT_TIMEOUT_MS,
server_default=text(str(DEFAULT_TIMEOUT_MS)),
)
draft_max_rows: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=DEFAULT_MAX_ROWS,
server_default=text(str(DEFAULT_MAX_ROWS)),
)
latest_published_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Active version for future rules/schedules and default preview (D26).
current_version_no: Mapped[int | None] = mapped_column(Integer, 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:
return (
f"QueryDefinition(id={self.id!s}, tenant_id={self.tenant_id!r}, "
f"name={self.name!r})"
)
class QueryVersion(Base):
"""An immutable published snapshot of a query definition; there is no updated_at."""
__tablename__ = "query_versions"
__table_args__ = (
UniqueConstraint("definition_id", "version_no", name="uq_query_versions_def_version"),
CheckConstraint("version_no >= 1", name="ck_query_versions_version_no"),
CheckConstraint("timeout_ms BETWEEN 1 AND 300000", name="ck_query_versions_timeout"),
CheckConstraint("max_rows BETWEEN 1 AND 10000", name="ck_query_versions_max_rows"),
)
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)
definition_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("query_definitions.id", ondelete="RESTRICT"),
nullable=False,
)
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
sql_template: Mapped[str] = mapped_column(Text, nullable=False)
param_schema: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
output_schema: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
allowed_identifiers: Mapped[list[Any]] = mapped_column(JSONB, nullable=False)
timeout_ms: Mapped[int] = mapped_column(Integer, nullable=False)
max_rows: Mapped[int] = mapped_column(Integer, nullable=False)
published_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
published_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
def __repr__(self) -> str:
return (
f"QueryVersion(id={self.id!s}, definition_id={self.definition_id!s}, "
f"version_no={self.version_no})"
)
@@ -0,0 +1,15 @@
"""Read-only parameterized query execution against saved datasources.
Boundary: executes user SQL templates once and classifies the outcome (success / empty /
illegal_type / failure). It does not persist query definitions or versions, does not create
alarms, rules or notifications, and never bypasses the datasource usability check and
circuit. Template preparation (bound parameters, whitelisted identifiers) is pure and
connection-free; only `run_query` touches a datasource.
Depends on watchman.services.datasources and watchman.datasources connectors.
"""
from watchman.queries.execute import run_query
from watchman.queries.result import QueryRunResult
from watchman.queries.template import PreparedQuery, prepare_query
__all__ = ["PreparedQuery", "QueryRunResult", "prepare_query", "run_query"]
@@ -0,0 +1,236 @@
"""Per-engine execution of one prepared statement on a short-lived connection.
Boundary: opens one connection, runs exactly one statement in a read-only transaction where
the engine supports it (PostgreSQL, MySQL; SQL Server has no session read-only mode, so it is
not supported here at all), fetches at most `limit` rows and closes. It classifies failures
but does not persist anything, decrypt secrets, or look at the data. Driver messages are
never copied into exceptions: only a category/kind and, for PostgreSQL, the 5-char SQLSTATE.
Connect-failure classification reuses the probe's rules so both agree on what a refused,
rejected or unauthenticated connection is.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import psycopg
import pymysql
from watchman.datasources import ProbeCategory, ProbeTarget, UnsupportedDataSourceError
from watchman.datasources.probe import (
_MYSQL_AUTH_CODES,
_MYSQL_SERVER_ERROR_LIMIT,
_chain_has_timeout,
_classify_after_failure,
_pg_connect,
_pg_is_auth_failure,
)
# MySQL: ER_QUERY_TIMEOUT (MAX_EXECUTION_TIME exceeded).
_MYSQL_QUERY_TIMEOUT = 3024
@dataclass(frozen=True)
class FetchResult:
columns: list[str]
rows: list[tuple[Any, ...]]
class ConnectFailure(Exception):
"""No usable connection was established. Counts against the datasource circuit."""
def __init__(self, category: ProbeCategory) -> None:
super().__init__(category.value)
self.category = category
class QueryFailure(Exception):
"""The statement did not complete on an established connection.
category is set only when the failure is clearly connectivity (connection lost
mid-query); then it counts against the circuit. A slow or broken statement does not.
"""
def __init__(
self,
kind: str,
*,
category: ProbeCategory | None = None,
details: dict[str, Any] | None = None,
) -> None:
super().__init__(kind)
self.kind = kind # "timeout" | "unreachable" | "sql_error"
self.category = category
self.details = details or {}
def fetch_rows(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
*,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
"""Run `sql` with bound `params` and return at most `limit` rows.
Raises UnsupportedDataSourceError (nothing opened), ConnectFailure or QueryFailure.
"""
runner = _RUNNERS.get(target.engine) if target.kind == "database" else None
if runner is None:
raise UnsupportedDataSourceError()
return runner(target, sql, params, timeout_ms, limit, connect_timeout)
# --- PostgreSQL -----------------------------------------------------------------------
def _run_postgresql(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
try:
conn = _pg_connect(target, connect_timeout, "UTF8")
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if sqlstate.startswith("28"):
raise ConnectFailure(ProbeCategory.AUTH_FAILED) from None
timed_out = isinstance(exc, psycopg.errors.ConnectionTimeout) or _chain_has_timeout(exc)
category = _classify_after_failure(
target,
connect_timeout,
timed_out,
lambda: _pg_is_auth_failure(exc, target, connect_timeout),
)
raise ConnectFailure(category) from None
except Exception: # noqa: BLE001
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
try:
# READ ONLY transaction (BEGIN READ ONLY), statement_timeout scoped to it.
conn.autocommit = False
conn.read_only = True
with conn.cursor() as cur:
cur.execute(f"SET LOCAL statement_timeout = {int(timeout_ms)}")
cur.execute(sql, params)
if cur.description is None:
raise QueryFailure("sql_error", details={"reason": "no_result_set"})
columns = [column.name for column in cur.description]
rows = cur.fetchmany(limit)
return FetchResult(columns=columns, rows=[tuple(r) for r in rows])
except QueryFailure:
raise
except psycopg.errors.QueryCanceled:
raise QueryFailure("timeout") from None
except psycopg.OperationalError as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if not sqlstate or sqlstate.startswith("08"):
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
raise QueryFailure("sql_error", details={"sqlstate": sqlstate}) from None
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
raise QueryFailure("sql_error", details={"sqlstate": sqlstate}) from None
finally:
_quiet(conn.rollback)
_quiet(conn.close)
# --- MySQL ----------------------------------------------------------------------------
def _mysql_code(exc: BaseException) -> int | None:
return exc.args[0] if exc.args and isinstance(exc.args[0], int) else None
def _run_mysql(
target: ProbeTarget,
sql: str,
params: dict[str, Any] | None,
timeout_ms: int,
limit: int,
connect_timeout: float,
) -> FetchResult:
try:
conn = pymysql.connect(
host=target.host,
port=target.port,
user=target.username,
password=target.password,
database=target.database,
connect_timeout=connect_timeout,
# read_timeout is the client-side cap on a running statement.
read_timeout=max(1.0, math.ceil(timeout_ms / 1000)),
write_timeout=connect_timeout,
autocommit=False,
)
except pymysql.err.MySQLError as exc:
code = _mysql_code(exc)
if code in _MYSQL_AUTH_CODES:
raise ConnectFailure(ProbeCategory.AUTH_FAILED) from None
if _chain_has_timeout(exc):
raise ConnectFailure(ProbeCategory.TIMEOUT) from None
if code is not None and code < _MYSQL_SERVER_ERROR_LIMIT:
raise ConnectFailure(ProbeCategory.REJECTED) from None
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
except OSError as exc:
raise ConnectFailure(
ProbeCategory.TIMEOUT if _chain_has_timeout(exc) else ProbeCategory.UNREACHABLE
) from None
except Exception: # noqa: BLE001
raise ConnectFailure(ProbeCategory.UNREACHABLE) from None
try:
with conn.cursor() as cur:
cur.execute("SET SESSION TRANSACTION READ ONLY")
cur.execute("START TRANSACTION READ ONLY")
try:
cur.execute(f"SET SESSION MAX_EXECUTION_TIME = {int(timeout_ms)}")
except pymysql.err.MySQLError:
pass # MariaDB / old servers: the client read_timeout still applies
cur.execute(sql, params)
if cur.description is None:
raise QueryFailure("sql_error", details={"reason": "no_result_set"})
columns = [column[0] for column in cur.description]
rows = cur.fetchmany(limit)
return FetchResult(columns=columns, rows=[tuple(r) for r in rows])
except QueryFailure:
raise
except pymysql.err.MySQLError as exc:
code = _mysql_code(exc)
if code == _MYSQL_QUERY_TIMEOUT or _chain_has_timeout(exc):
raise QueryFailure("timeout") from None
if code is not None and code >= _MYSQL_SERVER_ERROR_LIMIT:
# 2006/2013 and friends: the connection died, not the statement.
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
raise QueryFailure("sql_error", details={"code": code}) from None
except OSError as exc:
if _chain_has_timeout(exc):
raise QueryFailure("timeout") from None
raise QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE) from None
finally:
_quiet(conn.rollback)
_quiet(conn.close)
# --- SQL Server -----------------------------------------------------------------------
# Deliberately no runner: SQL Server has no server-enforced read-only session in this stack,
# so user templates are never executed on it (see execute.run_query). fetch_rows raises
# UnsupportedDataSourceError for it, and nothing here imports pymssql.
def _quiet(call) -> None: # type: ignore[no-untyped-def]
try:
call()
except Exception: # noqa: BLE001
pass
_RUNNERS = {
"postgresql": _run_postgresql,
"mysql": _run_mysql,
}
@@ -0,0 +1,269 @@
"""Read-only parameterized query runner for usable datasources.
Boundary: executes a user template once against a saved datasource and reports the outcome.
It does not persist query definitions or results, does not create alarms or notifications,
and never connects to a datasource that M03 `assert_usable` refuses. Connection-class
failures (connect, auth, rejected, unreachable, connection lost) are counted against the
datasource circuit; a slow or invalid statement on a healthy connection is not. Password,
connection details, parameter values and result sets are never logged.
Depends on the datasource service (usability, secret, circuit accounting), the probe's
connectors, and the template/schema helpers of this package.
"""
from __future__ import annotations
import logging
import math
import uuid
from datetime import date, datetime, time
from decimal import Decimal
from typing import Any
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import ConflictError, ValidationError
from watchman.datasources import ProbeCategory, UnsupportedDataSourceError
from watchman.models.query import MAX_ROWS_LIMIT, MAX_TIMEOUT_MS
from watchman.queries import drivers
from watchman.queries.result import (
KIND_AUTH_FAILED,
KIND_CIRCUIT_OPEN,
KIND_DISABLED,
KIND_ENGINE_READONLY_UNSUPPORTED,
KIND_LIMIT_EXCEEDED,
KIND_REJECTED,
KIND_SQL_ERROR,
KIND_TIMEOUT,
KIND_UNREACHABLE,
KIND_VALIDATION,
STATUS_EMPTY,
STATUS_ILLEGAL_TYPE,
STATUS_SUCCESS,
QueryRunResult,
failure,
)
from watchman.queries.schema import check_output_value, parse_output_schema
from watchman.queries.template import prepare_query
from watchman.services import datasources as datasource_service
logger = logging.getLogger("watchman.queries.execute")
# Fixed texts: driver messages can embed hosts, users or fragments of the statement.
_CATEGORY_KIND = {
ProbeCategory.AUTH_FAILED: KIND_AUTH_FAILED,
ProbeCategory.TIMEOUT: KIND_TIMEOUT,
ProbeCategory.UNREACHABLE: KIND_UNREACHABLE,
ProbeCategory.REJECTED: KIND_REJECTED,
}
_MESSAGES = {
KIND_AUTH_FAILED: "data source authentication failed",
KIND_TIMEOUT: "query timed out",
KIND_UNREACHABLE: "data source unreachable",
KIND_REJECTED: "data source rejected the connection",
KIND_SQL_ERROR: "query failed",
KIND_LIMIT_EXCEEDED: "query returned more rows than max_rows",
KIND_VALIDATION: "query template or parameters are invalid",
KIND_DISABLED: "data source is disabled",
KIND_CIRCUIT_OPEN: "data source circuit is open",
KIND_ENGINE_READONLY_UNSUPPORTED: (
"SQL Server query preview is not available until a server-enforced "
"read-only session exists"
),
}
# Engines without a server-enforced read-only session. User templates are never executed on
# them: a statement check would not be a security control. The M03 connectivity probe is
# unaffected (it runs no user SQL).
_READONLY_UNSUPPORTED_ENGINES = frozenset({"sqlserver"})
def _clamp(name: str, value: Any, maximum: int) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValidationError(
"Invalid query limits", details={"reason": "limit_invalid", "fields": [name]}
)
return min(value, maximum) # a form value above the server cap is capped, not trusted
def _json_value(value: Any) -> Any:
"""Convert a fetched value to something json.dumps accepts."""
if value is None or isinstance(value, (str, bool, int)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, Decimal):
return float(value) if value.is_finite() else None
if isinstance(value, (datetime, date, time)):
return value.isoformat()
if isinstance(value, (bytes, bytearray, memoryview)):
return bytes(value).hex()
return str(value)
def _type_problems(
declared: dict[str, str], columns: list[str], rows: list[tuple[Any, ...]]
) -> list[dict[str, Any]]:
"""First offending row per declared column; values are never included."""
problems: list[dict[str, Any]] = []
for index, name in enumerate(columns):
expected = declared.get(name)
if expected is None:
continue
for row_no, row in enumerate(rows):
if not check_output_value(expected, row[index]):
problems.append(
{
"field": name,
"expected": expected,
"actual": type(row[index]).__name__,
"row": row_no,
}
)
break
return problems
def run_query(
session: Session,
*,
datasource_id: str | uuid.UUID,
sql_template: str,
param_schema: Any,
output_schema: Any,
allowed_identifiers: Any,
params: Any,
timeout_ms: int,
max_rows: int,
) -> QueryRunResult:
"""Run one template read-only and classify the outcome; never raises for query problems.
Order: assert_usable (disabled/circuit_open come back as failures, no SQL, no secret
read) -> refuse engines without a server-enforced read-only session (SQL Server:
failure `engine_readonly_unsupported`, nothing opened) -> validate limits, schemas, parameters and identifiers (failure `validation`) ->
decrypt in memory, commit so no transaction spans the network call -> run with timeout
-> classify. Fetches max_rows+1 rows: one extra row is `limit_exceeded` (no rows
returned), zero is `empty`, a declared output type violated is `illegal_type`.
Unknown datasource (NotFoundError) and an unreadable stored secret propagate as the
platform's own errors. This function commits the session; connection failures are
recorded on the circuit and committed before it returns.
"""
ds_id = str(datasource_id)
try:
row = datasource_service.assert_usable(session, ds_id)
except ConflictError as exc:
reason = exc.details.get("reason")
kind = KIND_CIRCUIT_OPEN if reason == KIND_CIRCUIT_OPEN else KIND_DISABLED
extra = {k: v for k, v in exc.details.items() if k == "circuit_open_until"}
return failure(kind, _MESSAGES[kind], reason=reason, **extra)
if row.engine in _READONLY_UNSUPPORTED_ENGINES:
# Refuse before validation, secret decryption or any connection: nothing is opened.
session.commit() # persists an auto-closed circuit and ends the read transaction
logger.info(
"query run engine=%s datasource=%s status=failure kind=%s",
row.engine,
ds_id,
KIND_ENGINE_READONLY_UNSUPPORTED,
)
return failure(
KIND_ENGINE_READONLY_UNSUPPORTED,
_MESSAGES[KIND_ENGINE_READONLY_UNSUPPORTED],
reason=KIND_ENGINE_READONLY_UNSUPPORTED,
engine=row.engine,
)
try:
timeout = _clamp("timeout_ms", timeout_ms, MAX_TIMEOUT_MS)
limit = _clamp("max_rows", max_rows, MAX_ROWS_LIMIT)
declared = parse_output_schema(output_schema)
prepared = prepare_query(
engine=row.engine,
sql_template=sql_template,
param_schema=param_schema,
allowed_identifiers=allowed_identifiers,
params=params,
)
if row.kind != "database":
raise ValidationError(
"Unsupported datasource kind or engine",
details={"reason": "unsupported_datasource", "fields": ["kind", "engine"]},
)
target = datasource_service.build_probe_target(row)
except ValidationError as exc:
session.commit() # persists an auto-closed circuit and ends the read transaction
return failure(KIND_VALIDATION, _MESSAGES[KIND_VALIDATION], **exc.details)
# No transaction may stay open while the source database runs the statement.
session.commit()
connect_timeout = get_settings().datasource_probe_timeout_seconds
try:
fetched = drivers.fetch_rows(
target,
prepared.sql,
prepared.params,
timeout_ms=timeout,
limit=limit + 1,
connect_timeout=connect_timeout,
)
except UnsupportedDataSourceError:
return failure(
KIND_VALIDATION,
_MESSAGES[KIND_VALIDATION],
reason="unsupported_datasource",
fields=["kind", "engine"],
)
except drivers.ConnectFailure as exc:
return _connection_failure(session, ds_id, exc.category, row.engine)
except drivers.QueryFailure as exc:
if exc.category is not None:
return _connection_failure(session, ds_id, exc.category, row.engine)
kind = KIND_TIMEOUT if exc.kind == "timeout" else KIND_SQL_ERROR
logger.info("query run engine=%s datasource=%s status=failure kind=%s", row.engine, ds_id, kind)
return failure(kind, _MESSAGES[kind], **exc.details)
if len(fetched.rows) > limit:
logger.info("query run engine=%s datasource=%s status=failure kind=limit_exceeded", row.engine, ds_id)
return failure(
KIND_LIMIT_EXCEEDED, _MESSAGES[KIND_LIMIT_EXCEEDED], max_rows=limit
)
columns = list(fetched.columns)
if not fetched.rows:
logger.info("query run engine=%s datasource=%s status=empty", row.engine, ds_id)
return QueryRunResult(status=STATUS_EMPTY, message="query returned no rows", columns=columns)
problems = _type_problems(declared, columns, fetched.rows)
if problems:
logger.info("query run engine=%s datasource=%s status=illegal_type", row.engine, ds_id)
return QueryRunResult(
status=STATUS_ILLEGAL_TYPE,
message="query result violates the output schema",
columns=columns,
details={"fields": problems},
)
rows = [
{name: _json_value(value) for name, value in zip(columns, values)}
for values in fetched.rows
]
logger.info(
"query run engine=%s datasource=%s status=success rows=%d", row.engine, ds_id, len(rows)
)
return QueryRunResult(
status=STATUS_SUCCESS, message="query succeeded", columns=columns, rows=rows
)
def _connection_failure(
session: Session, ds_id: str, category: ProbeCategory, engine: str
) -> QueryRunResult:
"""Count the failure on the circuit (committed here) and return its classification."""
opened = datasource_service.record_connection_failure(session, ds_id, category)
session.commit()
kind = _CATEGORY_KIND.get(category, KIND_UNREACHABLE)
logger.info(
"query run engine=%s datasource=%s status=failure kind=%s circuit_opened=%s",
engine,
ds_id,
kind,
opened,
)
return failure(kind, _MESSAGES[kind], category=category.value, circuit_opened=opened)
@@ -0,0 +1,47 @@
"""Outcome type of one read-only query run.
Boundary: a plain value object; no I/O. status separates the four outcomes callers must
never confuse: success (rows), empty (zero rows), illegal_type (rows violate the output
contract) and failure (anything that stopped the run, classified by failure_kind).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
STATUS_SUCCESS = "success"
STATUS_EMPTY = "empty"
STATUS_ILLEGAL_TYPE = "illegal_type"
STATUS_FAILURE = "failure"
# failure_kind values (status == failure only).
KIND_VALIDATION = "validation"
KIND_DISABLED = "disabled"
KIND_CIRCUIT_OPEN = "circuit_open"
KIND_TIMEOUT = "timeout"
KIND_UNREACHABLE = "unreachable"
KIND_AUTH_FAILED = "auth_failed"
KIND_REJECTED = "rejected"
KIND_LIMIT_EXCEEDED = "limit_exceeded"
KIND_SQL_ERROR = "sql_error"
# The engine has no server-enforced read-only session, so no user template is run on it.
KIND_ENGINE_READONLY_UNSUPPORTED = "engine_readonly_unsupported"
@dataclass(frozen=True)
class QueryRunResult:
"""One run's outcome. message is a fixed safe string (never driver text or data)."""
status: str
message: str
failure_kind: str | None = None
columns: list[str] = field(default_factory=list)
rows: list[dict[str, Any]] = field(default_factory=list)
details: dict[str, Any] = field(default_factory=dict)
def failure(kind: str, message: str, **details: Any) -> QueryRunResult:
return QueryRunResult(
status=STATUS_FAILURE, failure_kind=kind, message=message, details=dict(details)
)
@@ -0,0 +1,151 @@
"""Parameter and output schemas of a query template: parsing and value checks.
Boundary: pure validation of the JSON shapes stored on a query definition/version and of
single values against a declared type. No SQL, no database, no HTTP. Errors are the shared
ValidationError with a stable reason and field names, never echoing caller values.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any
from watchman.core.errors import ValidationError
VALUE_TYPES = ("string", "integer", "number", "boolean", "datetime")
# "nullish" is output-only: the column carries no type constraint (see check_output_value).
OUTPUT_TYPES = VALUE_TYPES + ("nullish",)
IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_PARAM_KEYS = frozenset({"name", "type", "required", "default"})
_OUTPUT_KEYS = frozenset({"name", "type"})
_MAX_OUTPUT_NAME = 128
_MISSING = object()
@dataclass(frozen=True)
class ParamSpec:
name: str
type: str
required: bool
default: Any = _MISSING
@property
def has_default(self) -> bool:
return self.default is not _MISSING
def _invalid(reason: str, *fields: str) -> ValidationError:
return ValidationError(
"Invalid query definition", details={"reason": reason, "fields": list(fields)}
)
def coerce_param_value(spec_type: str, value: Any) -> Any:
"""Return `value` as a driver-bindable Python value of `spec_type` or raise ValueError."""
if spec_type == "string" and isinstance(value, str):
return value
if spec_type == "integer" and isinstance(value, int) and not isinstance(value, bool):
return value
if (
spec_type == "number"
and isinstance(value, (int, float, Decimal))
and not isinstance(value, bool)
and math.isfinite(float(value))
):
return value
if spec_type == "boolean" and isinstance(value, bool):
return value
if spec_type == "datetime":
if isinstance(value, datetime):
return value
if isinstance(value, str):
return datetime.fromisoformat(value) # ValueError on a bad string
raise ValueError("type mismatch")
def parse_param_schema(raw: Any) -> list[ParamSpec]:
"""Validate the param_schema list; unknown keys, duplicates and bad defaults are rejected."""
if not isinstance(raw, list):
raise _invalid("param_schema_invalid", "param_schema")
specs: list[ParamSpec] = []
seen: set[str] = set()
for item in raw:
if not isinstance(item, dict) or set(item) - _PARAM_KEYS:
raise _invalid("param_schema_invalid", "param_schema")
name, type_ = item.get("name"), item.get("type")
if not isinstance(name, str) or not IDENTIFIER_RE.match(name) or name in seen:
raise _invalid("param_schema_invalid", "param_schema")
if type_ not in VALUE_TYPES:
raise _invalid("param_schema_invalid", f"param_schema.{name}")
required = item.get("required", True)
if not isinstance(required, bool):
raise _invalid("param_schema_invalid", f"param_schema.{name}")
default = item.get("default", _MISSING)
if default is not _MISSING:
try:
default = coerce_param_value(type_, default)
except ValueError:
raise _invalid("param_default_invalid", f"param_schema.{name}") from None
seen.add(name)
specs.append(ParamSpec(name=name, type=type_, required=required, default=default))
return specs
def parse_output_schema(raw: Any) -> dict[str, str]:
"""Validate output_schema and return {column name: declared type}."""
if not isinstance(raw, list):
raise _invalid("output_schema_invalid", "output_schema")
result: dict[str, str] = {}
for item in raw:
if not isinstance(item, dict) or set(item) - _OUTPUT_KEYS:
raise _invalid("output_schema_invalid", "output_schema")
name, type_ = item.get("name"), item.get("type")
if (
not isinstance(name, str)
or not name
or len(name) > _MAX_OUTPUT_NAME
or name in result
or type_ not in OUTPUT_TYPES
):
raise _invalid("output_schema_invalid", "output_schema")
result[name] = type_
return result
def parse_allowed_identifiers(raw: Any) -> frozenset[str]:
if not isinstance(raw, list):
raise _invalid("allowed_identifiers_invalid", "allowed_identifiers")
if any(not isinstance(i, str) or not IDENTIFIER_RE.match(i) for i in raw):
raise _invalid("allowed_identifiers_invalid", "allowed_identifiers")
return frozenset(raw)
def check_output_value(declared_type: str, value: Any) -> bool:
"""True if a fetched value satisfies the declared output type.
SQL NULL satisfies every type (an absent value is not a type error; whether it is
acceptable is a rule-level question). "nullish" imposes no constraint at all.
"""
if value is None or declared_type == "nullish":
return True
if declared_type == "string":
return isinstance(value, str)
if declared_type == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if declared_type == "number":
return (
isinstance(value, (int, float, Decimal))
and not isinstance(value, bool)
and math.isfinite(float(value))
)
if declared_type == "boolean":
return isinstance(value, bool)
if declared_type == "datetime":
return isinstance(value, datetime)
return False
@@ -0,0 +1,233 @@
"""SQL template preparation: named-parameter binding and whitelisted identifiers.
Boundary: pure text/value work, no connection. A template may contain `:name` parameters
(values, always bound by the driver, never spliced) and `{{ident}}` identifiers (only from
the declared allow-list, strictly [A-Za-z_][A-Za-z0-9_]*, substituted as quoted identifiers).
Placeholders inside string literals, quoted identifiers and comments are left alone, `::`
casts are not parameters, and a template must be one statement. This is structural
validation, not a read-only guarantee: that comes from the session settings and the
read-only account of the source.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from watchman.core.errors import ValidationError
from watchman.queries.schema import (
IDENTIFIER_RE,
ParamSpec,
coerce_param_value,
parse_allowed_identifiers,
parse_param_schema,
)
_WORD = re.compile(r"[A-Za-z0-9_]")
_PARAM_NAME = re.compile(r":([A-Za-z_][A-Za-z0-9_]*)")
_DOLLAR_TAG = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)?\$")
_QUOTE = {"postgresql": '"{}"', "mysql": "`{}`", "sqlserver": "[{}]"}
@dataclass(frozen=True)
class PreparedQuery:
"""Driver-ready statement. params is None when the statement has no parameters."""
sql: str
params: dict[str, Any] | None
def _bad(reason: str, *fields: str) -> ValidationError:
return ValidationError(
"Invalid query template", details={"reason": reason, "fields": list(fields)}
)
def _skip_quoted(sql: str, i: int, quote: str, *, backslash: bool, end: str | None = None) -> int:
"""Return the index just after the quoted run starting at sql[i]; doubled quotes escape."""
end = end or quote
j = i + 1
while j < len(sql):
ch = sql[j]
if backslash and ch == "\\":
j += 2
continue
if ch == end:
if sql[j + 1 : j + 2] == end:
j += 2
continue
return j + 1
j += 1
raise _bad("template_unterminated", "sql_template")
def _scan(sql: str, engine: str) -> list[tuple[str, str]]:
"""Split a template into ("text"|"param"|"ident", value) parts."""
parts: list[tuple[str, str]] = []
buf: list[str] = []
ended = False # a statement-terminating ';' was seen: only blanks/comments may follow
n = len(sql)
i = 0
def flush() -> None:
if buf:
parts.append(("text", "".join(buf)))
buf.clear()
def emit(raw: str, *, meaningful: bool) -> None:
if ended and meaningful:
raise _bad("multiple_statements", "sql_template")
buf.append(raw)
mysql = engine == "mysql"
while i < n:
ch = sql[i]
nxt = sql[i + 1 : i + 2]
if ch in ("'", '"'):
# Literal or quoted identifier. mysql and PG E'..' strings also use backslashes.
prev = sql[i - 1] if i else ""
e_string = (
engine == "postgresql"
and ch == "'"
and prev in ("e", "E")
and not (i >= 2 and _WORD.match(sql[i - 2]))
)
j = _skip_quoted(sql, i, ch, backslash=mysql or e_string)
emit(sql[i:j], meaningful=True)
i = j
elif ch == "`" and mysql:
j = _skip_quoted(sql, i, "`", backslash=False)
emit(sql[i:j], meaningful=True)
i = j
elif ch == "[" and engine == "sqlserver":
j = _skip_quoted(sql, i, "[", backslash=False, end="]")
emit(sql[i:j], meaningful=True)
i = j
elif (ch == "-" and nxt == "-") or (ch == "#" and mysql):
j = sql.find("\n", i)
j = n if j == -1 else j
emit(sql[i:j], meaningful=False)
i = j
elif ch == "/" and nxt == "*":
j = sql.find("*/", i + 2)
if j == -1:
raise _bad("template_unterminated", "sql_template")
emit(sql[i : j + 2], meaningful=False)
i = j + 2
elif ch == "$" and engine == "postgresql" and not (i and _WORD.match(sql[i - 1])):
tag = _DOLLAR_TAG.match(sql, i)
if tag is None:
emit(ch, meaningful=True)
i += 1
continue
j = sql.find(tag.group(0), tag.end())
if j == -1:
raise _bad("template_unterminated", "sql_template")
emit(sql[i : j + len(tag.group(0))], meaningful=True)
i = j + len(tag.group(0))
elif ch == ":" and nxt == ":":
emit("::", meaningful=True)
i += 2
elif ch == ":":
match = _PARAM_NAME.match(sql, i)
if match and not (i and _WORD.match(sql[i - 1])):
if ended:
raise _bad("multiple_statements", "sql_template")
flush()
parts.append(("param", match.group(1)))
i = match.end()
else:
emit(ch, meaningful=True)
i += 1
elif ch == "{" and nxt == "{":
j = sql.find("}}", i + 2)
if j == -1:
raise _bad("identifier_unterminated", "sql_template")
if ended:
raise _bad("multiple_statements", "sql_template")
flush()
parts.append(("ident", sql[i + 2 : j].strip()))
i = j + 2
elif ch == ";":
if ended:
raise _bad("multiple_statements", "sql_template")
ended = True
i += 1 # the terminator itself is dropped
else:
emit(ch, meaningful=not ch.isspace())
i += 1
flush()
return parts
def prepare_query(
*,
engine: str,
sql_template: str,
param_schema: Any,
allowed_identifiers: Any,
params: Any,
) -> PreparedQuery:
"""Validate everything, then return SQL with `%(name)s` markers and the bound values.
Raises ValidationError before any connection when: a parameter is unknown, missing or
mistyped, a placeholder is undeclared, an identifier is malformed or not allowed, or
the template is not a single statement. Caller values are never echoed in errors.
"""
if engine not in _QUOTE:
raise _bad("unsupported_engine", "engine")
if not isinstance(sql_template, str) or not sql_template.strip():
raise _bad("template_empty", "sql_template")
specs = {spec.name: spec for spec in parse_param_schema(param_schema)}
allowed = parse_allowed_identifiers(allowed_identifiers)
supplied = {} if params is None else params
if not isinstance(supplied, dict):
raise _bad("params_invalid", "params")
unknown = sorted(str(k)[:64] for k in supplied if k not in specs)[:10]
if unknown:
raise _bad("unknown_param", *unknown)
bound: dict[str, Any] = {}
for spec in specs.values():
bound[spec.name] = _resolve(spec, supplied)
parts = _scan(sql_template, engine)
used: set[str] = set()
for kind, value in parts:
if kind == "param":
if value not in specs:
raise _bad("undeclared_param", value)
used.add(value)
elif kind == "ident":
if not IDENTIFIER_RE.match(value):
raise _bad("identifier_invalid", "sql_template")
if value not in allowed:
raise _bad("identifier_not_allowed", value)
if not used:
# Nothing to bind: a '%' in the text must stay literal, so pass no parameters.
out = "".join(_render(kind, value, engine, escape=False) for kind, value in parts)
return PreparedQuery(sql=out.strip(), params=None)
out = "".join(_render(kind, value, engine, escape=True) for kind, value in parts)
return PreparedQuery(sql=out.strip(), params={name: bound[name] for name in used})
def _resolve(spec: ParamSpec, supplied: dict[str, Any]) -> Any:
if spec.name in supplied:
try:
return coerce_param_value(spec.type, supplied[spec.name])
except ValueError:
raise _bad("param_type_mismatch", spec.name) from None
if spec.required:
raise _bad("missing_param", spec.name)
return spec.default if spec.has_default else None
def _render(kind: str, value: str, engine: str, *, escape: bool) -> str:
if kind == "param":
return f"%({value})s"
if kind == "ident":
return _QUOTE[engine].format(value)
return value.replace("%", "%%") if escape else value
@@ -15,7 +15,7 @@ import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy import asc, desc, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
@@ -29,7 +29,8 @@ from watchman.datasources import (
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.models.datasource import DataSource, validate_kind_engine
from watchman.models.datasource import ALLOWED_ENGINES, DataSource, validate_kind_engine
from watchman.models.query import QueryDefinition
from watchman.services.platform_records import create_audit_event
# Only these probe categories are worth retrying; the others need a config change.
@@ -235,12 +236,30 @@ def _audit(session: Session, action: str, row: DataSource, **extra: Any) -> None
)
_DS_SORT = {
"name": DataSource.name,
"engine": DataSource.engine,
"host": DataSource.host,
"port": DataSource.port,
"database_name": DataSource.database_name,
"username": DataSource.username,
"enabled": DataSource.enabled,
"last_test_at": DataSource.last_test_at,
"created_at": DataSource.created_at,
"updated_at": DataSource.updated_at,
}
_DS_SORT_DEFAULT = "created_at"
_LIST_PAGE_SIZE_MAX = 100
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.
Healthcheck and option dropdowns use this complete list; the console table uses
search_datasources so filters, ORDER BY and LIMIT run in SQL.
"""
rows = list(
session.scalars(
@@ -257,6 +276,62 @@ def list_datasources(session: Session, *, usable_only: bool = False) -> list[Dat
return [row for row in rows if row.enabled and row.circuit_state != CIRCUIT_OPEN]
def search_datasources(
session: Session,
*,
name: str | None = None,
engine: str | None = None,
enabled: bool | None = None,
sort_by: str = _DS_SORT_DEFAULT,
sort_order: str = "asc",
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""Filter, ORDER BY and page datasources in SQL for the console list.
Cooldown close runs on the returned page only so circuit state in the page is fresh;
the caller commits. usable_only option lists still go through list_datasources.
"""
if sort_by not in _DS_SORT:
raise ValidationError("Invalid sort_by", details={"field": "sort_by", "allowed": sorted(_DS_SORT)})
if sort_order not in ("asc", "desc"):
raise ValidationError("Invalid sort_order", details={"field": "sort_order", "allowed": ["asc", "desc"]})
if page < 1:
raise ValidationError("Invalid page", details={"field": "page"})
if page_size < 1 or page_size > _LIST_PAGE_SIZE_MAX:
raise ValidationError(
"Invalid page_size",
details={"field": "page_size", "min": 1, "max": _LIST_PAGE_SIZE_MAX},
)
if engine is not None and engine not in ALLOWED_ENGINES:
raise ValidationError("Invalid engine", details={"field": "engine"})
filters = [DataSource.tenant_id == _tenant_id()]
needle = (name or "").strip()
if needle:
filters.append(DataSource.name.ilike(f"%{needle}%"))
if engine:
filters.append(DataSource.engine == engine)
if enabled is not None:
filters.append(DataSource.enabled.is_(enabled))
total = int(session.scalar(select(func.count()).select_from(DataSource).where(*filters)) or 0)
order_col = _DS_SORT[sort_by]
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
stmt = (
select(DataSource)
.where(*filters)
.order_by(order_expr, asc(DataSource.id))
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = list(session.scalars(stmt))
now = _now()
for row in rows:
_close_if_cooled_down(row, now)
return {"items": rows, "total": total, "page": page, "page_size": page_size}
def get_datasource(session: Session, datasource_id: str) -> DataSource:
"""Return one datasource or raise 404.
@@ -456,9 +531,20 @@ def record_probe_outcome(
def list_references(session: Session, datasource_id: str) -> dict[str, Any]:
"""Return the references to a datasource. No module references datasources yet."""
"""Return what references a datasource: the query definitions bound to it (read-only hint)."""
row = _get_row(session, datasource_id)
return {"id": str(row.id), "items": []}
queries = session.scalars(
select(QueryDefinition)
.where(
QueryDefinition.tenant_id == _tenant_id(),
QueryDefinition.datasource_id == row.id,
)
.order_by(QueryDefinition.name)
)
items = [
{"type": "query", "id": str(q.id), "name": q.name, "enabled": q.enabled} for q in queries
]
return {"id": str(row.id), "items": items}
def _probe(target: ProbeTarget) -> ProbeResult:
@@ -484,6 +570,42 @@ def _decrypt_stored(row: DataSource) -> str:
raise DatasourceSecretUnavailableError() from None
def build_probe_target(row: DataSource) -> ProbeTarget:
"""Build a connection target from the stored row; the password lives only in memory.
Raises DatasourceSecretUnavailableError when the stored secret cannot be decrypted.
"""
return ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=_decrypt_stored(row),
)
def record_connection_failure(
session: Session, datasource_id: str, category: ProbeCategory
) -> bool:
"""Count one failed connection of a real query run against the circuit.
Same accounting as a saved-connection test (window, threshold, circuit_open audit) but
last_test_* is left alone because no test was run. A source deleted meanwhile is
ignored. The caller commits. Returns True if the circuit opened.
"""
if category is ProbeCategory.SUCCESS:
return False
try:
row = _get_row(session, datasource_id, lock=True)
except NotFoundError:
session.rollback()
return False
result = ProbeResult(category=category, message=f"query run: {category.value}")
return record_probe_outcome(session, row, result, update_last_test=False)
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.
@@ -0,0 +1,719 @@
"""Query definition service: metadata CRUD, save-as-version, activate, versions and preview.
Why: the console saves immutable numbered versions (D26: no draft/publish two-step), activates
one as current, and trial-runs the current or a chosen version.
Boundary: tenant comes only from server settings; a QueryVersion is only ever inserted, never
updated or deleted. draft_* columns mirror the current version for transitional internals and
are not an editable draft API. Preview delegates to watchman.queries.run_query; it never
persists rows or creates alarms. Callers own the final commit; preview_* commits inside
run_query, then audit once.
Depends on the query models, the datasource service, the S2 executor and create_audit_event.
"""
from __future__ import annotations
import re
import uuid
from datetime import datetime, timezone
from typing import Any
from sqlalchemy import asc, desc, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
from watchman.models.datasource import DataSource
from watchman.models.query import (
DEFAULT_MAX_ROWS,
DEFAULT_TIMEOUT_MS,
MAX_ROWS_LIMIT,
MAX_TIMEOUT_MS,
QueryDefinition,
QueryVersion,
)
from watchman.queries import QueryRunResult, run_query
from watchman.queries.schema import (
parse_allowed_identifiers,
parse_output_schema,
parse_param_schema,
)
from watchman.services import datasources as datasource_service
from watchman.services.platform_records import create_audit_event
# Draft fields a create or PATCH may set; API name -> definition column.
_DRAFT_COLUMNS = {
"sql_template": "draft_sql_template",
"param_schema": "draft_param_schema",
"output_schema": "draft_output_schema",
"allowed_identifiers": "draft_allowed_identifiers",
"timeout_ms": "draft_timeout_ms",
"max_rows": "draft_max_rows",
}
# Plain definition fields (not draft content) a PATCH may set; only description may be null.
_PLAIN_FIELDS = ("name", "description", "datasource_id")
MAX_PUBLISHED_BY_LENGTH = 128
# Preview rows are samples: values of columns whose name looks sensitive are masked. The
# output contract carries no sensitivity flag, so this is a simple name-based policy.
SENSITIVE_COLUMN_RE = re.compile(
r"pass(word|wd)?|pwd|secret|token|credential|api[_-]?key|private[_-]?key|"
r"id[_-]?card|phone|mobile|email",
re.IGNORECASE,
)
MASK = "***"
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:
# Always UTC: a just-written value (UTC) and a re-read one (session zone) must match.
return value.astimezone(timezone.utc).isoformat() if value is not None else None
def _parse_id(query_id: str) -> uuid.UUID:
try:
return uuid.UUID(query_id)
except ValueError:
# An id that cannot exist is the same as an unknown id.
raise NotFoundError("Query not found") from None
def content_from_draft_columns(row: QueryDefinition) -> dict[str, Any]:
"""Mirrored content from draft_* columns (same keys as a version body)."""
return {
"sql_template": row.draft_sql_template,
"param_schema": row.draft_param_schema,
"output_schema": row.draft_output_schema,
"allowed_identifiers": row.draft_allowed_identifiers,
"timeout_ms": row.draft_timeout_ms,
"max_rows": row.draft_max_rows,
}
def _mirror_draft(row: QueryDefinition, content: dict[str, Any]) -> None:
"""Keep draft_* in sync with the active version content (D26 transitional mirror)."""
for key, column in _DRAFT_COLUMNS.items():
setattr(row, column, content[key])
def summary_public(row: QueryDefinition) -> dict[str, Any]:
"""List item: identity, state and version pointers; no SQL content."""
return {
"id": str(row.id),
"name": row.name,
"description": row.description,
"datasource_id": str(row.datasource_id),
"enabled": row.enabled,
"current_version_no": row.current_version_no,
"latest_version_no": row.latest_published_version_no,
# Legacy alias kept for older clients during the transition.
"latest_published_version_no": row.latest_published_version_no,
"created_at": _isoformat(row.created_at),
"updated_at": _isoformat(row.updated_at),
}
def to_public(row: QueryDefinition) -> dict[str, Any]:
"""Detail: summary plus the current version content snapshot (not a draft)."""
return {**summary_public(row), "current": content_from_draft_columns(row)}
def version_summary(row: QueryVersion) -> dict[str, Any]:
"""Version list item: number and provenance only."""
return {
"id": str(row.id),
"definition_id": str(row.definition_id),
"version_no": row.version_no,
"published_at": _isoformat(row.published_at),
"published_by": row.published_by,
}
def version_public(row: QueryVersion) -> dict[str, Any]:
"""Full frozen version content."""
return {
**version_summary(row),
"sql_template": row.sql_template,
"param_schema": row.param_schema,
"output_schema": row.output_schema,
"allowed_identifiers": row.allowed_identifiers,
"timeout_ms": row.timeout_ms,
"max_rows": row.max_rows,
}
def _get_row(session: Session, query_id: str, *, lock: bool = False) -> QueryDefinition:
"""Load one definition of the server tenant or raise 404 (also for other tenants)."""
statement = select(QueryDefinition).where(
QueryDefinition.id == _parse_id(query_id),
QueryDefinition.tenant_id == _tenant_id(),
)
if lock:
statement = statement.execution_options(populate_existing=True).with_for_update()
row = session.scalar(statement)
if row is None:
raise NotFoundError("Query not found")
return row
def _get_version(session: Session, definition: QueryDefinition, version_no: int) -> QueryVersion:
row = session.scalar(
select(QueryVersion).where(
QueryVersion.tenant_id == _tenant_id(),
QueryVersion.definition_id == definition.id,
QueryVersion.version_no == version_no,
)
)
if row is None:
raise NotFoundError("Query version not found")
return row
def _check_datasource(session: Session, datasource_id: str) -> uuid.UUID:
"""The datasource must exist for this tenant and be a database source."""
try:
source = datasource_service.get_datasource(session, datasource_id)
except NotFoundError:
raise ValidationError(
"Datasource not found",
details={"reason": "datasource_not_found", "fields": ["datasource_id"]},
) from None
if source.kind != "database":
raise ValidationError(
"Queries can only use a database datasource",
details={"reason": "datasource_not_database", "fields": ["datasource_id"]},
)
return source.id
def _validate_draft_content(values: dict[str, Any]) -> None:
"""Reject malformed draft content; reuses the executor's schema parsers (no SQL parsing)."""
if "sql_template" in values:
sql = values["sql_template"]
if not isinstance(sql, str) or not sql.strip():
raise ValidationError(
"Invalid query definition",
details={"reason": "template_empty", "fields": ["sql_template"]},
)
if "param_schema" in values:
parse_param_schema(values["param_schema"])
if "output_schema" in values:
parse_output_schema(values["output_schema"])
if "allowed_identifiers" in values:
parse_allowed_identifiers(values["allowed_identifiers"])
def _cap_limit(name: str, value: Any, maximum: int) -> int:
"""A limit must be an int >= 1; one above the server cap is capped, not rejected."""
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValidationError(
"Invalid query limits", details={"reason": "limit_invalid", "fields": [name]}
)
return min(value, maximum)
def _normalize_limits(values: dict[str, Any]) -> None:
if "timeout_ms" in values:
values["timeout_ms"] = _cap_limit("timeout_ms", values["timeout_ms"], MAX_TIMEOUT_MS)
if "max_rows" in values:
values["max_rows"] = _cap_limit("max_rows", values["max_rows"], MAX_ROWS_LIMIT)
def _ensure_name_free(session: Session, name: str, *, exclude_id: uuid.UUID | None = None) -> None:
statement = select(QueryDefinition.id).where(
QueryDefinition.tenant_id == _tenant_id(),
QueryDefinition.name == name,
)
if exclude_id is not None:
statement = statement.where(QueryDefinition.id != exclude_id)
if session.scalar(statement) is not None:
raise ConflictError("Query 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(
"Query name already exists", details={"reason": "duplicate_name"}
) from None
def _audit(session: Session, action: str, payload: dict[str, Any]) -> None:
"""Write an audit event with a server-generated key. Payloads never hold SQL or rows."""
create_audit_event(
session,
action=action,
payload=payload,
idempotency_key=f"{action}:{uuid.uuid4().hex}",
)
# Console list sort keys → SQL columns (datasource_name needs a join).
_QUERY_SORT = {
"name": QueryDefinition.name,
"enabled": QueryDefinition.enabled,
"latest_published_version_no": QueryDefinition.latest_published_version_no,
"current_version_no": QueryDefinition.current_version_no,
"updated_at": QueryDefinition.updated_at,
"created_at": QueryDefinition.created_at,
"datasource_name": DataSource.name,
}
_QUERY_SORT_DEFAULT = "updated_at"
_LIST_PAGE_SIZE_MAX = 100
def list_queries(session: Session, *, enabled: bool | None = None) -> list[QueryDefinition]:
"""Return definitions of the server tenant, oldest first; enabled filters when given.
Internal callers (seed, references) use this complete list. The console list uses
search_queries so filters, ORDER BY and LIMIT run in SQL.
"""
statement = select(QueryDefinition).where(QueryDefinition.tenant_id == _tenant_id())
if enabled is not None:
statement = statement.where(QueryDefinition.enabled.is_(enabled))
return list(
session.scalars(statement.order_by(QueryDefinition.created_at, QueryDefinition.name))
)
def search_queries(
session: Session,
*,
enabled: bool | None = None,
name: str | None = None,
datasource_id: str | None = None,
sort_by: str = _QUERY_SORT_DEFAULT,
sort_order: str = "desc",
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""Filter, ORDER BY and page query definitions in SQL for the console list."""
if sort_by not in _QUERY_SORT:
raise ValidationError("Invalid sort_by", details={"field": "sort_by", "allowed": sorted(_QUERY_SORT)})
if sort_order not in ("asc", "desc"):
raise ValidationError("Invalid sort_order", details={"field": "sort_order", "allowed": ["asc", "desc"]})
if page < 1:
raise ValidationError("Invalid page", details={"field": "page"})
if page_size < 1 or page_size > _LIST_PAGE_SIZE_MAX:
raise ValidationError(
"Invalid page_size",
details={"field": "page_size", "min": 1, "max": _LIST_PAGE_SIZE_MAX},
)
tenant = _tenant_id()
filters = [QueryDefinition.tenant_id == tenant]
if enabled is not None:
filters.append(QueryDefinition.enabled.is_(enabled))
needle = (name or "").strip()
if needle:
filters.append(QueryDefinition.name.ilike(f"%{needle}%"))
if datasource_id:
try:
ds_uuid = uuid.UUID(datasource_id)
except ValueError as exc:
raise ValidationError(
"Invalid datasource_id", details={"field": "datasource_id"}
) from exc
filters.append(QueryDefinition.datasource_id == ds_uuid)
# Join when sorting by datasource display name; otherwise stay on the definition table.
needs_join = sort_by == "datasource_name"
count_stmt = select(func.count()).select_from(QueryDefinition).where(*filters)
total = int(session.scalar(count_stmt) or 0)
order_col = _QUERY_SORT[sort_by]
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
# Stable tie-break so equal sort keys do not reshuffle across pages.
tie_break = asc(QueryDefinition.id)
stmt = select(QueryDefinition).where(*filters)
if needs_join:
stmt = stmt.join(DataSource, DataSource.id == QueryDefinition.datasource_id)
stmt = (
stmt.order_by(order_expr, tie_break)
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = list(session.scalars(stmt))
return {"items": rows, "total": total, "page": page, "page_size": page_size}
def get_query(session: Session, query_id: str) -> QueryDefinition:
"""Return one definition or raise 404."""
return _get_row(session, query_id)
def _insert_version(
session: Session,
row: QueryDefinition,
content: dict[str, Any],
*,
version_no: int,
published_by: str | None,
) -> QueryVersion:
version = QueryVersion(
tenant_id=row.tenant_id,
definition_id=row.id,
version_no=version_no,
sql_template=content["sql_template"],
param_schema=content["param_schema"],
output_schema=content["output_schema"],
allowed_identifiers=content["allowed_identifiers"],
timeout_ms=content["timeout_ms"],
max_rows=content["max_rows"],
published_at=_now(),
published_by=published_by[:MAX_PUBLISHED_BY_LENGTH] if published_by else None,
)
session.add(version)
try:
with session.begin_nested():
session.flush()
except IntegrityError:
raise ConflictError(
"Query version already exists", details={"reason": "version_conflict"}
) from None
return version
def create_query(
session: Session,
*,
name: str,
description: str | None,
datasource_id: str,
sql_template: str,
param_schema: list[Any] | None = None,
output_schema: list[Any] | None = None,
allowed_identifiers: list[Any] | None = None,
timeout_ms: int = DEFAULT_TIMEOUT_MS,
max_rows: int = DEFAULT_MAX_ROWS,
published_by: str | None = None,
) -> QueryDefinition:
"""Create an enabled definition with immutable v1 as current (D26)."""
content: dict[str, Any] = {
"sql_template": sql_template,
"param_schema": [] if param_schema is None else param_schema,
"output_schema": [] if output_schema is None else output_schema,
"allowed_identifiers": [] if allowed_identifiers is None else allowed_identifiers,
"timeout_ms": timeout_ms,
"max_rows": max_rows,
}
_validate_draft_content(content)
_normalize_limits(content)
ds_id = _check_datasource(session, datasource_id)
_ensure_name_free(session, name)
now = _now()
row = QueryDefinition(
tenant_id=_tenant_id(),
name=name,
description=description,
datasource_id=ds_id,
enabled=True,
latest_published_version_no=1,
current_version_no=1,
created_at=now,
updated_at=now,
**{_DRAFT_COLUMNS[key]: value for key, value in content.items()},
)
session.add(row)
_flush_unique(session)
_insert_version(session, row, content, version_no=1, published_by=published_by)
_audit(
session,
"query.create",
{
"id": str(row.id),
"name": row.name,
"datasource_id": str(row.datasource_id),
"version_no": 1,
},
)
return row
def update_query(session: Session, query_id: str, changes: dict[str, Any]) -> QueryDefinition:
"""Update definition metadata only. Content changes must use save_as_version (D26)."""
row = _get_row(session, query_id)
content_keys = [key for key in _DRAFT_COLUMNS if key in changes]
if content_keys:
raise ValidationError(
"Query content cannot be patched; save a new version",
details={"reason": "use_save_version", "fields": content_keys},
)
nulled = [f for f in _PLAIN_FIELDS if f != "description" and f in changes and changes[f] is None]
if nulled:
raise ValidationError("Fields cannot be null", details={"fields": nulled})
if "datasource_id" in changes:
row.datasource_id = _check_datasource(session, changes["datasource_id"])
if "name" in changes and changes["name"] != row.name:
_ensure_name_free(session, changes["name"], exclude_id=row.id)
row.name = changes["name"]
if "description" in changes:
row.description = changes["description"]
row.updated_at = _now()
_flush_unique(session)
changed = [f for f in _PLAIN_FIELDS if f in changes]
_audit(
session,
"query.update",
{"id": str(row.id), "name": row.name, "fields": changed},
)
return row
def save_as_version(
session: Session,
query_id: str,
content: dict[str, Any],
*,
published_by: str | None = None,
) -> QueryVersion:
"""Insert the next immutable version, activate it, and mirror draft_* (D26)."""
row = _get_row(session, query_id, lock=True)
body = {
"sql_template": content["sql_template"],
"param_schema": content.get("param_schema") or [],
"output_schema": content.get("output_schema") or [],
"allowed_identifiers": content.get("allowed_identifiers") or [],
"timeout_ms": content.get("timeout_ms", DEFAULT_TIMEOUT_MS),
"max_rows": content.get("max_rows", DEFAULT_MAX_ROWS),
}
_validate_draft_content(body)
_normalize_limits(body)
version_no = (row.latest_published_version_no or 0) + 1
version = _insert_version(
session, row, body, version_no=version_no, published_by=published_by
)
row.latest_published_version_no = version_no
row.current_version_no = version_no
_mirror_draft(row, body)
row.updated_at = _now()
session.flush()
_audit(
session,
"query.save_version",
{"id": str(row.id), "name": row.name, "version_no": version_no},
)
return version
def activate_version(
session: Session, query_id: str, version_no: int
) -> QueryDefinition:
"""Set current_version_no to an existing version and mirror its content into draft_*."""
if version_no < 1:
raise ValidationError("Invalid version_no", details={"field": "version_no"})
row = _get_row(session, query_id, lock=True)
version = _get_version(session, row, version_no)
content = {
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
}
row.current_version_no = version.version_no
_mirror_draft(row, content)
row.updated_at = _now()
session.flush()
_audit(
session,
"query.activate_version",
{"id": str(row.id), "name": row.name, "version_no": version.version_no},
)
return row
def _set_enabled(session: Session, query_id: str, enabled: bool) -> QueryDefinition:
row = _get_row(session, query_id)
row.enabled = enabled
row.updated_at = _now()
session.flush()
_audit(
session,
"query.enable" if enabled else "query.disable",
{"id": str(row.id), "name": row.name},
)
return row
def disable_query(session: Session, query_id: str) -> QueryDefinition:
"""Mark a definition disabled. It stays readable and can be enabled again."""
return _set_enabled(session, query_id, False)
def enable_query(session: Session, query_id: str) -> QueryDefinition:
"""Mark a definition enabled again."""
return _set_enabled(session, query_id, True)
def list_versions(session: Session, query_id: str) -> list[QueryVersion]:
"""Return the versions of one definition, newest first."""
row = _get_row(session, query_id)
return list(
session.scalars(
select(QueryVersion)
.where(
QueryVersion.tenant_id == _tenant_id(),
QueryVersion.definition_id == row.id,
)
.order_by(QueryVersion.version_no.desc())
)
)
def get_version(session: Session, query_id: str, version_no: int) -> QueryVersion:
"""Return one frozen version or raise 404."""
return _get_version(session, _get_row(session, query_id), version_no)
def list_references(session: Session, query_id: str) -> dict[str, Any]:
"""Return what references this query. No scenario module exists yet, so items is empty."""
row = _get_row(session, query_id)
return {"id": str(row.id), "items": []}
def _mask_rows(columns: list[str], rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
"""Replace non-null values of sensitive-looking columns with a fixed mask."""
masked = [name for name in columns if SENSITIVE_COLUMN_RE.search(name)]
if not masked:
return rows, []
out = [
{k: (MASK if k in masked and v is not None else v) for k, v in row.items()}
for row in rows
]
return out, masked
def preview_public(
result: QueryRunResult,
*,
definition_id: str,
version_no: int | None,
source: str = "version",
) -> dict[str, Any]:
"""Map one run outcome to the API shape. Distinct fields per status, no secrets.
success/empty carry columns, rows and row_count; illegal_type carries details.fields
(names and types only); failure carries failure_kind and its safe details.
"""
data: dict[str, Any] = {
"id": definition_id,
"version_no": version_no,
"source": source,
"status": result.status,
"message": result.message,
}
if result.status in ("success", "empty"):
rows, masked = _mask_rows(result.columns, result.rows)
data.update(columns=result.columns, rows=rows, row_count=len(rows), masked_columns=masked)
elif result.status == "illegal_type":
data.update(columns=result.columns, details=result.details)
else:
data.update(failure_kind=result.failure_kind, details=result.details)
return data
def _require_enabled(row: QueryDefinition) -> None:
if not row.enabled:
raise ConflictError("Query is disabled", details={"reason": "disabled"})
def _run_and_audit(
session: Session,
*,
definition_id: str,
version_no: int | None,
datasource_id: str,
content: dict[str, Any],
params: dict[str, Any],
source: str = "version",
) -> dict[str, Any]:
# `content` was copied out of the ORM rows: run_query commits the session.
result = run_query(
session,
datasource_id=datasource_id,
sql_template=content["sql_template"],
param_schema=content["param_schema"],
output_schema=content["output_schema"],
allowed_identifiers=content["allowed_identifiers"],
params=params,
timeout_ms=content["timeout_ms"],
max_rows=content["max_rows"],
)
# GUARD: only definition id, version_no (if any) and status; no name, SQL, rows, columns,
# parameter values or messages.
payload: dict[str, Any] = {"id": definition_id, "status": result.status}
if version_no is not None:
payload["version_no"] = version_no
_audit(session, "query.preview", payload)
return preview_public(
result, definition_id=definition_id, version_no=version_no, source=source
)
def preview_current(session: Session, query_id: str, params: dict[str, Any]) -> dict[str, Any]:
"""Trial-run the current active version. Disabled definitions are refused (409)."""
row = _get_row(session, query_id)
_require_enabled(row)
if row.current_version_no is None:
raise ConflictError("Query has no current version", details={"reason": "no_current_version"})
version = _get_version(session, row, row.current_version_no)
return _run_and_audit(
session,
definition_id=str(row.id),
version_no=version.version_no,
datasource_id=str(row.datasource_id),
content={
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
},
params=params,
source="current",
)
# Temporary alias for call sites still named preview_draft during the transition.
preview_draft = preview_current
def preview_version(
session: Session, query_id: str, version_no: int, params: dict[str, Any]
) -> dict[str, Any]:
"""Trial-run a frozen version against the definition's datasource (409 if disabled)."""
row = _get_row(session, query_id)
_require_enabled(row)
version = _get_version(session, row, version_no)
return _run_and_audit(
session,
definition_id=str(row.id),
version_no=version.version_no,
datasource_id=str(row.datasource_id),
content={
"sql_template": version.sql_template,
"param_schema": version.param_schema,
"output_schema": version.output_schema,
"allowed_identifiers": version.allowed_identifiers,
"timeout_ms": version.timeout_ms,
"max_rows": version.max_rows,
},
params=params,
source="version",
)
@@ -0,0 +1,36 @@
"""Immutability guard for published query versions.
Boundary: refuses content changes to an existing QueryVersion; snapshotting a draft into a
new version belongs to a later slice. Identity and audit columns (published_at/published_by)
are frozen too, because a version is a historical record. No database access, no HTTP concerns.
Depends on the QueryVersion model and the shared semantic errors.
"""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from watchman.core.errors import ValidationError
from watchman.models.query import VERSION_CONTENT_COLUMNS, QueryVersion
# Identity/audit columns are frozen as well; changing them would rewrite history.
_FROZEN_COLUMNS = VERSION_CONTENT_COLUMNS | frozenset(
{"tenant_id", "definition_id", "version_no", "published_at", "published_by"}
)
def forbid_version_content_mutation(changes: Mapping[str, Any]) -> None:
"""Raise ValidationError if `changes` touches any frozen column of a published version."""
touched = sorted(set(changes) & _FROZEN_COLUMNS)
if touched:
raise ValidationError(
"published query versions are immutable; publish a new version instead",
details={"reason": "version_immutable", "fields": touched},
)
def assert_version_immutable(version: QueryVersion, changes: Mapping[str, Any]) -> QueryVersion:
"""Return `version` untouched, or raise if `changes` would rewrite it (never mutates it)."""
forbid_version_content_mutation(changes)
return version
@@ -0,0 +1,52 @@
"""Superuser-only purge of query rows created by tests.
query_versions is append-only for the application and migrator roles (migration 0007), so a
test cannot delete the versions it published through the app session. Cleanup therefore
connects with the local bootstrap superuser and opts out of the append-only trigger with
`SET LOCAL session_replication_role = replica`. Only synthetic rows carrying a test name
prefix or belonging to a given datasource are removed. Never used by production code.
"""
from __future__ import annotations
import uuid
from sqlalchemy import create_engine, text
from sqlalchemy.engine import make_url
from watchman.core.config import get_settings, merge_layered_env
def _superuser_engine(): # type: ignore[no-untyped-def]
env = merge_layered_env()
bootstrap = env.get("WATCHMAN_BOOTSTRAP_DATABASE_URL")
if not bootstrap:
raise RuntimeError(
"WATCHMAN_BOOTSTRAP_DATABASE_URL is required to clean up append-only query_versions rows"
)
database = make_url(get_settings().database_url).database
return create_engine(make_url(bootstrap).set(database=database), pool_pre_ping=True)
def purge_query_rows(
*, name_like: str | None = None, datasource_id: uuid.UUID | str | None = None
) -> None:
"""Delete query versions and definitions matched by name prefix or datasource."""
if (name_like is None) == (datasource_id is None):
raise ValueError("pass exactly one of name_like or datasource_id")
where = "name LIKE :v" if name_like is not None else "datasource_id = :v"
value = name_like if name_like is not None else str(datasource_id)
engine = _superuser_engine()
try:
with engine.begin() as conn:
conn.execute(text("SET LOCAL session_replication_role = replica"))
conn.execute(
text(
"DELETE FROM query_versions WHERE definition_id IN "
f"(SELECT id FROM query_definitions WHERE {where})"
),
{"v": value},
)
conn.execute(text(f"DELETE FROM query_definitions WHERE {where}"), {"v": value})
finally:
engine.dispose()
+920
View File
@@ -0,0 +1,920 @@
"""Query definition API tests (M04 S3): permissions, draft CRUD, publish, preview, references.
Why: these routes are the only way to maintain query drafts and freeze versions, and they
can trigger a run against a customer database, so roles, version immutability and the
no-secret/no-rows audit rules need proof.
Boundary: uses the local platform Postgres and seeded sessions like test_datasource_api;
the executor is replaced by a fake for outcome-shape tests, and the real run_query is used
only for paths that never open a socket (validation failure, disabled datasource). Rows
created here are removed afterwards (audit events are append-only and kept).
Depends on watchman.api.app, the session store and the query/datasource services.
"""
from __future__ import annotations
import json
import uuid
import pytest
from sqlalchemy import select, text
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
OPERATOR,
VIEWER,
_client,
_create,
cleanup,
datasource_key,
)
from _privileged_cleanup import purge_query_rows
from watchman.auth.access import (
QUERY_PREVIEW_NODE,
QUERY_PUBLISH_NODE,
QUERY_READ_NODE,
QUERY_WRITE_NODE,
require_query_preview,
require_query_publish,
require_query_read,
require_query_write,
)
from watchman.core.config import get_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.core.errors import ForbiddenError
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent
from watchman.models.query import QueryDefinition, QueryVersion
from watchman.queries import QueryRunResult
from watchman.queries.result import failure
from watchman.services import queries as service
SQL = "SELECT 1 AS n WHERE :flag"
PARAM_SCHEMA = [{"name": "flag", "type": "boolean", "required": False, "default": True}]
OUTPUT_SCHEMA = [{"name": "n", "type": "integer"}]
FOREIGN_TENANT = "other-tenant-query-api-test"
@pytest.fixture(autouse=True)
def query_cleanup(cleanup): # noqa: F811
"""Remove this run's queries before the datasource cleanup (RESTRICT foreign keys)."""
yield
# query_versions is append-only for the app role, so cleanup is a superuser purge.
purge_query_rows(name_like=f"{NAME_PREFIX}%")
def _qbody(ds_id: str, **overrides) -> dict:
values = {
"name": f"{NAME_PREFIX}q-{uuid.uuid4().hex[:8]}",
"description": "synthetic query",
"datasource_id": ds_id,
"sql_template": SQL,
"param_schema": PARAM_SCHEMA,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 50,
}
values.update(overrides)
return values
def _make(client, ds_id: str | None = None, **overrides) -> dict:
if ds_id is None:
ds_id = _create(client)["id"]
response = client.post("/queries", json=_qbody(ds_id, **overrides))
assert response.status_code == 200, response.text
return response.json()["data"]
def _db_rows(query_id: str) -> tuple[QueryDefinition, list[QueryVersion]]:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
definition = session.scalar(
select(QueryDefinition).where(QueryDefinition.id == uuid.UUID(query_id))
)
assert definition is not None
versions = list(
session.scalars(
select(QueryVersion)
.where(QueryVersion.definition_id == definition.id)
.order_by(QueryVersion.version_no)
)
)
return definition, versions
finally:
session.close()
def _audit(query_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() == query_id,
)
)
)
finally:
session.close()
@pytest.fixture
def fake_run(monkeypatch: pytest.MonkeyPatch):
"""Replace the executor; records every call and returns the configured result."""
state: dict = {"calls": [], "result": QueryRunResult(status="success", message="ok")}
def _fake(session, **kwargs):
state["calls"].append(kwargs)
return state["result"]
monkeypatch.setattr(service, "run_query", _fake)
return state
# --- permission nodes and role rules ---------------------------------------------------------
def test_node_strings_and_role_rules() -> None:
assert QUERY_READ_NODE == "perm:data:emp:watchman.query.read"
assert QUERY_WRITE_NODE == "perm:data:emp:watchman.query.write"
assert QUERY_PUBLISH_NODE == "perm:data:emp:watchman.query.publish"
assert QUERY_PREVIEW_NODE == "perm:data:emp:watchman.query.preview"
checks = [
(require_query_read, QUERY_READ_NODE),
(require_query_write, QUERY_WRITE_NODE),
(require_query_publish, QUERY_PUBLISH_NODE),
(require_query_preview, QUERY_PREVIEW_NODE),
]
for check, node in checks:
check(ADMIN)
for roles in (OPERATOR, VIEWER, [], ["someone-else"]):
with pytest.raises(ForbiddenError) as raised:
check(roles)
assert raised.value.permission_node == node
ANY_ID = str(uuid.uuid4())
ROUTES = [
("GET", "/queries", None),
("POST", "/queries", {"name": "x", "datasource_id": ANY_ID, "sql_template": "SELECT 1"}),
("GET", f"/queries/{ANY_ID}", None),
("PATCH", f"/queries/{ANY_ID}", {"description": "x"}),
("POST", f"/queries/{ANY_ID}/disable", None),
("POST", f"/queries/{ANY_ID}/enable", None),
("POST", f"/queries/{ANY_ID}/versions", {"sql_template": "SELECT 1"}),
("POST", f"/queries/{ANY_ID}/versions/1/activate", None),
("GET", f"/queries/{ANY_ID}/versions", None),
("GET", f"/queries/{ANY_ID}/versions/1", None),
("POST", f"/queries/{ANY_ID}/preview", {"params": {}}),
("POST", f"/queries/{ANY_ID}/versions/1/preview", {"params": {}}),
("GET", f"/queries/{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
def _node_for(method: str, path: str) -> str:
if path.endswith("/preview"):
return QUERY_PREVIEW_NODE
if path.endswith("/activate") or (
method == "POST" and (path == "/queries" or path.endswith("/versions"))
):
return QUERY_PUBLISH_NODE
if method == "GET":
return QUERY_READ_NODE
return QUERY_WRITE_NODE
@pytest.mark.parametrize("roles", [VIEWER, OPERATOR, [], ["someone-else"]])
@pytest.mark.parametrize(("method", "path", "payload"), ROUTES)
def test_non_admin_is_42000_with_node_and_nothing_changes(
cleanup, roles, method, path, payload
) -> None:
# A real definition proves a denied write cannot touch it; denial precedes any lookup.
created = _make(_client(cleanup, ADMIN))
real_path = path.replace(ANY_ID, created["id"])
body = payload
if method == "POST" and path == "/queries":
body = _qbody(created["datasource_id"])
response = _client(cleanup, roles).request(method, real_path, json=body)
assert response.status_code == 403
error = response.json()["error"]
assert error["code"] == 42000
assert error["permission_node"] == _node_for(method, path)
definition, versions = _db_rows(created["id"])
assert definition.enabled is True and definition.description == "synthetic query"
assert definition.latest_published_version_no == 1 and definition.current_version_no == 1
assert len(versions) == 1
# --- create, read, update, enable, disable ---------------------------------------------------
def test_create_get_list_and_audit(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
body = _qbody(ds_id)
response = client.post("/queries", json=body)
assert response.status_code == 200
data = response.json()["data"]
assert response.json()["success"] is True
assert set(data) >= {
"id", "name", "description", "datasource_id", "enabled",
"current_version_no", "latest_version_no", "latest_published_version_no",
"created_at", "updated_at", "current",
}
assert "draft" not in data
assert data["enabled"] is True
assert data["current_version_no"] == 1 and data["latest_version_no"] == 1
assert data["datasource_id"] == ds_id and data["name"] == body["name"]
assert data["current"] == {
"sql_template": SQL,
"param_schema": PARAM_SCHEMA,
"output_schema": OUTPUT_SCHEMA,
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 50,
}
detail = client.get(f"/queries/{data['id']}")
assert detail.status_code == 200 and detail.json()["data"] == data
listing = client.get("/queries").json()["data"]["items"]
item = next(i for i in listing if i["id"] == data["id"])
assert "draft" not in item and "current" not in item
assert item["current_version_no"] == 1
events = _audit(data["id"], "query.create")
assert len(events) == 1
assert events[0].payload == {
"id": data["id"],
"name": body["name"],
"datasource_id": ds_id,
"version_no": 1,
}
assert SQL not in json.dumps(events[0].payload)
def test_create_defaults_and_limit_cap(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
minimal = {
"name": f"{NAME_PREFIX}min-{uuid.uuid4().hex[:6]}",
"datasource_id": ds_id,
"sql_template": "SELECT 1",
}
created = client.post("/queries", json=minimal).json()["data"]
assert created["current"]["timeout_ms"] == 10000 and created["current"]["max_rows"] == 100
assert created["current"]["param_schema"] == [] and created["description"] is None
capped = _make(client, ds_id, timeout_ms=10**9, max_rows=10**9)
assert capped["current"]["timeout_ms"] == 300000 and capped["current"]["max_rows"] == 10000
def test_create_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
bad_bodies = [
_qbody(ds_id, tenant_id="other-tenant"),
_qbody(ds_id, enabled=False),
_qbody(ds_id, latest_published_version_no=5),
_qbody(ds_id, draft_sql_template="SELECT 2"),
_qbody(ds_id, name=" "),
_qbody(ds_id, sql_template=" "),
_qbody(ds_id, sql_template=""),
_qbody(ds_id, param_schema=[{"name": "p", "type": "string", "extra": 1}]),
_qbody(ds_id, param_schema=[{"name": "p", "type": "blob"}]),
_qbody(ds_id, param_schema="nope"),
_qbody(ds_id, output_schema=[{"name": "c", "type": "string", "x": 1}]),
_qbody(ds_id, allowed_identifiers=["bad-name"]),
_qbody(ds_id, timeout_ms=0),
_qbody(ds_id, max_rows=-1),
_qbody(ds_id, max_rows=True),
_qbody(ds_id, datasource_id=str(uuid.uuid4())),
_qbody(ds_id, datasource_id="not-a-uuid"),
]
for body in bad_bodies:
response = client.post("/queries", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
missing = _qbody(ds_id)
del missing["datasource_id"]
assert client.post("/queries", json=missing).status_code == 400
# Nothing leaked into storage from the rejected bodies.
names = {i["name"] for i in client.get("/queries").json()["data"]["items"]}
assert not any(b["name"] in names for b in bad_bodies if b["name"].strip())
def test_create_rejects_non_database_datasource_and_duplicate_name(cleanup) -> None:
client = _client(cleanup, ADMIN)
first = _make(client)
clash = client.post("/queries", json=_qbody(first["datasource_id"], name=first["name"]))
assert clash.status_code == 409
assert clash.json()["error"]["details"]["reason"] == "duplicate_name"
# Another tenant's datasource cannot be bound.
foreign = _foreign_datasource()
try:
response = client.post("/queries", json=_qbody(str(foreign)))
assert response.status_code == 400
assert response.json()["error"]["details"]["reason"] == "datasource_not_found"
finally:
_drop_foreign(foreign)
def test_patch_updates_metadata_only_and_content_uses_save_version(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
new_ds = _create(client)["id"]
new_name = f"{NAME_PREFIX}renamed-{uuid.uuid4().hex[:6]}"
# Content fields on PATCH are refused (D26): either pydantic extra-forbid or service reason.
refused = client.patch(
f"/queries/{qid}",
json={"sql_template": "SELECT 2 AS n", "max_rows": 7},
)
assert refused.status_code == 400
assert refused.json()["error"]["code"] == 40000
response = client.patch(
f"/queries/{qid}",
json={"name": new_name, "description": None, "datasource_id": new_ds},
)
assert response.status_code == 200, response.text
data = response.json()["data"]
assert data["name"] == new_name and data["description"] is None
assert data["datasource_id"] == new_ds
assert data["current"]["sql_template"] == SQL
assert data["current_version_no"] == 1
saved = client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 2 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 7,
},
)
assert saved.status_code == 200, saved.text
assert saved.json()["data"]["version_no"] == 2
detail = client.get(f"/queries/{qid}").json()["data"]
assert detail["current_version_no"] == 2 and detail["latest_version_no"] == 2
assert detail["current"]["sql_template"] == "SELECT 2 AS n"
assert detail["current"]["max_rows"] == 7
events = _audit(qid, "query.update")
assert len(events) == 1
assert set(events[0].payload["fields"]) == {"name", "description", "datasource_id"}
assert client.patch(f"/queries/{qid}", json={"name": new_name}).status_code == 200
assert client.patch(f"/queries/{qid}", json={}).status_code == 200
def test_patch_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
other = _make(client, created["datasource_id"])
qid = created["id"]
bad_bodies = [
{"tenant_id": "x"},
{"enabled": False},
{"version_no": 3},
{"published_by": "someone"},
{"latest_published_version_no": 9},
{"current_version_no": 2},
{"draft_sql_template": "SELECT 2"},
{"id": str(uuid.uuid4())},
{"name": None},
{"datasource_id": None},
{"sql_template": "SELECT 1"},
{"param_schema": []},
{"timeout_ms": 1000},
{"max_rows": 10},
{"datasource_id": str(uuid.uuid4())},
]
for body in bad_bodies:
response = client.patch(f"/queries/{qid}", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
clash = client.patch(f"/queries/{qid}", json={"name": other["name"]})
assert clash.status_code == 409
assert clash.json()["error"]["details"]["reason"] == "duplicate_name"
assert client.get(f"/queries/{qid}").json()["data"] == created
def test_enable_disable_roundtrip_and_filter(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
disabled = client.post(f"/queries/{qid}/disable")
assert disabled.status_code == 200 and disabled.json()["data"]["enabled"] is False
assert client.get(f"/queries/{qid}").json()["data"]["enabled"] is False
assert client.delete(f"/queries/{qid}").status_code == 405
def ids(**params) -> list[str]:
items = client.get("/queries", params=params).json()["data"]["items"]
return [i["id"] for i in items]
assert qid in ids() and qid in ids(enabled="false") and qid not in ids(enabled="true")
enabled = client.post(f"/queries/{qid}/enable")
assert enabled.status_code == 200 and enabled.json()["data"]["enabled"] is True
assert qid in ids(enabled="true") and qid not in ids(enabled="false")
assert client.get("/queries", params={"enabled": "maybe"}).status_code == 400
assert len(_audit(qid, "query.disable")) == 1 and len(_audit(qid, "query.enable")) == 1
def test_list_supports_name_filter_sort_and_pagination(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
suffix = uuid.uuid4().hex[:6]
first = _make(client, ds_id, name=f"{NAME_PREFIX}alpha-{suffix}")
second = _make(client, ds_id, name=f"{NAME_PREFIX}beta-{suffix}")
page = client.get(
"/queries",
params={
"name": suffix,
"sort_by": "name",
"sort_order": "asc",
"page": 1,
"page_size": 1,
},
)
assert page.status_code == 200
body = page.json()["data"]
assert body["total"] >= 2 and body["page"] == 1 and body["page_size"] == 1
assert len(body["items"]) == 1
assert body["items"][0]["id"] == first["id"]
page2 = client.get(
"/queries",
params={"name": suffix, "sort_by": "name", "sort_order": "asc", "page": 2, "page_size": 1},
).json()["data"]
assert page2["items"][0]["id"] == second["id"]
assert client.get("/queries", params={"sort_by": "nope"}).status_code == 400
assert client.get("/queries", params={"page_size": 0}).status_code == 400
def test_unknown_foreign_and_malformed_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
foreign_ds = _foreign_datasource()
foreign_q = _foreign_query(foreign_ds)
try:
for path in (
f"/queries/{uuid.uuid4()}",
f"/queries/{foreign_q}",
f"/queries/{foreign_q}/versions",
f"/queries/{foreign_q}/references",
"/queries/not-a-uuid",
):
assert client.get(path).status_code == 404, path
assert client.patch(f"/queries/{foreign_q}", json={"description": "x"}).status_code == 404
assert client.post(f"/queries/{foreign_q}/disable").status_code == 404
assert client.post(
f"/queries/{foreign_q}/versions", json={"sql_template": "SELECT 1"}
).status_code == 404
assert client.post(f"/queries/{foreign_q}/versions/1/activate").status_code == 404
assert client.post(f"/queries/{foreign_q}/preview", json={"params": {}}).status_code == 404
assert foreign_q not in [i["id"] for i in client.get("/queries").json()["data"]["items"]]
finally:
_drop_foreign(foreign_ds)
# --- versions and activate -------------------------------------------------------------------
def test_create_has_v1_and_save_version_increments(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
listing0 = client.get(f"/queries/{qid}/versions").json()["data"]
assert [i["version_no"] for i in listing0["items"]] == [1]
v1 = client.get(f"/queries/{qid}/versions/1").json()["data"]
assert v1["version_no"] == 1 and v1["definition_id"] == qid
assert v1["published_by"] == "worker" and v1["sql_template"] == SQL
assert client.get(f"/queries/{qid}").json()["data"]["current_version_no"] == 1
second = client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 3,
},
)
assert second.status_code == 200, second.text
v2 = second.json()["data"]
assert v2["version_no"] == 2 and v2["sql_template"] == "SELECT 99 AS n"
assert client.get(f"/queries/{qid}/versions/1").json()["data"] == v1
detail = client.get(f"/queries/{qid}").json()["data"]
assert detail["current_version_no"] == 2 and detail["latest_version_no"] == 2
listing = client.get(f"/queries/{qid}/versions").json()["data"]
assert [i["version_no"] for i in listing["items"]] == [2, 1]
assert all("sql_template" not in i for i in listing["items"])
definition, versions = _db_rows(qid)
assert definition.current_version_no == 2 and definition.latest_published_version_no == 2
assert [v.version_no for v in versions] == [1, 2]
events = _audit(qid, "query.save_version")
assert [e.payload["version_no"] for e in events] == [2]
def test_activate_switches_current_without_new_version(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 3,
},
)
activated = client.post(f"/queries/{qid}/versions/1/activate")
assert activated.status_code == 200, activated.text
data = activated.json()["data"]
assert data["current_version_no"] == 1 and data["latest_version_no"] == 2
assert data["current"]["sql_template"] == SQL
_, versions = _db_rows(qid)
assert len(versions) == 2
events = _audit(qid, "query.activate_version")
assert len(events) == 1 and events[0].payload["version_no"] == 1
def test_disabled_query_can_still_save_version_and_version_reads_work(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(f"/queries/{qid}/disable")
saved = client.post(
f"/queries/{qid}/versions",
json={"sql_template": "SELECT 2", "param_schema": [], "output_schema": []},
)
assert saved.status_code == 200
assert client.get(f"/queries/{qid}/versions/2").status_code == 200
def test_save_version_refuses_blank_sql(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
response = client.post(
f"/queries/{qid}/versions",
json={"sql_template": " ", "param_schema": [], "output_schema": []},
)
assert response.status_code == 400
definition, versions = _db_rows(qid)
assert definition.latest_published_version_no == 1 and len(versions) == 1
def test_version_row_immutable_and_patch_refuses_version_fields(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
v1 = client.get(f"/queries/{qid}/versions/1").json()["data"]
for method in ("PATCH", "PUT", "DELETE"):
response = client.request(method, f"/queries/{qid}/versions/1", json={"sql_template": "x"})
assert response.status_code in (404, 405), method
for body in (
{"version_no": 1},
{"published_by": "mallory"},
{"published_at": "2020-01-01T00:00:00Z"},
{"latest_published_version_no": 1},
{"current_version_no": 1},
{"versions": [{"sql_template": "x"}]},
):
assert client.patch(f"/queries/{qid}", json=body).status_code == 400, body
assert client.get(f"/queries/{qid}/versions/1").json()["data"] == v1
_, versions = _db_rows(qid)
assert len(versions) == 1 and versions[0].sql_template == SQL
def test_version_lookup_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
assert client.get(f"/queries/{qid}/versions/2").status_code == 404
assert client.get(f"/queries/{qid}/versions/0").status_code == 404
assert client.get(f"/queries/{qid}/versions/abc").status_code == 400
assert client.post(f"/queries/{qid}/versions/2/preview", json={"params": {}}).status_code == 404
assert client.post(f"/queries/{qid}/versions/9/activate").status_code == 404
# --- preview ---------------------------------------------------------------------------------
def test_preview_outcomes_have_distinct_shapes(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
path = f"/queries/{qid}/preview"
fake_run["result"] = QueryRunResult(
status="success", message="query succeeded", columns=["n"], rows=[{"n": 1}, {"n": 2}]
)
ok = client.post(path, json={"params": {"flag": True}})
assert ok.status_code == 200 and ok.json()["success"] is True
data = ok.json()["data"]
assert data == {
"id": qid, "version_no": 1, "source": "current", "status": "success",
"message": "query succeeded", "columns": ["n"], "rows": [{"n": 1}, {"n": 2}],
"row_count": 2, "masked_columns": [],
} # fmt: skip
fake_run["result"] = QueryRunResult(status="empty", message="query returned no rows", columns=["n"])
empty = client.post(path, json={"params": {}}).json()["data"]
assert empty["status"] == "empty" and empty["rows"] == [] and empty["row_count"] == 0
assert "failure_kind" not in empty and "details" not in empty
fake_run["result"] = QueryRunResult(
status="illegal_type",
message="query result violates the output schema",
columns=["n"],
details={"fields": [{"field": "n", "expected": "integer", "actual": "str", "row": 0}]},
)
illegal = client.post(path, json={"params": {}}).json()["data"]
assert illegal["status"] == "illegal_type"
assert illegal["details"]["fields"][0]["expected"] == "integer"
assert "rows" not in illegal and "failure_kind" not in illegal
fake_run["result"] = failure("timeout", "query timed out", category="timeout")
failed = client.post(path, json={"params": {}})
assert failed.status_code == 200 # a failed run is a result, not an API error
failed_data = failed.json()["data"]
assert failed_data["status"] == "failure" and failed_data["failure_kind"] == "timeout"
assert "rows" not in failed_data and failed_data["details"] == {"category": "timeout"}
# The executor got the draft content and the bound datasource, never a tenant.
call = fake_run["calls"][0]
assert call["sql_template"] == SQL and call["params"] == {"flag": True}
assert call["timeout_ms"] == 5000 and call["max_rows"] == 50
assert call["param_schema"] == PARAM_SCHEMA and call["output_schema"] == OUTPUT_SCHEMA
assert "tenant_id" not in call
def test_preview_body_is_optional_and_strict(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
assert client.post(f"/queries/{qid}/preview").status_code == 200
assert fake_run["calls"][-1]["params"] == {}
for body in ({"sql": "DROP TABLE x"}, {"params": [1]}, {"params": {}, "datasource_id": "x"}):
assert client.post(f"/queries/{qid}/preview", json=body).status_code == 400, body
assert len(fake_run["calls"]) == 1
def test_preview_masks_sensitive_columns(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
fake_run["result"] = QueryRunResult(
status="success",
message="query succeeded",
columns=["user_name", "Password", "phone_no", "note"],
rows=[
{"user_name": "a", "Password": "hunter2", "phone_no": "13800000000", "note": None},
{"user_name": "b", "Password": None, "phone_no": "13900000000", "note": "x"},
],
)
data = client.post(f"/queries/{qid}/preview", json={"params": {}}).json()["data"]
assert data["masked_columns"] == ["Password", "phone_no"]
assert data["rows"][0] == {"user_name": "a", "Password": "***", "phone_no": "***", "note": None}
assert data["rows"][1] == {"user_name": "b", "Password": None, "phone_no": "***", "note": "x"}
assert "hunter2" not in json.dumps(data)
def test_preview_audit_has_only_id_version_and_status(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
fake_run["result"] = QueryRunResult(
status="success", message="secret-row-message", columns=["n"], rows=[{"n": "ROWVALUE-123"}]
)
assert client.post(f"/queries/{qid}/preview", json={"params": {"flag": True}}).status_code == 200
assert client.post(f"/queries/{qid}/versions/1/preview", json={"params": {}}).status_code == 200
fake_run["result"] = failure("sql_error", "query failed")
assert client.post(f"/queries/{qid}/preview", json={"params": {}}).status_code == 200
events = sorted(_audit(qid, "query.preview"), key=lambda e: e.id)
payloads = [e.payload for e in events]
assert len(payloads) == 3
assert payloads.count({"id": qid, "status": "success", "version_no": 1}) == 2
assert {"id": qid, "status": "failure", "version_no": 1} in payloads
for event in events:
assert set(event.payload) <= {"id", "status", "version_no"}
dumped = json.dumps(event.payload) + event.idempotency_key
assert "ROWVALUE" not in dumped and "secret-row-message" not in dumped
assert "SELECT" not in dumped and "flag" not in dumped
def test_preview_version_runs_frozen_content_not_current(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(
f"/queries/{qid}/versions",
json={
"sql_template": "SELECT 99 AS n",
"param_schema": [],
"output_schema": [],
"allowed_identifiers": [],
"timeout_ms": 5000,
"max_rows": 2,
},
)
fake_run["result"] = QueryRunResult(status="empty", message="query returned no rows")
response = client.post(f"/queries/{qid}/versions/1/preview", json={"params": {"flag": False}})
assert response.status_code == 200
data = response.json()["data"]
assert data["version_no"] == 1 and data["source"] == "version" and data["status"] == "empty"
call = fake_run["calls"][-1]
assert call["sql_template"] == SQL and call["max_rows"] == 50
assert call["params"] == {"flag": False}
client.post(f"/queries/{qid}/preview", json={"params": {}})
assert fake_run["calls"][-1]["sql_template"] == "SELECT 99 AS n"
assert fake_run["calls"][-1]["max_rows"] == 2
def test_disabled_definition_refuses_preview_without_running(cleanup, fake_run) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
client.post(f"/queries/{qid}/disable")
for path in (f"/queries/{qid}/preview", f"/queries/{qid}/versions/1/preview"):
response = client.post(path, json={"params": {}})
assert response.status_code == 409
error = response.json()["error"]
assert error["code"] == 40000 and error["details"]["reason"] == "disabled"
assert fake_run["calls"] == []
assert _audit(qid, "query.preview") == []
# Still readable, and previewable again once enabled.
assert client.get(f"/queries/{qid}").status_code == 200
client.post(f"/queries/{qid}/enable")
assert client.post(f"/queries/{qid}/preview", json={"params": {}}).status_code == 200
def test_preview_with_real_executor_without_network(cleanup, monkeypatch) -> None:
"""Validation failure and a disabled datasource come back as results, with no socket."""
def _boom(*_a, **_k):
raise AssertionError("network must not be used")
monkeypatch.setattr("socket.create_connection", _boom)
monkeypatch.setattr("watchman.queries.drivers.fetch_rows", _boom)
client = _client(cleanup, ADMIN)
created = _make(client)
qid = created["id"]
unknown = client.post(f"/queries/{qid}/preview", json={"params": {"nope": 1}})
assert unknown.status_code == 200
data = unknown.json()["data"]
assert data["status"] == "failure" and data["failure_kind"] == "validation"
assert data["details"]["reason"] == "unknown_param"
client.post(f"/datasources/{created['datasource_id']}/disable")
blocked = client.post(f"/queries/{qid}/preview", json={"params": {}})
assert blocked.status_code == 200
blocked_data = blocked.json()["data"]
assert blocked_data["status"] == "failure" and blocked_data["failure_kind"] == "disabled"
assert len(_audit(qid, "query.preview")) == 2
def test_preview_on_sqlserver_datasource_is_refused_without_a_connection(
cleanup, monkeypatch
) -> None:
"""SQL Server has no server-enforced read-only session: preview never reaches a driver."""
def _boom(*_a, **_k):
raise AssertionError("no connection may be opened for sqlserver")
monkeypatch.setattr("socket.create_connection", _boom)
monkeypatch.setattr("pymssql.connect", _boom)
monkeypatch.setattr("watchman.queries.drivers.fetch_rows", _boom)
client = _client(cleanup, ADMIN)
ds_id = _create(client, engine="sqlserver", port=1433)["id"]
qid = _make(client, ds_id, sql_template="SELECT 1 AS n WHERE :flag")["id"]
response = client.post(f"/queries/{qid}/preview", json={"params": {}})
assert response.status_code == 200
data = response.json()["data"]
assert data["status"] == "failure"
assert data["failure_kind"] == "engine_readonly_unsupported"
assert "rows" not in data or not data["rows"]
assert "SQL Server" in data["message"]
assert len(_audit(qid, "query.preview")) == 1
# --- references ------------------------------------------------------------------------------
def test_query_references_are_stably_empty(cleanup) -> None:
client = _client(cleanup, ADMIN)
qid = _make(client)["id"]
response = client.get(f"/queries/{qid}/references")
assert response.status_code == 200
assert response.json()["data"] == {"id": qid, "items": []}
def test_datasource_references_list_queries(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
other_ds = _create(client)["id"]
assert client.get(f"/datasources/{ds_id}/references").json()["data"] == {
"id": ds_id,
"items": [],
}
a = _make(client, ds_id, name=f"{NAME_PREFIX}ref-b")
b = _make(client, ds_id, name=f"{NAME_PREFIX}ref-a")
_make(client, other_ds)
data = client.get(f"/datasources/{ds_id}/references").json()["data"]
assert data["id"] == ds_id
assert data["items"] == [
{"type": "query", "id": b["id"], "name": b["name"], "enabled": True},
{"type": "query", "id": a["id"], "name": a["name"], "enabled": True},
]
client.post(f"/queries/{a['id']}/disable")
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert {i["id"]: i["enabled"] for i in items} == {a["id"]: False, b["id"]: True}
# Moving a query to another datasource moves the reference with it.
client.patch(f"/queries/{b['id']}", json={"datasource_id": other_ds})
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert [i["id"] for i in items] == [a["id"]]
assert b["id"] in [
i["id"] for i in client.get(f"/datasources/{other_ds}/references").json()["data"]["items"]
]
def test_datasource_references_ignore_other_tenants(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
foreign_ds = _foreign_datasource()
foreign_q = _foreign_query(foreign_ds)
try:
items = client.get(f"/datasources/{ds_id}/references").json()["data"]["items"]
assert foreign_q not in [i["id"] for i in items]
finally:
_drop_foreign(foreign_ds)
# --- foreign tenant helpers ------------------------------------------------------------------
def _foreign_datasource() -> uuid.UUID:
session = get_session_factory()()
try:
set_tenant(session, FOREIGN_TENANT)
row = DataSource(
tenant_id=FOREIGN_TENANT,
name=f"{NAME_PREFIX}foreign-ds",
kind="database",
engine="postgresql",
host="h.invalid",
port=5432,
database_name="d",
username="u",
secret_ciphertext="opaque",
)
session.add(row)
session.commit()
return row.id
finally:
session.close()
def _foreign_query(datasource_id: uuid.UUID) -> str:
session = get_session_factory()()
try:
set_tenant(session, FOREIGN_TENANT)
row = QueryDefinition(
tenant_id=FOREIGN_TENANT,
name=f"{NAME_PREFIX}foreign-q",
datasource_id=datasource_id,
draft_sql_template="SELECT 1",
)
session.add(row)
session.commit()
return str(row.id)
finally:
session.close()
def _drop_foreign(datasource_id: uuid.UUID) -> None:
session = get_session_factory()()
purge_query_rows(datasource_id=datasource_id) # versions are append-only for the app role
try:
set_tenant(session, FOREIGN_TENANT)
session.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": datasource_id})
session.commit()
finally:
session.close()
@@ -0,0 +1,964 @@
"""Read-only query executor tests (M04 S2): binding, whitelist, outcomes, circuit accounting.
Why: this is the only code that sends user SQL to a customer database, so injection
resistance, the usability gate and the empty/illegal_type/failure split need proof.
Boundary: template tests need no database; run_query tests use the platform Postgres for
datasource rows and replace the driver with fakes; the live tests run real statements against
WATCHMAN_TEST_PG_* and skip when it is not configured. Rows created here are removed by the
shared cleanup fixture from test_datasource_api (audit events are append-only and kept).
"""
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 NAME_PREFIX, cleanup, datasource_key # noqa: F401
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 NotFoundError, ValidationError
from watchman.datasources import ProbeCategory
from watchman.models.datasource import DataSource
from watchman.queries import drivers, run_query
from watchman.queries.drivers import ConnectFailure, FetchResult, QueryFailure
from watchman.queries.template import prepare_query
from watchman.services import datasources as service
PARAMS = [{"name": "object_id", "type": "string", "required": True}]
INJECTION = "x'; DROP TABLE data_sources; --"
# --- template preparation (no database) ---------------------------------------------------
def _prepare(sql: str, *, engine: str = "postgresql", schema=None, allowed=None, params=None):
return prepare_query(
engine=engine,
sql_template=sql,
param_schema=PARAMS if schema is None else schema,
allowed_identifiers=[] if allowed is None else allowed,
params={} if params is None else params,
)
def _reason(excinfo) -> str:
return excinfo.value.details["reason"]
def test_param_with_sql_fragment_is_bound_not_spliced() -> None:
prepared = _prepare(
"SELECT * FROM t WHERE id = :object_id", params={"object_id": INJECTION}
)
assert prepared.sql == "SELECT * FROM t WHERE id = %(object_id)s"
assert prepared.params == {"object_id": INJECTION}
assert "DROP" not in prepared.sql
def test_repeated_param_and_casts_and_literals() -> None:
prepared = _prepare(
"SELECT ':object_id' AS lit, x::int, :object_id AS a, :object_id AS b -- :object_id\n",
params={"object_id": "1"},
)
assert prepared.sql.count("%(object_id)s") == 2
assert "':object_id'" in prepared.sql and "x::int" in prepared.sql
assert prepared.params == {"object_id": "1"}
def test_percent_is_escaped_only_when_binding() -> None:
bound = _prepare("SELECT 'a%b' AS s, :object_id", params={"object_id": "1"})
assert "'a%%b'" in bound.sql
plain = _prepare("SELECT 'a%b' AS s", schema=[])
assert plain.sql == "SELECT 'a%b' AS s" and plain.params is None
def test_unknown_param_rejected() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :object_id", params={"object_id": "1", "extra": "2"})
assert _reason(exc) == "unknown_param"
assert exc.value.details["fields"] == ["extra"]
def test_missing_required_and_default_for_optional() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :object_id")
assert _reason(exc) == "missing_param"
schema = [
{"name": "n", "type": "integer", "required": False, "default": 7},
{"name": "m", "type": "integer", "required": False},
]
prepared = _prepare("SELECT :n, :m", schema=schema)
assert prepared.params == {"n": 7, "m": None}
@pytest.mark.parametrize(
("type_", "value"),
[
("integer", "1"),
("integer", True),
("number", "1.5"),
("boolean", 1),
("string", 5),
("datetime", "not-a-date"),
],
)
def test_param_type_mismatch_rejected(type_, value) -> None:
schema = [{"name": "v", "type": type_}]
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :v", schema=schema, params={"v": value})
assert _reason(exc) == "param_type_mismatch"
def test_datetime_string_is_parsed() -> None:
schema = [{"name": "v", "type": "datetime"}]
prepared = _prepare("SELECT :v", schema=schema, params={"v": "2030-01-02T03:04:05+00:00"})
assert prepared.params["v"] == datetime(2030, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
def test_undeclared_placeholder_rejected() -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT :nope", params={"object_id": "1"})
assert _reason(exc) == "undeclared_param"
@pytest.mark.parametrize(
"schema",
[
[{"name": "a", "type": "string", "bogus": 1}],
[{"name": "a", "type": "blob"}],
[{"name": "a", "type": "string"}, {"name": "a", "type": "string"}],
[{"name": "1bad", "type": "string"}],
[{"name": "a", "type": "integer", "default": "x"}],
{"name": "a"},
],
)
def test_bad_param_schema_rejected(schema) -> None:
with pytest.raises(ValidationError):
_prepare("SELECT 1", schema=schema)
def test_identifier_whitelist() -> None:
prepared = _prepare(
"SELECT * FROM {{orders}} WHERE id = :object_id",
allowed=["orders"],
params={"object_id": "1"},
)
assert prepared.sql == 'SELECT * FROM "orders" WHERE id = %(object_id)s'
mysql = _prepare("SELECT * FROM {{ orders }}", engine="mysql", schema=[], allowed=["orders"])
assert mysql.sql == "SELECT * FROM `orders`"
mssql = _prepare("SELECT * FROM {{orders}}", engine="sqlserver", schema=[], allowed=["orders"])
assert mssql.sql == "SELECT * FROM [orders]"
@pytest.mark.parametrize("allowed", [[], ["other"]])
def test_identifier_not_in_whitelist_rejected(allowed) -> None:
with pytest.raises(ValidationError) as exc:
_prepare("SELECT * FROM {{orders}}", schema=[], allowed=allowed)
assert _reason(exc) == "identifier_not_allowed"
@pytest.mark.parametrize("name", ["a-b", "a b", '"x"', "1a", "a;drop", "a.b", ""])
def test_identifier_must_match_pattern_even_if_listed(name) -> None:
with pytest.raises(ValidationError):
_prepare("SELECT * FROM {{" + name + "}}", schema=[], allowed=[name])
def test_identifier_in_literal_is_not_a_placeholder() -> None:
prepared = _prepare("SELECT '{{orders}}' AS s", schema=[])
assert prepared.sql == "SELECT '{{orders}}' AS s"
def test_param_value_can_never_become_an_identifier() -> None:
# A caller value containing the placeholder syntax stays a bound value.
prepared = _prepare("SELECT :object_id", params={"object_id": "{{orders}}"})
assert prepared.params == {"object_id": "{{orders}}"}
@pytest.mark.parametrize(
"sql",
[
"SELECT 1; DROP TABLE x",
"SELECT 1;; SELECT 2",
"SELECT 1; SELECT :object_id",
"SELECT 'unterminated",
"SELECT 1 /* open",
],
)
def test_non_single_or_broken_template_rejected(sql) -> None:
with pytest.raises(ValidationError):
_prepare(sql, params={"object_id": "1"})
def test_trailing_semicolon_and_comment_allowed() -> None:
assert _prepare("SELECT 1 ; -- done\n", schema=[]).sql == "SELECT 1 -- done"
def test_semicolon_inside_literal_is_fine() -> None:
assert _prepare("SELECT 'a;b'", schema=[]).sql == "SELECT 'a;b'"
def test_dollar_quote_hides_placeholders_on_postgres() -> None:
sql = "SELECT $$ :nope ; {{x}} $$ AS s"
assert _prepare(sql, schema=[]).sql == sql
# --- run_query with a fake driver ---------------------------------------------------------
def _session():
reload_settings()
session = get_session_factory()()
set_tenant(session, get_settings().tenant_id)
return session
def _make_datasource(session, **overrides) -> str:
row = service.create_datasource(
session,
name=f"{NAME_PREFIX}{uuid.uuid4().hex[:10]}",
description=None,
kind="database",
engine=overrides.pop("engine", "postgresql"),
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
password="synthetic-pw-not-a-credential",
read_only_intent=True,
)
for key, value in overrides.items():
setattr(row, key, value)
session.commit()
return str(row.id)
def _stored(datasource_id: str) -> DataSource:
session = _session()
try:
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(datasource_id)))
assert row is not None
return row
finally:
session.close()
class FakeFetch:
"""Replaces drivers.fetch_rows; records the call; returns or raises the queued outcome."""
def __init__(self, outcome) -> None:
self.outcome = outcome
self.calls: list[dict] = []
def __call__(self, target, sql, params, **kwargs):
self.calls.append({"target": target, "sql": sql, "params": params, **kwargs})
if isinstance(self.outcome, BaseException):
raise self.outcome
return self.outcome
def _install(monkeypatch, outcome) -> FakeFetch:
fake = FakeFetch(outcome)
monkeypatch.setattr(drivers, "fetch_rows", fake)
return fake
def _run(session, datasource_id: str, **overrides):
kwargs = dict(
datasource_id=datasource_id,
sql_template="SELECT object_id, v FROM t WHERE object_id = :object_id",
param_schema=PARAMS,
output_schema=[{"name": "object_id", "type": "string"}, {"name": "v", "type": "number"}],
allowed_identifiers=[],
params={"object_id": "A1"},
timeout_ms=5000,
max_rows=10,
)
kwargs.update(overrides)
return run_query(session, **kwargs)
ROWS = FetchResult(columns=["object_id", "v"], rows=[("A1", 1.5), ("A2", 2)])
def test_success_returns_json_serializable_rows(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
result = _run(session, ds)
assert result.status == "success" and result.failure_kind is None
assert result.columns == ["object_id", "v"]
assert result.rows == [{"object_id": "A1", "v": 1.5}, {"object_id": "A2", "v": 2}]
json.dumps(result.rows)
call = fake.calls[0]
assert call["sql"] == "SELECT object_id, v FROM t WHERE object_id = %(object_id)s"
assert call["params"] == {"object_id": "A1"}
assert call["limit"] == 11 and call["timeout_ms"] == 5000
# The decrypted password reaches the driver target only, never the result.
assert call["target"].password == "synthetic-pw-not-a-credential"
assert "synthetic-pw" not in repr(result)
session.close()
def test_sql_fragment_param_reaches_driver_only_as_a_bound_value(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(session, ds, params={"object_id": INJECTION})
call = fake.calls[0]
assert "DROP" not in call["sql"]
assert call["params"] == {"object_id": INJECTION}
session.close()
def test_empty_illegal_type_and_failure_are_distinct(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[]))
empty = _run(session, ds)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[("A1", "not-a-number")]))
illegal = _run(session, ds)
_install(monkeypatch, QueryFailure("sql_error", details={"sqlstate": "42601"}))
failed = _run(session, ds)
assert (empty.status, illegal.status, failed.status) == ("empty", "illegal_type", "failure")
assert empty.failure_kind is None and empty.rows == [] and empty.columns == ["object_id", "v"]
assert illegal.failure_kind is None and illegal.rows == []
assert illegal.details["fields"] == [
{"field": "v", "expected": "number", "actual": "str", "row": 0}
]
assert "not-a-number" not in json.dumps(illegal.details)
assert failed.failure_kind == "sql_error" and failed.rows == []
session.close()
def test_null_values_and_unlisted_columns_pass_type_check(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v", "extra"], rows=[("A1", None, {})]))
result = _run(session, ds)
assert result.status == "success"
assert result.rows == [{"object_id": "A1", "v": None, "extra": "{}"}]
session.close()
def test_row_limit_exceeded_is_a_failure_without_rows(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, FetchResult(columns=["object_id", "v"], rows=[("A", 1)] * 3))
result = _run(session, ds, max_rows=2)
assert result.status == "failure" and result.failure_kind == "limit_exceeded"
assert result.rows == [] and result.details == {"max_rows": 2}
session.close()
def test_limits_are_capped_and_invalid_limits_rejected(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(session, ds, timeout_ms=10**9, max_rows=10**9)
assert fake.calls[0]["timeout_ms"] == 300000 and fake.calls[0]["limit"] == 10001
for bad in (0, -1, True, "5"):
result = _run(session, ds, timeout_ms=bad)
assert result.failure_kind == "validation"
assert result.details["reason"] == "limit_invalid"
assert len(fake.calls) == 1
session.close()
def test_validation_failures_never_connect(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, AssertionError("must not connect"))
unknown = _run(session, ds, params={"object_id": "A1", "extra": 1})
not_listed = _run(
session, ds, sql_template="SELECT * FROM {{orders}}", param_schema=[], params={}
)
empty_list = _run(
session,
ds,
sql_template="SELECT * FROM {{orders}}",
param_schema=[],
params={},
allowed_identifiers=[],
)
missing = _run(session, ds, params={})
bad_output = _run(session, ds, output_schema=[{"name": "v", "type": "blob"}])
assert [r.failure_kind for r in (unknown, not_listed, empty_list, missing, bad_output)] == [
"validation"
] * 5
assert unknown.details["reason"] == "unknown_param"
assert not_listed.details["reason"] == "identifier_not_allowed"
assert empty_list.details["reason"] == "identifier_not_allowed"
assert missing.details["reason"] == "missing_param"
assert fake.calls == []
session.close()
def test_whitelisted_identifier_is_quoted_not_bound(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
fake = _install(monkeypatch, ROWS)
_run(
session,
ds,
sql_template="SELECT * FROM {{orders}} WHERE object_id = :object_id",
allowed_identifiers=["orders"],
)
assert fake.calls[0]["sql"] == 'SELECT * FROM "orders" WHERE object_id = %(object_id)s'
assert fake.calls[0]["params"] == {"object_id": "A1"}
session.close()
def test_disabled_datasource_is_refused_without_running_sql(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, enabled=False)
fake = _install(monkeypatch, AssertionError("must not connect"))
result = _run(session, ds)
assert result.status == "failure" and result.failure_kind == "disabled"
assert result.details["reason"] == "disabled"
assert fake.calls == []
session.close()
@pytest.mark.parametrize(
"sql",
[
"SELECT object_id, v FROM t WHERE object_id = :object_id",
"UPDATE t SET v = 0 WHERE object_id = :object_id",
"DELETE FROM t WHERE object_id = :object_id",
"EXEC sp_write_everything",
],
)
def test_sqlserver_run_is_refused_before_any_connection_or_secret_read(
monkeypatch, sql
) -> None:
"""SQL Server has no server-enforced read-only session, so no template ever runs on it.
The refusal does not depend on the statement text: a SELECT is refused exactly like a write.
"""
import pymssql
def _no_write_path(*_a, **_k):
raise AssertionError("sqlserver must not open a connection or read the secret")
session = _session()
ds = _make_datasource(session, engine="sqlserver")
fake = _install(monkeypatch, AssertionError("must not connect"))
monkeypatch.setattr(pymssql, "connect", _no_write_path)
monkeypatch.setattr(service, "build_probe_target", _no_write_path)
result = _run(session, ds, sql_template=sql)
assert result.status == "failure"
assert result.failure_kind == "engine_readonly_unsupported"
assert result.details["reason"] == "engine_readonly_unsupported"
assert "SQL Server" in result.message and "read-only" in result.message
assert result.rows == [] and result.columns == []
assert fake.calls == []
# Not a connectivity problem: the circuit stays untouched.
assert _stored(ds).circuit_failure_count == 0
session.close()
def test_sqlserver_fetch_rows_has_no_runner_and_opens_nothing(monkeypatch) -> None:
import pymssql
from watchman.datasources import UnsupportedDataSourceError
def _forbidden(*_a, **_k):
raise AssertionError("pymssql.connect must not be called")
monkeypatch.setattr(pymssql, "connect", _forbidden)
assert "sqlserver" not in drivers._RUNNERS
with pytest.raises(UnsupportedDataSourceError):
drivers.fetch_rows(
_target("sqlserver"), "UPDATE t SET v = 1", None, timeout_ms=1000, limit=2, connect_timeout=1
)
def test_open_circuit_is_refused_without_running_sql(monkeypatch) -> None:
session = _session()
ds = _make_datasource(
session,
circuit_state="open",
circuit_opened_at=datetime.now(timezone.utc) - timedelta(seconds=5),
)
fake = _install(monkeypatch, AssertionError("must not connect"))
result = _run(session, ds)
assert result.failure_kind == "circuit_open"
assert result.details["reason"] == "circuit_open"
assert "circuit_open_until" in result.details
assert fake.calls == []
session.close()
def test_elapsed_circuit_cooldown_lets_the_run_through(monkeypatch) -> None:
session = _session()
ds = _make_datasource(
session,
circuit_state="open",
circuit_opened_at=datetime.now(timezone.utc) - timedelta(hours=2),
)
fake = _install(monkeypatch, ROWS)
assert _run(session, ds).status == "success"
assert len(fake.calls) == 1
assert _stored(ds).circuit_state == "closed"
session.close()
def test_unknown_datasource_propagates_not_found(monkeypatch) -> None:
session = _session()
_install(monkeypatch, AssertionError("must not connect"))
with pytest.raises(NotFoundError):
_run(session, str(uuid.uuid4()))
session.close()
@pytest.mark.parametrize(
("category", "kind"),
[
(ProbeCategory.AUTH_FAILED, "auth_failed"),
(ProbeCategory.TIMEOUT, "timeout"),
(ProbeCategory.UNREACHABLE, "unreachable"),
(ProbeCategory.REJECTED, "rejected"),
],
)
def test_connection_failures_are_classified_and_recorded(monkeypatch, category, kind) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, ConnectFailure(category))
result = _run(session, ds)
assert result.status == "failure" and result.failure_kind == kind
assert result.details["category"] == category.value
stored = _stored(ds)
assert stored.circuit_failure_count == 1
assert stored.circuit_state == "closed"
# No saved-connection test ran, so last_test_* is untouched.
assert stored.last_test_category is None and stored.last_test_at is None
session.close()
def test_repeated_connection_failures_open_the_circuit_then_block(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, circuit_failure_threshold=2)
fake = _install(monkeypatch, ConnectFailure(ProbeCategory.UNREACHABLE))
first = _run(session, ds)
second = _run(session, ds)
third = _run(session, ds)
assert first.details["circuit_opened"] is False
assert second.details["circuit_opened"] is True
assert third.failure_kind == "circuit_open"
assert len(fake.calls) == 2 # the third never reached the driver
assert _stored(ds).circuit_state == "open"
session.close()
def test_sql_and_statement_timeout_failures_do_not_touch_the_circuit(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session, circuit_failure_threshold=1)
_install(monkeypatch, QueryFailure("sql_error", details={"sqlstate": "42601"}))
sql_error = _run(session, ds)
_install(monkeypatch, QueryFailure("timeout"))
timed_out = _run(session, ds)
assert sql_error.failure_kind == "sql_error"
assert timed_out.failure_kind == "timeout" and "category" not in timed_out.details
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_connection_lost_mid_query_counts_against_the_circuit(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(
monkeypatch, QueryFailure("unreachable", category=ProbeCategory.UNREACHABLE)
)
result = _run(session, ds)
assert result.failure_kind == "unreachable"
assert _stored(ds).circuit_failure_count == 1
session.close()
def test_result_never_contains_driver_text(monkeypatch) -> None:
session = _session()
ds = _make_datasource(session)
_install(monkeypatch, QueryFailure("sql_error"))
result = _run(session, ds)
blob = repr(result)
assert "synthetic_user" not in blob and "127.0.0.1" not in blob
session.close()
# --- driver classification with faked client libraries ------------------------------------
class _Boom(Exception):
pass
def test_mysql_connect_auth_error_maps_to_auth_failed(monkeypatch) -> None:
import pymysql
def connect(**_kwargs):
raise pymysql.err.OperationalError(1045, "Access denied for user 'x'@'h'")
monkeypatch.setattr(pymysql, "connect", connect)
target = _target("mysql")
with pytest.raises(ConnectFailure) as exc:
drivers.fetch_rows(target, "SELECT 1", None, timeout_ms=1000, limit=2, connect_timeout=1)
assert exc.value.category is ProbeCategory.AUTH_FAILED
assert "Access denied" not in str(exc.value)
def test_mysql_query_after_connect_is_read_only_and_maps_errors(monkeypatch) -> None:
import pymysql
executed: list[str] = []
class Cursor:
description = None
def __enter__(self):
return self
def __exit__(self, *_exc):
return False
def execute(self, sql, params=None):
executed.append(sql)
if sql.startswith("SELECT"):
raise pymysql.err.ProgrammingError(1064, "syntax near secret")
class Conn:
def cursor(self):
return Cursor()
def rollback(self):
pass
def close(self):
pass
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: Conn())
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "sql_error" and exc.value.category is None
assert executed[:2] == ["SET SESSION TRANSACTION READ ONLY", "START TRANSACTION READ ONLY"]
assert "secret" not in str(exc.value.details)
def test_mysql_lost_connection_is_connectivity_but_read_timeout_is_not(monkeypatch) -> None:
import pymysql
def make(error):
class Cursor:
description = None
def __enter__(self):
return self
def __exit__(self, *_exc):
return False
def execute(self, sql, params=None):
if sql.startswith("SELECT"):
raise error
class Conn:
def cursor(self):
return Cursor()
def rollback(self):
pass
def close(self):
pass
return Conn()
lost = pymysql.err.OperationalError(2006, "MySQL server has gone away")
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: make(lost))
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "unreachable" and exc.value.category is ProbeCategory.UNREACHABLE
slow = pymysql.err.OperationalError(2013, "Lost connection during query")
slow.__cause__ = TimeoutError("timed out")
monkeypatch.setattr(pymysql, "connect", lambda **_kwargs: make(slow))
with pytest.raises(QueryFailure) as exc:
drivers.fetch_rows(
_target("mysql"), "SELECT x", None, timeout_ms=1000, limit=2, connect_timeout=1
)
assert exc.value.kind == "timeout" and exc.value.category is None
def test_unsupported_engine_opens_nothing() -> None:
from watchman.datasources import UnsupportedDataSourceError
with pytest.raises(UnsupportedDataSourceError):
drivers.fetch_rows(
_target("oracle"), "SELECT 1", None, timeout_ms=1000, limit=2, connect_timeout=1
)
def _target(engine: str):
from watchman.datasources import ProbeTarget
return ProbeTarget(
engine=engine, host="127.0.0.1", port=1, database="d", username="u", password="p"
)
# --- live PostgreSQL ----------------------------------------------------------------------
@pytest.fixture()
def live():
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")
values = {k: env[f"WATCHMAN_TEST_PG_{k}"] for k in keys}
from watchman.datasources import ProbeTarget, probe_datasource
precheck = probe_datasource(
ProbeTarget(
engine="postgresql",
host=values["HOST"],
port=int(values["PORT"]),
database=values["DATABASE"],
username=values["USER"],
password=values["PASSWORD"],
)
)
if precheck.category is not ProbeCategory.SUCCESS:
pytest.skip(f"live postgres not available ({precheck.category.value})")
return values
def _live_datasource(session, live, **overrides) -> str:
row = service.create_datasource(
session,
name=f"{NAME_PREFIX}{uuid.uuid4().hex[:10]}",
description=None,
kind="database",
engine="postgresql",
host=overrides.pop("host", live["HOST"]),
port=overrides.pop("port", int(live["PORT"])),
database_name=live["DATABASE"],
username=live["USER"],
password=overrides.pop("password", live["PASSWORD"]),
read_only_intent=True,
)
for key, value in overrides.items():
setattr(row, key, value)
session.commit()
return str(row.id)
def _live_run(session, ds, sql, *, params=None, schema=None, output=None, **kw):
return run_query(
session,
datasource_id=ds,
sql_template=sql,
param_schema=schema or [],
output_schema=output or [],
allowed_identifiers=kw.pop("allowed", []),
params=params or {},
timeout_ms=kw.pop("timeout_ms", 5000),
max_rows=kw.pop("max_rows", 100),
)
def test_live_binding_neutralizes_injection_and_escapes_percent(live) -> None:
session = _session()
ds = _live_datasource(session, live)
schema = [{"name": "v", "type": "string"}]
echoed = _live_run(
session,
ds,
"SELECT 'a%b' AS lit, :v AS v, 7::int AS n",
params={"v": INJECTION},
schema=schema,
output=[{"name": "v", "type": "string"}, {"name": "n", "type": "integer"}],
)
assert echoed.status == "success"
assert echoed.rows == [{"lit": "a%b", "v": INJECTION, "n": 7}]
matched = _live_run(
session,
ds,
"SELECT 1 AS one FROM (VALUES ('a'), ('b')) AS t(name) WHERE name = :v",
params={"v": "' OR '1'='1"},
schema=schema,
)
assert matched.status == "empty" # an injected tautology matched nothing
session.close()
def test_live_typed_params_and_whitelisted_identifier(live) -> None:
session = _session()
ds = _live_datasource(session, live)
schema = [
{"name": "n", "type": "integer"},
{"name": "f", "type": "number"},
{"name": "b", "type": "boolean"},
{"name": "t", "type": "datetime"},
]
result = _live_run(
session,
ds,
"SELECT :n AS n, :f AS f, :b AS b, :t AS t",
params={"n": 3, "f": 1.5, "b": True, "t": "2030-01-02T03:04:05+00:00"},
schema=schema,
output=[
{"name": "n", "type": "integer"},
{"name": "f", "type": "number"},
{"name": "b", "type": "boolean"},
{"name": "t", "type": "datetime"},
],
)
assert result.status == "success", result
assert result.rows[0]["n"] == 3 and result.rows[0]["b"] is True
# The server renders in its session time zone; the instant itself must be unchanged.
assert datetime.fromisoformat(result.rows[0]["t"]) == datetime(
2030, 1, 2, 3, 4, 5, tzinfo=timezone.utc
)
ident = _live_run(
session,
ds,
"SELECT count(*) AS c FROM {{pg_class}}",
allowed=["pg_class"],
output=[{"name": "c", "type": "integer"}],
)
assert ident.status == "success"
session.close()
def test_live_empty_illegal_type_and_sql_error_are_distinct(live) -> None:
session = _session()
ds = _live_datasource(session, live, circuit_failure_threshold=1)
empty = _live_run(session, ds, "SELECT 1 AS n WHERE false")
illegal = _live_run(
session, ds, "SELECT 'x' AS n", output=[{"name": "n", "type": "integer"}]
)
syntax = _live_run(session, ds, "SELEC 1")
assert (empty.status, illegal.status, syntax.status) == ("empty", "illegal_type", "failure")
assert syntax.failure_kind == "sql_error" and syntax.details["sqlstate"] == "42601"
assert "SELEC" not in repr(syntax)
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_live_row_limit(live) -> None:
session = _session()
ds = _live_datasource(session, live)
sql = "SELECT g AS n FROM generate_series(1, 5) g"
output = [{"name": "n", "type": "integer"}]
exact = _live_run(session, ds, sql, output=output, max_rows=5)
over = _live_run(session, ds, sql, output=output, max_rows=4)
assert exact.status == "success" and len(exact.rows) == 5
assert over.failure_kind == "limit_exceeded" and over.rows == []
session.close()
def test_live_statement_timeout_is_not_a_connection_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, circuit_failure_threshold=1)
result = _live_run(session, ds, "SELECT pg_sleep(5)", timeout_ms=300)
assert result.failure_kind == "timeout"
stored = _stored(ds)
assert stored.circuit_failure_count == 0 and stored.circuit_state == "closed"
session.close()
def test_live_session_is_read_only(live) -> None:
session = _session()
ds = _live_datasource(session, live)
table = f"wm_ro_{uuid.uuid4().hex[:8]}"
created = _live_run(session, ds, f"CREATE TABLE {table} (i int)")
flag = _live_run(
session,
ds,
"SELECT current_setting('transaction_read_only') AS ro",
output=[{"name": "ro", "type": "string"}],
)
assert created.status == "failure"
assert flag.rows == [{"ro": "on"}]
exists = _live_run(
session, ds, f"SELECT to_regclass('{table}')::text AS r"
)
assert exists.rows == [{"r": None}]
session.close()
def test_live_wrong_password_records_auth_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, password="wrong-pw-not-a-credential")
result = _live_run(session, ds, "SELECT 1 AS n")
assert result.failure_kind == "auth_failed"
assert "wrong-pw" not in repr(result)
assert _stored(ds).circuit_failure_count == 1
session.close()
def test_live_unreachable_port_records_connection_failure(live) -> None:
session = _session()
ds = _live_datasource(session, live, host="127.0.0.1", port=1)
result = _live_run(session, ds, "SELECT 1 AS n")
assert result.failure_kind in ("unreachable", "timeout")
assert _stored(ds).circuit_failure_count == 1
session.close()
reset_engine()
@@ -0,0 +1,513 @@
"""Query definition/version constraints, RLS, and the version immutability helper.
The helper tests need no database; the persistence tests run against local Postgres like
test_datasource_rls.py and fail loudly if the migration was not applied.
"""
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 _privileged_cleanup import purge_query_rows
from watchman.core.config import get_settings, reload_settings
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
from watchman.core.errors import ValidationError
from watchman.models import DataSource, QueryDefinition, QueryVersion
from watchman.models.query import VERSION_CONTENT_COLUMNS
from watchman.services.query_versions import (
assert_version_immutable,
forbid_version_content_mutation,
)
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
# --- helper tests (no database) -------------------------------------------------------
@pytest.mark.parametrize("column", sorted(VERSION_CONTENT_COLUMNS))
def test_helper_rejects_each_content_column(column: str) -> None:
with pytest.raises(ValidationError) as exc:
forbid_version_content_mutation({column: "x"})
assert exc.value.http_status == 400
assert exc.value.details["reason"] == "version_immutable"
assert exc.value.details["fields"] == [column]
@pytest.mark.parametrize("column", ["version_no", "published_by", "published_at", "tenant_id"])
def test_helper_rejects_identity_and_audit_columns(column: str) -> None:
with pytest.raises(ValidationError):
forbid_version_content_mutation({column: "x"})
def test_helper_allows_empty_and_unrelated_changes() -> None:
forbid_version_content_mutation({})
forbid_version_content_mutation({"unrelated": 1})
def test_assert_version_immutable_leaves_instance_untouched() -> None:
version = QueryVersion(version_no=1, sql_template="SELECT 1", max_rows=10)
with pytest.raises(ValidationError):
assert_version_immutable(version, {"sql_template": "DROP TABLE x"})
assert version.sql_template == "SELECT 1"
assert assert_version_immutable(version, {}) is version
# --- persistence tests ----------------------------------------------------------------
@pytest.fixture()
def q_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)
datasource_ids: list[tuple[str, uuid.UUID]] = [] # (tenant_id, datasource id)
yield factory, datasource_ids, settings
cleanup = factory()
try:
for tenant, ds_id in datasource_ids:
# Versions are append-only for the app role: superuser purge of versions and
# definitions, then the datasource they reference (RESTRICT) as the app role.
purge_query_rows(datasource_id=ds_id)
set_tenant(cleanup, tenant)
cleanup.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": ds_id})
cleanup.commit()
finally:
cleanup.close()
engine.dispose()
reset_engine()
def _datasource(session: Session, tenant: str, registry: list) -> uuid.UUID: # type: ignore[type-arg]
row = DataSource(
tenant_id=tenant,
name=f"q-ds-{uuid.uuid4().hex[:12]}",
kind="database",
engine="postgresql",
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
secret_ciphertext=FAKE_CIPHERTEXT,
)
session.add(row)
session.commit()
registry.append((tenant, row.id))
return row.id
def _definition(tenant: str, datasource_id: uuid.UUID, **overrides) -> QueryDefinition: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant,
name=f"q-{uuid.uuid4().hex[:12]}",
datasource_id=datasource_id,
draft_sql_template="SELECT 1",
)
values.update(overrides)
return QueryDefinition(**values)
def _version(tenant: str, definition_id: uuid.UUID, version_no: int = 1, **overrides) -> QueryVersion: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant,
definition_id=definition_id,
version_no=version_no,
sql_template="SELECT 1",
param_schema=[],
output_schema=[],
allowed_identifiers=[],
timeout_ms=10000,
max_rows=100,
)
values.update(overrides)
return QueryVersion(**values)
def test_tables_force_rls_and_not_owned_by_app_role() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
for table in ("query_definitions", "query_versions"):
owner = conn.execute(
text(
"SELECT tableowner FROM pg_tables "
"WHERE schemaname = 'public' AND tablename = :t"
),
{"t": table},
).scalar_one()
flags = conn.execute(
text(
"SELECT relrowsecurity, relforcerowsecurity FROM pg_class "
"WHERE relname = :t"
),
{"t": table},
).one()
assert owner != "watchman_app"
assert flags.relrowsecurity is True
assert flags.relforcerowsecurity is True
engine.dispose()
def test_insert_definition_and_version_with_defaults(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id))
session.commit()
stored = session.execute(
text(
"SELECT enabled, draft_param_schema, draft_output_schema, "
"draft_allowed_identifiers, draft_timeout_ms, draft_max_rows, "
"latest_published_version_no, current_version_no, "
"created_at IS NOT NULL AS has_created "
"FROM query_definitions WHERE id = :i"
),
{"i": definition.id},
).one()
assert stored.enabled is True
assert stored.draft_param_schema == []
assert stored.draft_output_schema == []
assert stored.draft_allowed_identifiers == []
assert stored.draft_timeout_ms == 10000
assert stored.draft_max_rows == 100
assert stored.latest_published_version_no is None
assert stored.current_version_no is None
assert stored.has_created is True
published = session.execute(
text(
"SELECT published_at IS NOT NULL AS ok, published_by "
"FROM query_versions WHERE definition_id = :i"
),
{"i": definition.id},
).one()
assert published.ok is True
assert published.published_by is None
finally:
session.close()
def test_other_tenant_cannot_see_definition_or_version(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id))
session.commit()
def_id = definition.id
finally:
session.close()
for tenant in ("other-tenant", None):
other: Session = factory()
try:
if tenant:
set_tenant(other, tenant)
assert other.execute(
text("SELECT count(*) FROM query_definitions WHERE id = :i"), {"i": def_id}
).scalar() == 0
assert other.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :i"),
{"i": def_id},
).scalar() == 0
finally:
other.close()
same: Session = factory()
try:
set_tenant(same, settings.tenant_id)
assert same.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :i"), {"i": def_id}
).scalar() == 1
finally:
same.close()
def test_write_for_foreign_tenant_is_rejected(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition("other-tenant", ds_id))
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
finally:
session.close()
def test_duplicate_definition_name_and_version_no_rejected(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id, name="dup-name")
session.add(definition)
session.commit()
session.add(_definition(settings.tenant_id, ds_id, name="dup-name"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
session.add(_version(settings.tenant_id, definition.id, 1))
session.commit()
session.add(_version(settings.tenant_id, definition.id, 1))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[
{"draft_timeout_ms": 0},
{"draft_timeout_ms": 300001},
{"draft_max_rows": 0},
{"draft_max_rows": 10001},
{"latest_published_version_no": 0},
],
)
def test_definition_check_constraints(q_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition(settings.tenant_id, ds_id, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[{"timeout_ms": 0}, {"timeout_ms": 300001}, {"max_rows": 0}, {"max_rows": 10001}],
)
def test_version_numeric_checks_and_version_no(q_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
session.add(_version(settings.tenant_id, definition.id, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
session.add(_version(settings.tenant_id, definition.id, version_no=0))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
def test_datasource_delete_restricted_while_definition_exists(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
session.add(_definition(settings.tenant_id, ds_id))
session.commit()
with pytest.raises(IntegrityError):
session.execute(text("DELETE FROM data_sources WHERE id = :d"), {"d": ds_id})
session.rollback()
finally:
session.close()
def test_helper_blocks_update_of_persisted_version(q_factory) -> None: # type: ignore[no-untyped-def]
"""The helper rejects the change, so the stored row keeps its published content."""
factory, registry, settings = q_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
version = _version(settings.tenant_id, definition.id, sql_template="SELECT 42")
session.add(version)
session.commit()
with pytest.raises(ValidationError):
assert_version_immutable(version, {"sql_template": "SELECT 43", "max_rows": 5})
stored = session.execute(
text("SELECT sql_template, max_rows FROM query_versions WHERE id = :i"),
{"i": version.id},
).one()
assert stored.sql_template == "SELECT 42"
assert stored.max_rows == 100
finally:
session.close()
# --- database-enforced immutability (migration 0007) ---------------------------------------
def _published_version(session: Session, settings, registry) -> tuple[uuid.UUID, uuid.UUID]: # type: ignore[no-untyped-def]
set_tenant(session, settings.tenant_id)
ds_id = _datasource(session, settings.tenant_id, registry)
definition = _definition(settings.tenant_id, ds_id)
session.add(definition)
session.commit()
version = _version(settings.tenant_id, definition.id, sql_template="SELECT 42")
session.add(version)
session.commit()
return definition.id, version.id
def _stored_sql(factory, settings, version_id: uuid.UUID) -> str: # type: ignore[no-untyped-def]
check: Session = factory()
try:
set_tenant(check, settings.tenant_id)
return check.execute(
text("SELECT sql_template FROM query_versions WHERE id = :i"), {"i": version_id}
).scalar_one()
finally:
check.close()
def test_app_role_privileges_on_query_versions_are_append_only() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
granted = {
privilege: conn.execute(
text("SELECT has_table_privilege('watchman_app', 'query_versions', :p)"),
{"p": privilege},
).scalar_one()
for privilege in ("SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE")
}
engine.dispose()
assert granted == {
"SELECT": True,
"INSERT": True,
"UPDATE": False,
"DELETE": False,
"TRUNCATE": False,
}
def test_insert_new_version_still_works_under_app_role(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
definition_id, _ = _published_version(session, settings, registry)
session.add(_version(settings.tenant_id, definition_id, version_no=2, sql_template="SELECT 2"))
session.commit()
count = session.execute(
text("SELECT count(*) FROM query_versions WHERE definition_id = :d"),
{"d": definition_id},
).scalar_one()
assert count == 2
finally:
session.close()
def test_app_role_core_update_and_delete_of_version_fail_in_database(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
with pytest.raises(DBAPIError) as update_exc:
session.execute(
text("UPDATE query_versions SET sql_template = 'DROP TABLE x' WHERE id = :i"),
{"i": version_id},
)
assert getattr(update_exc.value.orig, "sqlstate", None) == "42501" # insufficient_privilege
session.rollback()
with pytest.raises(DBAPIError) as delete_exc:
session.execute(text("DELETE FROM query_versions WHERE id = :i"), {"i": version_id})
assert getattr(delete_exc.value.orig, "sqlstate", None) == "42501"
session.rollback()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"
finally:
session.close()
def test_app_role_orm_update_and_delete_of_version_fail_in_database(q_factory) -> None: # type: ignore[no-untyped-def]
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
version = session.get(QueryVersion, version_id)
assert version is not None
version.sql_template = "DROP TABLE x"
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
version = session.get(QueryVersion, version_id)
assert version is not None
session.delete(version)
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"
finally:
session.close()
def test_trigger_rejects_update_delete_even_for_table_owner(q_factory) -> None: # type: ignore[no-untyped-def]
"""The owner (migrator) holds every privilege, so only the trigger can stop it.
The statement-level trigger fires even though forced RLS shows the owner zero rows.
"""
factory, registry, settings = q_factory
session: Session = factory()
try:
_, version_id = _published_version(session, settings, registry)
finally:
session.close()
owner_engine = create_engine(settings.database_migrator_url, pool_pre_ping=True)
try:
for statement in (
"UPDATE query_versions SET sql_template = 'x' WHERE id = :i",
"DELETE FROM query_versions WHERE id = :i",
"UPDATE query_versions SET max_rows = max_rows",
"DELETE FROM query_versions",
"TRUNCATE query_versions",
):
with owner_engine.connect() as conn:
with pytest.raises(DBAPIError) as exc:
conn.execute(text(statement), {"i": version_id} if ":i" in statement else {})
assert getattr(exc.value.orig, "sqlstate", None) == "23001" # restrict_violation
assert "append-only" in str(exc.value.orig)
conn.rollback()
finally:
owner_engine.dispose()
assert _stored_sql(factory, settings, version_id) == "SELECT 42"