chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1 @@
|
||||
"""LogStore extension unit tests."""
|
||||
Whitespace-only changes.
+410
@@ -0,0 +1,410 @@
|
||||
import datetime
|
||||
import sqlite3
|
||||
import time
|
||||
from collections.abc import Generator
|
||||
from contextlib import closing
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from aliyun.log import GetLogsRequest, GetLogsResponse
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
from extensions.logstore.aliyun_logstore_pg import AliyunLogStorePG
|
||||
from extensions.logstore.repositories.logstore_api_workflow_node_execution_repository import (
|
||||
LogstoreAPIWorkflowNodeExecutionRepository,
|
||||
_dict_to_workflow_node_execution_model,
|
||||
)
|
||||
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def logstore_database() -> Generator[sqlite3.Connection]:
|
||||
with closing(sqlite3.connect(":memory:")) as database:
|
||||
database.row_factory = sqlite3.Row
|
||||
database.execute(
|
||||
"CREATE TABLE workflow_node_execution ("
|
||||
"id TEXT, node_execution_id TEXT, tenant_id TEXT, app_id TEXT, workflow_id TEXT, "
|
||||
"workflow_run_id TEXT, triggered_from_workflow_id TEXT, triggered_from_node_execution_id TEXT, "
|
||||
'triggered_from TEXT, node_id TEXT, node_type TEXT, title TEXT, "index" INTEGER, '
|
||||
"status TEXT, elapsed_time REAL, created_at INTEGER, finished_at INTEGER, execution_metadata TEXT, "
|
||||
"log_version INTEGER, __time__ INTEGER, inputs TEXT, process_data TEXT, outputs TEXT)"
|
||||
)
|
||||
yield database
|
||||
|
||||
|
||||
@pytest.fixture(params=["pg", "sdk"])
|
||||
def sql_repository(
|
||||
request: pytest.FixtureRequest,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
mocker: MockerFixture,
|
||||
logstore_database: sqlite3.Connection,
|
||||
):
|
||||
"""Exercise the real protocol adapter while executing its SQL against local records."""
|
||||
monkeypatch.setattr(AliyunLogStore, "_instance", None)
|
||||
monkeypatch.setattr(AliyunLogStore, "_initialized", False)
|
||||
monkeypatch.setenv("ALIYUN_SLS_ENDPOINT", "localhost")
|
||||
mocker.patch.object(AliyunLogStore, "_check_endpoint_connectivity")
|
||||
store = AliyunLogStore()
|
||||
store._use_pg_protocol = request.param == "pg"
|
||||
store._pg_client = AliyunLogStorePG("key", "secret", "localhost", "test")
|
||||
store.project_name = "test"
|
||||
store.log_enabled = False
|
||||
|
||||
def execute(sql: str, *_args: object) -> list[dict[str, object]]:
|
||||
return [dict(row) for row in logstore_database.execute(sql)]
|
||||
|
||||
def get_logs(log_request: GetLogsRequest):
|
||||
search, separator, sql = log_request.get_query().partition(" | ")
|
||||
assert separator
|
||||
assert search
|
||||
assert log_request.get_from() == 0
|
||||
assert log_request.get_to() <= int(time.time())
|
||||
return GetLogsResponse({"meta": {"progress": "Complete"}, "data": execute(sql)}, {})
|
||||
|
||||
mocker.patch.object(store._pg_client, "execute_sql", side_effect=execute)
|
||||
mocker.patch.object(store.client, "get_logs", side_effect=get_logs)
|
||||
repository = LogstoreAPIWorkflowNodeExecutionRepository(session_maker=None)
|
||||
return repository, logstore_database
|
||||
|
||||
|
||||
def test_sql_history_excludes_recursive_tool_executions_and_retains_legacy_rows(sql_repository) -> None:
|
||||
repository, database = sql_repository
|
||||
rows = [
|
||||
{
|
||||
"id": execution_id,
|
||||
"tenant_id": "tenant",
|
||||
"app_id": "app",
|
||||
"workflow_id": "workflow",
|
||||
"workflow_run_id": "run",
|
||||
"node_id": "same-node",
|
||||
"triggered_from": origin.value if origin is not None else None,
|
||||
"status": "succeeded",
|
||||
"index": index,
|
||||
"created_at": index,
|
||||
"log_version": 1,
|
||||
"__time__": 1,
|
||||
}
|
||||
for execution_id, index, origin in (
|
||||
("root", 1, WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN),
|
||||
("legacy", 2, None),
|
||||
("child", 3, WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL),
|
||||
)
|
||||
]
|
||||
insert = (
|
||||
"INSERT INTO workflow_node_execution (id, tenant_id, app_id, workflow_id, workflow_run_id, "
|
||||
'node_id, triggered_from, status, "index", created_at, log_version, __time__) VALUES '
|
||||
"(:id, :tenant_id, :app_id, :workflow_id, :workflow_run_id, :node_id, :triggered_from, :status, "
|
||||
":index, :created_at, :log_version, :__time__)"
|
||||
)
|
||||
database.executemany(insert, rows)
|
||||
history = repository.get_executions_by_workflow_run(tenant_id="tenant", app_id="app", workflow_run_id="run")
|
||||
# A newer paused/hidden version must not expose the earlier visible version.
|
||||
rows = [
|
||||
{**rows[0], "id": "paused", "created_at": 10, "status": "running"},
|
||||
{**rows[0], "id": "paused", "created_at": 10, "status": "paused", "log_version": 2},
|
||||
{**rows[0], "id": "hidden", "created_at": 11},
|
||||
{**rows[2], "id": "hidden", "created_at": 11, "log_version": 2},
|
||||
{**rows[1], "id": "null-status", "created_at": 0, "status": None},
|
||||
*[
|
||||
{**rows[0], "id": f"other-{field}", field: "other", "created_at": 99}
|
||||
for field in ("tenant_id", "app_id", "workflow_id", "node_id")
|
||||
],
|
||||
]
|
||||
database.executemany(insert, rows)
|
||||
latest = repository.get_node_last_execution(
|
||||
tenant_id="tenant", app_id="app", workflow_id="workflow", node_id="same-node"
|
||||
)
|
||||
|
||||
assert [execution.id for execution in history] == ["legacy", "root"]
|
||||
assert latest is not None
|
||||
assert latest.id == "legacy"
|
||||
assert repository.get_node_last_execution("tenant", "app", "workflow", "unknown") is None
|
||||
database.execute("DELETE FROM workflow_node_execution WHERE id IN ('legacy', 'root')")
|
||||
assert repository.get_node_last_execution("tenant", "app", "workflow", "same-node").id == "null-status"
|
||||
|
||||
|
||||
def test_sdk_history_searches_use_owner_scope() -> None:
|
||||
with patch("extensions.logstore.repositories.logstore_api_workflow_node_execution_repository.AliyunLogStore"):
|
||||
repository = LogstoreAPIWorkflowNodeExecutionRepository(session_maker=None)
|
||||
repository.logstore_client = MagicMock(supports_pg_protocol=False)
|
||||
repository.logstore_client.execute_sql.return_value = []
|
||||
|
||||
repository.get_executions_by_workflow_run(tenant_id="tenant", app_id="app", workflow_run_id="run")
|
||||
repository.get_node_last_execution(tenant_id="tenant", app_id="app", workflow_id="workflow", node_id="same-node")
|
||||
|
||||
history_query, latest_query = [call.kwargs for call in repository.logstore_client.execute_sql.call_args_list]
|
||||
assert latest_query["query"] == (
|
||||
'tenant_id: "tenant" and app_id: "app" and workflow_id: "workflow" and node_id: "same-node"'
|
||||
)
|
||||
assert history_query["query"] == 'tenant_id: "tenant" and app_id: "app" and workflow_run_id: "run"'
|
||||
|
||||
|
||||
def test_resumption_snapshots_read_latest_nodes_with_full_owner_scope(logstore_database: sqlite3.Connection) -> None:
|
||||
with patch("extensions.logstore.repositories.logstore_api_workflow_node_execution_repository.AliyunLogStore"):
|
||||
repository = LogstoreAPIWorkflowNodeExecutionRepository(session_maker=None)
|
||||
database = logstore_database
|
||||
database.row_factory = sqlite3.Row
|
||||
base = {
|
||||
"id": "row-id",
|
||||
"node_execution_id": "engine-id",
|
||||
"tenant_id": "tenant",
|
||||
"app_id": "app",
|
||||
"workflow_id": "workflow",
|
||||
"workflow_run_id": "run",
|
||||
"triggered_from": "workflow-run",
|
||||
"node_id": "tool",
|
||||
"node_type": "tool",
|
||||
"title": "Approval",
|
||||
"index": 2,
|
||||
"status": "paused",
|
||||
"elapsed_time": 3.5,
|
||||
"created_at": 100,
|
||||
"finished_at": 104,
|
||||
"execution_metadata": '{"iteration_id":"iteration"}',
|
||||
"log_version": 2,
|
||||
"__time__": 1,
|
||||
"inputs": '{"private":"input"}',
|
||||
"process_data": '{"private":"trace"}',
|
||||
"outputs": '{"private":"output"}',
|
||||
}
|
||||
rows = [base, {**base, "log_version": 1, "status": "running"}]
|
||||
rows.extend(
|
||||
{**base, "id": f"page-{index}", "index": index, "execution_metadata": "[]", "elapsed_time": None}
|
||||
for index in range(3, 1003)
|
||||
)
|
||||
for field in ("tenant_id", "app_id", "workflow_id", "workflow_run_id", "triggered_from"):
|
||||
rows.append({**base, "id": f"other-{field}", field: "other", "index": 99})
|
||||
database.executemany(
|
||||
'INSERT INTO workflow_node_execution ("'
|
||||
+ '", "'.join(base)
|
||||
+ '") VALUES ('
|
||||
+ ", ".join(f":{key}" for key in base)
|
||||
+ ")",
|
||||
rows,
|
||||
)
|
||||
|
||||
def execute_query(*, sql: str, **_kwargs: object) -> list[dict[str, object]]:
|
||||
result = [dict(row) for row in database.execute(sql)]
|
||||
assert all(row.keys().isdisjoint({"inputs", "process_data", "outputs"}) for row in result)
|
||||
return result
|
||||
|
||||
repository.logstore_client.execute_sql.side_effect = execute_query
|
||||
snapshots = repository.get_execution_snapshots_by_workflow_run(
|
||||
tenant_id="tenant",
|
||||
app_id="app",
|
||||
workflow_id="workflow",
|
||||
triggered_from="workflow-run",
|
||||
workflow_run_id="run",
|
||||
)
|
||||
assert len(snapshots) == 1001
|
||||
snapshot = snapshots[0]
|
||||
assert (snapshot.execution_id, snapshot.title, snapshot.index, snapshot.status) == (
|
||||
"engine-id",
|
||||
"Approval",
|
||||
2,
|
||||
"paused",
|
||||
)
|
||||
assert snapshot.iteration_id == "iteration"
|
||||
assert snapshot.elapsed_time == 3.5
|
||||
assert snapshot.created_at == datetime.datetime(1970, 1, 1, 0, 1, 40)
|
||||
assert snapshots[-1].index == 1002
|
||||
assert snapshots[-1].iteration_id is None
|
||||
assert snapshots[-1].elapsed_time == 4
|
||||
assert repository.logstore_client.execute_sql.call_count == 2
|
||||
query = repository.logstore_client.execute_sql.call_args.kwargs
|
||||
assert (
|
||||
query["query"] == 'tenant_id: "tenant" and app_id: "app" and workflow_run_id: "run" and workflow_id: "workflow"'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requested_id", ["parent-row", "parent-engine"])
|
||||
def test_workflow_tool_children_only_fetch_matching_latest_payloads(
|
||||
requested_id: str, sql_repository, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
repository, database = sql_repository
|
||||
rows = [
|
||||
{
|
||||
"id": "parent-row",
|
||||
"node_execution_id": "parent-engine",
|
||||
"workflow_id": "caller-workflow",
|
||||
"node_type": "tool",
|
||||
"log_version": 1,
|
||||
"created_at": 0,
|
||||
},
|
||||
*[
|
||||
{
|
||||
"id": "child",
|
||||
"node_type": "human-input",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
"log_version": version,
|
||||
"status": status,
|
||||
"created_at": 1,
|
||||
"index": 2,
|
||||
"outputs": '{"answer":"approved"}',
|
||||
}
|
||||
for version, status in ((1, "running"), (2, "paused"))
|
||||
],
|
||||
{
|
||||
"id": "other-call",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_node_execution_id": "other-engine",
|
||||
"created_at": 2,
|
||||
},
|
||||
{
|
||||
"id": "earlier-child",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
"created_at": 1,
|
||||
"index": 1,
|
||||
},
|
||||
{
|
||||
"id": "wrong-origin",
|
||||
"triggered_from": "workflow-run",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
},
|
||||
{
|
||||
"id": "other-tenant",
|
||||
"tenant_id": "other-tenant",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
},
|
||||
{
|
||||
"id": "other-run",
|
||||
"workflow_run_id": "other-run",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
},
|
||||
{
|
||||
"id": "other-caller",
|
||||
"triggered_from": "workflow-tool",
|
||||
"triggered_from_workflow_id": "other-workflow",
|
||||
"triggered_from_node_execution_id": "parent-engine",
|
||||
},
|
||||
*[{"id": f"unrelated-{index}"} for index in range(1001)],
|
||||
]
|
||||
defaults = {
|
||||
"id": "",
|
||||
"tenant_id": "tenant",
|
||||
"app_id": "source-app",
|
||||
"workflow_run_id": "run",
|
||||
"node_execution_id": None,
|
||||
"workflow_id": "source-workflow",
|
||||
"triggered_from_workflow_id": "caller-workflow",
|
||||
"triggered_from_node_execution_id": None,
|
||||
"node_type": "start",
|
||||
"triggered_from": "workflow-run",
|
||||
"process_data": None,
|
||||
"outputs": None,
|
||||
"status": "succeeded",
|
||||
"index": 0,
|
||||
"created_at": 0,
|
||||
"log_version": 1,
|
||||
"__time__": 1,
|
||||
}
|
||||
rows = [{**defaults, **row} for row in rows]
|
||||
fetched_payload_ids: list[str] = []
|
||||
database.executemany(
|
||||
"INSERT INTO workflow_node_execution (id, tenant_id, app_id, workflow_run_id, node_execution_id, "
|
||||
"workflow_id, triggered_from_workflow_id, triggered_from_node_execution_id, node_type, triggered_from, "
|
||||
'process_data, outputs, status, "index", created_at, log_version, __time__) VALUES '
|
||||
"(:id, :tenant_id, :app_id, :workflow_run_id, :node_execution_id, :workflow_id, "
|
||||
":triggered_from_workflow_id, :triggered_from_node_execution_id, :node_type, :triggered_from, "
|
||||
":process_data, :outputs, :status, :index, :created_at, :log_version, :__time__)",
|
||||
rows,
|
||||
)
|
||||
|
||||
execute_sql = repository.logstore_client.execute_sql
|
||||
|
||||
def execute_query(*, sql: str, **kwargs: object) -> list[dict[str, object]]:
|
||||
result = execute_sql(sql=sql, **kwargs)
|
||||
fetched_payload_ids.extend(str(row["id"]) for row in result if "outputs" in row)
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(repository.logstore_client, "execute_sql", execute_query)
|
||||
children = repository.get_workflow_tool_executions("tenant", "run", requested_id)
|
||||
assert repository.get_workflow_tool_executions("tenant", "run", "unknown") == []
|
||||
assert repository.get_workflow_tool_executions("tenant", "run", "child") == []
|
||||
|
||||
assert [child.id for child in children] == ["earlier-child", "child"]
|
||||
assert children[1].status.value == "paused"
|
||||
assert children[1].outputs_dict == {"answer": "approved"}
|
||||
assert fetched_payload_ids == ["earlier-child", "child"]
|
||||
|
||||
|
||||
def test_load_full_process_data_returns_logstore_mapping() -> None:
|
||||
with patch("extensions.logstore.repositories.logstore_api_workflow_node_execution_repository.AliyunLogStore"):
|
||||
repository = LogstoreAPIWorkflowNodeExecutionRepository(session_maker=None)
|
||||
execution = WorkflowNodeExecutionModel()
|
||||
execution.process_data = '{"__dify_retry_history": [{"retry_index": 1}]}'
|
||||
|
||||
assert repository.load_full_process_data(execution) == {"__dify_retry_history": [{"retry_index": 1}]}
|
||||
|
||||
|
||||
def test_get_execution_by_id_keeps_process_data_from_highest_failed_log_version(sql_repository) -> None:
|
||||
repository, database = sql_repository
|
||||
execution_id, tenant_id = "execution'1", 'tenant"1'
|
||||
database.executemany(
|
||||
"INSERT INTO workflow_node_execution (id, tenant_id, log_version, status, process_data, __time__) "
|
||||
"VALUES (?, ?, ?, ?, ?, 1)",
|
||||
[
|
||||
(execution_id, tenant_id, 1, "running", "{}"),
|
||||
(execution_id, tenant_id, 2, "failed", '{"workflow_agent_binding_id":"binding-1"}'),
|
||||
("other-execution", "other-tenant", 3, "succeeded", "{}"),
|
||||
],
|
||||
)
|
||||
execution = repository.get_execution_by_id(execution_id, tenant_id)
|
||||
|
||||
assert execution is not None
|
||||
assert execution.status.value == "failed"
|
||||
assert execution.process_data_dict == {"workflow_agent_binding_id": "binding-1"}
|
||||
if not repository.logstore_client.supports_pg_protocol:
|
||||
sdk_query = repository.logstore_client.client.get_logs.call_args.args[0].get_query()
|
||||
assert sdk_query.startswith('id: "execution\'1" and tenant_id: "tenant\\"1" | ')
|
||||
assert repository.get_execution_by_id(execution_id).id == execution_id
|
||||
assert repository.get_execution_by_id(execution_id, "other-tenant") is None
|
||||
assert repository.get_execution_by_id("unknown") is None
|
||||
assert repository.get_execution_by_id("execution' OR '1'='1") is None
|
||||
|
||||
|
||||
_CREATED_AT = datetime.datetime(2026, 8, 18, 2, 0, 0, tzinfo=datetime.UTC)
|
||||
_FINISHED_AT = _CREATED_AT + datetime.timedelta(seconds=30)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def non_utc_host_timezone(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
|
||||
"""Run the host clock in UTC+05:30 so local-time conversions become observable."""
|
||||
monkeypatch.setenv("TZ", "Asia/Kolkata")
|
||||
time.tzset()
|
||||
yield
|
||||
monkeypatch.undo()
|
||||
time.tzset()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("case", "payload"),
|
||||
[
|
||||
("both epoch", {"created_at": _CREATED_AT.timestamp(), "finished_at": _FINISHED_AT.timestamp()}),
|
||||
("aware iso and epoch", {"created_at": _CREATED_AT.isoformat(), "finished_at": _FINISHED_AT.timestamp()}),
|
||||
(
|
||||
"naive iso and epoch",
|
||||
{"created_at": _CREATED_AT.replace(tzinfo=None).isoformat(), "finished_at": _FINISHED_AT.timestamp()},
|
||||
),
|
||||
("both datetime", {"created_at": _CREATED_AT, "finished_at": _FINISHED_AT}),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("non_utc_host_timezone")
|
||||
def test_dict_to_node_execution_normalizes_timestamps_to_naive_utc(case: str, payload: dict[str, object]) -> None:
|
||||
model = _dict_to_workflow_node_execution_model({"id": "execution-1", **payload})
|
||||
|
||||
assert model.created_at == _CREATED_AT.replace(tzinfo=None), case
|
||||
assert model.finished_at == _FINISHED_AT.replace(tzinfo=None), case
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("non_utc_host_timezone")
|
||||
def test_dict_to_node_execution_defaults_missing_created_at_to_naive_utc_now() -> None:
|
||||
model = _dict_to_workflow_node_execution_model({"id": "execution-1"})
|
||||
|
||||
assert model.created_at.tzinfo is None
|
||||
assert abs((model.created_at - datetime.datetime.now(tz=datetime.UTC).replace(tzinfo=None)).total_seconds()) < 60
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import datetime
|
||||
import time
|
||||
from collections.abc import Generator
|
||||
from typing import cast, override
|
||||
|
||||
import pytest
|
||||
|
||||
from extensions.logstore.aliyun_logstore import AliyunLogStore
|
||||
from extensions.logstore.repositories.logstore_api_workflow_run_repository import (
|
||||
LogstoreAPIWorkflowRunRepository,
|
||||
_dict_to_workflow_run,
|
||||
)
|
||||
from graphon.enums import WorkflowExecutionStatus
|
||||
from models.enums import WorkflowRunTriggeredFrom
|
||||
from repositories.api_workflow_run_repository import AppWorkflowRunStats
|
||||
|
||||
_START = datetime.datetime(2026, 8, 18, 2, 0, 0, tzinfo=datetime.UTC)
|
||||
_FINISH = _START + datetime.timedelta(seconds=30)
|
||||
_EXPECTED_CREATED_AT = _START.replace(tzinfo=None)
|
||||
_EXPECTED_FINISHED_AT = _FINISH.replace(tzinfo=None)
|
||||
|
||||
_BASE: dict[str, object] = {"id": "run-1", "tenant_id": "tenant-1", "app_id": "app-1", "workflow_id": "workflow-1"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def non_utc_host_timezone(monkeypatch: pytest.MonkeyPatch) -> Generator[None]:
|
||||
"""Run the host clock in UTC+05:30 so local-time conversions become observable."""
|
||||
monkeypatch.setenv("TZ", "Asia/Kolkata")
|
||||
time.tzset()
|
||||
yield
|
||||
monkeypatch.undo()
|
||||
time.tzset()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("case", "payload"),
|
||||
[
|
||||
("both epoch", {"started_at": _START.timestamp(), "finished_at": _FINISH.timestamp()}),
|
||||
("aware iso and epoch", {"started_at": _START.isoformat(), "finished_at": _FINISH.timestamp()}),
|
||||
(
|
||||
"naive iso and epoch",
|
||||
{"started_at": _START.replace(tzinfo=None).isoformat(), "finished_at": _FINISH.timestamp()},
|
||||
),
|
||||
("both datetime", {"started_at": _START, "finished_at": _FINISH}),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("non_utc_host_timezone")
|
||||
def test_dict_to_workflow_run_normalizes_timestamps_to_naive_utc(case: str, payload: dict[str, object]) -> None:
|
||||
model = _dict_to_workflow_run({**_BASE, **payload})
|
||||
|
||||
assert model.created_at == _EXPECTED_CREATED_AT, case
|
||||
assert model.finished_at == _EXPECTED_FINISHED_AT, case
|
||||
assert model.elapsed_time == 30.0, case
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("non_utc_host_timezone")
|
||||
def test_dict_to_workflow_run_defaults_missing_started_at_to_naive_utc_now() -> None:
|
||||
model = _dict_to_workflow_run({**_BASE, "finished_at": _FINISH.timestamp()})
|
||||
|
||||
assert model.created_at.tzinfo is None
|
||||
# A naive local-time default would sit 5h30m ahead of UTC and drive elapsed_time negative.
|
||||
assert abs((model.created_at - datetime.datetime.now(tz=datetime.UTC).replace(tzinfo=None)).total_seconds()) < 60
|
||||
|
||||
|
||||
class _FakeLogStore:
|
||||
def __init__(self, rows: list[dict[str, object]]) -> None:
|
||||
self.rows = rows
|
||||
self.sql: list[str] = []
|
||||
|
||||
def execute_sql(self, sql: str, logstore: str | None = None, **_options: object) -> list[dict[str, object]]:
|
||||
assert logstore == AliyunLogStore.workflow_execution_logstore
|
||||
self.sql.append(sql)
|
||||
return self.rows
|
||||
|
||||
|
||||
def _repository(rows: list[dict[str, object]]) -> tuple[LogstoreAPIWorkflowRunRepository, _FakeLogStore]:
|
||||
repository = LogstoreAPIWorkflowRunRepository.__new__(LogstoreAPIWorkflowRunRepository)
|
||||
client = _FakeLogStore(rows)
|
||||
repository.logstore_client = cast(AliyunLogStore, client)
|
||||
return repository, client
|
||||
|
||||
|
||||
_APPS = {"app-1": "tenant-1", "app-'2": "tenant-1"}
|
||||
_SOURCES = [WorkflowRunTriggeredFrom.APP_RUN, WorkflowRunTriggeredFrom.WEBHOOK]
|
||||
|
||||
|
||||
class _RoutingLogStore(_FakeLogStore):
|
||||
"""Answer the windowed count query and the newest-start query with separate rows."""
|
||||
|
||||
def __init__(self, counts: list[dict[str, object]], last: list[dict[str, object]]) -> None:
|
||||
super().__init__([])
|
||||
self.counts = counts
|
||||
self.last = last
|
||||
|
||||
@override
|
||||
def execute_sql(self, sql: str, logstore: str | None = None, **_options: object) -> list[dict[str, object]]:
|
||||
super().execute_sql(sql, logstore)
|
||||
return self.last if "MAX(started_at)" in sql else self.counts
|
||||
|
||||
|
||||
def test_stats_by_app_ids_dedupes_versions_and_keeps_each_apps_tenant() -> None:
|
||||
repository = LogstoreAPIWorkflowRunRepository.__new__(LogstoreAPIWorkflowRunRepository)
|
||||
client = _RoutingLogStore(
|
||||
counts=[
|
||||
{"tenant_id": "tenant-1", "app_id": "app-1", "status": "succeeded", "count": "3"},
|
||||
{"tenant_id": "tenant-1", "app_id": "app-1", "status": "running", "count": 1},
|
||||
{"tenant_id": "tenant-2", "app_id": "app-1", "status": "failed", "count": 9},
|
||||
{"tenant_id": "tenant-1", "app_id": "app-1", "status": "bogus", "count": 9},
|
||||
],
|
||||
last=[
|
||||
{"tenant_id": "tenant-1", "app_id": "app-1", "last_started_at": "2026-10-14T12:30:00"},
|
||||
{"tenant_id": "tenant-1", "app_id": "app-'2", "last_started_at": "2026-01-01T00:00:00"},
|
||||
{"tenant_id": "tenant-2", "app_id": "app-'2", "last_started_at": "2026-10-14T13:00:00"},
|
||||
],
|
||||
)
|
||||
repository.logstore_client = cast(AliyunLogStore, client)
|
||||
since = datetime.datetime(2026, 10, 14, 12)
|
||||
|
||||
stats = repository.get_stats_by_app_ids(_APPS, _SOURCES, since)
|
||||
|
||||
assert stats == {
|
||||
"app-1": AppWorkflowRunStats(
|
||||
status_counts={WorkflowExecutionStatus.SUCCEEDED: 3, WorkflowExecutionStatus.RUNNING: 1},
|
||||
last_created_at=datetime.datetime(2026, 10, 14, 12, 30),
|
||||
),
|
||||
"app-'2": AppWorkflowRunStats(status_counts={}, last_created_at=datetime.datetime(2026, 1, 1)),
|
||||
}
|
||||
counts_sql, last_sql = client.sql
|
||||
assert "ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC)" in counts_sql
|
||||
assert "app_id IN ('app-1', 'app-''2')" in counts_sql
|
||||
assert "triggered_from IN ('app-run', 'webhook')" in counts_sql
|
||||
assert f"__time__ >= {int(since.replace(tzinfo=datetime.UTC).timestamp())}" in counts_sql
|
||||
assert "started_at >= '2026-10-14T12:00:00'" in counts_sql
|
||||
assert "app_id IN ('app-1', 'app-''2')" in last_sql
|
||||
|
||||
|
||||
def test_stats_by_app_ids_skips_the_queries_without_apps() -> None:
|
||||
repository, client = _repository([])
|
||||
|
||||
assert repository.get_stats_by_app_ids({}, _SOURCES, datetime.datetime(2026, 10, 14)) == {}
|
||||
assert client.sql == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("elapsed_time", ["0.0", "5.5"])
|
||||
def test_dict_to_workflow_run_prefers_stored_active_duration(elapsed_time: str) -> None:
|
||||
model = _dict_to_workflow_run({**_BASE, "started_at": _START, "finished_at": _FINISH, "elapsed_time": elapsed_time})
|
||||
|
||||
assert model.elapsed_time == float(elapsed_time)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("elapsed_time", [None, "null"])
|
||||
def test_dict_to_workflow_run_defaults_legacy_unfinished_duration_to_zero(elapsed_time: str | None) -> None:
|
||||
model = _dict_to_workflow_run({**_BASE, "elapsed_time": elapsed_time})
|
||||
|
||||
assert model.elapsed_time == 0.0
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
from unittest.mock import patch
|
||||
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from extensions.logstore.repositories.logstore_workflow_execution_repository import (
|
||||
LogstoreWorkflowExecutionRepository,
|
||||
)
|
||||
from models.account import Account
|
||||
from models.enums import WorkflowRunTriggeredFrom
|
||||
|
||||
|
||||
def test_repository_uses_typed_logstore_migration_flags(
|
||||
config_overrides: Callable[..., None],
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
) -> None:
|
||||
config_overrides(
|
||||
LOGSTORE_DUAL_WRITE_ENABLED=True,
|
||||
LOGSTORE_ENABLE_PUT_GRAPH_FIELD=False,
|
||||
)
|
||||
with (
|
||||
patch("extensions.logstore.repositories.logstore_workflow_execution_repository.AliyunLogStore"),
|
||||
patch(
|
||||
"extensions.logstore.repositories.logstore_workflow_execution_repository."
|
||||
"SQLAlchemyWorkflowExecutionRepository"
|
||||
),
|
||||
):
|
||||
repository = LogstoreWorkflowExecutionRepository(
|
||||
session_factory=sqlite_session_factory,
|
||||
tenant_id="tenant-1",
|
||||
user=cast(Account, SimpleNamespace(id="account-1")),
|
||||
app_id="app-1",
|
||||
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
|
||||
)
|
||||
|
||||
assert repository._enable_dual_write is True
|
||||
assert repository._enable_put_graph_field is False
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
from collections.abc import Callable
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from core.workflow.node_execution_process_data import WORKFLOW_TOOL_ROOT_APP_ID_KEY
|
||||
from extensions.logstore.repositories.logstore_workflow_node_execution_repository import (
|
||||
LogstoreWorkflowNodeExecutionRepository,
|
||||
)
|
||||
from graphon.entities import WorkflowNodeExecution
|
||||
from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from models.account import Account
|
||||
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
|
||||
|
||||
|
||||
def _make_account() -> Account:
|
||||
account = Account(name="Logstore User", email="logstore@example.com")
|
||||
account.id = "account-1"
|
||||
return account
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def logstore_schema(sqlite_engine: Engine) -> None:
|
||||
with sqlite_engine.begin() as connection:
|
||||
connection.exec_driver_sql(
|
||||
"CREATE TABLE workflow_node_execution AS SELECT *, 1 AS log_version FROM workflow_node_executions WHERE 0"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("logstore_schema")
|
||||
@pytest.mark.parametrize("source_app", ["caller-app", "source-app"])
|
||||
def test_workflow_tool_scope_preserves_logstore_and_source_scoped_synchronous_agent_rows(
|
||||
config_overrides: Callable[..., None],
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
sqlite_engine: Engine,
|
||||
source_app: str,
|
||||
) -> None:
|
||||
config_overrides(LOGSTORE_DUAL_WRITE_ENABLED=False)
|
||||
with patch(
|
||||
"extensions.logstore.repositories.logstore_workflow_node_execution_repository.AliyunLogStore"
|
||||
) as logstore:
|
||||
caller = LogstoreWorkflowNodeExecutionRepository(
|
||||
session_factory=sqlite_session_factory,
|
||||
tenant_id="tenant-1",
|
||||
user=_make_account(),
|
||||
app_id="caller-app",
|
||||
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
|
||||
)
|
||||
source = caller.for_workflow_tool(source_app)
|
||||
|
||||
node = WorkflowNodeExecution(
|
||||
id="source-exec",
|
||||
node_execution_id="source-exec",
|
||||
workflow_id="source-workflow",
|
||||
workflow_execution_id="caller-run",
|
||||
index=1,
|
||||
node_id="agent",
|
||||
node_type=BuiltinNodeTypes.AGENT,
|
||||
title="Agent",
|
||||
created_at=naive_utc_now(),
|
||||
process_data={WORKFLOW_TOOL_ROOT_APP_ID_KEY: "caller-app"},
|
||||
)
|
||||
source.save_synchronously(node)
|
||||
with sqlite_session_factory() as session:
|
||||
row = session.get(WorkflowNodeExecutionModel, "source-exec")
|
||||
assert row is not None
|
||||
assert (row.app_id, row.tenant_id, row.created_by, row.workflow_run_id) == (
|
||||
source_app,
|
||||
"tenant-1",
|
||||
"account-1",
|
||||
"caller-run",
|
||||
)
|
||||
assert row.triggered_from == WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL
|
||||
|
||||
node.status = WorkflowNodeExecutionStatus.SUCCEEDED
|
||||
source.save(node)
|
||||
logstore.return_value.put_log.assert_called_once()
|
||||
payload = dict(logstore.return_value.put_log.call_args.args[1])
|
||||
assert (payload["app_id"], payload["tenant_id"], payload["created_by"], payload["status"]) == (
|
||||
source_app,
|
||||
"tenant-1",
|
||||
"account-1",
|
||||
"succeeded",
|
||||
)
|
||||
assert payload["triggered_from"] == WorkflowNodeExecutionTriggeredFrom.WORKFLOW_TOOL
|
||||
|
||||
caller.save_synchronously(node.model_copy(update={"id": "caller-exec", "node_execution_id": "caller-exec"}))
|
||||
caller.save_synchronously(node.model_copy(update={"id": "legacy-exec", "node_execution_id": "legacy-exec"}))
|
||||
for execution_id in ("foreign-root", "foreign-run", "foreign-tenant"):
|
||||
source.save_synchronously(node.model_copy(update={"id": execution_id, "node_execution_id": execution_id}))
|
||||
with sqlite_session_factory() as session:
|
||||
foreign_root = session.get(WorkflowNodeExecutionModel, "foreign-root")
|
||||
foreign_run = session.get(WorkflowNodeExecutionModel, "foreign-run")
|
||||
foreign_tenant = session.get(WorkflowNodeExecutionModel, "foreign-tenant")
|
||||
assert foreign_root is not None
|
||||
assert foreign_run is not None
|
||||
assert foreign_tenant is not None
|
||||
foreign_root.process_data = '{"workflow_tool_root_app_id": "other-app"}'
|
||||
foreign_run.workflow_run_id = "other-run"
|
||||
foreign_tenant.tenant_id = "other-tenant"
|
||||
session.commit()
|
||||
with sqlite_engine.begin() as connection:
|
||||
connection.exec_driver_sql(
|
||||
"INSERT INTO workflow_node_execution SELECT *, 1 AS log_version FROM workflow_node_executions"
|
||||
)
|
||||
connection.exec_driver_sql("UPDATE workflow_node_execution SET triggered_from = NULL WHERE id = 'legacy-exec'")
|
||||
|
||||
def execute_query(*, sql: str, **_kwargs: object) -> list[dict[str, object]]:
|
||||
with sqlite_engine.connect() as connection:
|
||||
return [
|
||||
dict(row)
|
||||
for row in connection.exec_driver_sql(sql.replace("json_extract_scalar", "json_extract")).mappings()
|
||||
]
|
||||
|
||||
logstore.return_value.execute_sql.side_effect = execute_query
|
||||
assert {execution.id for execution in caller.get_by_workflow_execution("caller-run")} == {
|
||||
"caller-exec",
|
||||
"legacy-exec",
|
||||
}
|
||||
assert {execution.id for execution in source.get_by_workflow_execution("caller-run")} == {
|
||||
"source-exec",
|
||||
"foreign-root",
|
||||
}
|
||||
|
||||
|
||||
def test_save_synchronously_writes_sql_when_dual_write_is_disabled(
|
||||
config_overrides: Callable[..., None], sqlite_session_factory: sessionmaker[Session]
|
||||
) -> None:
|
||||
config_overrides(LOGSTORE_DUAL_WRITE_ENABLED=False)
|
||||
with (
|
||||
patch("extensions.logstore.repositories.logstore_workflow_node_execution_repository.AliyunLogStore"),
|
||||
patch(
|
||||
"extensions.logstore.repositories.logstore_workflow_node_execution_repository."
|
||||
"SQLAlchemyWorkflowNodeExecutionRepository"
|
||||
) as sql_repository_type,
|
||||
):
|
||||
repository = LogstoreWorkflowNodeExecutionRepository(
|
||||
session_factory=sqlite_session_factory,
|
||||
tenant_id="tenant-1",
|
||||
user=_make_account(),
|
||||
app_id="app-1",
|
||||
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
|
||||
)
|
||||
|
||||
execution = MagicMock()
|
||||
repository.save_synchronously(execution)
|
||||
|
||||
assert repository._enable_dual_write is False
|
||||
sql_repository_type.return_value.save_synchronously.assert_called_once_with(execution)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Test that the AliyunLogStorePG port-connectivity logger captures the traceback.
|
||||
|
||||
Cycle 21 (sibling of #41066 / merged in #41068): `logger.debug("...: %s", str(e))`
|
||||
sites in `extensions/logstore/aliyun_logstore_pg.py` were converted to
|
||||
`logger.debug("...", exc_info=True)` so the traceback is captured at the
|
||||
same log level rather than being silently dropped. This test exercises one
|
||||
of the modified sites — `_check_port_connectivity` — to confirm the fix
|
||||
shape is correct: the captured log record has a non-empty traceback.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from extensions.logstore.aliyun_logstore_pg import AliyunLogStorePG
|
||||
|
||||
|
||||
def test_check_port_connectivity_captures_traceback_on_exception(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""A socket failure during the port check must produce a log record with exc_info set.
|
||||
|
||||
Before cycle 21: the record was logged as
|
||||
`Port connectivity check failed for host:port: <str(exception)>` with no
|
||||
traceback. After cycle 21: the record is logged as
|
||||
`Port connectivity check failed for host:port` with `exc_info=True`, so
|
||||
the traceback is part of the log record (and the host/port are still
|
||||
included via the format args).
|
||||
"""
|
||||
store = AliyunLogStorePG(
|
||||
access_key_id="ak",
|
||||
access_key_secret="sk",
|
||||
endpoint="https://example.com",
|
||||
project_name="p",
|
||||
)
|
||||
|
||||
with (
|
||||
patch("extensions.logstore.aliyun_logstore_pg.socket.socket", side_effect=OSError("boom")),
|
||||
caplog.at_level("DEBUG", logger="extensions.logstore.aliyun_logstore_pg"),
|
||||
):
|
||||
result = store._check_port_connectivity("example.invalid", 9999)
|
||||
|
||||
assert result is False
|
||||
|
||||
matching_records = [r for r in caplog.records if r.name == "extensions.logstore.aliyun_logstore_pg"]
|
||||
assert len(matching_records) == 1
|
||||
record = matching_records[0]
|
||||
assert record.levelname == "DEBUG"
|
||||
assert record.exc_info is not None
|
||||
formatted = caplog.text
|
||||
assert "Port connectivity check failed for example.invalid:9999" in formatted
|
||||
assert "Traceback (most recent call last)" in formatted
|
||||
assert "OSError: boom" in formatted
|
||||
# The exception is captured via the traceback, not interpolated into the
|
||||
# format string — so the message text is the short form, not the long one.
|
||||
assert "boom" not in record.getMessage()
|
||||
@@ -0,0 +1,469 @@
|
||||
"""
|
||||
Unit tests for SQL escape utility functions.
|
||||
|
||||
These tests ensure that SQL injection attacks are properly prevented
|
||||
in LogStore queries, particularly for cross-tenant access scenarios.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from extensions.logstore.sql_escape import escape_identifier, escape_logstore_query_value, escape_sql_string
|
||||
|
||||
|
||||
class TestEscapeSQLString:
|
||||
"""Test escape_sql_string function."""
|
||||
|
||||
def test_escape_empty_string(self):
|
||||
"""Test escaping empty string."""
|
||||
assert escape_sql_string("") == ""
|
||||
|
||||
def test_escape_normal_string(self):
|
||||
"""Test escaping string without special characters."""
|
||||
assert escape_sql_string("tenant_abc123") == "tenant_abc123"
|
||||
assert escape_sql_string("app-uuid-1234") == "app-uuid-1234"
|
||||
|
||||
def test_escape_single_quote(self):
|
||||
"""Test escaping single quote."""
|
||||
# Single quote should be doubled
|
||||
assert escape_sql_string("tenant'id") == "tenant''id"
|
||||
assert escape_sql_string("O'Reilly") == "O''Reilly"
|
||||
|
||||
def test_escape_multiple_quotes(self):
|
||||
"""Test escaping multiple single quotes."""
|
||||
assert escape_sql_string("a'b'c") == "a''b''c"
|
||||
assert escape_sql_string("'''") == "''''''"
|
||||
|
||||
# === SQL Injection Attack Scenarios ===
|
||||
|
||||
def test_prevent_boolean_injection(self):
|
||||
"""Test prevention of boolean injection attacks."""
|
||||
# Classic OR 1=1 attack
|
||||
malicious_input = "tenant' OR '1'='1"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant'' OR ''1''=''1"
|
||||
|
||||
# When used in SQL, this becomes a safe string literal
|
||||
sql = f"WHERE tenant_id='{escaped}'"
|
||||
assert sql == "WHERE tenant_id='tenant'' OR ''1''=''1'"
|
||||
# The entire input is now a string literal that won't match any tenant
|
||||
|
||||
def test_prevent_or_injection(self):
|
||||
"""Test prevention of OR-based injection."""
|
||||
malicious_input = "tenant_a' OR tenant_id='tenant_b"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant_a'' OR tenant_id=''tenant_b"
|
||||
|
||||
sql = f"WHERE tenant_id='{escaped}'"
|
||||
# The OR is now part of the string literal, not SQL logic
|
||||
assert "OR tenant_id=" in sql
|
||||
# The SQL has: opening ', doubled internal quotes '', and closing '
|
||||
assert sql == "WHERE tenant_id='tenant_a'' OR tenant_id=''tenant_b'"
|
||||
|
||||
def test_prevent_union_injection(self):
|
||||
"""Test prevention of UNION-based injection."""
|
||||
malicious_input = "xxx' UNION SELECT password FROM users WHERE '1'='1"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "xxx'' UNION SELECT password FROM users WHERE ''1''=''1"
|
||||
|
||||
# UNION becomes part of the string literal
|
||||
assert "UNION" in escaped
|
||||
assert escaped.count("''") == 4 # All internal quotes are doubled
|
||||
|
||||
def test_prevent_comment_injection(self):
|
||||
"""Test prevention of comment-based injection."""
|
||||
# SQL comment to bypass remaining conditions
|
||||
malicious_input = "tenant' --"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant'' --"
|
||||
|
||||
sql = f"WHERE tenant_id='{escaped}' AND deleted=false"
|
||||
# The -- is now inside the string, not a SQL comment
|
||||
assert "--" in sql
|
||||
assert "AND deleted=false" in sql # This part is NOT commented out
|
||||
|
||||
def test_prevent_semicolon_injection(self):
|
||||
"""Test prevention of semicolon-based multi-statement injection."""
|
||||
malicious_input = "tenant'; DROP TABLE users; --"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant''; DROP TABLE users; --"
|
||||
|
||||
# Semicolons and DROP are now part of the string
|
||||
assert "DROP TABLE" in escaped
|
||||
|
||||
def test_prevent_time_based_blind_injection(self):
|
||||
"""Test prevention of time-based blind SQL injection."""
|
||||
malicious_input = "tenant' AND SLEEP(5) --"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant'' AND SLEEP(5) --"
|
||||
|
||||
# SLEEP becomes part of the string
|
||||
assert "SLEEP" in escaped
|
||||
|
||||
def test_prevent_wildcard_injection(self):
|
||||
"""Test prevention of wildcard-based injection."""
|
||||
malicious_input = "tenant' OR tenant_id LIKE '%"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
assert escaped == "tenant'' OR tenant_id LIKE ''%"
|
||||
|
||||
# The LIKE and wildcard are now part of the string
|
||||
assert "LIKE" in escaped
|
||||
|
||||
def test_prevent_null_byte_injection(self):
|
||||
"""Test handling of null bytes."""
|
||||
# Null bytes can sometimes bypass filters
|
||||
malicious_input = "tenant\x00' OR '1'='1"
|
||||
escaped = escape_sql_string(malicious_input)
|
||||
# Null byte is preserved, but quote is escaped
|
||||
assert "''1''=''1" in escaped
|
||||
|
||||
# === Real-world SAAS Scenarios ===
|
||||
|
||||
def test_cross_tenant_access_attempt(self):
|
||||
"""Test prevention of cross-tenant data access."""
|
||||
# Attacker tries to access another tenant's data
|
||||
attacker_input = "tenant_b' OR tenant_id='tenant_a"
|
||||
escaped = escape_sql_string(attacker_input)
|
||||
|
||||
sql = f"SELECT * FROM workflow_runs WHERE tenant_id='{escaped}'"
|
||||
# The query will look for a tenant literally named "tenant_b' OR tenant_id='tenant_a"
|
||||
# which doesn't exist - preventing access to either tenant's data
|
||||
assert "tenant_b'' OR tenant_id=''tenant_a" in sql
|
||||
|
||||
def test_cross_app_access_attempt(self):
|
||||
"""Test prevention of cross-application data access."""
|
||||
attacker_input = "app1' OR app_id='app2"
|
||||
escaped = escape_sql_string(attacker_input)
|
||||
|
||||
sql = f"WHERE app_id='{escaped}'"
|
||||
# Cannot access app2's data
|
||||
assert "app1'' OR app_id=''app2" in sql
|
||||
|
||||
def test_bypass_status_filter(self):
|
||||
"""Test prevention of bypassing status filters."""
|
||||
# Try to see all statuses instead of just 'running'
|
||||
attacker_input = "running' OR status LIKE '%"
|
||||
escaped = escape_sql_string(attacker_input)
|
||||
|
||||
sql = f"WHERE status='{escaped}'"
|
||||
# Status condition is not bypassed
|
||||
assert "running'' OR status LIKE ''%" in sql
|
||||
|
||||
# === Edge Cases ===
|
||||
|
||||
def test_escape_only_quotes(self):
|
||||
"""Test string with only quotes."""
|
||||
assert escape_sql_string("'") == "''"
|
||||
assert escape_sql_string("''") == "''''"
|
||||
|
||||
def test_escape_mixed_content(self):
|
||||
"""Test string with mixed quotes and other chars."""
|
||||
input_str = "It's a 'test' of O'Reilly's code"
|
||||
escaped = escape_sql_string(input_str)
|
||||
assert escaped == "It''s a ''test'' of O''Reilly''s code"
|
||||
|
||||
def test_escape_unicode_with_quotes(self):
|
||||
"""Test Unicode strings with quotes."""
|
||||
input_str = "租户' OR '1'='1"
|
||||
escaped = escape_sql_string(input_str)
|
||||
assert escaped == "租户'' OR ''1''=''1"
|
||||
|
||||
|
||||
class TestEscapeIdentifier:
|
||||
"""Test escape_identifier function."""
|
||||
|
||||
def test_escape_uuid(self):
|
||||
"""Test escaping UUID identifiers."""
|
||||
uuid = "550e8400-e29b-41d4-a716-446655440000"
|
||||
assert escape_identifier(uuid) == uuid
|
||||
|
||||
def test_escape_alphanumeric_id(self):
|
||||
"""Test escaping alphanumeric identifiers."""
|
||||
assert escape_identifier("tenant_123") == "tenant_123"
|
||||
assert escape_identifier("app-abc-123") == "app-abc-123"
|
||||
|
||||
def test_escape_identifier_with_quote(self):
|
||||
"""Test escaping identifier with single quote."""
|
||||
malicious = "tenant' OR '1'='1"
|
||||
escaped = escape_identifier(malicious)
|
||||
assert escaped == "tenant'' OR ''1''=''1"
|
||||
|
||||
def test_identifier_injection_attempt(self):
|
||||
"""Test prevention of injection through identifiers."""
|
||||
# Common identifier injection patterns
|
||||
test_cases = [
|
||||
("id' OR '1'='1", "id'' OR ''1''=''1"),
|
||||
("id'; DROP TABLE", "id''; DROP TABLE"),
|
||||
("id' UNION SELECT", "id'' UNION SELECT"),
|
||||
]
|
||||
|
||||
for malicious, expected in test_cases:
|
||||
assert escape_identifier(malicious) == expected
|
||||
|
||||
|
||||
class TestSQLInjectionIntegration:
|
||||
"""Integration tests simulating real SQL construction scenarios."""
|
||||
|
||||
def test_complete_where_clause_safety(self):
|
||||
"""Test that a complete WHERE clause is safe from injection."""
|
||||
# Simulating typical query construction
|
||||
tenant_id = "tenant' OR '1'='1"
|
||||
app_id = "app' UNION SELECT"
|
||||
run_id = "run' --"
|
||||
|
||||
escaped_tenant = escape_identifier(tenant_id)
|
||||
escaped_app = escape_identifier(app_id)
|
||||
escaped_run = escape_identifier(run_id)
|
||||
|
||||
sql = f"""
|
||||
SELECT * FROM workflow_runs
|
||||
WHERE tenant_id='{escaped_tenant}'
|
||||
AND app_id='{escaped_app}'
|
||||
AND id='{escaped_run}'
|
||||
"""
|
||||
|
||||
# Verify all special characters are escaped
|
||||
assert "tenant'' OR ''1''=''1" in sql
|
||||
assert "app'' UNION SELECT" in sql
|
||||
assert "run'' --" in sql
|
||||
|
||||
# Verify SQL structure is preserved (3 conditions with AND)
|
||||
assert sql.count("AND") == 2
|
||||
|
||||
def test_multiple_conditions_with_injection_attempts(self):
|
||||
"""Test multiple conditions all attempting injection."""
|
||||
conditions = {
|
||||
"tenant_id": "t1' OR tenant_id='t2",
|
||||
"app_id": "a1' OR app_id='a2",
|
||||
"status": "running' OR '1'='1",
|
||||
}
|
||||
|
||||
where_parts = []
|
||||
for field, value in conditions.items():
|
||||
escaped = escape_sql_string(value)
|
||||
where_parts.append(f"{field}='{escaped}'")
|
||||
|
||||
where_clause = " AND ".join(where_parts)
|
||||
|
||||
# All injection attempts are neutralized
|
||||
assert "t1'' OR tenant_id=''t2" in where_clause
|
||||
assert "a1'' OR app_id=''a2" in where_clause
|
||||
assert "running'' OR ''1''=''1" in where_clause
|
||||
|
||||
# AND structure is preserved
|
||||
assert where_clause.count(" AND ") == 2
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attack_vector", "description"),
|
||||
[
|
||||
("' OR '1'='1", "Boolean injection"),
|
||||
("' OR '1'='1' --", "Boolean with comment"),
|
||||
("' UNION SELECT * FROM users --", "Union injection"),
|
||||
("'; DROP TABLE workflow_runs; --", "Destructive command"),
|
||||
("' AND SLEEP(10) --", "Time-based blind"),
|
||||
("' OR tenant_id LIKE '%", "Wildcard injection"),
|
||||
("admin' --", "Comment bypass"),
|
||||
("' OR 1=1 LIMIT 1 --", "Limit bypass"),
|
||||
],
|
||||
)
|
||||
def test_common_injection_vectors(self, attack_vector, description):
|
||||
"""Test protection against common injection attack vectors."""
|
||||
escaped = escape_sql_string(attack_vector)
|
||||
|
||||
# Build SQL
|
||||
sql = f"WHERE tenant_id='{escaped}'"
|
||||
|
||||
# Verify the attack string is now a safe literal
|
||||
# The key indicator: all internal single quotes are doubled
|
||||
internal_quotes = escaped.count("''")
|
||||
original_quotes = attack_vector.count("'")
|
||||
|
||||
# Each original quote should be doubled
|
||||
assert internal_quotes == original_quotes
|
||||
|
||||
# Verify SQL has exactly 2 quotes (opening and closing)
|
||||
assert sql.count("'") >= 2 # At least opening and closing
|
||||
|
||||
def test_logstore_specific_scenario(self):
|
||||
"""Test SQL injection prevention in LogStore-specific scenarios."""
|
||||
# Simulate LogStore query with window function
|
||||
tenant_id = "tenant' OR '1'='1"
|
||||
app_id = "app' UNION SELECT"
|
||||
|
||||
escaped_tenant = escape_identifier(tenant_id)
|
||||
escaped_app = escape_identifier(app_id)
|
||||
|
||||
sql = f"""
|
||||
SELECT * FROM (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC) as rn
|
||||
FROM workflow_execution_logstore
|
||||
WHERE tenant_id='{escaped_tenant}'
|
||||
AND app_id='{escaped_app}'
|
||||
AND __time__ > 0
|
||||
) AS subquery WHERE rn = 1
|
||||
"""
|
||||
|
||||
# Complex query structure is maintained
|
||||
assert "ROW_NUMBER()" in sql
|
||||
assert "PARTITION BY id" in sql
|
||||
|
||||
# Injection attempts are escaped
|
||||
assert "tenant'' OR ''1''=''1" in sql
|
||||
assert "app'' UNION SELECT" in sql
|
||||
|
||||
|
||||
# ====================================================================================
|
||||
# Tests for LogStore Query Syntax (SDK Mode)
|
||||
# ====================================================================================
|
||||
|
||||
|
||||
class TestLogStoreQueryEscape:
|
||||
"""Test escape_logstore_query_value for SDK mode query syntax."""
|
||||
|
||||
def test_normal_value(self):
|
||||
"""Test escaping normal alphanumeric value."""
|
||||
value = "550e8400-e29b-41d4-a716-446655440000"
|
||||
escaped = escape_logstore_query_value(value)
|
||||
|
||||
# Should be wrapped in double quotes
|
||||
assert escaped == '"550e8400-e29b-41d4-a716-446655440000"'
|
||||
|
||||
def test_empty_value(self):
|
||||
"""Test escaping empty string."""
|
||||
assert escape_logstore_query_value("") == '""'
|
||||
|
||||
def test_value_with_and_keyword(self):
|
||||
"""Test that 'and' keyword is neutralized when quoted."""
|
||||
malicious = "value and field:evil"
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
# Should be wrapped in quotes, making 'and' a literal
|
||||
assert escaped == '"value and field:evil"'
|
||||
|
||||
# Simulate using in query
|
||||
query = f"tenant_id:{escaped}"
|
||||
assert query == 'tenant_id:"value and field:evil"'
|
||||
|
||||
def test_value_with_or_keyword(self):
|
||||
"""Test that 'or' keyword is neutralized when quoted."""
|
||||
malicious = "tenant_a or tenant_id:tenant_b"
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
assert escaped == '"tenant_a or tenant_id:tenant_b"'
|
||||
|
||||
query = f"tenant_id:{escaped}"
|
||||
assert "or" in query # Present but as literal string
|
||||
|
||||
def test_value_with_not_keyword(self):
|
||||
"""Test that 'not' keyword is neutralized when quoted."""
|
||||
malicious = "not field:value"
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
assert escaped == '"not field:value"'
|
||||
|
||||
def test_value_with_parentheses(self):
|
||||
"""Test that parentheses are neutralized when quoted."""
|
||||
malicious = "(tenant_a or tenant_b)"
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
assert escaped == '"(tenant_a or tenant_b)"'
|
||||
assert "(" in escaped # Present as literal
|
||||
assert ")" in escaped # Present as literal
|
||||
|
||||
def test_value_with_colon(self):
|
||||
"""Test that colons are neutralized when quoted."""
|
||||
malicious = "field:value"
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
assert escaped == '"field:value"'
|
||||
assert ":" in escaped # Present as literal
|
||||
|
||||
def test_value_with_double_quotes(self):
|
||||
"""Test that internal double quotes are escaped."""
|
||||
value_with_quotes = 'tenant"test"value'
|
||||
escaped = escape_logstore_query_value(value_with_quotes)
|
||||
|
||||
# Double quotes should be escaped with backslash
|
||||
assert escaped == '"tenant\\"test\\"value"'
|
||||
# Should have outer quotes plus escaped inner quotes
|
||||
assert '\\"' in escaped
|
||||
|
||||
def test_value_with_backslash(self):
|
||||
"""Test that backslashes are escaped."""
|
||||
value_with_backslash = "tenant\\test"
|
||||
escaped = escape_logstore_query_value(value_with_backslash)
|
||||
|
||||
# Backslash should be escaped
|
||||
assert escaped == '"tenant\\\\test"'
|
||||
assert "\\\\" in escaped
|
||||
|
||||
def test_value_with_backslash_and_quote(self):
|
||||
"""Test escaping both backslash and double quote."""
|
||||
value = 'path\\to\\"file"'
|
||||
escaped = escape_logstore_query_value(value)
|
||||
|
||||
# Both should be escaped
|
||||
assert escaped == '"path\\\\to\\\\\\"file\\""'
|
||||
# Verify escape order is correct
|
||||
assert "\\\\" in escaped # Escaped backslash
|
||||
assert '\\"' in escaped # Escaped double quote
|
||||
|
||||
def test_complex_injection_attempt(self):
|
||||
"""Test complex injection combining multiple operators."""
|
||||
malicious = 'tenant_a" or (tenant_id:"tenant_b" and app_id:"evil")'
|
||||
escaped = escape_logstore_query_value(malicious)
|
||||
|
||||
# All special chars should be literals or escaped
|
||||
assert escaped.startswith('"')
|
||||
assert escaped.endswith('"')
|
||||
# Inner double quotes escaped, operators become literals
|
||||
assert "or" in escaped
|
||||
assert "and" in escaped
|
||||
assert '\\"' in escaped # Escaped quotes
|
||||
|
||||
def test_only_backslash(self):
|
||||
"""Test escaping a single backslash."""
|
||||
assert escape_logstore_query_value("\\") == '"\\\\"'
|
||||
|
||||
def test_only_double_quote(self):
|
||||
"""Test escaping a single double quote."""
|
||||
assert escape_logstore_query_value('"') == '"\\""'
|
||||
|
||||
def test_multiple_backslashes(self):
|
||||
"""Test escaping multiple consecutive backslashes."""
|
||||
assert escape_logstore_query_value("\\\\\\") == '"\\\\\\\\\\\\"' # 3 backslashes -> 6
|
||||
|
||||
def test_escape_sequence_like_input(self):
|
||||
"""Test that existing escape sequences are properly escaped."""
|
||||
# Input looks like already escaped, but we still escape it
|
||||
value = 'value\\"test'
|
||||
escaped = escape_logstore_query_value(value)
|
||||
# \\ -> \\\\, " -> \"
|
||||
assert escaped == '"value\\\\\\"test"'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attack_scenario", "field", "malicious_value"),
|
||||
[
|
||||
("Cross-tenant via OR", "tenant_id", "tenant_a or tenant_id:tenant_b"),
|
||||
("Cross-app via AND", "app_id", "app_a and (app_id:app_b or app_id:app_c)"),
|
||||
("Boolean logic", "status", "succeeded or status:failed"),
|
||||
("Negation", "tenant_id", "not tenant_a"),
|
||||
("Field injection", "run_id", "run123 and tenant_id:evil_tenant"),
|
||||
("Parentheses grouping", "app_id", "app1 or (app_id:app2 and tenant_id:tenant2)"),
|
||||
("Quote breaking attempt", "tenant_id", 'tenant" or "1"="1'),
|
||||
("Backslash escape bypass", "app_id", "app\\ and app_id:evil"),
|
||||
],
|
||||
)
|
||||
def test_logstore_query_injection_scenarios(attack_scenario: str, field: str, malicious_value: str):
|
||||
"""Test that various LogStore query injection attempts are neutralized."""
|
||||
escaped = escape_logstore_query_value(malicious_value)
|
||||
|
||||
# Build query
|
||||
query = f"{field}:{escaped}"
|
||||
|
||||
# All operators should be within quoted string (literals)
|
||||
assert escaped.startswith('"')
|
||||
assert escaped.endswith('"')
|
||||
|
||||
# Verify the full query structure is safe
|
||||
assert query.count(":") >= 1 # At least the main field:value separator
|
||||
Reference in new issue
Block a user