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
Whitespace-only changes.
+336
@@ -0,0 +1,336 @@
|
||||
"""Real HTTP, PostgreSQL, Redis and Celery publication for annotation import jobs.
|
||||
|
||||
Workers are not executed: admission and publication are exercised without vector I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, replace
|
||||
from io import BytesIO
|
||||
from queue import Empty
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from celery import Celery, Task
|
||||
from celery.signals import before_task_publish
|
||||
from flask import Flask
|
||||
from kombu.simple import SimpleQueue
|
||||
from sqlalchemy import Connection, event, update
|
||||
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
|
||||
from werkzeug.test import TestResponse
|
||||
|
||||
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
|
||||
from controllers.console.wraps import _is_setup_completed
|
||||
from enums import DeploymentEdition
|
||||
from enums.account import TenantAccountRole
|
||||
from extensions.ext_application_services import ApplicationServices, _get_annotation_import_quota
|
||||
from extensions.ext_database import db
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.passport import PassportService
|
||||
from libs.token import generate_csrf_token
|
||||
from models import Account, App, Tenant
|
||||
from models.account import TenantAccountJoin
|
||||
from models.model import DifySetup
|
||||
from repositories.annotation_import_job_repository import (
|
||||
RedisAnnotationImportJobRepository,
|
||||
annotation_import_job_owner_key,
|
||||
)
|
||||
from repositories.annotation_repository import AnnotationRepository
|
||||
from services.annotation_import_service import AnnotationImportLimits, AnnotationImportService
|
||||
from tasks.annotation.batch_import_annotations_task import batch_import_annotations_task
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
from tests.helpers.unit.model_factories import make_account, make_app
|
||||
|
||||
_CSV = b"question,answer\n Question , Answer \nNA,N/A\n"
|
||||
_RECORDS = [{"question": "Question", "answer": "Answer"}, {"question": "NA", "answer": "N/A"}]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Harness:
|
||||
app: Flask
|
||||
account: Account
|
||||
target: App
|
||||
other: App
|
||||
factory: sessionmaker[Session]
|
||||
redis: RedisClientWrapper
|
||||
celery: Celery
|
||||
task: Task[..., None]
|
||||
queue: str
|
||||
sessions: list[Session]
|
||||
publications: list[bool]
|
||||
|
||||
def request(
|
||||
self,
|
||||
*,
|
||||
app_id: str | None = None,
|
||||
job_id: str | None = None,
|
||||
content: bytes = _CSV,
|
||||
filename: str = "annotations.CSV",
|
||||
) -> TestResponse:
|
||||
client = self.app.test_client()
|
||||
token = generate_csrf_token(self.account.id)
|
||||
headers = {
|
||||
HEADER_NAME_CSRF_TOKEN: token,
|
||||
"Authorization": f"Bearer {PassportService().issue({'user_id': self.account.id})}",
|
||||
}
|
||||
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, token)
|
||||
path = f"/console/api/apps/{app_id or self.target.id}/annotations/batch-import"
|
||||
if job_id is None:
|
||||
response = client.post(
|
||||
path,
|
||||
data={"file": (BytesIO(content), filename)},
|
||||
content_type="multipart/form-data",
|
||||
headers=headers,
|
||||
)
|
||||
else:
|
||||
response = client.get(f"{path}-status/{job_id}", headers=headers)
|
||||
assert response.headers["Content-Type"] == "application/json"
|
||||
assert int(response.headers["Content-Length"]) == len(response.data)
|
||||
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
|
||||
app = flask_app_with_containers
|
||||
services = app.extensions["application_services"]
|
||||
assert isinstance(services, ApplicationServices)
|
||||
redis = app.extensions["redis"]
|
||||
assert isinstance(redis, RedisClientWrapper)
|
||||
with app.app_context():
|
||||
factory = sessionmaker(bind=db.engine, expire_on_commit=False)
|
||||
workspace = Tenant(name="Annotation import workspace")
|
||||
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
|
||||
account.last_active_at = naive_utc_now()
|
||||
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
with factory.begin() as session:
|
||||
session.add_all(
|
||||
[
|
||||
workspace,
|
||||
account,
|
||||
target,
|
||||
other,
|
||||
TenantAccountJoin(
|
||||
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
|
||||
),
|
||||
DifySetup(version="test"),
|
||||
]
|
||||
)
|
||||
queue = f"annotation-import-{uuid4()}"
|
||||
celery = Celery(queue, broker="memory://", set_as_current=False)
|
||||
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
|
||||
task = celery.task(name=batch_import_annotations_task.name, shared=False)(batch_import_annotations_task.run)
|
||||
service = AnnotationImportService(
|
||||
apps=AnnotationRepository(session_factory=factory),
|
||||
jobs=RedisAnnotationImportJobRepository(redis=redis),
|
||||
publish=task.delay,
|
||||
quota=_get_annotation_import_quota,
|
||||
limits=AnnotationImportLimits(
|
||||
min_records=1, max_records=2, requests_per_minute=5, requests_per_hour=20, max_concurrent=3
|
||||
),
|
||||
)
|
||||
app.extensions["application_services"] = replace(services, annotation_imports=service)
|
||||
sessions: list[Session] = []
|
||||
publications: list[bool] = []
|
||||
|
||||
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
|
||||
sessions.append(session)
|
||||
|
||||
def observe_publish(**_kwargs: object) -> None:
|
||||
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
|
||||
|
||||
event.listen(Session, "after_begin", track)
|
||||
before_task_publish.connect(observe_publish, weak=True)
|
||||
_is_setup_completed.reset_success()
|
||||
try:
|
||||
with config_overrides_context(
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
|
||||
SECRET_KEY="annotation-import-passport-test-key-32-bytes",
|
||||
LOGIN_DISABLED=False,
|
||||
INIT_PASSWORD="",
|
||||
CONSOLE_API_URL="http://localhost",
|
||||
CONSOLE_WEB_URL="http://localhost",
|
||||
COOKIE_DOMAIN="",
|
||||
RBAC_ENABLED=False,
|
||||
):
|
||||
with app.app_context():
|
||||
assert _is_setup_completed()
|
||||
db.session.remove()
|
||||
yield _Harness(app, account, target, other, factory, redis, celery, task, queue, sessions, publications)
|
||||
finally:
|
||||
app.extensions["application_services"] = services
|
||||
del observe_publish
|
||||
event.remove(Session, "after_begin", track)
|
||||
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
|
||||
messages.clear()
|
||||
celery.close()
|
||||
_is_setup_completed.reset_success()
|
||||
with app.app_context():
|
||||
db.session.remove()
|
||||
|
||||
|
||||
def _assert_no_task(harness: _Harness) -> None:
|
||||
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
|
||||
with pytest.raises(Empty):
|
||||
messages.get(block=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR])
|
||||
def test_import_publishes_scoped_records_after_sql_sessions_close(harness: _Harness, role: TenantAccountRole) -> None:
|
||||
with harness.factory.begin() as session:
|
||||
session.execute(
|
||||
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(role=role)
|
||||
)
|
||||
|
||||
response = harness.request()
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
job_id = body["job_id"]
|
||||
assert str(UUID(job_id)) == job_id
|
||||
assert body == {"job_id": job_id, "job_status": "waiting", "record_count": 2, "error_msg": None}
|
||||
assert harness.redis.get(f"app_annotation_batch_import_{job_id}") == b"waiting"
|
||||
assert harness.redis.get(annotation_import_job_owner_key(job_id=job_id)) == (
|
||||
f"{harness.target.tenant_id}:{harness.target.id}".encode()
|
||||
)
|
||||
assert harness.redis.zscore(f"annotation_import_active:{harness.target.tenant_id}", job_id) is not None
|
||||
assert harness.publications == [True]
|
||||
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
|
||||
message = messages.get(block=False)
|
||||
assert message.headers["task"] == batch_import_annotations_task.name
|
||||
assert message.payload[0] == []
|
||||
assert message.payload[1] == {
|
||||
"job_id": job_id,
|
||||
"content_list": _RECORDS,
|
||||
"app_id": harness.target.id,
|
||||
"tenant_id": harness.target.tenant_id,
|
||||
"user_id": harness.account.id,
|
||||
}
|
||||
message.ack()
|
||||
_assert_no_task(harness)
|
||||
status = harness.request(job_id=job_id)
|
||||
assert status.status_code == 200
|
||||
assert status.get_json() == {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "message"),
|
||||
[
|
||||
(b"question\nQuestion\n", "at least 2 columns"),
|
||||
(b"question,answer\n", "at least 1 valid annotation record"),
|
||||
(b"question,answer", "appears to be empty or invalid"),
|
||||
(b"question,answer\nQ1,A1\nQ2,A2\nQ3,A3\n", "Maximum 2 records"),
|
||||
(b"question,answer\n" + b"Q" * 2001 + b",Answer\n", "Maximum 2000 characters"),
|
||||
(b"question,answer\nQuestion," + b"A" * 10001 + b"\n", "Maximum 10000 characters"),
|
||||
(b"question,answer\n\xff,Answer\n", "can't decode byte"),
|
||||
],
|
||||
ids=["one-column", "header-only", "no-newline", "too-many-records", "long-question", "long-answer", "bad-encoding"],
|
||||
)
|
||||
def test_invalid_csv_preserves_error_message_response_without_creating_a_job(
|
||||
harness: _Harness, content: bytes, message: str
|
||||
) -> None:
|
||||
response = harness.request(content=content)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body == {"job_id": None, "job_status": None, "record_count": None, "error_msg": body["error_msg"]}
|
||||
assert message in body["error_msg"]
|
||||
for window in ("1min", "1hour"):
|
||||
assert harness.redis.zcard(f"annotation_import_rate_limit:{harness.target.tenant_id}:{window}") == 1
|
||||
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
|
||||
assert list(harness.redis.scan_iter(match="app_annotation_batch_import_owner_*")) == []
|
||||
assert harness.publications == []
|
||||
_assert_no_task(harness)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("window", "limit"), [("1min", 5), ("1hour", 20)])
|
||||
def test_rate_limit_returns_429_without_registering_or_publishing_job(
|
||||
harness: _Harness, window: str, limit: int
|
||||
) -> None:
|
||||
now_ms = int(time.time() * 1000)
|
||||
harness.redis.zadd(
|
||||
f"annotation_import_rate_limit:{harness.target.tenant_id}:{window}",
|
||||
{f"prior-{index}": now_ms for index in range(limit)},
|
||||
)
|
||||
|
||||
response = harness.request()
|
||||
|
||||
assert response.status_code == 429
|
||||
assert response.get_json()["code"] == "too_many_requests"
|
||||
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
|
||||
assert harness.publications == []
|
||||
_assert_no_task(harness)
|
||||
|
||||
|
||||
def test_concurrency_limit_returns_429_and_preserves_existing_jobs(harness: _Harness) -> None:
|
||||
active_key = f"annotation_import_active:{harness.target.tenant_id}"
|
||||
existing = {str(uuid4()) for _ in range(3)}
|
||||
now_ms = int(time.time() * 1000)
|
||||
harness.redis.zadd(active_key, dict.fromkeys(existing, now_ms))
|
||||
|
||||
response = harness.request()
|
||||
|
||||
assert response.status_code == 429
|
||||
assert response.get_json()["code"] == "too_many_requests"
|
||||
assert {job.decode() for job in harness.redis.zrange(active_key, 0, -1)} == existing
|
||||
assert harness.publications == []
|
||||
_assert_no_task(harness)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mismatch", ["app", "tenant", "legacy", "missing", "status_missing"])
|
||||
def test_job_status_requires_complete_owner_and_status(harness: _Harness, mismatch: str) -> None:
|
||||
job_id = str(uuid4())
|
||||
requested_app = harness.other.id if mismatch == "app" else harness.target.id
|
||||
if mismatch not in {"missing", "status_missing"}:
|
||||
harness.redis.set(f"app_annotation_batch_import_{job_id}", "completed")
|
||||
if mismatch not in {"legacy", "missing"}:
|
||||
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
|
||||
harness.redis.set(annotation_import_job_owner_key(job_id=job_id), f"{tenant_id}:{harness.target.id}")
|
||||
|
||||
response = harness.request(app_id=requested_app, job_id=job_id)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["code"] == "not_found"
|
||||
assert response.get_json()["message"] == "The job does not exist."
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("status", "error", "expected"),
|
||||
[
|
||||
("waiting", None, ""),
|
||||
("completed", "Old error", ""),
|
||||
("error", "Worker failed", "Worker failed"),
|
||||
("error", None, ""),
|
||||
],
|
||||
)
|
||||
def test_status_preserves_worker_error_and_handles_expired_error_key(
|
||||
harness: _Harness, status: str, error: str | None, expected: str
|
||||
) -> None:
|
||||
job_id = str(uuid4())
|
||||
harness.redis.set(annotation_import_job_owner_key(job_id=job_id), f"{harness.target.tenant_id}:{harness.target.id}")
|
||||
harness.redis.set(f"app_annotation_batch_import_{job_id}", status)
|
||||
if error is not None:
|
||||
harness.redis.set(f"app_annotation_batch_import_error_msg_{job_id}", error)
|
||||
|
||||
response = harness.request(job_id=job_id)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"job_id": job_id, "job_status": status, "error_msg": expected}
|
||||
|
||||
|
||||
def test_publish_failure_returns_500_and_removes_pending_job(harness: _Harness) -> None:
|
||||
harness.task.serializer = "not-installed"
|
||||
|
||||
response = harness.request()
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.get_json()["code"] == "internal_server_error"
|
||||
assert "error_msg" not in response.get_json()
|
||||
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
|
||||
assert list(harness.redis.scan_iter(match="app_annotation_batch_import_*")) == []
|
||||
_assert_no_task(harness)
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
"""Real HTTP admission, PostgreSQL, Redis and Celery memory transport for reply jobs.
|
||||
|
||||
Exercises admission, publication and worker cleanup without embedding/vector I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, replace
|
||||
from queue import Empty
|
||||
from threading import Barrier, Event
|
||||
from typing import Literal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from celery import Celery, Task
|
||||
from celery.signals import before_task_publish
|
||||
from flask import Flask
|
||||
from kombu.exceptions import SerializerNotInstalled
|
||||
from kombu.simple import SimpleQueue
|
||||
from sqlalchemy import Connection, delete, event, select, update
|
||||
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
|
||||
from werkzeug.test import TestResponse
|
||||
|
||||
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
|
||||
from controllers.console.wraps import _is_setup_completed
|
||||
from enums import DeploymentEdition
|
||||
from enums.account import TenantAccountRole
|
||||
from extensions.ext_application_services import ApplicationServices
|
||||
from extensions.ext_database import db
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.passport import PassportService
|
||||
from libs.token import generate_csrf_token
|
||||
from models import Account, App, Tenant
|
||||
from models.account import TenantAccountJoin
|
||||
from models.model import AppAnnotationSetting, DifySetup
|
||||
from repositories.annotation_reply_job_repository import (
|
||||
RedisAnnotationReplyJobRepository,
|
||||
annotation_reply_job_owner_key,
|
||||
)
|
||||
from repositories.annotation_repository import AnnotationRepository
|
||||
from services.annotation_reply_service import AnnotationReplyAction, AnnotationReplyService
|
||||
from tasks.annotation.disable_annotation_reply_task import disable_annotation_reply_task
|
||||
from tasks.annotation.enable_annotation_reply_task import enable_annotation_reply_task
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
from tests.helpers.unit.model_factories import make_account, make_app
|
||||
|
||||
_PAYLOAD: dict[str, object] = {
|
||||
"score_threshold": 0.75,
|
||||
"embedding_provider_name": "openai",
|
||||
"embedding_model_name": "text-embedding-3-small",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Harness:
|
||||
app: Flask
|
||||
account: Account
|
||||
target: App
|
||||
other: App
|
||||
factory: sessionmaker[Session]
|
||||
redis: RedisClientWrapper
|
||||
service: AnnotationReplyService
|
||||
celery: Celery
|
||||
tasks: tuple[Task[..., None], ...]
|
||||
queue: str
|
||||
sessions: list[Session]
|
||||
publications: list[bool]
|
||||
|
||||
def request(
|
||||
self,
|
||||
action: AnnotationReplyAction,
|
||||
*,
|
||||
app_id: str | None = None,
|
||||
job_id: str | None = None,
|
||||
) -> TestResponse:
|
||||
client = self.app.test_client()
|
||||
token = generate_csrf_token(self.account.id)
|
||||
headers = {
|
||||
HEADER_NAME_CSRF_TOKEN: token,
|
||||
"Authorization": f"Bearer {PassportService().issue({'user_id': self.account.id})}",
|
||||
}
|
||||
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, token)
|
||||
path = f"/console/api/apps/{app_id or self.target.id}/annotation-reply/{action}"
|
||||
if job_id is None:
|
||||
response = client.post(path, json=_PAYLOAD, headers=headers)
|
||||
else:
|
||||
response = client.get(f"{path}/status/{job_id}", headers=headers)
|
||||
assert response.headers["Content-Type"] == "application/json"
|
||||
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
|
||||
app = flask_app_with_containers
|
||||
services = app.extensions["application_services"]
|
||||
assert isinstance(services, ApplicationServices)
|
||||
redis = app.extensions["redis"]
|
||||
assert isinstance(redis, RedisClientWrapper)
|
||||
with app.app_context():
|
||||
factory = sessionmaker(bind=db.engine, expire_on_commit=False)
|
||||
workspace = Tenant(name="Annotation reply workspace")
|
||||
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
|
||||
account.last_active_at = naive_utc_now()
|
||||
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
with factory.begin() as session:
|
||||
session.add_all(
|
||||
[
|
||||
workspace,
|
||||
account,
|
||||
target,
|
||||
other,
|
||||
TenantAccountJoin(
|
||||
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
|
||||
),
|
||||
DifySetup(version="test"),
|
||||
]
|
||||
)
|
||||
queue = f"annotation-reply-{uuid4()}"
|
||||
celery = Celery(queue, broker="memory://", set_as_current=False)
|
||||
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
|
||||
tasks = (
|
||||
celery.task(name=enable_annotation_reply_task.name, shared=False)(enable_annotation_reply_task.run),
|
||||
celery.task(name=disable_annotation_reply_task.name, shared=False)(disable_annotation_reply_task.run),
|
||||
)
|
||||
service = AnnotationReplyService(
|
||||
apps=AnnotationRepository(session_factory=factory),
|
||||
jobs=RedisAnnotationReplyJobRepository(redis=redis),
|
||||
enable_task=tasks[0].delay,
|
||||
disable_task=tasks[1].delay,
|
||||
)
|
||||
app.extensions["application_services"] = replace(services, annotation_reply=service)
|
||||
sessions: list[Session] = []
|
||||
publications: list[bool] = []
|
||||
|
||||
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
|
||||
sessions.append(session)
|
||||
|
||||
def observe_publish(**_kwargs: object) -> None:
|
||||
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
|
||||
|
||||
event.listen(Session, "after_begin", track)
|
||||
before_task_publish.connect(observe_publish, weak=True)
|
||||
_is_setup_completed.reset_success()
|
||||
try:
|
||||
with config_overrides_context(
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
|
||||
SECRET_KEY="annotation-reply-passport-test-key-32-bytes",
|
||||
LOGIN_DISABLED=False,
|
||||
INIT_PASSWORD="",
|
||||
CONSOLE_API_URL="http://localhost",
|
||||
CONSOLE_WEB_URL="http://localhost",
|
||||
COOKIE_DOMAIN="",
|
||||
RBAC_ENABLED=False,
|
||||
):
|
||||
with app.app_context():
|
||||
assert _is_setup_completed()
|
||||
db.session.remove()
|
||||
yield _Harness(
|
||||
app, account, target, other, factory, redis, service, celery, tasks, queue, sessions, publications
|
||||
)
|
||||
finally:
|
||||
app.extensions["application_services"] = services
|
||||
del observe_publish
|
||||
event.remove(Session, "after_begin", track)
|
||||
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
|
||||
messages.clear()
|
||||
celery.close()
|
||||
_is_setup_completed.reset_success()
|
||||
with app.app_context():
|
||||
db.session.remove()
|
||||
|
||||
|
||||
def _consume_task(harness: _Harness, action: AnnotationReplyAction, job_id: str) -> None:
|
||||
expected: dict[str, object] = {
|
||||
"job_id": job_id,
|
||||
"app_id": harness.target.id,
|
||||
"tenant_id": harness.target.tenant_id,
|
||||
}
|
||||
if action == "enable":
|
||||
expected.update(_PAYLOAD, user_id=harness.account.id)
|
||||
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
|
||||
message = messages.get(block=False)
|
||||
assert message.headers["task"] == harness.tasks[0 if action == "enable" else 1].name
|
||||
assert message.payload[0] == []
|
||||
assert message.payload[1] == expected
|
||||
message.ack()
|
||||
with pytest.raises(Empty):
|
||||
messages.get(block=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
@pytest.mark.parametrize("role", [TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR])
|
||||
def test_reply_actions_publish_scoped_task_after_sql_sessions_close(
|
||||
harness: _Harness, action: AnnotationReplyAction, role: TenantAccountRole
|
||||
) -> None:
|
||||
with harness.factory.begin() as session:
|
||||
session.execute(
|
||||
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(role=role)
|
||||
)
|
||||
|
||||
response = harness.request(action)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
job_id = body["job_id"]
|
||||
assert str(UUID(job_id)) == job_id
|
||||
assert body == {"job_id": job_id, "job_status": "waiting"}
|
||||
assert harness.redis.get(f"{action}_app_annotation_job_{job_id}") == b"waiting"
|
||||
assert harness.redis.get(annotation_reply_job_owner_key(action=action, job_id=job_id)) == (
|
||||
f"{harness.target.tenant_id}:{harness.target.id}".encode()
|
||||
)
|
||||
assert harness.publications == [True]
|
||||
_consume_task(harness, action, job_id)
|
||||
status = harness.request(action, job_id=job_id)
|
||||
assert status.status_code == 200
|
||||
assert status.get_json() == {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_cached_owned_job_returns_decoded_identifier_without_duplicate_publish(
|
||||
harness: _Harness, action: AnnotationReplyAction
|
||||
) -> None:
|
||||
started = harness.request(action).get_json()
|
||||
job_id = started["job_id"]
|
||||
_consume_task(harness, action, job_id)
|
||||
|
||||
response = harness.request(action)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"job_id": job_id, "job_status": "processing"}
|
||||
assert harness.publications == [True]
|
||||
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
|
||||
with pytest.raises(Empty):
|
||||
messages.get(block=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
@pytest.mark.parametrize("mismatch", ["app", "tenant", "action", "legacy", "missing"])
|
||||
def test_job_status_rejects_missing_or_unverifiable_ownership(
|
||||
harness: _Harness, action: AnnotationReplyAction, mismatch: Literal["app", "tenant", "action", "legacy", "missing"]
|
||||
) -> None:
|
||||
job_id = str(uuid4())
|
||||
requested_app = harness.target.id
|
||||
stored_action: AnnotationReplyAction = (
|
||||
("disable" if action == "enable" else "enable") if mismatch == "action" else action
|
||||
)
|
||||
if mismatch != "missing":
|
||||
harness.redis.set(f"{stored_action}_app_annotation_job_{job_id}", "completed")
|
||||
if mismatch not in {"legacy", "missing"}:
|
||||
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
|
||||
harness.redis.set(
|
||||
annotation_reply_job_owner_key(action=stored_action, job_id=job_id),
|
||||
f"{tenant_id}:{harness.target.id}",
|
||||
)
|
||||
if mismatch == "app":
|
||||
requested_app = harness.other.id
|
||||
|
||||
response = harness.request(action, app_id=requested_app, job_id=job_id)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["code"] == "not_found"
|
||||
assert response.get_json()["message"] == "The job does not exist."
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
@pytest.mark.parametrize(
|
||||
("status", "error", "expected"),
|
||||
[("error", "Provider unavailable", "Provider unavailable"), ("error", None, ""), ("completed", "Old error", "")],
|
||||
)
|
||||
def test_status_preserves_worker_error_and_handles_expired_error_key(
|
||||
harness: _Harness, action: AnnotationReplyAction, status: str, error: str | None, expected: str
|
||||
) -> None:
|
||||
body = harness.request(action).get_json()
|
||||
job_id = body["job_id"]
|
||||
harness.redis.set(f"{action}_app_annotation_job_{job_id}", status)
|
||||
if error is not None:
|
||||
harness.redis.set(f"{action}_app_annotation_error_{job_id}", error)
|
||||
|
||||
response = harness.request(action, job_id=job_id)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"job_id": job_id, "job_status": status, "error_msg": expected}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_concurrent_caller_can_poll_publication_failure_and_retry(
|
||||
harness: _Harness, action: AnnotationReplyAction
|
||||
) -> None:
|
||||
task = harness.tasks[0 if action == "enable" else 1]
|
||||
task.serializer = "not-installed"
|
||||
vars(task).pop("_exec_options", None)
|
||||
publishing = Event()
|
||||
resume_publication = Event()
|
||||
|
||||
def pause_publication(**_kwargs: object) -> None:
|
||||
publishing.set()
|
||||
assert resume_publication.wait(timeout=10)
|
||||
|
||||
def start_job() -> None:
|
||||
if action == "enable":
|
||||
harness.service.enable(
|
||||
tenant_id=harness.target.tenant_id,
|
||||
app_id=harness.target.id,
|
||||
account_id=harness.account.id,
|
||||
score_threshold=0.75,
|
||||
embedding_provider_name="openai",
|
||||
embedding_model_name="text-embedding-3-small",
|
||||
)
|
||||
else:
|
||||
harness.service.disable(tenant_id=harness.target.tenant_id, app_id=harness.target.id)
|
||||
|
||||
# Pause the real publisher after reservation, then let its serializer fail.
|
||||
before_task_publish.connect(pause_publication, sender=task.name, weak=True)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
first = executor.submit(start_job)
|
||||
try:
|
||||
assert publishing.wait(timeout=10)
|
||||
response = harness.request(action)
|
||||
assert response.status_code == 200
|
||||
job_id = response.get_json()["job_id"]
|
||||
assert response.get_json() == {"job_id": job_id, "job_status": "processing"}
|
||||
pending = harness.request(action, job_id=job_id)
|
||||
assert pending.status_code == 200
|
||||
assert pending.get_json()["job_status"] == "waiting"
|
||||
assert not first.done()
|
||||
finally:
|
||||
resume_publication.set()
|
||||
with pytest.raises(SerializerNotInstalled) as error:
|
||||
first.result(timeout=10)
|
||||
finally:
|
||||
del pause_publication
|
||||
task.serializer = "json"
|
||||
# Celery caches publication options on the first delay(), including a failed attempt.
|
||||
vars(task).pop("_exec_options", None)
|
||||
|
||||
status = harness.request(action, job_id=job_id)
|
||||
assert status.status_code == 200
|
||||
assert status.get_json() == {"job_id": job_id, "job_status": "error", "error_msg": str(error.value)}
|
||||
for key in (
|
||||
annotation_reply_job_owner_key(action=action, job_id=job_id),
|
||||
f"{action}_app_annotation_job_{job_id}",
|
||||
f"{action}_app_annotation_error_{job_id}",
|
||||
):
|
||||
assert 0 < harness.redis.ttl(key) <= 600
|
||||
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") is None
|
||||
assert harness.publications == [True]
|
||||
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
|
||||
with pytest.raises(Empty):
|
||||
messages.get(block=False)
|
||||
|
||||
response = harness.request(action)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["job_status"] == "waiting"
|
||||
assert response.get_json()["job_id"] != job_id
|
||||
_consume_task(harness, action, response.get_json()["job_id"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_concurrent_requests_publish_only_one_reply_task(harness: _Harness, action: AnnotationReplyAction) -> None:
|
||||
barrier = Barrier(8)
|
||||
|
||||
def request() -> str:
|
||||
barrier.wait(timeout=10)
|
||||
if action == "enable":
|
||||
result = harness.service.enable(
|
||||
tenant_id=harness.target.tenant_id,
|
||||
app_id=harness.target.id,
|
||||
account_id=harness.account.id,
|
||||
score_threshold=0.75,
|
||||
embedding_provider_name="openai",
|
||||
embedding_model_name="text-embedding-3-small",
|
||||
)
|
||||
else:
|
||||
result = harness.service.disable(tenant_id=harness.target.tenant_id, app_id=harness.target.id)
|
||||
return result.job_id
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
futures = [executor.submit(request) for _ in range(8)]
|
||||
job_ids = [future.result() for future in futures]
|
||||
|
||||
assert len(set(job_ids)) == 1
|
||||
_consume_task(harness, action, job_ids[0])
|
||||
|
||||
|
||||
def _run_worker(harness: _Harness, action: AnnotationReplyAction, job_id: str) -> None:
|
||||
with harness.app.app_context():
|
||||
if action == "enable":
|
||||
enable_annotation_reply_task.run(
|
||||
job_id,
|
||||
harness.target.id,
|
||||
harness.account.id,
|
||||
harness.target.tenant_id,
|
||||
0.75,
|
||||
"openai",
|
||||
"text-embedding-3-small",
|
||||
)
|
||||
else:
|
||||
disable_annotation_reply_task.run(job_id, harness.target.id, harness.target.tenant_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_finished_worker_releases_its_reservation(harness: _Harness, action: AnnotationReplyAction) -> None:
|
||||
if action == "disable":
|
||||
with harness.factory.begin() as session:
|
||||
session.add(
|
||||
AppAnnotationSetting(
|
||||
app_id=harness.target.id,
|
||||
score_threshold=0.75,
|
||||
collection_binding_id=str(uuid4()),
|
||||
created_user_id=harness.account.id,
|
||||
updated_user_id=harness.account.id,
|
||||
)
|
||||
)
|
||||
started = harness.request(action).get_json()
|
||||
job_id = started["job_id"]
|
||||
_consume_task(harness, action, job_id)
|
||||
|
||||
_run_worker(harness, action, job_id)
|
||||
|
||||
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") is None
|
||||
response = harness.request(action, job_id=job_id)
|
||||
assert response.get_json() == {"job_id": job_id, "job_status": "completed", "error_msg": ""}
|
||||
assert 0 < harness.redis.ttl(annotation_reply_job_owner_key(action=action, job_id=job_id)) <= 600
|
||||
with harness.factory() as session:
|
||||
setting = session.scalar(select(AppAnnotationSetting).where(AppAnnotationSetting.app_id == harness.target.id))
|
||||
assert (setting is not None) == (action == "enable")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_early_returning_old_worker_does_not_release_new_reservation(
|
||||
harness: _Harness, action: AnnotationReplyAction
|
||||
) -> None:
|
||||
started = harness.request(action).get_json()
|
||||
old_job_id = started["job_id"]
|
||||
_consume_task(harness, action, old_job_id)
|
||||
harness.redis.expire(f"{action}_app_annotation_{harness.target.id}", 0)
|
||||
current = harness.request(action).get_json()
|
||||
_consume_task(harness, action, current["job_id"])
|
||||
if action == "enable":
|
||||
with harness.factory.begin() as session:
|
||||
session.execute(delete(App).where(App.id == harness.target.id))
|
||||
|
||||
_run_worker(harness, action, old_job_id)
|
||||
|
||||
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") == current["job_id"].encode()
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"""Integration coverage for console app endpoints that require real persistence boundaries."""
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.model import AppMode
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path_template",
|
||||
[
|
||||
"/console/api/apps/{app_id}/trace-config?tracing_provider=langfuse",
|
||||
"/console/api/apps/{app_id}/trace",
|
||||
],
|
||||
)
|
||||
def test_trace_endpoints_hide_apps_from_other_tenants(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
path_template: str,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_app = create_console_app(
|
||||
db_session_with_containers,
|
||||
tenant_id=foreign_tenant.id,
|
||||
account_id=foreign_account.id,
|
||||
mode=AppMode.CHAT,
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
path_template.format(app_id=foreign_app.id),
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
"""App detail responses must not write masked configuration back to storage."""
|
||||
|
||||
import json
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.model import AppMode, AppModelConfig
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def test_put_app_detail_preserves_agent_tool_secret_after_commit(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.AGENT_CHAT)
|
||||
agent_mode = {
|
||||
"enabled": True,
|
||||
"strategy": "react",
|
||||
"tools": [
|
||||
{
|
||||
"provider_type": "api",
|
||||
"provider_id": "00000000-0000-0000-0000-000000000001",
|
||||
"tool_name": "private_tool",
|
||||
"tool_parameters": {"api_key": "encrypted-secret"},
|
||||
}
|
||||
],
|
||||
}
|
||||
config = AppModelConfig(app_id=app.id, agent_mode=json.dumps(agent_mode))
|
||||
db_session_with_containers.add(config)
|
||||
db_session_with_containers.flush()
|
||||
app.app_model_config_id = config.id
|
||||
db_session_with_containers.commit()
|
||||
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
response = test_client_with_containers.put(
|
||||
f"/console/api/apps/{app.id}",
|
||||
headers=headers,
|
||||
json={"name": "Updated App"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json is not None
|
||||
assert response.json["model_config"]["agent_mode"]["tools"][0]["tool_parameters"] != {"api_key": "encrypted-secret"}
|
||||
with Session(db_session_with_containers.get_bind()) as reread_session:
|
||||
persisted = reread_session.get(AppModelConfig, config.id)
|
||||
assert persisted is not None
|
||||
assert persisted.agent_mode is not None
|
||||
assert json.loads(persisted.agent_mode) == agent_mode
|
||||
|
||||
|
||||
def test_get_and_put_app_detail_preserve_historical_agent_mode_without_tools(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.AGENT_CHAT)
|
||||
agent_mode = {"enabled": True, "max_iteration": 5, "strategy": "function_call"}
|
||||
config = AppModelConfig(app_id=app.id, agent_mode=json.dumps(agent_mode))
|
||||
db_session_with_containers.add(config)
|
||||
db_session_with_containers.flush()
|
||||
app.app_model_config_id = config.id
|
||||
db_session_with_containers.commit()
|
||||
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
get_response = test_client_with_containers.get(f"/console/api/apps/{app.id}", headers=headers)
|
||||
assert get_response.status_code == 200
|
||||
assert get_response.json is not None
|
||||
assert get_response.json["model_config"]["agent_mode"] == agent_mode
|
||||
|
||||
put_response = test_client_with_containers.put(
|
||||
f"/console/api/apps/{app.id}", headers=headers, json={"name": "Updated App"}
|
||||
)
|
||||
assert put_response.status_code == 200
|
||||
assert put_response.json is not None
|
||||
assert put_response.json["model_config"]["agent_mode"] == agent_mode
|
||||
|
||||
with Session(db_session_with_containers.get_bind()) as reread_session:
|
||||
persisted = reread_session.get(AppModelConfig, config.id)
|
||||
assert persisted is not None
|
||||
assert persisted.agent_mode == json.dumps(agent_mode)
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
"""TestContainers integration tests for ChatConversationApi status_count behavior."""
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from constants import HEADER_NAME_CSRF_TOKEN
|
||||
from extensions.ext_application_services import application_services
|
||||
from graphon.enums import WorkflowExecutionStatus
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.token import _real_cookie_name, generate_csrf_token
|
||||
from models import Account, Tenant, TenantAccountJoin
|
||||
from models.account import AccountStatus, TenantAccountRole, TenantStatus
|
||||
from models.enums import ConversationFromSource, CreatorUserRole
|
||||
from models.model import App, AppMode, Conversation, Message
|
||||
from models.workflow import WorkflowRun
|
||||
from models.workflow import WorkflowType as ModelWorkflowType
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import ensure_dify_setup
|
||||
|
||||
|
||||
def _create_account_and_tenant(db_session: Session) -> tuple[Account, Tenant]:
|
||||
account = Account(
|
||||
email=f"test-{uuid.uuid4()}@example.com",
|
||||
name="Test User",
|
||||
interface_language="en-US",
|
||||
status=AccountStatus.ACTIVE,
|
||||
)
|
||||
account.initialized_at = naive_utc_now()
|
||||
db_session.add(account)
|
||||
db_session.commit()
|
||||
|
||||
tenant = Tenant(name="Test Tenant", status=TenantStatus.NORMAL)
|
||||
db_session.add(tenant)
|
||||
db_session.commit()
|
||||
|
||||
join = TenantAccountJoin(
|
||||
tenant_id=tenant.id,
|
||||
account_id=account.id,
|
||||
role=TenantAccountRole.OWNER,
|
||||
current=True,
|
||||
)
|
||||
db_session.add(join)
|
||||
db_session.commit()
|
||||
|
||||
account.set_tenant_id_with_session(tenant.id, session=db_session)
|
||||
account.timezone = "UTC"
|
||||
db_session.commit()
|
||||
|
||||
ensure_dify_setup(db_session)
|
||||
|
||||
return account, tenant
|
||||
|
||||
|
||||
def _create_app(db_session: Session, tenant_id: str, account_id: str) -> App:
|
||||
app = App(
|
||||
tenant_id=tenant_id,
|
||||
name="Test Chat App",
|
||||
mode=AppMode.CHAT,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
created_by=account_id,
|
||||
)
|
||||
db_session.add(app)
|
||||
db_session.commit()
|
||||
return app
|
||||
|
||||
|
||||
def _create_conversation(db_session: Session, app_id: str, account_id: str) -> Conversation:
|
||||
conversation = Conversation(
|
||||
app_id=app_id,
|
||||
name="Test Conversation",
|
||||
_inputs={},
|
||||
status="normal",
|
||||
mode=AppMode.CHAT,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account_id,
|
||||
)
|
||||
db_session.add(conversation)
|
||||
db_session.commit()
|
||||
return conversation
|
||||
|
||||
|
||||
def _create_workflow_run(db_session: Session, app_id: str, tenant_id: str, account_id: str) -> WorkflowRun:
|
||||
workflow_run = WorkflowRun(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=str(uuid.uuid4()),
|
||||
type=ModelWorkflowType("chat"),
|
||||
triggered_from="app-run",
|
||||
version="1.0.0",
|
||||
graph=json.dumps({"nodes": [], "edges": []}),
|
||||
inputs=json.dumps({"query": "test"}),
|
||||
status=WorkflowExecutionStatus.PAUSED,
|
||||
outputs=json.dumps({}),
|
||||
elapsed_time=0.0,
|
||||
total_tokens=0,
|
||||
total_steps=0,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=account_id,
|
||||
)
|
||||
workflow_run.created_at = naive_utc_now()
|
||||
db_session.add(workflow_run)
|
||||
db_session.commit()
|
||||
return workflow_run
|
||||
|
||||
|
||||
def _create_message(
|
||||
db_session: Session, app_id: str, conversation_id: str, workflow_run_id: str, account_id: str
|
||||
) -> Message:
|
||||
message = Message(
|
||||
app_id=app_id,
|
||||
conversation_id=conversation_id,
|
||||
query="Hello",
|
||||
message={"type": "text", "content": "Hello"},
|
||||
answer="Hi there",
|
||||
message_tokens=1,
|
||||
answer_tokens=1,
|
||||
message_unit_price=0.001,
|
||||
answer_unit_price=0.001,
|
||||
message_price_unit=0.001,
|
||||
answer_price_unit=0.001,
|
||||
currency="USD",
|
||||
status="normal",
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account_id,
|
||||
workflow_run_id=workflow_run_id,
|
||||
_inputs={"query": "Hello"},
|
||||
)
|
||||
db_session.add(message)
|
||||
db_session.commit()
|
||||
return message
|
||||
|
||||
|
||||
def test_chat_conversation_status_count_includes_paused(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
):
|
||||
account, tenant = _create_account_and_tenant(db_session_with_containers)
|
||||
app = _create_app(db_session_with_containers, tenant.id, account.id)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id)
|
||||
conversation_id = conversation.id
|
||||
workflow_run = _create_workflow_run(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, workflow_run.id, account.id)
|
||||
|
||||
access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_token
|
||||
csrf_token = generate_csrf_token(account.id)
|
||||
cookie_name = _real_cookie_name("csrf_token")
|
||||
|
||||
test_client_with_containers.set_cookie(cookie_name, csrf_token, domain="localhost")
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/chat-conversations",
|
||||
headers={
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
HEADER_NAME_CSRF_TOKEN: csrf_token,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["total"] == 1
|
||||
assert payload["data"][0]["id"] == conversation_id
|
||||
assert payload["data"][0]["status_count"]["paused"] == 1
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
"""Execute Console read-marker writes against PostgreSQL without replacing the clock."""
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from machinery.context import RequestContext
|
||||
from models.enums import ConversationFromSource, ConversationStatus
|
||||
from models.model import AppMode, Conversation
|
||||
from repositories.conversation_repository import ConversationRepository
|
||||
from services.errors.conversation import ConversationNotExistsError
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def test_console_detail_then_mark_preserves_updated_at_and_the_first_reader(
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
original_updated_at = datetime(2020, 2, 8)
|
||||
conversation = Conversation(
|
||||
app_id=app.id,
|
||||
name="read timestamp test",
|
||||
_inputs={},
|
||||
status=ConversationStatus.NORMAL,
|
||||
mode=AppMode.CHAT,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account.id,
|
||||
)
|
||||
conversation.updated_at = original_updated_at
|
||||
db_session_with_containers.add(conversation)
|
||||
db_session_with_containers.commit()
|
||||
context = RequestContext(
|
||||
request_id="postgres-read", trace_id=None, account_id=account.id, active_workspace_id=tenant.id
|
||||
)
|
||||
app_id, conversation_id = app.id, conversation.id
|
||||
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
|
||||
db_session_with_containers.rollback()
|
||||
repository = ConversationRepository(session_factory=sessions)
|
||||
|
||||
loaded = repository.get_console_detail(context, app_id, conversation_id, kind="chat")
|
||||
assert loaded.record.id == conversation_id
|
||||
with sessions() as session:
|
||||
stored = session.get_one(Conversation, conversation_id)
|
||||
assert stored.read_at is None
|
||||
assert stored.read_account_id is None
|
||||
assert stored.updated_at == original_updated_at
|
||||
|
||||
before = naive_utc_now()
|
||||
repository.mark_console_read(context, app_id, conversation_id, kind="chat")
|
||||
after = naive_utc_now()
|
||||
with sessions() as session:
|
||||
stored = session.get_one(Conversation, conversation_id)
|
||||
first_read_at = stored.read_at
|
||||
assert first_read_at is not None
|
||||
assert before <= first_read_at <= after
|
||||
assert stored.read_account_id == context.account_id
|
||||
assert stored.updated_at == original_updated_at
|
||||
|
||||
second_reader = context._replace(account_id=str(uuid4()))
|
||||
repository.mark_console_read(second_reader, app_id, conversation_id, kind="chat")
|
||||
with sessions() as session:
|
||||
stored = session.get_one(Conversation, conversation_id)
|
||||
assert stored.read_at == first_read_at
|
||||
assert stored.read_account_id == context.account_id
|
||||
assert stored.updated_at == original_updated_at
|
||||
|
||||
|
||||
def test_console_missing_detail_or_mark_does_not_mark_another_conversation(
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = Conversation(
|
||||
app_id=app.id,
|
||||
name="Untouched conversation",
|
||||
_inputs={},
|
||||
mode=AppMode.CHAT,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account.id,
|
||||
)
|
||||
db_session_with_containers.add(conversation)
|
||||
db_session_with_containers.commit()
|
||||
context = RequestContext(
|
||||
request_id="postgres-read", trace_id=None, account_id=account.id, active_workspace_id=tenant.id
|
||||
)
|
||||
app_id, conversation_id = app.id, conversation.id
|
||||
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
|
||||
db_session_with_containers.rollback()
|
||||
repository = ConversationRepository(session_factory=sessions)
|
||||
missing_id = str(uuid4())
|
||||
with pytest.raises(ConversationNotExistsError):
|
||||
repository.get_console_detail(context, app_id, missing_id, kind="chat")
|
||||
with pytest.raises(ConversationNotExistsError):
|
||||
repository.mark_console_read(context, app_id, missing_id, kind="chat")
|
||||
with sessions() as session:
|
||||
stored = session.get_one(Conversation, conversation_id)
|
||||
assert stored.read_at is None
|
||||
assert stored.read_account_id is None
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
"""Authenticated controller integration tests for console message APIs."""
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.console.app.message import AppMessageFeedbackPayload, ChatMessagesQuery
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from models.enums import ConversationFromSource, ConversationStatus, FeedbackRating
|
||||
from models.model import AppMode, AppModelConfig, Conversation, Message, MessageAnnotation, MessageFeedback
|
||||
from models.provider import Provider
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def _create_conversation(db_session: Session, app_id: str, account_id: str, mode: AppMode) -> Conversation:
|
||||
conversation = Conversation(
|
||||
app_id=app_id,
|
||||
app_model_config_id=None,
|
||||
model_provider=None,
|
||||
model_id="",
|
||||
override_model_configs=None,
|
||||
mode=mode,
|
||||
name="Test Conversation",
|
||||
_inputs={},
|
||||
introduction="",
|
||||
system_instruction="",
|
||||
system_instruction_tokens=0,
|
||||
status=ConversationStatus.NORMAL,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account_id,
|
||||
)
|
||||
db_session.add(conversation)
|
||||
db_session.commit()
|
||||
return conversation
|
||||
|
||||
|
||||
def _create_message(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
conversation_id: str,
|
||||
account_id: str,
|
||||
*,
|
||||
created_at_offset_seconds: int = 0,
|
||||
) -> Message:
|
||||
created_at = naive_utc_now() + timedelta(seconds=created_at_offset_seconds)
|
||||
message = Message(
|
||||
app_id=app_id,
|
||||
model_provider=None,
|
||||
model_id="",
|
||||
override_model_configs=None,
|
||||
conversation_id=conversation_id,
|
||||
_inputs={},
|
||||
query="Hello",
|
||||
message={"type": "text", "content": "Hello"},
|
||||
message_tokens=1,
|
||||
message_unit_price=Decimal("0.0001"),
|
||||
message_price_unit=Decimal("0.001"),
|
||||
answer="Hi there",
|
||||
answer_tokens=1,
|
||||
answer_unit_price=Decimal("0.0001"),
|
||||
answer_price_unit=Decimal("0.001"),
|
||||
parent_message_id=None,
|
||||
provider_response_latency=0,
|
||||
total_price=Decimal("0.0002"),
|
||||
currency="USD",
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account_id,
|
||||
app_mode=AppMode.CHAT,
|
||||
)
|
||||
message.created_at = created_at
|
||||
message.updated_at = created_at
|
||||
db_session.add(message)
|
||||
db_session.commit()
|
||||
return message
|
||||
|
||||
|
||||
class TestMessageValidators:
|
||||
def test_chat_messages_query_validators(self) -> None:
|
||||
assert ChatMessagesQuery.empty_to_none("") is None
|
||||
assert ChatMessagesQuery.empty_to_none("val") == "val"
|
||||
assert ChatMessagesQuery.validate_uuid(None) is None
|
||||
assert (
|
||||
ChatMessagesQuery.validate_uuid("123e4567-e89b-12d3-a456-426614174000")
|
||||
== "123e4567-e89b-12d3-a456-426614174000"
|
||||
)
|
||||
|
||||
def test_message_feedback_validators(self) -> None:
|
||||
assert (
|
||||
AppMessageFeedbackPayload.validate_message_id("123e4567-e89b-12d3-a456-426614174000")
|
||||
== "123e4567-e89b-12d3-a456-426614174000"
|
||||
)
|
||||
|
||||
|
||||
def test_chat_message_list_not_found(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/chat-messages",
|
||||
query_string={"conversation_id": str(uuid4())},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "not_found"
|
||||
|
||||
|
||||
def test_chat_message_list_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, account.id, created_at_offset_seconds=0)
|
||||
second = _create_message(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
conversation.id,
|
||||
account.id,
|
||||
created_at_offset_seconds=1,
|
||||
)
|
||||
# Capture IDs before the HTTP request detaches ORM instances from the session
|
||||
app_id = app.id
|
||||
conversation_id = conversation.id
|
||||
second_id = second.id
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app_id}/chat-messages",
|
||||
query_string={"conversation_id": conversation_id, "limit": 1},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["limit"] == 1
|
||||
assert payload["has_more"] is True
|
||||
assert len(payload["data"]) == 1
|
||||
assert payload["data"][0]["id"] == second_id
|
||||
|
||||
|
||||
def test_message_feedback_not_found(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
f"/console/api/apps/{app.id}/feedbacks",
|
||||
json={"message_id": str(uuid4()), "rating": "like"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "not_found"
|
||||
|
||||
|
||||
def test_message_feedback_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
|
||||
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
f"/console/api/apps/{app.id}/feedbacks",
|
||||
json={"message_id": message.id, "rating": "like"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"result": "success"}
|
||||
|
||||
feedback = db_session_with_containers.scalar(
|
||||
select(MessageFeedback).where(MessageFeedback.message_id == message.id)
|
||||
)
|
||||
assert feedback is not None
|
||||
assert feedback.rating == FeedbackRating.LIKE
|
||||
assert feedback.from_account_id == account.id
|
||||
|
||||
|
||||
def test_message_annotation_count(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
|
||||
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
|
||||
db_session_with_containers.add(
|
||||
MessageAnnotation(
|
||||
app_id=app.id,
|
||||
conversation_id=conversation.id,
|
||||
message_id=message.id,
|
||||
question="Q",
|
||||
content="A",
|
||||
account_id=account.id,
|
||||
)
|
||||
)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/annotations/count",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"count": 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("scenario", "expected_status", "expected_code"),
|
||||
[
|
||||
("invalid-provider", 200, None),
|
||||
("missing-message", 404, "not_found"),
|
||||
("other-account", 404, "not_found"),
|
||||
("deleted-conversation", 404, "not_found"),
|
||||
("disabled", 403, "app_suggested_questions_after_answer_disabled"),
|
||||
("broken-config", 500, "internal_server_error"),
|
||||
],
|
||||
)
|
||||
def test_message_suggested_questions_with_persisted_configuration(
|
||||
scenario: str,
|
||||
expected_status: int,
|
||||
expected_code: str | None,
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
session = db_session_with_containers
|
||||
account, tenant = create_console_account_and_tenant(session)
|
||||
app = create_console_app(session, tenant.id, account.id, AppMode.CHAT)
|
||||
config = AppModelConfig(
|
||||
app_id=app.id,
|
||||
suggested_questions_after_answer=(
|
||||
"not json"
|
||||
if scenario == "broken-config"
|
||||
else '{"enabled":false}'
|
||||
if scenario == "disabled"
|
||||
else '{"enabled":true}'
|
||||
),
|
||||
)
|
||||
session.add(config)
|
||||
session.flush()
|
||||
app.app_model_config_id = config.id
|
||||
conversation = _create_conversation(session, app.id, account.id, AppMode.CHAT)
|
||||
conversation.app_model_config_id = config.id
|
||||
message = _create_message(session, app.id, conversation.id, account.id)
|
||||
if scenario == "other-account":
|
||||
message.from_account_id = str(uuid4())
|
||||
elif scenario == "deleted-conversation":
|
||||
conversation.is_deleted = True
|
||||
elif scenario == "invalid-provider":
|
||||
# Real model resolution rejects the stored ID before contacting the daemon.
|
||||
session.add(Provider(tenant_id=tenant.id, provider_name="invalid/provider", is_valid=True))
|
||||
session.commit()
|
||||
message_id = str(uuid4()) if scenario == "missing-message" else message.id
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/chat-messages/{message_id}/suggested-questions",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == expected_status
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
if expected_code is None:
|
||||
assert payload == {"data": []}
|
||||
else:
|
||||
assert payload["code"] == expected_code
|
||||
|
||||
|
||||
def test_message_api_get_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
|
||||
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/messages/{message.id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["id"] == message.id
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
"""Controller integration tests for console statistic routes."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from uuid import uuid4
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from models.enums import ConversationFromSource, ConversationStatus, FeedbackFromSource, FeedbackRating, InvokeFrom
|
||||
from models.model import AppMode, Conversation, Message, MessageFeedback
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def _create_conversation(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
account_id: str,
|
||||
*,
|
||||
mode: AppMode,
|
||||
created_at_offset_days: int = 0,
|
||||
) -> Conversation:
|
||||
created_at = naive_utc_now() + timedelta(days=created_at_offset_days)
|
||||
conversation = Conversation(
|
||||
app_id=app_id,
|
||||
app_model_config_id=None,
|
||||
model_provider=None,
|
||||
model_id="",
|
||||
override_model_configs=None,
|
||||
mode=mode,
|
||||
name="Stats Conversation",
|
||||
_inputs={},
|
||||
introduction="",
|
||||
system_instruction="",
|
||||
system_instruction_tokens=0,
|
||||
status=ConversationStatus.NORMAL,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_account_id=account_id,
|
||||
)
|
||||
conversation.created_at = created_at
|
||||
conversation.updated_at = created_at
|
||||
db_session.add(conversation)
|
||||
db_session.commit()
|
||||
return conversation
|
||||
|
||||
|
||||
def _create_message(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
conversation_id: str,
|
||||
*,
|
||||
from_account_id: str | None,
|
||||
from_end_user_id: str | None = None,
|
||||
message_tokens: int = 1,
|
||||
answer_tokens: int = 1,
|
||||
total_price: Decimal = Decimal("0.01"),
|
||||
provider_response_latency: float = 1.0,
|
||||
created_at_offset_days: int = 0,
|
||||
) -> Message:
|
||||
created_at = naive_utc_now() + timedelta(days=created_at_offset_days)
|
||||
message = Message(
|
||||
app_id=app_id,
|
||||
model_provider=None,
|
||||
model_id="",
|
||||
override_model_configs=None,
|
||||
conversation_id=conversation_id,
|
||||
_inputs={},
|
||||
query="Hello",
|
||||
message={"type": "text", "content": "Hello"},
|
||||
message_tokens=message_tokens,
|
||||
message_unit_price=Decimal("0.001"),
|
||||
message_price_unit=Decimal("0.001"),
|
||||
answer="Hi there",
|
||||
answer_tokens=answer_tokens,
|
||||
answer_unit_price=Decimal("0.001"),
|
||||
answer_price_unit=Decimal("0.001"),
|
||||
parent_message_id=None,
|
||||
provider_response_latency=provider_response_latency,
|
||||
total_price=total_price,
|
||||
currency="USD",
|
||||
invoke_from=InvokeFrom.EXPLORE,
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
from_end_user_id=from_end_user_id,
|
||||
from_account_id=from_account_id,
|
||||
app_mode=AppMode.CHAT,
|
||||
)
|
||||
message.created_at = created_at
|
||||
message.updated_at = created_at
|
||||
db_session.add(message)
|
||||
db_session.commit()
|
||||
return message
|
||||
|
||||
|
||||
def _create_like_feedback(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
conversation_id: str,
|
||||
message_id: str,
|
||||
account_id: str,
|
||||
) -> None:
|
||||
db_session.add(
|
||||
MessageFeedback(
|
||||
app_id=app_id,
|
||||
conversation_id=conversation_id,
|
||||
message_id=message_id,
|
||||
rating=FeedbackRating.LIKE,
|
||||
from_source=FeedbackFromSource.ADMIN,
|
||||
from_account_id=account_id,
|
||||
)
|
||||
)
|
||||
db_session.commit()
|
||||
|
||||
|
||||
def test_daily_message_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/daily-messages",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["message_count"] == 1
|
||||
|
||||
|
||||
def test_daily_conversation_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/daily-conversations",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["conversation_count"] == 1
|
||||
|
||||
|
||||
def test_daily_terminals_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
conversation.id,
|
||||
from_account_id=None,
|
||||
from_end_user_id=str(uuid4()),
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/daily-end-users",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["terminal_count"] == 1
|
||||
|
||||
|
||||
def test_daily_token_cost_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
conversation.id,
|
||||
from_account_id=account.id,
|
||||
message_tokens=40,
|
||||
answer_tokens=60,
|
||||
total_price=Decimal("0.02"),
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/token-costs",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload["data"][0]["token_count"] == 100
|
||||
assert Decimal(payload["data"][0]["total_price"]) == Decimal("0.02")
|
||||
|
||||
|
||||
def test_average_session_interaction_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/average-session-interactions",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["interactions"] == 2.0
|
||||
|
||||
|
||||
def test_user_satisfaction_rate_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
first = _create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
for _ in range(9):
|
||||
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
_create_like_feedback(db_session_with_containers, app.id, conversation.id, first.id, account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/user-satisfaction-rate",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["rate"] == 100.0
|
||||
|
||||
|
||||
def test_average_response_time_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.COMPLETION)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
conversation.id,
|
||||
from_account_id=account.id,
|
||||
provider_response_latency=1.234,
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/average-response-time",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["latency"] == 1234.0
|
||||
|
||||
|
||||
def test_tokens_per_second_statistic(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
_create_message(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
conversation.id,
|
||||
from_account_id=account.id,
|
||||
answer_tokens=31,
|
||||
provider_response_latency=2.0,
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/tokens-per-second",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"][0]["tps"] == 15.5
|
||||
|
||||
|
||||
def test_invalid_time_range(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/daily-messages",
|
||||
query_string={"start": "invalid", "end": "invalid"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["code"] == "invalid_param"
|
||||
assert response.get_json()["message"].startswith("Invalid start time format:")
|
||||
|
||||
|
||||
def test_daily_messages_use_account_timezone_and_exclude_other_apps(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
account.timezone = "Asia/Shanghai"
|
||||
db_session_with_containers.commit()
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
|
||||
for created_at in (
|
||||
datetime(2026, 9, 30, 15, 59), # Before the local start date.
|
||||
datetime(2026, 9, 30, 16), # Local midnight: included.
|
||||
datetime(2026, 10, 1, 15, 59),
|
||||
datetime(2026, 10, 1, 16), # Local end date: excluded.
|
||||
):
|
||||
message = _create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
|
||||
message.created_at = created_at
|
||||
db_session_with_containers.commit()
|
||||
|
||||
other_app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
other_conversation = _create_conversation(db_session_with_containers, other_app.id, account.id, mode=other_app.mode)
|
||||
other_message = _create_message(
|
||||
db_session_with_containers, other_app.id, other_conversation.id, from_account_id=account.id
|
||||
)
|
||||
other_message.created_at = datetime(2026, 10, 1, 8)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/statistics/daily-messages",
|
||||
query_string={"start": "2026-10-01 00:00", "end": "2026-10-02 00:00"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"data": [{"date": "2026-10-01", "message_count": 2}]}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
"""Authenticated controller integration tests for workflow draft variable APIs."""
|
||||
|
||||
import uuid
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.workflow.variable_prefixes import CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID
|
||||
from factories.variable_factory import segment_to_variable
|
||||
from graphon.variables.segments import StringSegment
|
||||
from models import Workflow
|
||||
from models.model import AppMode
|
||||
from models.workflow import WorkflowDraftVariable
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def _create_draft_workflow(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
tenant_id: str,
|
||||
account_id: str,
|
||||
*,
|
||||
environment_variables: list | None = None,
|
||||
conversation_variables: list | None = None,
|
||||
) -> Workflow:
|
||||
workflow = Workflow.new(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
type="workflow",
|
||||
version=Workflow.VERSION_DRAFT,
|
||||
graph='{"nodes": [], "edges": []}',
|
||||
features="{}",
|
||||
created_by=account_id,
|
||||
environment_variables=environment_variables or [],
|
||||
conversation_variables=conversation_variables or [],
|
||||
rag_pipeline_variables=[],
|
||||
)
|
||||
db_session.add(workflow)
|
||||
db_session.commit()
|
||||
return workflow
|
||||
|
||||
|
||||
def _create_node_variable(
|
||||
db_session: Session,
|
||||
app_id: str,
|
||||
user_id: str,
|
||||
*,
|
||||
node_id: str = "node_1",
|
||||
name: str = "test_var",
|
||||
) -> WorkflowDraftVariable:
|
||||
variable = WorkflowDraftVariable.new_node_variable(
|
||||
app_id=app_id,
|
||||
user_id=user_id,
|
||||
node_id=node_id,
|
||||
name=name,
|
||||
value=StringSegment(value="test_value"),
|
||||
node_execution_id=str(uuid.uuid4()),
|
||||
visible=True,
|
||||
editable=True,
|
||||
)
|
||||
db_session.add(variable)
|
||||
db_session.commit()
|
||||
return variable
|
||||
|
||||
|
||||
def _create_system_variable(
|
||||
db_session: Session, app_id: str, user_id: str, name: str = "query"
|
||||
) -> WorkflowDraftVariable:
|
||||
variable = WorkflowDraftVariable.new_sys_variable(
|
||||
app_id=app_id,
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
value=StringSegment(value="system-value"),
|
||||
node_execution_id=str(uuid.uuid4()),
|
||||
editable=True,
|
||||
)
|
||||
db_session.add(variable)
|
||||
db_session.commit()
|
||||
return variable
|
||||
|
||||
|
||||
def _build_environment_variable(name: str, value: str):
|
||||
return segment_to_variable(
|
||||
segment=StringSegment(value=value),
|
||||
selector=[ENVIRONMENT_VARIABLE_NODE_ID, name],
|
||||
name=name,
|
||||
description=f"Environment variable {name}",
|
||||
)
|
||||
|
||||
|
||||
def _build_conversation_variable(name: str, value: str):
|
||||
return segment_to_variable(
|
||||
segment=StringSegment(value=value),
|
||||
selector=[CONVERSATION_VARIABLE_NODE_ID, name],
|
||||
name=name,
|
||||
description=f"Conversation variable {name}",
|
||||
)
|
||||
|
||||
|
||||
def test_workflow_variable_collection_get_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables?page=1&limit=20",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"items": [], "total": 0}
|
||||
|
||||
|
||||
def test_workflow_variable_collection_get_not_exist(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "draft_workflow_not_exist"
|
||||
|
||||
|
||||
def test_workflow_variable_collection_delete(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_node_variable(db_session_with_containers, app.id, account.id)
|
||||
_create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_2", name="other_var")
|
||||
|
||||
response = test_client_with_containers.delete(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
remaining = db_session_with_containers.scalars(
|
||||
select(WorkflowDraftVariable).where(
|
||||
WorkflowDraftVariable.app_id == app.id,
|
||||
WorkflowDraftVariable.user_id == account.id,
|
||||
)
|
||||
).all()
|
||||
assert remaining == []
|
||||
|
||||
|
||||
def test_node_variable_collection_get_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
node_variable = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_123")
|
||||
node_variable_id = node_variable.id
|
||||
_create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_456", name="other")
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/nodes/node_123/variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert [item["id"] for item in payload["items"]] == [node_variable_id]
|
||||
|
||||
|
||||
def test_node_variable_collection_get_invalid_node_id(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/nodes/sys/variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "invalid_param"
|
||||
|
||||
|
||||
def test_node_variable_collection_delete(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
target = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_123")
|
||||
untouched = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_456")
|
||||
target_id = target.id
|
||||
untouched_id = untouched.id
|
||||
|
||||
response = test_client_with_containers.delete(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/nodes/node_123/variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert (
|
||||
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == target_id))
|
||||
is None
|
||||
)
|
||||
assert (
|
||||
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == untouched_id))
|
||||
is not None
|
||||
)
|
||||
|
||||
|
||||
def test_variable_api_get_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["id"] == variable.id
|
||||
assert payload["name"] == "test_var"
|
||||
|
||||
|
||||
def test_variable_api_get_not_found(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables/{uuid.uuid4()}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "not_found"
|
||||
|
||||
|
||||
def test_variable_api_patch_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
|
||||
|
||||
response = test_client_with_containers.patch(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
json={"name": "renamed_var"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["id"] == variable.id
|
||||
assert payload["name"] == "renamed_var"
|
||||
|
||||
refreshed = db_session_with_containers.scalar(
|
||||
select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id)
|
||||
)
|
||||
assert refreshed is not None
|
||||
assert refreshed.name == "renamed_var"
|
||||
|
||||
|
||||
def test_variable_api_delete_success(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
|
||||
|
||||
response = test_client_with_containers.delete(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert (
|
||||
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id))
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_variable_reset_api_put_success_returns_no_content_without_execution(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
|
||||
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
|
||||
|
||||
response = test_client_with_containers.put(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}/reset",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert (
|
||||
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id))
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_conversation_variable_collection_get(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
tenant.id,
|
||||
account.id,
|
||||
conversation_variables=[_build_conversation_variable("session_name", "Alice")],
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/conversation-variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert [item["name"] for item in payload["items"]] == ["session_name"]
|
||||
|
||||
created = db_session_with_containers.scalars(
|
||||
select(WorkflowDraftVariable).where(
|
||||
WorkflowDraftVariable.app_id == app.id,
|
||||
WorkflowDraftVariable.user_id == account.id,
|
||||
WorkflowDraftVariable.node_id == CONVERSATION_VARIABLE_NODE_ID,
|
||||
)
|
||||
).all()
|
||||
assert len(created) == 1
|
||||
|
||||
|
||||
def test_system_variable_collection_get(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
variable = _create_system_variable(db_session_with_containers, app.id, account.id)
|
||||
variable_id = variable.id
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/system-variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert [item["id"] for item in payload["items"]] == [variable_id]
|
||||
|
||||
|
||||
def test_environment_variable_collection_get(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
_create_draft_workflow(
|
||||
db_session_with_containers,
|
||||
app.id,
|
||||
tenant.id,
|
||||
account.id,
|
||||
environment_variables=[_build_environment_variable("api_key", "secret-value")],
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflows/draft/environment-variables",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["items"][0]["name"] == "api_key"
|
||||
assert payload["items"][0]["value"] == "secret-value"
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"""Exercise workflow statistics through console admission and PostgreSQL."""
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from graphon.enums import WorkflowExecutionStatus
|
||||
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
|
||||
from models.model import AppMode
|
||||
from models.workflow import WorkflowRun, WorkflowType
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
def _create_workflow_run(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
app_id: str,
|
||||
created_by: str,
|
||||
created_at: datetime,
|
||||
total_tokens: int,
|
||||
triggered_from: WorkflowRunTriggeredFrom = WorkflowRunTriggeredFrom.APP_RUN,
|
||||
) -> None:
|
||||
run = WorkflowRun(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=str(uuid4()),
|
||||
type=WorkflowType.WORKFLOW,
|
||||
triggered_from=triggered_from,
|
||||
version="1",
|
||||
graph="{}",
|
||||
inputs="{}",
|
||||
status=WorkflowExecutionStatus.SUCCEEDED,
|
||||
total_tokens=total_tokens,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=created_by,
|
||||
)
|
||||
run.created_at = created_at
|
||||
session.add(run)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("endpoint", "metric", "expected"),
|
||||
[
|
||||
("daily-conversations", "runs", 3),
|
||||
("daily-terminals", "terminal_count", 2),
|
||||
("token-costs", "token_count", 60),
|
||||
("average-app-interactions", "interactions", 1.5),
|
||||
],
|
||||
)
|
||||
def test_workflow_statistics_scope_and_local_date_range(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
endpoint: str,
|
||||
metric: str,
|
||||
expected: int | float,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
account.timezone = "Asia/Shanghai"
|
||||
db_session_with_containers.commit()
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
other_app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
|
||||
other_account, other_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
|
||||
for created_by, created_at, tokens in (
|
||||
(account.id, datetime(2026, 9, 30, 16), 10),
|
||||
(account.id, datetime(2026, 10, 1, 8), 20),
|
||||
(other_account.id, datetime(2026, 10, 1, 15, 59), 30),
|
||||
):
|
||||
_create_workflow_run(
|
||||
db_session_with_containers,
|
||||
tenant_id=tenant.id,
|
||||
app_id=app.id,
|
||||
created_by=created_by,
|
||||
created_at=created_at,
|
||||
total_tokens=tokens,
|
||||
)
|
||||
|
||||
# Each decoy is independently excluded by the repository's scope or range.
|
||||
for tenant_id, app_id, triggered_from, created_at in (
|
||||
(tenant.id, other_app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 8)),
|
||||
(other_tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 8)),
|
||||
(tenant.id, app.id, WorkflowRunTriggeredFrom.DEBUGGING, datetime(2026, 10, 1, 8)),
|
||||
(tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 9, 30, 15, 59)),
|
||||
(tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 16)),
|
||||
):
|
||||
_create_workflow_run(
|
||||
db_session_with_containers,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
created_by=account.id,
|
||||
created_at=created_at,
|
||||
total_tokens=100,
|
||||
triggered_from=triggered_from,
|
||||
)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/apps/{app.id}/workflow/statistics/{endpoint}",
|
||||
query_string={"start": "2026-10-01 00:00", "end": "2026-10-02 00:00"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"data": [{"date": "2026-10-01", metric: expected}]}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
"""Controller integration tests for API key data source auth routes."""
|
||||
|
||||
import json
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.source import DataSourceApiKeyAuthBinding
|
||||
from services.auth.errors import DataSourceApiKeyAuthCredentialValidationError
|
||||
from services.data_source.entities.api_key_auth import (
|
||||
DataSourceApiKeyAuthBindingCreate,
|
||||
DataSourceApiKeyAuthCredentials,
|
||||
)
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def test_get_api_key_auth_data_source(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
binding = DataSourceApiKeyAuthBinding(
|
||||
tenant_id=tenant.id,
|
||||
category="api_key",
|
||||
provider="custom_provider",
|
||||
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
|
||||
disabled=False,
|
||||
)
|
||||
foreign_binding = DataSourceApiKeyAuthBinding(
|
||||
tenant_id=foreign_tenant.id,
|
||||
category="api_key",
|
||||
provider="foreign_provider",
|
||||
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
|
||||
disabled=False,
|
||||
)
|
||||
db_session_with_containers.add_all([binding, foreign_binding])
|
||||
db_session_with_containers.commit()
|
||||
authenticate_console_client(test_client_with_containers, foreign_account)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/api-key-auth/data-source",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert len(payload["sources"]) == 1
|
||||
assert payload["sources"][0]["provider"] == "custom_provider"
|
||||
|
||||
|
||||
def test_get_api_key_auth_data_source_empty(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/api-key-auth/data-source",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"sources": []}
|
||||
|
||||
|
||||
def test_create_binding_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant_id = tenant.id
|
||||
payload = {
|
||||
"category": "api_key",
|
||||
"provider": "custom",
|
||||
"credentials": {"auth_type": "bearer", "config": {"api_key": "secret"}},
|
||||
}
|
||||
|
||||
with patch("services.data_source.auth.api_key_service.DataSourceApiKeyAuthService.create_binding") as create_auth:
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/api-key-auth/data-source/binding",
|
||||
json=payload,
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"result": "success"}
|
||||
create_auth.assert_called_once_with(
|
||||
ANY,
|
||||
DataSourceApiKeyAuthBindingCreate(
|
||||
category=payload["category"],
|
||||
provider=payload["provider"],
|
||||
credentials=DataSourceApiKeyAuthCredentials("bearer", "secret", {}),
|
||||
),
|
||||
)
|
||||
assert create_auth.call_args.args[0].active_workspace_id == tenant_id
|
||||
|
||||
|
||||
def test_create_binding_failure(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
|
||||
with patch(
|
||||
"services.data_source.auth.api_key_service.DataSourceApiKeyAuthService.create_binding",
|
||||
side_effect=DataSourceApiKeyAuthCredentialValidationError("Credentials rejected"),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/api-key-auth/data-source/binding",
|
||||
json={
|
||||
"category": "api_key",
|
||||
"provider": "custom",
|
||||
"credentials": {"auth_type": "bearer", "config": {"api_key": "secret"}},
|
||||
},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert payload["code"] == "data_source_api_key_auth_credentials_rejected"
|
||||
assert payload["message"] == "Credentials rejected"
|
||||
|
||||
|
||||
def test_delete_binding_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
binding = DataSourceApiKeyAuthBinding(
|
||||
tenant_id=tenant.id,
|
||||
category="api_key",
|
||||
provider="custom_provider",
|
||||
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
|
||||
disabled=False,
|
||||
)
|
||||
db_session_with_containers.add(binding)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.delete(
|
||||
f"/console/api/api-key-auth/data-source/{binding.id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert (
|
||||
db_session_with_containers.scalar(
|
||||
select(DataSourceApiKeyAuthBinding).where(DataSourceApiKeyAuthBinding.id == binding.id)
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_delete_binding_scopes_to_authenticated_tenant(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_binding = DataSourceApiKeyAuthBinding(
|
||||
tenant_id=foreign_tenant.id,
|
||||
category="api_key",
|
||||
provider="custom_provider",
|
||||
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
|
||||
disabled=False,
|
||||
)
|
||||
db_session_with_containers.add(foreign_binding)
|
||||
db_session_with_containers.commit()
|
||||
foreign_binding_id = foreign_binding.id
|
||||
authenticate_console_client(test_client_with_containers, foreign_account)
|
||||
|
||||
response = test_client_with_containers.delete(
|
||||
f"/console/api/api-key-auth/data-source/{foreign_binding_id}",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert (
|
||||
db_session_with_containers.scalar(
|
||||
select(DataSourceApiKeyAuthBinding).where(DataSourceApiKeyAuthBinding.id == foreign_binding_id)
|
||||
)
|
||||
is not None
|
||||
)
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"""Controller integration tests for console OAuth data source routes."""
|
||||
|
||||
from unittest.mock import MagicMock, create_autospec, patch
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from extensions.ext_application_services import ApplicationServices
|
||||
from models.source import DataSourceOauthBinding
|
||||
from services.data_source.entities.oauth import DataSourceOAuthCallback
|
||||
from services.data_source.oauth_service import InvalidDataSourceOAuthProviderError
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def _services(service: MagicMock) -> MagicMock:
|
||||
services = create_autospec(ApplicationServices, instance=True, spec_set=True)
|
||||
services.data_sources.resolve_oauth.return_value = service
|
||||
return services
|
||||
|
||||
|
||||
def test_get_oauth_url_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant_id = tenant.id
|
||||
current_tenant_id = account.current_tenant_id
|
||||
service = MagicMock()
|
||||
service.start_authorization.return_value = "http://oauth.provider/auth"
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/oauth/data-source/notion",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert tenant_id == current_tenant_id
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"data": "http://oauth.provider/auth"}
|
||||
service.start_authorization.assert_called_once()
|
||||
|
||||
|
||||
def test_get_oauth_url_invalid_provider(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
|
||||
service = MagicMock()
|
||||
services = _services(service)
|
||||
services.data_sources.resolve_oauth.side_effect = InvalidDataSourceOAuthProviderError
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=services,
|
||||
):
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/oauth/data-source/unknown_provider",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.get_json() == {"error": "Invalid provider"}
|
||||
|
||||
|
||||
def test_oauth_callback_successful(test_client_with_containers: FlaskClient) -> None:
|
||||
service = MagicMock()
|
||||
service.complete_callback.return_value = DataSourceOAuthCallback(provider="notion", code="mock_code", error=None)
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/notion?code=mock_code")
|
||||
|
||||
assert response.status_code == 302
|
||||
assert "code=mock_code" in response.location
|
||||
|
||||
|
||||
def test_oauth_callback_missing_code(test_client_with_containers: FlaskClient) -> None:
|
||||
service = MagicMock()
|
||||
service.complete_callback.return_value = DataSourceOAuthCallback(
|
||||
provider="notion", code=None, error="Access denied"
|
||||
)
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/notion")
|
||||
|
||||
assert response.status_code == 302
|
||||
assert "error=Access%20denied" in response.location
|
||||
|
||||
|
||||
def test_oauth_callback_invalid_provider(test_client_with_containers: FlaskClient) -> None:
|
||||
service = MagicMock()
|
||||
services = _services(service)
|
||||
services.data_sources.resolve_oauth.side_effect = InvalidDataSourceOAuthProviderError
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=services,
|
||||
):
|
||||
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/invalid?code=mock_code")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.get_json() == {"error": "Invalid provider"}
|
||||
|
||||
|
||||
def test_get_binding_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/oauth/data-source/binding/notion?code=auth_code_123",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"result": "success"}
|
||||
service.bind.assert_called_once()
|
||||
|
||||
|
||||
def test_get_binding_missing_code(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/oauth/data-source/binding/notion?code=",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.get_json() == {"error": "Invalid code"}
|
||||
|
||||
|
||||
def test_sync_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
binding = DataSourceOauthBinding(
|
||||
tenant_id=tenant.id,
|
||||
access_token="test-access-token",
|
||||
provider="notion",
|
||||
source_info={"workspace_name": "Workspace", "workspace_icon": None, "workspace_id": tenant.id, "pages": []},
|
||||
disabled=False,
|
||||
)
|
||||
db_session_with_containers.add(binding)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
service = MagicMock()
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/oauth/data-source/notion/{binding.id}/sync",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"result": "success"}
|
||||
service.sync.assert_called_once()
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
"""Controller integration tests for console OAuth server routes."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from services.entities.oauth_server_entities import (
|
||||
OAuthAuthorizationCode,
|
||||
OAuthProviderAccount,
|
||||
OAuthProviderAppPresentation,
|
||||
OAuthTokenSet,
|
||||
)
|
||||
from services.oauth_server_service import (
|
||||
OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
OAuthServerClientNotFoundError,
|
||||
OAuthServerRequestError,
|
||||
OAuthServerUnauthorizedError,
|
||||
)
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
ensure_dify_setup,
|
||||
)
|
||||
|
||||
|
||||
def _application_services(service: MagicMock) -> SimpleNamespace:
|
||||
return SimpleNamespace(oauth_server=service)
|
||||
|
||||
|
||||
def test_oauth_provider_successful_post(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.get_provider.return_value = OAuthProviderAppPresentation(
|
||||
app_icon="icon_url",
|
||||
app_label={"en-US": "Test App"},
|
||||
scope="read,write",
|
||||
auto_authorize=True,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider",
|
||||
json={"client_id": "test_client_id", "redirect_uri": "http://localhost/callback"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {
|
||||
"app_icon": "icon_url",
|
||||
"app_label": {"en-US": "Test App"},
|
||||
"scope": "read,write",
|
||||
"auto_authorize": True,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "status", "message"),
|
||||
[
|
||||
(OAuthServerRequestError("redirect_uri is invalid"), 400, "redirect_uri is invalid"),
|
||||
(OAuthServerClientNotFoundError("client_id is invalid"), 404, "client_id is invalid"),
|
||||
],
|
||||
)
|
||||
def test_oauth_provider_maps_application_errors(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
error: Exception,
|
||||
status: int,
|
||||
message: str,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.get_provider.side_effect = error
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider",
|
||||
json={"client_id": "test_client_id", "redirect_uri": "http://invalid/callback"},
|
||||
)
|
||||
|
||||
assert response.status_code == status
|
||||
assert message in response.get_json()["message"]
|
||||
|
||||
|
||||
def test_oauth_authorize_successful(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.authorize.return_value = OAuthAuthorizationCode(code="auth_code_123")
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/authorize",
|
||||
json={"client_id": "test_client_id"},
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"code": "auth_code_123"}
|
||||
context = service.authorize.call_args.args[0]
|
||||
assert context.account_id == account.id
|
||||
|
||||
|
||||
def test_oauth_token_authorization_code_grant(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.exchange_token.return_value = OAuthTokenSet(
|
||||
access_token="access_123",
|
||||
token_type="Bearer",
|
||||
expires_in=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
refresh_token="refresh_123",
|
||||
)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/token",
|
||||
json={
|
||||
"client_id": "test_client_id",
|
||||
"grant_type": "authorization_code",
|
||||
"code": "auth_code",
|
||||
"client_secret": "test_secret",
|
||||
"redirect_uri": "http://localhost/callback",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {
|
||||
"access_token": "access_123",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
"refresh_token": "refresh_123",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("payload", "message"),
|
||||
[
|
||||
(
|
||||
{
|
||||
"client_id": "test_client_id",
|
||||
"grant_type": "authorization_code",
|
||||
"client_secret": "test_secret",
|
||||
"redirect_uri": "http://localhost/callback",
|
||||
},
|
||||
"code is required",
|
||||
),
|
||||
(
|
||||
{
|
||||
"client_id": "test_client_id",
|
||||
"grant_type": "authorization_code",
|
||||
"code": "auth_code",
|
||||
"client_secret": "invalid_secret",
|
||||
"redirect_uri": "http://localhost/callback",
|
||||
},
|
||||
"client_secret is invalid",
|
||||
),
|
||||
(
|
||||
{
|
||||
"client_id": "test_client_id",
|
||||
"grant_type": "authorization_code",
|
||||
"code": "auth_code",
|
||||
"client_secret": "test_secret",
|
||||
"redirect_uri": "http://invalid/callback",
|
||||
},
|
||||
"redirect_uri is invalid",
|
||||
),
|
||||
(
|
||||
{"client_id": "test_client_id", "grant_type": "refresh_token"},
|
||||
"refresh_token is required",
|
||||
),
|
||||
(
|
||||
{"client_id": "test_client_id", "grant_type": "invalid_grant"},
|
||||
"invalid grant_type",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_oauth_token_maps_invalid_grant_requests(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
payload: dict[str, str],
|
||||
message: str,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.exchange_token.side_effect = OAuthServerRequestError(message)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post("/console/api/oauth/provider/token", json=payload)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["message"] == message
|
||||
|
||||
|
||||
def test_oauth_token_refresh_token_grant(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.exchange_token.return_value = OAuthTokenSet(
|
||||
access_token="new_access",
|
||||
token_type="Bearer",
|
||||
expires_in=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
refresh_token="new_refresh",
|
||||
)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/token",
|
||||
json={"client_id": "test_client_id", "grant_type": "refresh_token", "refresh_token": "refresh_123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {
|
||||
"access_token": "new_access",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": OAUTH_ACCESS_TOKEN_EXPIRES_IN,
|
||||
"refresh_token": "new_refresh",
|
||||
}
|
||||
|
||||
|
||||
def test_oauth_account_successful_retrieval(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.get_account.return_value = OAuthProviderAccount(
|
||||
id="account-1",
|
||||
name="Test User",
|
||||
email="test@example.com",
|
||||
avatar=None,
|
||||
interface_language=None,
|
||||
timezone=None,
|
||||
created_at=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
|
||||
)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/account",
|
||||
json={"client_id": "test_client_id"},
|
||||
headers={"Authorization": "Bearer valid_access_token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {
|
||||
"id": "account-1",
|
||||
"name": "Test User",
|
||||
"email": "test@example.com",
|
||||
"avatar": None,
|
||||
"interface_language": None,
|
||||
"timezone": None,
|
||||
"created_at": 1704164645,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("headers", "message"),
|
||||
[
|
||||
({}, "Authorization header is required"),
|
||||
({"Authorization": "InvalidFormat"}, "Invalid Authorization header format"),
|
||||
({"Authorization": "Basic token"}, "token_type is invalid"),
|
||||
({"Authorization": "Bearer "}, "Invalid Authorization header format"),
|
||||
],
|
||||
)
|
||||
def test_oauth_account_rejects_invalid_authorization_header(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
headers: dict[str, str],
|
||||
message: str,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.get_account.side_effect = OAuthServerUnauthorizedError("access_token is required")
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/account",
|
||||
json={"client_id": "test_client_id"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.get_json() == {"error": message}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_oauth_account_validates_client_before_authorization_header(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
ensure_dify_setup(db_session_with_containers)
|
||||
service = MagicMock()
|
||||
service.get_account.side_effect = OAuthServerClientNotFoundError("client_id is invalid")
|
||||
with patch(
|
||||
"controllers.console.auth.oauth_server.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/oauth/provider/account",
|
||||
json={"client_id": "invalid"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "client_id is invalid" in response.get_json()["message"]
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"""Integration coverage for customized pipeline template persistence."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from inspect import unwrap
|
||||
from typing import cast
|
||||
from uuid import uuid4
|
||||
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.common.schema import JsonResponseWithStatus
|
||||
from controllers.console.datasets.rag_pipeline.rag_pipeline import CustomizedPipelineTemplateApi
|
||||
from models.dataset import PipelineCustomizedTemplate
|
||||
|
||||
|
||||
def test_export_customized_pipeline_template_from_database(
|
||||
flask_app_with_containers: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
api = CustomizedPipelineTemplateApi()
|
||||
method = unwrap(cast(Callable[..., JsonResponseWithStatus], api.post))
|
||||
template = PipelineCustomizedTemplate(
|
||||
tenant_id=str(uuid4()),
|
||||
name="Test Template",
|
||||
description="Test",
|
||||
chunk_structure="hierarchical",
|
||||
icon={"icon": "📘"},
|
||||
position=0,
|
||||
yaml_content="yaml-data",
|
||||
install_count=0,
|
||||
language="en-US",
|
||||
created_by=str(uuid4()),
|
||||
)
|
||||
db_session_with_containers.add(template)
|
||||
db_session_with_containers.commit()
|
||||
db_session_with_containers.expire_all()
|
||||
|
||||
with flask_app_with_containers.test_request_context("/"):
|
||||
response, status = method(api, db_session_with_containers, template.tenant_id, template.id)
|
||||
|
||||
assert status == 200
|
||||
assert response == {"data": "yaml-data"}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"""Integration coverage for persisted empty RAG pipeline dataset responses."""
|
||||
|
||||
from inspect import unwrap
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.console.datasets.rag_pipeline.rag_pipeline_datasets import CreateEmptyRagPipelineDatasetApi
|
||||
from models.dataset import Dataset, DatasetPermissionEnum, DatasetRuntimeMode, Pipeline
|
||||
|
||||
|
||||
def test_create_empty_rag_pipeline_dataset_serializes_persisted_models(
|
||||
flask_app_with_containers: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
tenant_id = str(uuid4())
|
||||
account_id = str(uuid4())
|
||||
pipeline = Pipeline(
|
||||
tenant_id=tenant_id,
|
||||
name="Pipeline dataset",
|
||||
description="",
|
||||
created_by=account_id,
|
||||
)
|
||||
db_session_with_containers.add(pipeline)
|
||||
db_session_with_containers.flush()
|
||||
dataset = Dataset(
|
||||
tenant_id=tenant_id,
|
||||
name="Pipeline dataset",
|
||||
description="",
|
||||
permission=DatasetPermissionEnum.ONLY_ME,
|
||||
provider="vendor",
|
||||
runtime_mode=DatasetRuntimeMode.RAG_PIPELINE,
|
||||
icon_info={"icon": "📙", "icon_background": "#FFF4ED", "icon_type": "emoji"},
|
||||
created_by=account_id,
|
||||
pipeline_id=pipeline.id,
|
||||
)
|
||||
db_session_with_containers.add(dataset)
|
||||
db_session_with_containers.commit()
|
||||
db_session_with_containers.expire_all()
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/"),
|
||||
patch(
|
||||
"controllers.console.datasets.rag_pipeline.rag_pipeline_datasets.DatasetService.create_empty_rag_pipeline_dataset",
|
||||
return_value=dataset,
|
||||
),
|
||||
):
|
||||
response, status = unwrap(CreateEmptyRagPipelineDatasetApi().post)(
|
||||
CreateEmptyRagPipelineDatasetApi(), tenant_id, MagicMock(is_dataset_editor=True)
|
||||
)
|
||||
|
||||
assert status == 201
|
||||
assert response["id"] == dataset.id
|
||||
assert response["pipeline_id"] == pipeline.id
|
||||
assert response["runtime_mode"] == "rag_pipeline"
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"""Integration coverage for Notion page bindings backed by persisted documents."""
|
||||
|
||||
from inspect import unwrap
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from controllers.console.datasets.data_source import DataSourceNotionListApi, DataSourceNotionListQuery
|
||||
from extensions.application_services.data_sources import build_data_source_credentials
|
||||
from machinery.context import RequestContext
|
||||
from models import Account, Tenant, TenantAccountJoin, TenantAccountRole
|
||||
from models.dataset import Dataset, Document
|
||||
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus
|
||||
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
|
||||
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
|
||||
from repositories.workspace.workspace_repository import WorkspaceRepository
|
||||
from services.data_source.notion_import_adapters import PluginNotionSourceGateway
|
||||
from services.data_source.notion_import_application_service import NotionImportApplicationService
|
||||
from services.knowledge.dataset_access import DatasetAccessService
|
||||
|
||||
|
||||
def test_notion_page_is_marked_bound_from_persisted_document(
|
||||
flask_app_with_containers: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
tenant = Tenant(name="Workspace")
|
||||
tenant_id = tenant.id
|
||||
dataset_id = str(uuid4())
|
||||
account = Account(name="Test User", email="user@example.com")
|
||||
account.id = str(uuid4())
|
||||
dataset = Dataset(
|
||||
id=dataset_id,
|
||||
tenant_id=tenant_id,
|
||||
name="Notion dataset",
|
||||
created_by=account.id,
|
||||
data_source_type=DataSourceType.NOTION_IMPORT,
|
||||
)
|
||||
db_session_with_containers.add_all(
|
||||
[
|
||||
account,
|
||||
tenant,
|
||||
TenantAccountJoin(tenant_id=tenant_id, account_id=account.id, role=TenantAccountRole.OWNER, current=True),
|
||||
dataset,
|
||||
]
|
||||
)
|
||||
document = Document(
|
||||
tenant_id=tenant_id,
|
||||
dataset_id=dataset_id,
|
||||
position=1,
|
||||
data_source_type=DataSourceType.NOTION_IMPORT,
|
||||
data_source_info='{"notion_page_id": "page-1"}',
|
||||
batch=f"batch-{uuid4()}",
|
||||
name="Notion Page",
|
||||
created_from=DocumentCreatedFrom.WEB,
|
||||
created_by=account.id,
|
||||
indexing_status=IndexingStatus.COMPLETED,
|
||||
enabled=True,
|
||||
)
|
||||
db_session_with_containers.add(document)
|
||||
db_session_with_containers.commit()
|
||||
runtime = MagicMock(
|
||||
get_online_document_pages=lambda **_kwargs: iter(
|
||||
[
|
||||
MagicMock(
|
||||
result=[
|
||||
MagicMock(
|
||||
workspace_id="workspace-1",
|
||||
workspace_name="Workspace",
|
||||
workspace_icon=None,
|
||||
pages=[
|
||||
MagicMock(
|
||||
page_id="page-1",
|
||||
page_name="Page",
|
||||
type="page",
|
||||
parent_id="parent",
|
||||
page_icon=None,
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
]
|
||||
),
|
||||
datasource_provider_type=lambda: None,
|
||||
)
|
||||
|
||||
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
|
||||
datasets = SQLAlchemyDatasetRepository(session_factory=sessions)
|
||||
credentials = build_data_source_credentials(database_client=sessions).actor
|
||||
notion_imports = NotionImportApplicationService(
|
||||
dataset_access=DatasetAccessService(
|
||||
datasets=datasets,
|
||||
workspace_roles=WorkspaceRepository(session_factory=sessions),
|
||||
legacy_permissions_enabled=True,
|
||||
),
|
||||
datasets=datasets,
|
||||
documents=SQLAlchemyDocumentRepository(session_factory=sessions),
|
||||
source=PluginNotionSourceGateway(credentials=credentials, runtime_loader=MagicMock(return_value=runtime)),
|
||||
)
|
||||
context = RequestContext(
|
||||
request_id="notion-binding-test", trace_id=None, account_id=account.id, active_workspace_id=tenant_id
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(credentials, "resolve", return_value={"token": "token"}) as resolve_credentials,
|
||||
flask_app_with_containers.test_request_context(f"/?credential_id=c1&dataset_id={dataset_id}"),
|
||||
patch(
|
||||
"controllers.console.datasets.data_source.application_services",
|
||||
return_value=SimpleNamespace(data_sources=SimpleNamespace(notion_imports=notion_imports)),
|
||||
),
|
||||
):
|
||||
response, status = unwrap(DataSourceNotionListApi.get)(
|
||||
DataSourceNotionListApi(),
|
||||
DataSourceNotionListQuery(credential_id="c1", dataset_id=dataset_id),
|
||||
context,
|
||||
)
|
||||
|
||||
assert status == 200
|
||||
assert response["notion_info"][0]["pages"][0]["is_bound"] is True
|
||||
resolve_credentials.assert_called_once_with(
|
||||
workspace_id=tenant_id,
|
||||
actor_id=account.id,
|
||||
credential_id="c1",
|
||||
provider="notion_datasource",
|
||||
plugin_id="langgenius/notion_datasource",
|
||||
)
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
"""Integration tests for console external knowledge API endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.dataset import ExternalKnowledgeApis
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def _create_external_api(
|
||||
db_session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
account_id: str,
|
||||
name: str,
|
||||
) -> ExternalKnowledgeApis:
|
||||
external_api = ExternalKnowledgeApis(
|
||||
tenant_id=tenant_id,
|
||||
created_by=account_id,
|
||||
updated_by=account_id,
|
||||
name=name,
|
||||
description=f"{name} description",
|
||||
settings=json.dumps(
|
||||
{
|
||||
"endpoint": "https://example.com",
|
||||
"api_key": "test-api-key",
|
||||
}
|
||||
),
|
||||
)
|
||||
db_session.add(external_api)
|
||||
db_session.commit()
|
||||
return external_api
|
||||
|
||||
|
||||
def test_external_api_template_list_filters_paginates_and_scopes_to_authenticated_tenant(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise the real list route, including query parsing, DB lookup, and tenant isolation."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
account_id = account.id
|
||||
tenant_id = tenant.id
|
||||
foreign_account_id = foreign_account.id
|
||||
foreign_tenant_id = foreign_tenant.id
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
_create_external_api(
|
||||
db_session_with_containers,
|
||||
tenant_id=tenant_id,
|
||||
account_id=account_id,
|
||||
name="Alpha Primary",
|
||||
)
|
||||
_create_external_api(
|
||||
db_session_with_containers,
|
||||
tenant_id=tenant_id,
|
||||
account_id=account_id,
|
||||
name="Alpha Secondary",
|
||||
)
|
||||
_create_external_api(
|
||||
db_session_with_containers,
|
||||
tenant_id=tenant_id,
|
||||
account_id=account_id,
|
||||
name="Beta Unmatched",
|
||||
)
|
||||
_create_external_api(
|
||||
db_session_with_containers,
|
||||
tenant_id=foreign_tenant_id,
|
||||
account_id=foreign_account_id,
|
||||
name="Alpha Foreign",
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/datasets/external-knowledge-api?page=1&limit=1&keyword=Alpha",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json is not None
|
||||
assert response.json["page"] == 1
|
||||
assert response.json["limit"] == 1
|
||||
assert response.json["total"] == 2
|
||||
assert response.json["has_more"] is True
|
||||
assert len(response.json["data"]) == 1
|
||||
|
||||
first_page_item = response.json["data"][0]
|
||||
assert first_page_item["tenant_id"] == tenant_id
|
||||
assert first_page_item["name"] in {"Alpha Primary", "Alpha Secondary"}
|
||||
assert first_page_item["settings"] == {
|
||||
"endpoint": "https://example.com",
|
||||
"api_key": "test-api-key",
|
||||
}
|
||||
assert first_page_item["dataset_bindings"] == []
|
||||
|
||||
second_response = test_client_with_containers.get(
|
||||
"/console/api/datasets/external-knowledge-api?page=2&limit=1&keyword=Alpha",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert second_response.status_code == 200
|
||||
assert second_response.json is not None
|
||||
assert second_response.json["page"] == 2
|
||||
assert second_response.json["limit"] == 1
|
||||
assert second_response.json["total"] == 2
|
||||
assert len(second_response.json["data"]) == 1
|
||||
|
||||
second_page_item = second_response.json["data"][0]
|
||||
assert second_page_item["name"] in {"Alpha Primary", "Alpha Secondary"}
|
||||
assert second_response.json["data"][0]["tenant_id"] == tenant_id
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
"""DB-backed integration tests for console dataset segment endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
|
||||
from models.dataset import Dataset, Document, DocumentSegment, DocumentSegmentSummary
|
||||
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus, SummaryStatus
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def test_list_segments_uses_real_db_query_and_console_response_shape(
|
||||
test_client_with_containers: FlaskClient,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
dataset = Dataset(
|
||||
tenant_id=tenant.id,
|
||||
name=f"Console Segment Dataset {uuid4()}",
|
||||
description="Console segment integration dataset",
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
indexing_technique=IndexTechniqueType.ECONOMY,
|
||||
created_by=account.id,
|
||||
permission="only_me",
|
||||
provider="vendor",
|
||||
)
|
||||
db_session_with_containers.add(dataset)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
document = Document(
|
||||
tenant_id=tenant.id,
|
||||
dataset_id=dataset.id,
|
||||
position=1,
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
batch=f"batch-{uuid4()}",
|
||||
name="console-segment-doc.txt",
|
||||
created_from=DocumentCreatedFrom.WEB,
|
||||
created_by=account.id,
|
||||
enabled=True,
|
||||
archived=False,
|
||||
indexing_status=IndexingStatus.COMPLETED,
|
||||
doc_form=IndexStructureType.PARAGRAPH_INDEX,
|
||||
word_count=3,
|
||||
tokens=4,
|
||||
)
|
||||
db_session_with_containers.add(document)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
segment = DocumentSegment(
|
||||
tenant_id=tenant.id,
|
||||
dataset_id=dataset.id,
|
||||
document_id=document.id,
|
||||
position=1,
|
||||
content="Console integration segment",
|
||||
word_count=3,
|
||||
tokens=4,
|
||||
keywords=["console", "integration"],
|
||||
status=SegmentStatus.COMPLETED,
|
||||
created_by=account.id,
|
||||
)
|
||||
db_session_with_containers.add(segment)
|
||||
db_session_with_containers.commit()
|
||||
segment_id = segment.id
|
||||
|
||||
db_session_with_containers.add(
|
||||
DocumentSegmentSummary(
|
||||
dataset_id=dataset.id,
|
||||
document_id=document.id,
|
||||
chunk_id=segment.id,
|
||||
summary_content="Console DB summary",
|
||||
status=SummaryStatus.COMPLETED,
|
||||
)
|
||||
)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/console/api/datasets/{dataset.id}/documents/{document.id}/segments"
|
||||
"?page=1&limit=10&status=completed&keyword=integration&enabled=all",
|
||||
headers=authenticate_console_client(test_client_with_containers, account),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert set(body) == {"data", "limit", "total", "total_pages", "page"}
|
||||
assert body["limit"] == 10
|
||||
assert body["total"] == 1
|
||||
assert body["total_pages"] == 1
|
||||
assert "has_more" not in body
|
||||
assert body["data"][0]["id"] == segment_id
|
||||
assert body["data"][0]["summary"] == "Console DB summary"
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Shared helpers for console controller integration tests."""
|
||||
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from typing import cast
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from configs import dify_config
|
||||
from constants import HEADER_NAME_CSRF_TOKEN
|
||||
from extensions.ext_application_services import application_services
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.token import _real_cookie_name, generate_csrf_token
|
||||
from models import Account, DifySetup, Tenant, TenantAccountJoin
|
||||
from models.account import AccountStatus, TenantAccountRole, TenantStatus
|
||||
from models.model import App, AppMode
|
||||
|
||||
|
||||
def ensure_dify_setup(db_session: Session) -> None:
|
||||
"""Create a setup marker once so setup-protected console routes can be exercised."""
|
||||
if db_session.scalar(select(DifySetup).limit(1)) is not None:
|
||||
return
|
||||
|
||||
db_session.add(DifySetup(version=dify_config.project.version))
|
||||
db_session.commit()
|
||||
|
||||
|
||||
def create_console_account_and_tenant(db_session: Session) -> tuple[Account, Tenant]:
|
||||
"""Create an initialized owner account with a current tenant."""
|
||||
account = Account(
|
||||
email=f"test-{uuid.uuid4()}@example.com",
|
||||
name="Test User",
|
||||
interface_language="en-US",
|
||||
status=AccountStatus.ACTIVE,
|
||||
)
|
||||
account.initialized_at = naive_utc_now()
|
||||
db_session.add(account)
|
||||
db_session.commit()
|
||||
|
||||
tenant = Tenant(name="Test Tenant", status=TenantStatus.NORMAL)
|
||||
db_session.add(tenant)
|
||||
db_session.commit()
|
||||
|
||||
db_session.add(
|
||||
TenantAccountJoin(
|
||||
tenant_id=tenant.id,
|
||||
account_id=account.id,
|
||||
role=TenantAccountRole.OWNER,
|
||||
current=True,
|
||||
)
|
||||
)
|
||||
db_session.commit()
|
||||
|
||||
account.set_tenant_id_with_session(tenant.id, session=db_session)
|
||||
account.timezone = "UTC"
|
||||
db_session.commit()
|
||||
|
||||
ensure_dify_setup(db_session)
|
||||
return account, tenant
|
||||
|
||||
|
||||
def create_console_app(db_session: Session, tenant_id: str, account_id: str, mode: AppMode) -> App:
|
||||
"""Create a minimal app row that can be loaded by get_app_model."""
|
||||
app = App(
|
||||
tenant_id=tenant_id,
|
||||
name="Test App",
|
||||
mode=mode,
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
created_by=account_id,
|
||||
)
|
||||
db_session.add(app)
|
||||
db_session.commit()
|
||||
return app
|
||||
|
||||
|
||||
def authenticate_console_client(test_client: FlaskClient, account: Account) -> dict[str, str]:
|
||||
"""Attach console auth cookies/headers for endpoints guarded by login_required."""
|
||||
access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_token
|
||||
csrf_token = generate_csrf_token(account.id)
|
||||
test_client.set_cookie(_real_cookie_name("csrf_token"), csrf_token, domain="localhost")
|
||||
return {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
HEADER_NAME_CSRF_TOKEN: csrf_token,
|
||||
}
|
||||
|
||||
|
||||
def unwrap[R](func: Callable[..., R]) -> Callable[..., R]:
|
||||
"""Return the undecorated callable for controller methods wrapped by Flask/RESTX."""
|
||||
while hasattr(func, "__wrapped__"):
|
||||
func = cast(Callable[..., R], func.__wrapped__)
|
||||
return func
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
"""Integration tests for console API-based extension endpoints using testcontainers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from constants import HIDDEN_VALUE
|
||||
from core.helper.encrypter import encrypt_token
|
||||
from libs.rsa import generate_key_pair
|
||||
from models.api_based_extension import APIBasedExtension
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def _masked_api_key(api_key: str) -> str:
|
||||
if len(api_key) <= 8:
|
||||
return api_key[0] + "******" + api_key[-1]
|
||||
return api_key[:3] + "******" + api_key[-3:]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api_extension_client(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> tuple[FlaskClient, dict[str, str], str]:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant_id = tenant.id
|
||||
tenant.encrypt_public_key = generate_key_pair(tenant.id)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
return test_client_with_containers, headers, tenant_id
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_api_based_extension_ping() -> Iterator[MagicMock]:
|
||||
with patch("services.api_based_extension_adapters.APIBasedExtensionRequestor") as requestor:
|
||||
requestor.return_value.request.return_value = {"result": "pong"}
|
||||
yield requestor
|
||||
|
||||
|
||||
def test_create_response_masks_plaintext_api_key(
|
||||
api_extension_client: tuple[FlaskClient, dict[str, str], str],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, tenant_id = api_extension_client
|
||||
api_key = "plain-secret-12345"
|
||||
|
||||
response = client.post(
|
||||
"/console/api/api-based-extension",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Docs API",
|
||||
"api_endpoint": "https://docs.example.com/hook",
|
||||
"api_key": api_key,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.json is not None
|
||||
assert response.json["api_key"] == _masked_api_key(api_key)
|
||||
extension = db_session_with_containers.scalar(
|
||||
select(APIBasedExtension).where(APIBasedExtension.id == response.json["id"]).limit(1)
|
||||
)
|
||||
assert extension is not None
|
||||
assert extension.tenant_id == tenant_id
|
||||
|
||||
|
||||
def test_list_scopes_api_based_extensions_to_authenticated_tenant(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
account_headers = authenticate_console_client(test_client_with_containers, account)
|
||||
tenant.encrypt_public_key = generate_key_pair(tenant.id)
|
||||
_foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_tenant_id = foreign_tenant.id
|
||||
foreign_tenant.encrypt_public_key = generate_key_pair(foreign_tenant.id)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
account_create_response = test_client_with_containers.post(
|
||||
"/console/api/api-based-extension",
|
||||
headers=account_headers,
|
||||
json={
|
||||
"name": "Tenant API",
|
||||
"api_endpoint": "https://tenant.example.com/hook",
|
||||
"api_key": "tenant-secret-12345",
|
||||
},
|
||||
)
|
||||
assert account_create_response.status_code == 201
|
||||
|
||||
# Seed another workspace's extension directly; the list endpoint must not expose it.
|
||||
db_session_with_containers.add(
|
||||
APIBasedExtension(
|
||||
tenant_id=foreign_tenant_id,
|
||||
name="Foreign API",
|
||||
api_endpoint="https://foreign.example.com/hook",
|
||||
api_key=encrypt_token(foreign_tenant_id, "foreign-secret-12345"),
|
||||
)
|
||||
)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/api-based-extension",
|
||||
headers=account_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json is not None
|
||||
assert [item["name"] for item in response.json] == ["Tenant API"]
|
||||
|
||||
|
||||
def test_update_response_masks_new_plaintext_api_key(
|
||||
api_extension_client: tuple[FlaskClient, dict[str, str], str],
|
||||
) -> None:
|
||||
client, headers, _ = api_extension_client
|
||||
new_api_key = "new-secret-67890"
|
||||
create_response = client.post(
|
||||
"/console/api/api-based-extension",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Docs API",
|
||||
"api_endpoint": "https://docs.example.com/hook",
|
||||
"api_key": "old-secret-12345",
|
||||
},
|
||||
)
|
||||
assert create_response.json is not None
|
||||
|
||||
update_response = client.post(
|
||||
f"/console/api/api-based-extension/{create_response.json['id']}",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Docs API Updated",
|
||||
"api_endpoint": "https://docs.example.com/v2",
|
||||
"api_key": new_api_key,
|
||||
},
|
||||
)
|
||||
|
||||
assert update_response.status_code == 200
|
||||
assert update_response.json is not None
|
||||
assert update_response.json["api_key"] == _masked_api_key(new_api_key)
|
||||
|
||||
|
||||
def test_update_response_masks_existing_plaintext_api_key_when_hidden_value_is_submitted(
|
||||
api_extension_client: tuple[FlaskClient, dict[str, str], str],
|
||||
) -> None:
|
||||
client, headers, _ = api_extension_client
|
||||
existing_api_key = "old-secret-12345"
|
||||
create_response = client.post(
|
||||
"/console/api/api-based-extension",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Docs API",
|
||||
"api_endpoint": "https://docs.example.com/hook",
|
||||
"api_key": existing_api_key,
|
||||
},
|
||||
)
|
||||
assert create_response.json is not None
|
||||
|
||||
update_response = client.post(
|
||||
f"/console/api/api-based-extension/{create_response.json['id']}",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "Docs API Updated",
|
||||
"api_endpoint": "https://docs.example.com/v2",
|
||||
"api_key": HIDDEN_VALUE,
|
||||
},
|
||||
)
|
||||
|
||||
assert update_response.status_code == 200
|
||||
assert update_response.json is not None
|
||||
assert update_response.json["api_key"] == _masked_api_key(existing_api_key)
|
||||
@@ -0,0 +1,453 @@
|
||||
"""Integration tests for console API key endpoints using testcontainers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from models.account import TenantAccountJoin, TenantAccountRole
|
||||
from models.dataset import Dataset
|
||||
from models.enums import ApiTokenType, DataSourceType
|
||||
from models.model import ApiToken, App, AppMode, DatasetApiTokenBinding
|
||||
from repositories.knowledge.dataset_api_key_repository import DatasetApiKeyRepository
|
||||
from services.auth.api_key_contracts import ApiKeyLimitExceededError
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
create_console_app,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_app(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> tuple[FlaskClient, dict[str, str], App]:
|
||||
"""Create an authenticated client with an app for API key tests."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
return test_client_with_containers, headers, app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_dataset(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> tuple[FlaskClient, dict[str, str], Dataset]:
|
||||
"""Create an authenticated client with a dataset for per-dataset API key tests."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
dataset = Dataset(
|
||||
tenant_id=tenant.id,
|
||||
name=f"API Key Dataset {uuid4()}",
|
||||
description="Dataset for API key scoping tests",
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
created_by=account.id,
|
||||
permission="only_me",
|
||||
provider="vendor",
|
||||
)
|
||||
db_session_with_containers.add(dataset)
|
||||
db_session_with_containers.commit()
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
return test_client_with_containers, headers, dataset
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cleanup_api_tokens(db_session_with_containers: Session) -> Iterator[None]:
|
||||
"""Remove API tokens created during each test."""
|
||||
yield
|
||||
db_session_with_containers.execute(delete(ApiToken))
|
||||
db_session_with_containers.commit()
|
||||
|
||||
|
||||
class TestAppApiKeyListResource:
|
||||
"""Tests for GET/POST /apps/<resource_id>/api-keys."""
|
||||
|
||||
def test_get_empty_keys(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
|
||||
client, headers, app = setup_app
|
||||
resp = client.get(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json is not None
|
||||
assert resp.json["data"] == []
|
||||
|
||||
def test_create_api_key(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
|
||||
client, headers, app = setup_app
|
||||
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
assert resp.status_code == 201
|
||||
data = resp.json
|
||||
assert data is not None
|
||||
assert data["token"].startswith("app-")
|
||||
assert data["id"] is not None
|
||||
|
||||
def test_create_api_key_persists_authenticated_tenant(
|
||||
self,
|
||||
setup_app: tuple[FlaskClient, dict[str, str], App],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, app = setup_app
|
||||
tenant_id = app.tenant_id
|
||||
|
||||
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
|
||||
assert resp.status_code == 201
|
||||
assert resp.json is not None
|
||||
api_token = db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == resp.json["id"]))
|
||||
assert api_token is not None
|
||||
assert api_token.tenant_id == tenant_id
|
||||
assert api_token.app_id == app.id
|
||||
assert api_token.type == ApiTokenType.APP
|
||||
|
||||
def test_get_keys_after_create(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
|
||||
client, headers, app = setup_app
|
||||
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
|
||||
resp = client.get(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json is not None
|
||||
assert len(resp.json["data"]) == 2
|
||||
|
||||
def test_create_key_max_limit(
|
||||
self,
|
||||
setup_app: tuple[FlaskClient, dict[str, str], App],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, app = setup_app
|
||||
# Create 10 keys (the max)
|
||||
for _ in range(10):
|
||||
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
|
||||
# 11th should fail
|
||||
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_get_keys_for_nonexistent_app(
|
||||
self,
|
||||
setup_app: tuple[FlaskClient, dict[str, str], App],
|
||||
) -> None:
|
||||
client, headers, _ = setup_app
|
||||
resp = client.get(
|
||||
"/console/api/apps/00000000-0000-0000-0000-000000000000/api-keys",
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_get_foreign_app_keys_not_found(
|
||||
self,
|
||||
setup_app: tuple[FlaskClient, dict[str, str], App],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, _ = setup_app
|
||||
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
foreign_app = create_console_app(
|
||||
db_session_with_containers, foreign_tenant.id, foreign_account.id, AppMode.CHAT
|
||||
)
|
||||
|
||||
resp = client.get(f"/console/api/apps/{foreign_app.id}/api-keys", headers=headers)
|
||||
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestAppApiKeyResource:
|
||||
"""Tests for DELETE /apps/<resource_id>/api-keys/<api_key_id>."""
|
||||
|
||||
def test_delete_key_success(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
|
||||
client, headers, app = setup_app
|
||||
create_resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
|
||||
assert create_resp.json is not None
|
||||
key_id = create_resp.json["id"]
|
||||
|
||||
resp = client.delete(f"/console/api/apps/{app.id}/api-keys/{key_id}", headers=headers)
|
||||
assert resp.status_code == 204
|
||||
|
||||
def test_delete_nonexistent_key(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
|
||||
client, headers, app = setup_app
|
||||
resp = client.delete(
|
||||
f"/console/api/apps/{app.id}/api-keys/00000000-0000-0000-0000-000000000000",
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_delete_key_nonexistent_app(
|
||||
self,
|
||||
setup_app: tuple[FlaskClient, dict[str, str], App],
|
||||
) -> None:
|
||||
client, headers, _ = setup_app
|
||||
resp = client.delete(
|
||||
"/console/api/apps/00000000-0000-0000-0000-000000000000/api-keys/00000000-0000-0000-0000-000000000000",
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_delete_forbidden_for_non_admin(
|
||||
self,
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""A non-admin member cannot delete API keys through Console admission."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
|
||||
membership = db_session_with_containers.scalar(
|
||||
select(TenantAccountJoin).where(
|
||||
TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id
|
||||
)
|
||||
)
|
||||
assert membership is not None
|
||||
membership.role = TenantAccountRole.NORMAL
|
||||
db_session_with_containers.commit()
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
response = test_client_with_containers.delete(f"/console/api/apps/{app.id}/api-keys/{uuid4()}", headers=headers)
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
class TestDatasetApiKeyListResource:
|
||||
"""Tests for GET/POST /datasets/api-keys with per-knowledge-base scope.
|
||||
|
||||
Scope is expressed by DatasetApiTokenBinding rows: absent/empty ``dataset_ids``
|
||||
on create makes an unrestricted key; a non-empty list binds the key to exactly
|
||||
those knowledge bases.
|
||||
"""
|
||||
|
||||
def _bound_dataset_ids(self, session: Session, api_token_id: str) -> set[str]:
|
||||
return {
|
||||
dataset_id
|
||||
for dataset_id in session.scalars(
|
||||
select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_token_id)
|
||||
).all()
|
||||
if dataset_id is not None
|
||||
}
|
||||
|
||||
def test_create_unbound_key(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, dataset = setup_dataset
|
||||
tenant_id = dataset.tenant_id
|
||||
|
||||
resp = client.post("/console/api/datasets/api-keys", headers=headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert resp.json is not None
|
||||
assert resp.json["token"].startswith("dataset-")
|
||||
assert resp.json["dataset_ids"] == []
|
||||
api_token = db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == resp.json["id"]))
|
||||
assert api_token is not None
|
||||
assert api_token.tenant_id == tenant_id
|
||||
assert api_token.type == ApiTokenType.DATASET
|
||||
# No bindings -> unrestricted key.
|
||||
assert self._bound_dataset_ids(db_session_with_containers, resp.json["id"]) == set()
|
||||
|
||||
def test_create_scoped_key_persists_bindings(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, dataset = setup_dataset
|
||||
dataset_id = dataset.id
|
||||
|
||||
resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [dataset_id]},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert resp.json is not None
|
||||
assert resp.json["dataset_ids"] == [dataset_id]
|
||||
assert self._bound_dataset_ids(db_session_with_containers, resp.json["id"]) == {dataset_id}
|
||||
|
||||
def test_create_rejects_dataset_outside_tenant(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
) -> None:
|
||||
"""A dataset id that does not belong to the tenant is rejected with 400."""
|
||||
client, headers, _ = setup_dataset
|
||||
|
||||
resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [str(uuid4())]},
|
||||
)
|
||||
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_list_reports_scope_for_each_key(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, dataset = setup_dataset
|
||||
dataset_id = dataset.id
|
||||
|
||||
scoped_resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [dataset_id]},
|
||||
)
|
||||
assert scoped_resp.status_code == 200
|
||||
unbound_resp = client.post("/console/api/datasets/api-keys", headers=headers)
|
||||
assert unbound_resp.status_code == 200
|
||||
|
||||
resp = client.get("/console/api/datasets/api-keys", headers=headers)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert resp.json is not None
|
||||
assert scoped_resp.json is not None
|
||||
assert unbound_resp.json is not None
|
||||
scopes = {item["id"]: item["dataset_ids"] for item in resp.json["data"]}
|
||||
assert scopes[scoped_resp.json["id"]] == [dataset_id]
|
||||
assert scopes[unbound_resp.json["id"]] == []
|
||||
# reveal-once: the list returns masked tokens, never the full secret.
|
||||
listed = {item["id"]: item["token"] for item in resp.json["data"]}
|
||||
assert listed[scoped_resp.json["id"]] != scoped_resp.json["token"]
|
||||
|
||||
|
||||
def test_dataset_creation_routes_serialize_on_the_same_workspace(
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The workspace request must wait until the per-dataset count/insert commits."""
|
||||
_, _, dataset = setup_dataset
|
||||
workspace_id, dataset_id = dataset.tenant_id, dataset.id
|
||||
db_session_with_containers.add_all(
|
||||
ApiToken(tenant_id=workspace_id, type=ApiTokenType.DATASET, token=f"dataset-{uuid4()}") for _ in range(9)
|
||||
)
|
||||
db_session_with_containers.commit()
|
||||
repository = DatasetApiKeyRepository(session_factory=sessionmaker(bind=db_session_with_containers.get_bind()))
|
||||
first_counted, release_first, second_started = Event(), Event(), Event()
|
||||
generate_key = ApiToken.generate_api_key
|
||||
|
||||
def pause_first_insert(prefix: str, n: int, *, session: Session) -> str:
|
||||
if prefix == "ds-":
|
||||
first_counted.set()
|
||||
assert release_first.wait(timeout=10), "Timed out waiting to release the first insertion"
|
||||
return generate_key(prefix, n, session=session)
|
||||
|
||||
def create_workspace_key() -> None:
|
||||
second_started.set()
|
||||
repository.create_workspace_key(workspace_id, (), max_keys=10, prefix="dataset-")
|
||||
|
||||
monkeypatch.setattr(ApiToken, "generate_api_key", pause_first_insert)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
first = pool.submit(repository.create_key, workspace_id, dataset_id, max_keys=10, prefix="ds-")
|
||||
try:
|
||||
assert first_counted.wait(timeout=5)
|
||||
second = pool.submit(create_workspace_key)
|
||||
assert second_started.wait(timeout=5)
|
||||
with pytest.raises(TimeoutError):
|
||||
second.result(timeout=0.5)
|
||||
finally:
|
||||
release_first.set()
|
||||
first.result(timeout=5)
|
||||
with pytest.raises(ApiKeyLimitExceededError):
|
||||
second.result(timeout=5)
|
||||
assert len(repository.list_workspace_keys(workspace_id)) == 10
|
||||
|
||||
|
||||
class TestDatasetApiKeyResource:
|
||||
"""Tests for DELETE /datasets/api-keys/<api_key_id>."""
|
||||
|
||||
def test_delete_key_removes_bindings(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
client, headers, dataset = setup_dataset
|
||||
dataset_id = dataset.id
|
||||
create_resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [dataset_id]},
|
||||
)
|
||||
assert create_resp.json is not None
|
||||
api_key_id = create_resp.json["id"]
|
||||
|
||||
resp = client.delete(f"/console/api/datasets/api-keys/{api_key_id}", headers=headers)
|
||||
|
||||
assert resp.status_code == 204
|
||||
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is None
|
||||
# The binding rows cascade away with the deleted key.
|
||||
remaining = db_session_with_containers.scalars(
|
||||
select(DatasetApiTokenBinding).where(DatasetApiTokenBinding.api_token_id == api_key_id)
|
||||
).all()
|
||||
assert remaining == []
|
||||
|
||||
|
||||
class TestDatasetDeleteCascadesToScopedKeys:
|
||||
"""Deleting a knowledge base must not let a scoped key degrade to access-all."""
|
||||
|
||||
def _create_other_dataset(self, session: Session, tenant_id: str, created_by: str) -> Dataset:
|
||||
other = Dataset(
|
||||
tenant_id=tenant_id,
|
||||
name=f"Other Dataset {uuid4()}",
|
||||
description="Second dataset",
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
created_by=created_by,
|
||||
permission="only_me",
|
||||
provider="vendor",
|
||||
)
|
||||
session.add(other)
|
||||
session.commit()
|
||||
return other
|
||||
|
||||
def test_deleting_last_bound_dataset_deletes_the_scoped_key(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
"""A key bound only to the deleted dataset is removed, never left unrestricted."""
|
||||
client, headers, dataset = setup_dataset
|
||||
dataset_id = dataset.id
|
||||
create_resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [dataset_id]},
|
||||
)
|
||||
assert create_resp.json is not None
|
||||
api_key_id = create_resp.json["id"]
|
||||
|
||||
resp = client.delete(f"/console/api/datasets/{dataset_id}", headers=headers)
|
||||
|
||||
assert resp.status_code == 204
|
||||
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is None
|
||||
|
||||
def test_deleting_one_bound_dataset_keeps_a_multi_scoped_key(
|
||||
self,
|
||||
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
"""A key bound to several datasets survives and just drops the deleted one."""
|
||||
client, headers, dataset = setup_dataset
|
||||
dataset_id = dataset.id
|
||||
other = self._create_other_dataset(db_session_with_containers, dataset.tenant_id, dataset.created_by)
|
||||
other_id = other.id
|
||||
create_resp = client.post(
|
||||
"/console/api/datasets/api-keys",
|
||||
headers=headers,
|
||||
json={"dataset_ids": [dataset_id, other_id]},
|
||||
)
|
||||
assert create_resp.json is not None
|
||||
api_key_id = create_resp.json["id"]
|
||||
|
||||
resp = client.delete(f"/console/api/datasets/{dataset_id}", headers=headers)
|
||||
|
||||
assert resp.status_code == 204
|
||||
# The key survives, still scoped to the remaining dataset only.
|
||||
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is not None
|
||||
remaining = set(
|
||||
db_session_with_containers.scalars(
|
||||
select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_key_id)
|
||||
).all()
|
||||
)
|
||||
assert remaining == {other_id}
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Integration tests for console feature endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from services.entities.feature_entities import FeatureModel, LimitationModel
|
||||
from services.feature_service import FeatureService
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def test_feature_list_returns_current_tenant_configuration_without_vector_space(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise auth, tenant injection, and the feature response shaping contract."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant_id = tenant.id
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
feature_model = FeatureModel(
|
||||
members=LimitationModel(size=1, limit=2),
|
||||
apps=LimitationModel(size=3, limit=4),
|
||||
vector_space=LimitationModel(size=5, limit=6),
|
||||
)
|
||||
|
||||
with patch.object(FeatureService, "get_features", return_value=feature_model) as get_features:
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/features",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json is not None
|
||||
assert response.json["members"] == {"size": 1, "limit": 2}
|
||||
assert response.json["apps"] == {"size": 3, "limit": 4}
|
||||
assert "vector_space" not in response.json
|
||||
get_features.assert_called_once_with(tenant_id, exclude_vector_space=True)
|
||||
|
||||
|
||||
def test_feature_vector_space_returns_current_tenant_usage(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise tenant injection and vector-space response serialization through the registered route."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant_id = tenant.id
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
vector_space = SimpleNamespace(model_dump=lambda: {"size": 0, "limit": 100})
|
||||
|
||||
with patch.object(FeatureService, "get_vector_space", return_value=vector_space) as get_vector_space:
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/features/vector-space",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json == {"size": 0, "limit": 100}
|
||||
get_vector_space.assert_called_once_with(tenant_id)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Integration tests for console file endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from configs import dify_config
|
||||
from models.model import UploadFile
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def test_file_upload_config_returns_console_limits(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise the authenticated upload-config route and response contract."""
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/files/upload",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json == {
|
||||
"file_size_limit": dify_config.UPLOAD_FILE_SIZE_LIMIT,
|
||||
"knowledge_file_size_limit": dify_config.UPLOAD_FILE_SIZE_LIMIT,
|
||||
"batch_count_limit": dify_config.UPLOAD_FILE_BATCH_LIMIT,
|
||||
"file_upload_limit": dify_config.BATCH_UPLOAD_LIMIT,
|
||||
"image_file_size_limit": dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT,
|
||||
"video_file_size_limit": dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT,
|
||||
"audio_file_size_limit": dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT,
|
||||
"skill_file_size_limit": dify_config.UPLOAD_SKILL_FILE_SIZE_LIMIT,
|
||||
"workflow_file_upload_limit": dify_config.WORKFLOW_FILE_UPLOAD_LIMIT,
|
||||
"image_file_batch_limit": dify_config.IMAGE_FILE_BATCH_LIMIT,
|
||||
"single_chunk_attachment_limit": dify_config.SINGLE_CHUNK_ATTACHMENT_LIMIT,
|
||||
"attachment_image_file_size_limit": dify_config.ATTACHMENT_IMAGE_FILE_SIZE_LIMIT,
|
||||
}
|
||||
|
||||
|
||||
def test_file_upload_persists_file_for_authenticated_current_user(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise real upload behavior plus current-user and tenant propagation."""
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
account_id = account.id
|
||||
tenant_id = tenant.id
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
content = b"hello from console integration"
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/files/upload",
|
||||
headers=headers,
|
||||
data={"file": (BytesIO(content), "tenant-owned.txt")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.json is not None
|
||||
assert response.json["name"] == "tenant-owned.txt"
|
||||
assert response.json["size"] == len(content)
|
||||
assert response.json["extension"] == "txt"
|
||||
assert response.json["mime_type"] == "text/plain"
|
||||
assert response.json["created_by"] == account_id
|
||||
|
||||
upload_file = db_session_with_containers.scalar(
|
||||
select(UploadFile).where(UploadFile.id == response.json["id"]).limit(1)
|
||||
)
|
||||
assert upload_file is not None
|
||||
assert upload_file.tenant_id == tenant_id
|
||||
assert upload_file.created_by == account_id
|
||||
assert upload_file.name == "tenant-owned.txt"
|
||||
assert upload_file.size == len(content)
|
||||
assert f"/{tenant_id}/" in upload_file.key
|
||||
|
||||
|
||||
def test_file_upload_rejects_missing_file_after_authentication(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
"""Exercise the route's validation path with a real authenticated account."""
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/files/upload",
|
||||
headers=headers,
|
||||
data={},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json is not None
|
||||
assert response.json["code"] == "no_file_uploaded"
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
"""Console Channel API through the real service and PostgreSQL transaction boundary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from base64 import b64decode
|
||||
from typing import Never
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from cryptography.fernet import Fernet
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from configs import dify_config
|
||||
from configs.deploy import IMEventTransportMode
|
||||
from core.human_input_v2.entities import IMProvider
|
||||
from core.human_input_v2.im_integration.adapters.credentials import IMProviderCredentials
|
||||
from core.human_input_v2.im_integration.adapters.entities import CredentialTestSuccess
|
||||
from core.human_input_v2.shared import AccountId, TenantId
|
||||
from models.human_input_v2 import HumanInputIMChannel
|
||||
from repositories.human_input_v2.im_channel_repository import IMChannel, IMChannelId
|
||||
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
|
||||
from services.human_input_v2 import im_channel_service as service_module
|
||||
from services.human_input_v2.im_channel_service_composition import build_workspace_im_channel_service
|
||||
from services.human_input_v2.im_tenant_credential_cipher import TenantBoundCredentialCipher
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
_BASE_PATH = "/console/api/workspaces/current/human-input/v2/channels/im"
|
||||
_SLACK_CREDENTIALS = {
|
||||
"provider": "slack",
|
||||
"client_id": "slack-client-1",
|
||||
"client_secret": "client-secret",
|
||||
"signing_secret": "signing-secret",
|
||||
"bot_token": "xoxb-bot-token",
|
||||
"app_token": None,
|
||||
}
|
||||
|
||||
|
||||
class _StaticAdapter:
|
||||
def __init__(self, credentials: IMProviderCredentials) -> None:
|
||||
assert credentials.provider is IMProvider.SLACK
|
||||
|
||||
def test_credentials(self) -> CredentialTestSuccess:
|
||||
return CredentialTestSuccess(IMProvider.SLACK, "slack-tenant-1")
|
||||
|
||||
def close(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def static_provider_and_cipher(monkeypatch: pytest.MonkeyPatch) -> Fernet:
|
||||
cipher = Fernet(Fernet.generate_key())
|
||||
monkeypatch.setattr(service_module, "build_im_provider_adapter", _StaticAdapter)
|
||||
monkeypatch.setattr(
|
||||
TenantBoundCredentialCipher,
|
||||
"encrypt",
|
||||
lambda _self, plaintext: cipher.encrypt(plaintext.encode()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
TenantBoundCredentialCipher,
|
||||
"decrypt",
|
||||
lambda _self, ciphertext: cipher.decrypt(ciphertext).decode(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_config,
|
||||
"HUMAN_INPUT_IM_EVENT_TRANSPORT_MODE",
|
||||
IMEventTransportMode.STREAM,
|
||||
)
|
||||
return cipher
|
||||
|
||||
|
||||
def test_im_update_wires_opaque_version_through_real_service_and_postgresql_cas(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
created_response = test_client_with_containers.post(
|
||||
_BASE_PATH,
|
||||
json={"credentials": _SLACK_CREDENTIALS},
|
||||
headers=headers,
|
||||
)
|
||||
assert created_response.status_code == 200
|
||||
created_summary = created_response.get_json()["summary"]
|
||||
channel_id = IMChannelId(created_summary["id"])
|
||||
original_config_version = created_summary["config_version"]
|
||||
original_record = db_session_with_containers.scalar(
|
||||
sa.select(HumanInputIMChannel).where(HumanInputIMChannel.id == str(channel_id))
|
||||
)
|
||||
assert original_record is not None
|
||||
original_webhook_id = original_record.webhook_id
|
||||
|
||||
rotated_response = test_client_with_containers.put(
|
||||
f"{_BASE_PATH}/{channel_id}",
|
||||
json={
|
||||
"credentials": _SLACK_CREDENTIALS,
|
||||
"expected_config_version": original_config_version,
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert rotated_response.status_code == 200
|
||||
rotated_summary = rotated_response.get_json()["summary"]
|
||||
assert rotated_summary["id"] == str(channel_id)
|
||||
assert rotated_summary["config_version"] != original_config_version
|
||||
assert rotated_summary["webhook_url"] is None
|
||||
|
||||
stale_response = test_client_with_containers.put(
|
||||
f"{_BASE_PATH}/{channel_id}",
|
||||
json={
|
||||
"credentials": _SLACK_CREDENTIALS,
|
||||
"expected_config_version": original_config_version,
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert stale_response.status_code == 409
|
||||
assert stale_response.get_json()["code"] == "provider_configuration_updated"
|
||||
|
||||
service = build_workspace_im_channel_service(TenantId(tenant.id), AccountId(account.id))
|
||||
persisted = service.get(channel_id)
|
||||
assert persisted.id == channel_id
|
||||
assert persisted.config_version == 2
|
||||
db_session_with_containers.expire_all()
|
||||
rotated_record = db_session_with_containers.scalar(
|
||||
sa.select(HumanInputIMChannel).where(HumanInputIMChannel.id == str(channel_id))
|
||||
)
|
||||
assert rotated_record is not None
|
||||
assert rotated_record.webhook_id == original_webhook_id
|
||||
|
||||
|
||||
def test_service_transaction_rolls_back_a_flushed_create_on_unclassified_failure(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
original_create = WorkspaceIMChannelWriter.create
|
||||
|
||||
def create_then_fail(self: WorkspaceIMChannelWriter, channel: IMChannel) -> Never:
|
||||
original_create(self, channel)
|
||||
raise RuntimeError("sql-owner-key-secret-detail")
|
||||
|
||||
monkeypatch.setattr(WorkspaceIMChannelWriter, "create", create_then_fail)
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
_BASE_PATH,
|
||||
json={"credentials": _SLACK_CREDENTIALS},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert "sql-owner-key-secret-detail" not in response.get_data(as_text=True)
|
||||
db_session_with_containers.expire_all()
|
||||
persisted_count = db_session_with_containers.scalar(
|
||||
sa.select(sa.func.count(HumanInputIMChannel.id)).where(
|
||||
HumanInputIMChannel.owner_key == f"workspace:{tenant.id}"
|
||||
)
|
||||
)
|
||||
assert persisted_count == 0
|
||||
|
||||
|
||||
def test_partial_edit_and_saved_test_preserve_one_encrypted_document(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
static_provider_and_cipher: Fernet,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
client = test_client_with_containers
|
||||
created = client.post(_BASE_PATH, json={"credentials": _SLACK_CREDENTIALS}, headers=headers)
|
||||
assert created.status_code == 200
|
||||
summary = created.get_json()["summary"]
|
||||
channel_id = summary["id"]
|
||||
record = db_session_with_containers.get(HumanInputIMChannel, channel_id)
|
||||
assert record is not None
|
||||
original_envelope = record.encrypted_credentials
|
||||
edit = {
|
||||
"provider": "slack",
|
||||
"client_id": {"type": "unchanged"},
|
||||
"client_secret": "rotated-client-secret",
|
||||
"signing_secret": {"type": "unchanged"},
|
||||
"bot_token": {"type": "unchanged"},
|
||||
"app_token": None,
|
||||
}
|
||||
payload = {"credentials": edit, "expected_config_version": summary["config_version"]}
|
||||
|
||||
tested = client.post(f"{_BASE_PATH}/{channel_id}/test", json=payload, headers=headers)
|
||||
assert tested.status_code == 200
|
||||
db_session_with_containers.refresh(record)
|
||||
assert record.config_version == 1
|
||||
assert record.encrypted_credentials == original_envelope
|
||||
|
||||
updated = client.put(f"{_BASE_PATH}/{channel_id}", json=payload, headers=headers)
|
||||
assert updated.status_code == 200
|
||||
db_session_with_containers.refresh(record)
|
||||
assert record.config_version == 2
|
||||
assert record.encrypted_credentials != original_envelope
|
||||
decrypted = json.loads(static_provider_and_cipher.decrypt(b64decode(record.encrypted_credentials.ciphertext)))
|
||||
assert decrypted == {
|
||||
"provider": "slack",
|
||||
"client_id": "slack-client-1",
|
||||
"client_secret": "rotated-client-secret",
|
||||
"signing_secret": "signing-secret",
|
||||
"bot_token": "xoxb-bot-token",
|
||||
"app_token": None,
|
||||
}
|
||||
assert "rotated-client-secret" not in record.encrypted_credentials.ciphertext
|
||||
detail = client.get(f"{_BASE_PATH}/{channel_id}", headers=headers)
|
||||
assert detail.status_code == 200
|
||||
assert detail.get_json()["credentials"] == {
|
||||
"provider": "slack",
|
||||
"client_id": "slack-client-1",
|
||||
"client_secret": {"type": "redacted"},
|
||||
"signing_secret": {"type": "redacted"},
|
||||
"bot_token": {"type": "redacted"},
|
||||
"app_token": None,
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import AbstractContextManager
|
||||
from threading import Event, Lock
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from faker import Faker
|
||||
from flask import Flask
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.account import Account, Tenant, TenantAccountJoin
|
||||
from models.model import DifySetup
|
||||
from services.account.contracts import SetupInput
|
||||
from services.account.service import AccountSetupProvisioner
|
||||
from services.setup_adapters import RedisSetupLock
|
||||
from tests.e2e_tests.containers.helpers import generate_valid_password
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_dependencies() -> Iterator[MagicMock]:
|
||||
with (
|
||||
patch("services.account.login_adapters.SystemFeatureService") as feature_service,
|
||||
patch("services.account.login_adapters.BillingService") as billing_service,
|
||||
patch("services.account.adapters.CommunityTelemetryService.report_install") as report_install,
|
||||
):
|
||||
feature_service.is_registration_allowed.return_value = True
|
||||
feature_service.get_license.return_value.seats.is_available.return_value = True
|
||||
feature_service.get_license.return_value.workspaces.is_available.return_value = True
|
||||
feature_service.is_workspace_creation_allowed.return_value = True
|
||||
billing_service.is_email_in_freeze.return_value = False
|
||||
yield report_install
|
||||
|
||||
|
||||
def _setup_payload(*, email: str, password: str) -> dict[str, str]:
|
||||
return {
|
||||
"email": email,
|
||||
"name": "Admin",
|
||||
"password": password,
|
||||
"language": "en-US",
|
||||
}
|
||||
|
||||
|
||||
def test_setup_endpoint_persists_bootstrap_state_and_rejects_repeat(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
setup_dependencies: MagicMock,
|
||||
) -> None:
|
||||
monkeypatch.delenv("INIT_PASSWORD", raising=False)
|
||||
password = generate_valid_password(Faker())
|
||||
|
||||
response = test_client_with_containers.post(
|
||||
"/console/api/setup",
|
||||
json=_setup_payload(email="admin@example.com", password=password),
|
||||
headers={"CF-Connecting-IP": "198.51.100.7"},
|
||||
environ_overrides={"REMOTE_ADDR": "203.0.113.7"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.get_json() == {"result": "success"}
|
||||
setup_dependencies.assert_called_once()
|
||||
|
||||
repeated_response = test_client_with_containers.post(
|
||||
"/console/api/setup",
|
||||
json=_setup_payload(email="other@example.com", password=password),
|
||||
)
|
||||
|
||||
assert repeated_response.status_code == 403
|
||||
|
||||
db_session_with_containers.expire_all()
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(DifySetup)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(Account)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(Tenant)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(TenantAccountJoin)) == 1
|
||||
|
||||
account = db_session_with_containers.scalar(select(Account))
|
||||
assert account is not None
|
||||
assert account.email == "admin@example.com"
|
||||
assert account.last_login_ip == "203.0.113.7"
|
||||
|
||||
|
||||
def test_concurrent_setup_requests_create_only_one_bootstrap_identity(
|
||||
flask_app_with_containers: Flask,
|
||||
db_session_with_containers: Session,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
setup_dependencies: MagicMock,
|
||||
) -> None:
|
||||
monkeypatch.delenv("INIT_PASSWORD", raising=False)
|
||||
password = generate_valid_password(Faker())
|
||||
provision_started = Event()
|
||||
allow_provision_to_finish = Event()
|
||||
second_lock_attempted = Event()
|
||||
attempt_guard = Lock()
|
||||
lock_attempts = 0
|
||||
original_setup = AccountSetupProvisioner.provision
|
||||
original_acquire = RedisSetupLock.acquire
|
||||
|
||||
def blocking_setup(self: AccountSetupProvisioner, setup: SetupInput) -> None:
|
||||
if not provision_started.is_set():
|
||||
provision_started.set()
|
||||
assert allow_provision_to_finish.wait(timeout=10)
|
||||
original_setup(self, setup)
|
||||
|
||||
def tracked_acquire(self: RedisSetupLock) -> AbstractContextManager[None]:
|
||||
nonlocal lock_attempts
|
||||
with attempt_guard:
|
||||
lock_attempts += 1
|
||||
if lock_attempts == 2:
|
||||
second_lock_attempted.set()
|
||||
return original_acquire(self)
|
||||
|
||||
def post_setup(email: str) -> int:
|
||||
with flask_app_with_containers.test_client() as client:
|
||||
response = client.post(
|
||||
"/console/api/setup",
|
||||
json=_setup_payload(email=email, password=password),
|
||||
)
|
||||
return response.status_code
|
||||
|
||||
with (
|
||||
patch.object(AccountSetupProvisioner, "provision", blocking_setup),
|
||||
patch.object(RedisSetupLock, "acquire", tracked_acquire),
|
||||
ThreadPoolExecutor(max_workers=2) as executor,
|
||||
):
|
||||
first_request = executor.submit(post_setup, "admin-1@example.com")
|
||||
try:
|
||||
assert provision_started.wait(timeout=10)
|
||||
second_request = executor.submit(post_setup, "admin-2@example.com")
|
||||
assert second_lock_attempted.wait(timeout=10)
|
||||
assert not second_request.done()
|
||||
finally:
|
||||
allow_provision_to_finish.set()
|
||||
|
||||
results = [first_request.result(timeout=30), second_request.result(timeout=30)]
|
||||
|
||||
assert sorted(results) == [201, 403]
|
||||
setup_dependencies.assert_called_once()
|
||||
|
||||
db_session_with_containers.expire_all()
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(DifySetup)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(Account)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(Tenant)) == 1
|
||||
assert db_session_with_containers.scalar(select(func.count()).select_from(TenantAccountJoin)) == 1
|
||||
@@ -0,0 +1,37 @@
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def test_schema_definitions_endpoint_uses_admission_and_builtin_registry(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _ = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
"/console/api/spec/schema-definitions",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
definitions = response.get_json()
|
||||
assert isinstance(definitions, list)
|
||||
assert definitions
|
||||
assert all({"name", "label", "schema"} <= definition.keys() for definition in definitions)
|
||||
|
||||
|
||||
def test_schema_definitions_endpoint_rejects_unauthenticated_request(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
create_console_account_and_tenant(db_session_with_containers)
|
||||
|
||||
response = test_client_with_containers.get("/console/api/spec/schema-definitions")
|
||||
|
||||
assert response.status_code == 401
|
||||
+430
@@ -0,0 +1,430 @@
|
||||
"""PostgreSQL and Redis HTTP contracts for the IM Contact Sync control plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.human_input_v2.entities import (
|
||||
IMProvider,
|
||||
IMSyncRemovalReason,
|
||||
IMSyncResultType,
|
||||
IMSyncRunStatus,
|
||||
)
|
||||
from core.human_input_v2.im_integration import (
|
||||
IMChannelRevision,
|
||||
IMSyncRun,
|
||||
SyncContactSnapshot,
|
||||
SyncIdentitySnapshot,
|
||||
SyncResultFact,
|
||||
)
|
||||
from core.human_input_v2.shared import (
|
||||
AccountId,
|
||||
ContactId,
|
||||
IMIdentityId,
|
||||
IMSyncResultId,
|
||||
IMSyncRunId,
|
||||
NormalizedEmail,
|
||||
TenantId,
|
||||
)
|
||||
from models.account import Account, Tenant
|
||||
from models.human_input_v2 import (
|
||||
ContactSubjectType,
|
||||
HumanInputContactIdentity,
|
||||
HumanInputIMBinding,
|
||||
HumanInputIMSyncRun,
|
||||
)
|
||||
from repositories.human_input_v2.channel_credentials import ChannelEncryptedCredentials
|
||||
from repositories.human_input_v2.contact import Contact, ContactType
|
||||
from repositories.human_input_v2.im_channel_repository import (
|
||||
IMChannel,
|
||||
IMChannelId,
|
||||
IMChannelStatus,
|
||||
WebhookId,
|
||||
)
|
||||
from repositories.human_input_v2.im_identity_repository import IMIdentity, IMIdentityObservation, OpaqueProviderPayload
|
||||
from repositories.human_input_v2.im_integration.mappers import (
|
||||
sync_result_to_record,
|
||||
sync_run_to_record,
|
||||
)
|
||||
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
|
||||
from repositories.human_input_v2.sqlalchemy_im_identity_repository import SQLAlchemyIMIdentityRepository
|
||||
from tasks.im_contact_sync_tasks import reconcile_im_contacts_task
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
_NOW = datetime(2026, 8, 11, 8)
|
||||
_LATER = datetime(2026, 8, 11, 9)
|
||||
_CONTACT_ID = ContactId("00000000-0000-0000-0000-000000000101")
|
||||
_CHANNEL_ID = IMChannelId("00000000-0000-0000-0000-000000000201")
|
||||
_PRIMARY_IDENTITY_ID = IMIdentityId("00000000-0000-0000-0000-000000000301")
|
||||
_SECONDARY_IDENTITY_ID = IMIdentityId("00000000-0000-0000-0000-000000000302")
|
||||
_SYNC_RUNS_PATH = "/console/api/workspaces/current/human-input/v2/im-sync-runs"
|
||||
|
||||
|
||||
def _seed_control_plane(
|
||||
session: Session,
|
||||
) -> tuple[Account, Tenant, Contact, IMChannel, IMIdentity, IMIdentity]:
|
||||
account, tenant = create_console_account_and_tenant(session)
|
||||
tenant_id = TenantId(tenant.id)
|
||||
account.name = "Reviewer"
|
||||
account.email = "reviewer@example.com"
|
||||
contact_identity = HumanInputContactIdentity(
|
||||
subject_type=ContactSubjectType.ACCOUNT,
|
||||
account_id=account.id,
|
||||
)
|
||||
contact_identity.id = str(_CONTACT_ID)
|
||||
contact_identity.created_at = _NOW
|
||||
contact_identity.updated_at = _NOW
|
||||
contact = Contact(
|
||||
id=_CONTACT_ID,
|
||||
type=ContactType.WORKSPACE,
|
||||
name="Reviewer",
|
||||
email="reviewer@example.com",
|
||||
avatar_file_id=None,
|
||||
created_at=_NOW,
|
||||
)
|
||||
channel = IMChannel(
|
||||
id=_CHANNEL_ID,
|
||||
created_at=_NOW,
|
||||
updated_at=_NOW,
|
||||
provider=IMProvider.FEISHU,
|
||||
provider_tenant_id="provider-tenant-1",
|
||||
encrypted_credentials=ChannelEncryptedCredentials(ciphertext="opaque-feishu-ciphertext"),
|
||||
app_identifier="app-1",
|
||||
webhook_id=WebhookId("00000000000000000000000000000001"),
|
||||
config_version=1,
|
||||
status=IMChannelStatus.CONNECTED,
|
||||
)
|
||||
session.add(contact_identity)
|
||||
WorkspaceIMChannelWriter(session, tenant_id, AccountId(account.id)).create(channel)
|
||||
identity_repository = SQLAlchemyIMIdentityRepository(session, channel.id)
|
||||
primary_identity = _create_identity(
|
||||
identity_repository,
|
||||
_PRIMARY_IDENTITY_ID,
|
||||
"provider-user-primary",
|
||||
"Primary Reviewer",
|
||||
"reviewer@example.com",
|
||||
)
|
||||
secondary_identity = _create_identity(
|
||||
identity_repository,
|
||||
_SECONDARY_IDENTITY_ID,
|
||||
"provider-user-secondary",
|
||||
"Secondary Reviewer",
|
||||
"secondary@example.com",
|
||||
)
|
||||
session.commit()
|
||||
return account, tenant, contact, channel, primary_identity, secondary_identity
|
||||
|
||||
|
||||
def _create_identity(
|
||||
repository: SQLAlchemyIMIdentityRepository,
|
||||
identity_id: IMIdentityId,
|
||||
provider_user_id: str,
|
||||
display_name: str,
|
||||
email: str,
|
||||
) -> IMIdentity:
|
||||
return repository.create(
|
||||
identity_id,
|
||||
IMIdentityObservation(
|
||||
provider_user_id=provider_user_id,
|
||||
display_name=display_name,
|
||||
email=email,
|
||||
raw_payload=OpaqueProviderPayload({}),
|
||||
sync_run_id=IMSyncRunId("00000000-0000-0000-0000-000000000901"),
|
||||
observed_at=_NOW,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_manual_binding_http_commands_use_real_guarded_postgresql_writes(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant, contact, _channel, _primary, _secondary = _seed_control_plane(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
binding_path = f"/console/api/workspaces/current/human-input/v2/contacts/{contact.id}/im-bindings"
|
||||
override_path = f"/console/api/workspaces/current/human-input/v2/contacts/{contact.id}/im-override"
|
||||
|
||||
created = test_client_with_containers.put(
|
||||
binding_path,
|
||||
json={"identity_id": str(_PRIMARY_IDENTITY_ID)},
|
||||
headers=headers,
|
||||
)
|
||||
assert created.status_code == 200
|
||||
created_payload = created.get_json()
|
||||
assert created_payload is not None
|
||||
organization_binding = created_payload["contact"]["im_bindings"][0]
|
||||
assert organization_binding["scope"] == "organization"
|
||||
|
||||
idempotent = test_client_with_containers.put(
|
||||
binding_path,
|
||||
json={"identity_id": str(_PRIMARY_IDENTITY_ID)},
|
||||
headers=headers,
|
||||
)
|
||||
assert idempotent.status_code == 200
|
||||
assert idempotent.get_json()["contact"]["im_bindings"] == [organization_binding]
|
||||
|
||||
replacement = test_client_with_containers.put(
|
||||
binding_path,
|
||||
json={"identity_id": str(_SECONDARY_IDENTITY_ID)},
|
||||
headers=headers,
|
||||
)
|
||||
assert replacement.status_code == 200
|
||||
replacement_bindings = replacement.get_json()["contact"]["im_bindings"]
|
||||
assert len(replacement_bindings) == 1
|
||||
replacement_binding = replacement_bindings[0]
|
||||
assert replacement_binding["scope"] == "organization"
|
||||
assert replacement_binding["id"] != organization_binding["id"]
|
||||
|
||||
missing_identity = test_client_with_containers.put(
|
||||
binding_path,
|
||||
json={"identity_id": "00000000-0000-0000-0000-000000000399"},
|
||||
headers=headers,
|
||||
)
|
||||
assert missing_identity.status_code == 404
|
||||
assert missing_identity.get_json()["code"] == "im_identity_not_found"
|
||||
|
||||
override = test_client_with_containers.put(
|
||||
override_path,
|
||||
json={"identity_id": str(_SECONDARY_IDENTITY_ID)},
|
||||
headers=headers,
|
||||
)
|
||||
assert override.status_code == 403
|
||||
assert override.get_json() == {
|
||||
"code": "workspace_im_override_not_allowed",
|
||||
"message": "Workspace IM overrides require centrally managed bindings.",
|
||||
"status": 403,
|
||||
}
|
||||
|
||||
reset = test_client_with_containers.delete(override_path, headers=headers)
|
||||
assert reset.status_code == 403
|
||||
assert reset.get_json() == override.get_json()
|
||||
db_session_with_containers.expire_all()
|
||||
stored_binding = db_session_with_containers.scalar(select(HumanInputIMBinding))
|
||||
assert stored_binding is not None
|
||||
assert stored_binding.id == replacement_binding["id"]
|
||||
assert stored_binding.im_identity_id == str(_SECONDARY_IDENTITY_ID)
|
||||
assert db_session_with_containers.get(HumanInputIMBinding, organization_binding["id"]) is None
|
||||
|
||||
deleted = test_client_with_containers.delete(binding_path, headers=headers)
|
||||
assert deleted.status_code == 200
|
||||
assert deleted.get_json() == {}
|
||||
db_session_with_containers.expire_all()
|
||||
assert db_session_with_containers.scalar(select(HumanInputIMBinding)) is None
|
||||
|
||||
missing_binding = test_client_with_containers.delete(binding_path, headers=headers)
|
||||
assert missing_binding.status_code == 404
|
||||
assert missing_binding.get_json()["code"] == "im_binding_not_found"
|
||||
|
||||
|
||||
def test_sync_command_and_identity_queries_use_real_postgresql(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
account, tenant, _contact, channel, _primary, _secondary = _seed_control_plane(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
dispatched: list[tuple[tuple[str, str, str | None], str]] = []
|
||||
|
||||
def capture_dispatch(*, args: tuple[str, str, str | None], queue: str) -> None:
|
||||
dispatched.append((args, queue))
|
||||
|
||||
monkeypatch.setattr(reconcile_im_contacts_task, "apply_async", capture_dispatch)
|
||||
|
||||
created = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
|
||||
replayed = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
|
||||
latest = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
|
||||
identities = test_client_with_containers.get(
|
||||
"/console/api/workspaces/current/human-input/v2/im-identities",
|
||||
query_string={"keyword": "provider-user", "page": 1, "limit": 1},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert created.status_code == replayed.status_code == latest.status_code == identities.status_code == 200
|
||||
created_run = created.get_json()["run"]
|
||||
assert replayed.get_json()["run"]["id"] == created_run["id"]
|
||||
assert latest.get_json()["run"]["id"] == created_run["id"]
|
||||
expected_dispatch = (
|
||||
(created_run["id"], "workspace", tenant.id),
|
||||
"human_input_contact_sync",
|
||||
)
|
||||
assert dispatched == [expected_dispatch, expected_dispatch]
|
||||
identity_page = identities.get_json()
|
||||
assert identity_page["total"] == 2
|
||||
assert len(identity_page["data"]) == 1
|
||||
assert identity_page["data"][0]["provider"] == IMProvider.FEISHU.value
|
||||
assert identity_page["data"][0]["binding_status"] == "unbound"
|
||||
assert created_run["channel_id"] == str(channel.id)
|
||||
|
||||
|
||||
def test_latest_result_http_projection_reads_every_persisted_bucket(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, _tenant, contact, channel, primary_identity, _secondary = _seed_control_plane(db_session_with_containers)
|
||||
run = replace(
|
||||
IMSyncRun.create(
|
||||
sync_run_id=IMSyncRunId("00000000-0000-0000-0000-000000000501"),
|
||||
channel_revision=IMChannelRevision(str(channel.id), channel.config_version),
|
||||
provider=channel.provider,
|
||||
started_by_account_id=AccountId(account.id),
|
||||
now=_NOW,
|
||||
),
|
||||
status=IMSyncRunStatus.SUCCEEDED,
|
||||
added_count=1,
|
||||
not_matched_count=1,
|
||||
failed_count=1,
|
||||
removed_count=1,
|
||||
skipped_count=1,
|
||||
started_at=_NOW,
|
||||
finished_at=_LATER,
|
||||
)
|
||||
results = _result_facts(run, contact, primary_identity, channel.provider)
|
||||
db_session_with_containers.add(sync_run_to_record(run))
|
||||
db_session_with_containers.add_all(sync_result_to_record(result) for result in results)
|
||||
db_session_with_containers.commit()
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
for result in results:
|
||||
response = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": result.result_type.value, "page": 1, "limit": 20},
|
||||
headers=headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload is not None
|
||||
assert (payload["page"], payload["limit"], payload["total"]) == (1, 20, 1)
|
||||
assert payload["data"][0]["result"]["type"] == result.result_type.value
|
||||
|
||||
added = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": IMSyncResultType.ADDED.value, "page": 1, "limit": 20},
|
||||
headers=headers,
|
||||
).get_json()["data"][0]["result"]
|
||||
failed = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": IMSyncResultType.FAILED.value, "page": 1, "limit": 20},
|
||||
headers=headers,
|
||||
).get_json()["data"][0]["result"]
|
||||
removed = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": IMSyncResultType.REMOVED.value, "page": 1, "limit": 20},
|
||||
headers=headers,
|
||||
).get_json()["data"][0]["result"]
|
||||
assert added["contact"]["id"] == str(contact.id)
|
||||
assert failed["reason"] == "Directory read failed"
|
||||
assert removed["last_known_identity"]["identity_id"] == str(primary_identity.id)
|
||||
assert removed["reason"] == IMSyncRemovalReason.NOT_PRESENT_IN_DIRECTORY.value
|
||||
|
||||
|
||||
def _result_facts(
|
||||
run: IMSyncRun,
|
||||
contact: Contact,
|
||||
identity: IMIdentity,
|
||||
provider: IMProvider,
|
||||
) -> tuple[SyncResultFact, ...]:
|
||||
contact_snapshot = SyncContactSnapshot(contact.id, contact.name, contact.email, contact.avatar_file_id)
|
||||
identity_snapshot = SyncIdentitySnapshot(
|
||||
identity.id,
|
||||
provider,
|
||||
identity.provider_user_id,
|
||||
identity.display_name,
|
||||
identity.email,
|
||||
)
|
||||
|
||||
def result(
|
||||
result_id: int,
|
||||
result_type: IMSyncResultType,
|
||||
*,
|
||||
include_entry: bool = True,
|
||||
include_contact: bool = False,
|
||||
removal_reason: IMSyncRemovalReason | None = None,
|
||||
reason_message: str | None = None,
|
||||
) -> SyncResultFact:
|
||||
suffix = str(result_id).zfill(12)
|
||||
return SyncResultFact(
|
||||
id=IMSyncResultId(f"00000000-0000-0000-0000-{suffix}"),
|
||||
channel_id=IMChannelId(run.channel_revision.channel_id),
|
||||
sync_run_id=run.id,
|
||||
operation_key=f"result:{result_type.value}:{result_id}",
|
||||
result_type=result_type,
|
||||
provider_user_id=identity.provider_user_id if include_entry else None,
|
||||
display_name=identity.display_name if include_entry else None,
|
||||
email=identity.email if include_entry else None,
|
||||
normalized_email=NormalizedEmail(identity.email) if include_entry and identity.email is not None else None,
|
||||
contact_id=contact.id if include_contact else None,
|
||||
identity_id=identity.id,
|
||||
binding_id=None,
|
||||
removal_reason=removal_reason,
|
||||
reason_code=None,
|
||||
reason_message=reason_message,
|
||||
directory_entry_payload=None,
|
||||
contact_snapshot=contact_snapshot if include_contact else None,
|
||||
identity_snapshot=identity_snapshot if removal_reason is not None else None,
|
||||
created_at=_NOW,
|
||||
updated_at=_NOW,
|
||||
)
|
||||
|
||||
return (
|
||||
result(1, IMSyncResultType.ADDED, include_contact=True),
|
||||
result(2, IMSyncResultType.NOT_MATCHED),
|
||||
result(3, IMSyncResultType.FAILED, reason_message="Directory read failed"),
|
||||
result(
|
||||
4,
|
||||
IMSyncResultType.REMOVED,
|
||||
include_entry=False,
|
||||
include_contact=True,
|
||||
removal_reason=IMSyncRemovalReason.NOT_PRESENT_IN_DIRECTORY,
|
||||
),
|
||||
result(5, IMSyncResultType.SKIPPED, include_contact=True),
|
||||
)
|
||||
|
||||
|
||||
def test_missing_control_plane_state_returns_stable_http_errors(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
|
||||
missing_integration = test_client_with_containers.get(
|
||||
"/console/api/workspaces/current/human-input/v2/im-identities",
|
||||
headers=headers,
|
||||
)
|
||||
missing_sync_integration = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
|
||||
assert missing_integration.status_code == missing_sync_integration.status_code == 404
|
||||
assert missing_integration.get_json()["code"] == "im_integration_not_configured"
|
||||
|
||||
channel = IMChannel(
|
||||
id=_CHANNEL_ID,
|
||||
created_at=_NOW,
|
||||
updated_at=_NOW,
|
||||
provider=IMProvider.FEISHU,
|
||||
provider_tenant_id="provider-tenant-1",
|
||||
encrypted_credentials=ChannelEncryptedCredentials(ciphertext="opaque-feishu-ciphertext"),
|
||||
app_identifier="app-1",
|
||||
webhook_id=WebhookId("00000000000000000000000000000001"),
|
||||
config_version=1,
|
||||
status=IMChannelStatus.CONNECTED,
|
||||
)
|
||||
WorkspaceIMChannelWriter(db_session_with_containers, TenantId(tenant.id), AccountId(account.id)).create(channel)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
missing_run = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
|
||||
missing_results = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": IMSyncResultType.ADDED.value},
|
||||
headers=headers,
|
||||
)
|
||||
assert missing_run.status_code == missing_results.status_code == 404
|
||||
assert missing_run.get_json()["code"] == "im_sync_run_not_found"
|
||||
assert db_session_with_containers.scalar(select(HumanInputIMSyncRun)) is None
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
"""Authenticated HTTP-to-worker live Slack reconciliation verification."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.human_input_v2.entities import IMProvider, IMSyncRunStatus
|
||||
from core.human_input_v2.im_integration.adapters import SlackCredentials
|
||||
from core.human_input_v2.shared import AccountId, IMSyncRunId, TenantId, WorkspaceScope
|
||||
from extensions.ext_key_provider import key_provider_manager
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.rsa import generate_key_pair
|
||||
from libs.uuid_utils import uuidv7
|
||||
from models.human_input_v2 import HumanInputIMIdentity, HumanInputIMSyncResult
|
||||
from repositories.human_input_v2.im_channel_repository import (
|
||||
IMChannel,
|
||||
IMChannelId,
|
||||
IMChannelStatus,
|
||||
WebhookId,
|
||||
)
|
||||
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
|
||||
from services.human_input_v2.im_contact_sync.composition import build_im_contact_sync_worker
|
||||
from services.human_input_v2.im_credential_codec import IMCredentialCodec
|
||||
from services.human_input_v2.im_tenant_credential_cipher import TenantBoundCredentialCipher
|
||||
from tasks.im_contact_sync_tasks import reconcile_im_contacts_task
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
_SYNC_RUNS_PATH = "/console/api/workspaces/current/human-input/v2/im-sync-runs"
|
||||
_REQUIRED_SLACK_ENVIRONMENT = (
|
||||
"SLACK_CLIENT_ID",
|
||||
"SLACK_CLIENT_SECRET",
|
||||
"SLACK_SIGNING_SECRET",
|
||||
"SLACK_BOT_TOKEN",
|
||||
"SLACK_APP_SOCKET_TOKEN",
|
||||
)
|
||||
|
||||
|
||||
def test_authenticated_http_sync_reaches_live_provider_worker_and_persisted_queries(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
credentials = _live_slack_credentials()
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tenant.encrypt_public_key = generate_key_pair(tenant.id)
|
||||
db_session_with_containers.commit()
|
||||
channel = _persist_live_slack_channel(
|
||||
db_session_with_containers,
|
||||
tenant_id=TenantId(tenant.id),
|
||||
actor_id=AccountId(account.id),
|
||||
credentials=credentials,
|
||||
now=naive_utc_now(),
|
||||
)
|
||||
headers = authenticate_console_client(test_client_with_containers, account)
|
||||
dispatched: list[tuple[tuple[str, str, str | None], str]] = []
|
||||
|
||||
def capture_dispatch(*, args: tuple[str, str, str | None], queue: str) -> None:
|
||||
dispatched.append((args, queue))
|
||||
|
||||
monkeypatch.setattr(reconcile_im_contacts_task, "apply_async", capture_dispatch)
|
||||
|
||||
create_response = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
|
||||
|
||||
assert create_response.status_code == 200
|
||||
create_payload = create_response.get_json()
|
||||
assert create_payload is not None
|
||||
run_payload = create_payload["run"]
|
||||
assert run_payload["status"] == IMSyncRunStatus.QUEUED.value
|
||||
sync_run_id = IMSyncRunId(run_payload["id"])
|
||||
assert dispatched == [
|
||||
(
|
||||
(str(sync_run_id), "workspace", tenant.id),
|
||||
"human_input_contact_sync",
|
||||
)
|
||||
]
|
||||
|
||||
terminal_run = build_im_contact_sync_worker().execute(
|
||||
sync_run_id,
|
||||
WorkspaceScope(id=TenantId(tenant.id)),
|
||||
)
|
||||
|
||||
assert terminal_run.status is IMSyncRunStatus.SUCCEEDED
|
||||
latest_response = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
|
||||
assert latest_response.status_code == 200
|
||||
latest_payload = latest_response.get_json()
|
||||
assert latest_payload is not None
|
||||
assert latest_payload["run"]["id"] == str(sync_run_id)
|
||||
assert latest_payload["run"]["status"] == IMSyncRunStatus.SUCCEEDED.value
|
||||
result_counts: dict[str, int] = latest_payload["run"]["result_counts"]
|
||||
assert sum(result_counts.values()) > 0
|
||||
|
||||
result_bucket, expected_total = next((bucket, count) for bucket, count in result_counts.items() if count > 0)
|
||||
first_page_response = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": result_bucket, "page": 1, "limit": 1},
|
||||
headers=headers,
|
||||
)
|
||||
assert first_page_response.status_code == 200
|
||||
first_page = first_page_response.get_json()
|
||||
assert first_page is not None
|
||||
assert (first_page["page"], first_page["limit"], first_page["total"]) == (1, 1, expected_total)
|
||||
assert len(first_page["data"]) == 1
|
||||
|
||||
if expected_total > 1:
|
||||
second_page_response = test_client_with_containers.get(
|
||||
f"{_SYNC_RUNS_PATH}/latest/results",
|
||||
query_string={"result": result_bucket, "page": 2, "limit": 1},
|
||||
headers=headers,
|
||||
)
|
||||
assert second_page_response.status_code == 200
|
||||
second_page = second_page_response.get_json()
|
||||
assert second_page is not None
|
||||
assert (second_page["page"], second_page["limit"], second_page["total"]) == (2, 1, expected_total)
|
||||
assert len(second_page["data"]) == 1
|
||||
|
||||
db_session_with_containers.expire_all()
|
||||
persisted_result_count = db_session_with_containers.scalar(
|
||||
select(func.count(HumanInputIMSyncResult.id)).where(HumanInputIMSyncResult.sync_run_id == str(sync_run_id))
|
||||
)
|
||||
persisted_identity_count = db_session_with_containers.scalar(
|
||||
select(func.count(HumanInputIMIdentity.id)).where(HumanInputIMIdentity.channel_id == str(channel.id))
|
||||
)
|
||||
assert persisted_result_count == sum(result_counts.values())
|
||||
assert persisted_identity_count == persisted_result_count
|
||||
|
||||
|
||||
def _live_slack_credentials() -> dict[str, str]:
|
||||
missing_names = tuple(name for name in _REQUIRED_SLACK_ENVIRONMENT if not os.getenv(name))
|
||||
if missing_names:
|
||||
pytest.skip("live Slack credentials are not configured")
|
||||
return {name: os.environ[name] for name in _REQUIRED_SLACK_ENVIRONMENT}
|
||||
|
||||
|
||||
def _persist_live_slack_channel(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: TenantId,
|
||||
actor_id: AccountId,
|
||||
credentials: dict[str, str],
|
||||
now: datetime,
|
||||
) -> IMChannel:
|
||||
plaintext_credentials = SlackCredentials(
|
||||
provider=IMProvider.SLACK,
|
||||
client_id=credentials["SLACK_CLIENT_ID"],
|
||||
client_secret=credentials["SLACK_CLIENT_SECRET"],
|
||||
signing_secret=credentials["SLACK_SIGNING_SECRET"],
|
||||
bot_token=credentials["SLACK_BOT_TOKEN"],
|
||||
app_token=credentials["SLACK_APP_SOCKET_TOKEN"],
|
||||
)
|
||||
protected = IMCredentialCodec(TenantBoundCredentialCipher(key_provider_manager.provider, str(tenant_id))).seal(
|
||||
plaintext_credentials
|
||||
)
|
||||
channel = IMChannel(
|
||||
id=IMChannelId(str(uuidv7())),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
provider=IMProvider.SLACK,
|
||||
provider_tenant_id="live-slack-workspace",
|
||||
encrypted_credentials=protected,
|
||||
app_identifier=plaintext_credentials.client_id,
|
||||
webhook_id=WebhookId(uuidv7().hex),
|
||||
config_version=1,
|
||||
status=IMChannelStatus.CONNECTED,
|
||||
)
|
||||
WorkspaceIMChannelWriter(session, tenant_id, actor_id).create(channel)
|
||||
session.commit()
|
||||
return channel
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from collections.abc import Callable
|
||||
from typing import cast
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
import services.errors.base
|
||||
import services.errors.workspace
|
||||
from controllers.console.auth.error import MemberNotInTenantError
|
||||
from controllers.console.workspace.members import MemberCancelInviteApi, MemberUpdateRoleApi, OwnerTransfer
|
||||
from extensions.ext_application_services import application_services
|
||||
from libs.exception import BaseHTTPException
|
||||
from libs.helper import TokenManager
|
||||
from machinery.context import RequestContext
|
||||
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus
|
||||
from services.workspace import gateways
|
||||
|
||||
JsonResponse = dict[str, object]
|
||||
StatusResponse = tuple[JsonResponse, int]
|
||||
|
||||
|
||||
def unwrap(func: Callable[..., object]) -> Callable[..., object]:
|
||||
return inspect.unwrap(func)
|
||||
|
||||
|
||||
def unwrap_status_response(func: Callable[..., object]) -> Callable[..., StatusResponse]:
|
||||
return cast(Callable[..., StatusResponse], inspect.unwrap(func))
|
||||
|
||||
|
||||
def unwrap_json_response(func: Callable[..., object]) -> Callable[..., JsonResponse]:
|
||||
return cast(Callable[..., JsonResponse], inspect.unwrap(func))
|
||||
|
||||
|
||||
def unwrap_json_or_status_response(func: Callable[..., object]) -> Callable[..., JsonResponse | StatusResponse]:
|
||||
return cast(Callable[..., JsonResponse | StatusResponse], inspect.unwrap(func))
|
||||
|
||||
|
||||
def unwrap_raises(func: Callable[..., object]) -> Callable[..., object]:
|
||||
return unwrap(func)
|
||||
|
||||
|
||||
class WorkspaceMembersIntegrationFactory:
|
||||
@staticmethod
|
||||
def create_tenant(db_session_with_containers: Session) -> Tenant:
|
||||
tenant = Tenant(name=f"Tenant {uuid4()}", plan="basic", status=TenantStatus.NORMAL)
|
||||
db_session_with_containers.add(tenant)
|
||||
db_session_with_containers.commit()
|
||||
return tenant
|
||||
|
||||
@staticmethod
|
||||
def create_account(
|
||||
db_session_with_containers: Session,
|
||||
*,
|
||||
email_prefix: str,
|
||||
tenant: Tenant | None = None,
|
||||
role: TenantAccountRole = TenantAccountRole.NORMAL,
|
||||
current: bool = False,
|
||||
) -> Account:
|
||||
account = Account(
|
||||
name=f"Account {uuid4()}",
|
||||
email=f"{email_prefix}-{uuid4()}@example.com",
|
||||
password="hashed-password",
|
||||
password_salt="salt",
|
||||
interface_language="en-US",
|
||||
timezone="UTC",
|
||||
)
|
||||
db_session_with_containers.add(account)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
if tenant is not None:
|
||||
join = TenantAccountJoin(
|
||||
tenant_id=tenant.id,
|
||||
account_id=account.id,
|
||||
role=role,
|
||||
current=current,
|
||||
)
|
||||
db_session_with_containers.add(join)
|
||||
db_session_with_containers.commit()
|
||||
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
|
||||
return account
|
||||
|
||||
@staticmethod
|
||||
def create_owner_workspace(db_session_with_containers: Session) -> tuple[Tenant, Account]:
|
||||
tenant = WorkspaceMembersIntegrationFactory.create_tenant(db_session_with_containers)
|
||||
owner = WorkspaceMembersIntegrationFactory.create_account(
|
||||
db_session_with_containers,
|
||||
email_prefix="owner",
|
||||
tenant=tenant,
|
||||
role=TenantAccountRole.OWNER,
|
||||
current=True,
|
||||
)
|
||||
return tenant, owner
|
||||
|
||||
@staticmethod
|
||||
def create_owner_transfer_token(account: Account) -> str:
|
||||
token = TokenManager.generate_token(
|
||||
account_id=account.id, email=account.email, token_type="owner_transfer", additional_data={"code": "123456"}
|
||||
)
|
||||
return token
|
||||
|
||||
@staticmethod
|
||||
def get_join(db_session_with_containers: Session, *, tenant: Tenant, account: Account) -> TenantAccountJoin:
|
||||
tenant_id = tenant.id
|
||||
account_id = account.id
|
||||
db_session_with_containers.expire_all()
|
||||
join = (
|
||||
db_session_with_containers.query(TenantAccountJoin)
|
||||
.filter_by(tenant_id=tenant_id, account_id=account_id)
|
||||
.one()
|
||||
)
|
||||
return join
|
||||
|
||||
|
||||
class TestMemberCancelInviteApiWithContainers:
|
||||
def test_cancel_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = MemberCancelInviteApi()
|
||||
method = unwrap_status_response(api.delete)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(db_session_with_containers, email_prefix="member")
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/"),
|
||||
patch.object(application_services().workspaces.members, "remove") as mock_remove_member,
|
||||
):
|
||||
result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
assert status == 200
|
||||
assert result["result"] == "success"
|
||||
mock_remove_member.assert_called_once()
|
||||
called_tenant, called_member, called_current_user = mock_remove_member.call_args.args
|
||||
assert called_tenant == tenant.id
|
||||
assert called_member == member.id
|
||||
assert called_current_user == current_user.id
|
||||
|
||||
def test_cancel_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = MemberCancelInviteApi()
|
||||
method = unwrap_raises(api.delete)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
|
||||
with flask_app_with_containers.test_request_context("/"):
|
||||
with pytest.raises(HTTPException):
|
||||
method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))
|
||||
|
||||
def test_cancel_cannot_operate_self(
|
||||
self, flask_app_with_containers: Flask, db_session_with_containers: Session
|
||||
) -> None:
|
||||
api = MemberCancelInviteApi()
|
||||
method = unwrap_status_response(api.delete)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(db_session_with_containers, email_prefix="member")
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/"),
|
||||
patch.object(
|
||||
application_services().workspaces.members,
|
||||
"remove",
|
||||
side_effect=services.errors.workspace.CannotOperateSelfError("x"),
|
||||
),
|
||||
):
|
||||
with pytest.raises(BaseHTTPException) as exc_info:
|
||||
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
assert exc_info.value.code == 400
|
||||
assert exc_info.value.data == {
|
||||
"code": "cannot_operate_self",
|
||||
"message": exc_info.value.description,
|
||||
"status": 400,
|
||||
}
|
||||
|
||||
def test_cancel_no_permission(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = MemberCancelInviteApi()
|
||||
method = unwrap_status_response(api.delete)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(db_session_with_containers, email_prefix="member")
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/"),
|
||||
patch.object(
|
||||
application_services().workspaces.members,
|
||||
"remove",
|
||||
side_effect=services.errors.base.NoPermissionError("x"),
|
||||
),
|
||||
):
|
||||
with pytest.raises(BaseHTTPException) as exc_info:
|
||||
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
assert exc_info.value.code == 403
|
||||
assert exc_info.value.data == {"code": "forbidden", "message": exc_info.value.description, "status": 403}
|
||||
|
||||
def test_cancel_member_not_in_tenant(
|
||||
self, flask_app_with_containers: Flask, db_session_with_containers: Session
|
||||
) -> None:
|
||||
api = MemberCancelInviteApi()
|
||||
method = unwrap_status_response(api.delete)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(db_session_with_containers, email_prefix="member")
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/"),
|
||||
patch.object(
|
||||
application_services().workspaces.members,
|
||||
"remove",
|
||||
side_effect=services.errors.workspace.MemberNotInTenantError(),
|
||||
),
|
||||
):
|
||||
with pytest.raises(BaseHTTPException) as exc_info:
|
||||
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
assert exc_info.value.code == 404
|
||||
assert exc_info.value.data == {"code": "member_not_found", "message": exc_info.value.description, "status": 404}
|
||||
|
||||
|
||||
class TestMemberUpdateRoleApiWithContainers:
|
||||
def test_update_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = MemberUpdateRoleApi()
|
||||
method = unwrap_json_or_status_response(api.put)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(
|
||||
db_session_with_containers,
|
||||
email_prefix="member",
|
||||
tenant=tenant,
|
||||
role=TenantAccountRole.EDITOR,
|
||||
)
|
||||
|
||||
with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):
|
||||
result = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
if isinstance(result, tuple):
|
||||
result = result[0]
|
||||
|
||||
assert result["result"] == "success"
|
||||
assert (
|
||||
factory.get_join(db_session_with_containers, tenant=tenant, account=member).role == TenantAccountRole.NORMAL
|
||||
)
|
||||
|
||||
def test_update_member_not_found(
|
||||
self, flask_app_with_containers: Flask, db_session_with_containers: Session
|
||||
) -> None:
|
||||
api = MemberUpdateRoleApi()
|
||||
method = unwrap_raises(api.put)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
|
||||
with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):
|
||||
with pytest.raises(HTTPException):
|
||||
method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))
|
||||
|
||||
|
||||
class TestOwnerTransferApiWithContainers:
|
||||
def test_member_not_in_tenant(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = OwnerTransfer()
|
||||
method = unwrap_raises(api.post)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(db_session_with_containers, email_prefix="member")
|
||||
token = factory.create_owner_transfer_token(current_user)
|
||||
|
||||
with flask_app_with_containers.test_request_context("/", json={"token": token}):
|
||||
with pytest.raises(MemberNotInTenantError):
|
||||
method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
def test_member_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = OwnerTransfer()
|
||||
method = unwrap_raises(api.post)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
token = factory.create_owner_transfer_token(current_user)
|
||||
|
||||
with flask_app_with_containers.test_request_context("/", json={"token": token}):
|
||||
with pytest.raises(HTTPException):
|
||||
method(api, RequestContext("test", None, current_user.id, tenant.id), str(uuid4()))
|
||||
|
||||
def test_transfer_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
|
||||
api = OwnerTransfer()
|
||||
method = unwrap_json_response(api.post)
|
||||
factory = WorkspaceMembersIntegrationFactory
|
||||
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
|
||||
member = factory.create_account(
|
||||
db_session_with_containers,
|
||||
email_prefix="member",
|
||||
tenant=tenant,
|
||||
role=TenantAccountRole.NORMAL,
|
||||
)
|
||||
token = factory.create_owner_transfer_token(current_user)
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context("/", json={"token": token}),
|
||||
patch.object(gateways.send_new_owner_transfer_notify_email_task, "delay") as notify_new,
|
||||
patch.object(gateways.send_old_owner_transfer_notify_email_task, "delay") as notify_old,
|
||||
):
|
||||
result = method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)
|
||||
|
||||
assert result["result"] == "success"
|
||||
assert (
|
||||
factory.get_join(db_session_with_containers, tenant=tenant, account=member).role == TenantAccountRole.OWNER
|
||||
)
|
||||
assert (
|
||||
factory.get_join(db_session_with_containers, tenant=tenant, account=current_user).role
|
||||
== TenantAccountRole.NORMAL
|
||||
)
|
||||
notify_new.assert_called_once_with(language="en-US", to=member.email, workspace=tenant.name)
|
||||
notify_old.assert_called_once_with(
|
||||
language="en-US", to=current_user.email, workspace=tenant.name, new_owner_email=member.email
|
||||
)
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
"""Integration coverage for the console MCP provider HTTP endpoint."""
|
||||
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.tools.entities.api_entities import ToolProviderApiEntity
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import (
|
||||
authenticate_console_client,
|
||||
create_console_account_and_tenant,
|
||||
)
|
||||
|
||||
|
||||
def _i18n(text: str) -> dict[str, str]:
|
||||
return {"en_US": text}
|
||||
|
||||
|
||||
def _tool_payload() -> dict[str, object]:
|
||||
return {
|
||||
"author": "langgenius",
|
||||
"name": "ping",
|
||||
"label": _i18n("Ping"),
|
||||
"description": _i18n("Ping description"),
|
||||
"parameters": [],
|
||||
"labels": ["utilities"],
|
||||
"output_schema": {},
|
||||
}
|
||||
|
||||
|
||||
def _provider_entity() -> ToolProviderApiEntity:
|
||||
return ToolProviderApiEntity.model_validate(
|
||||
{
|
||||
"id": "provider-1",
|
||||
"author": "langgenius",
|
||||
"name": "provider",
|
||||
"description": _i18n("Provider description"),
|
||||
"icon": {"content": "tool", "background": "#252525"},
|
||||
"icon_dark": {"content": "tool", "background": "#252525"},
|
||||
"label": _i18n("Provider"),
|
||||
"type": "mcp",
|
||||
"masked_credentials": {"api_key": "[__HIDDEN__]"},
|
||||
"original_credentials": {"api_key": "sk-secret"},
|
||||
"is_team_authorization": False,
|
||||
"allow_delete": True,
|
||||
"plugin_id": "langgenius/provider",
|
||||
"plugin_unique_identifier": "langgenius/provider:1.0.0",
|
||||
"tools": [_tool_payload()],
|
||||
"labels": ["utilities"],
|
||||
"server_url": "",
|
||||
"updated_at": 1710000000,
|
||||
"server_identifier": "",
|
||||
"masked_headers": None,
|
||||
"original_headers": None,
|
||||
"authentication": None,
|
||||
"is_dynamic_registration": True,
|
||||
"configuration": None,
|
||||
"identity_mode": "off",
|
||||
"workflow_app_id": None,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(flask_app_with_containers: Flask) -> FlaskClient:
|
||||
return flask_app_with_containers.test_client()
|
||||
|
||||
|
||||
def test_create_mcp_provider_populates_tools(
|
||||
client: FlaskClient,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
headers = authenticate_console_client(client, account)
|
||||
service = MagicMock()
|
||||
service.create_provider.return_value = MagicMock(id="provider-1")
|
||||
service.get_provider.return_value = MagicMock(id="provider-1", tenant_id="t1")
|
||||
|
||||
with (
|
||||
patch("controllers.console.workspace.tool_providers.MCPToolManageService", return_value=service, autospec=True),
|
||||
patch(
|
||||
"services.tools.tools_transform_service.ToolTransformService.mcp_provider_to_user_provider",
|
||||
return_value=_provider_entity(),
|
||||
autospec=True,
|
||||
),
|
||||
):
|
||||
response = client.post(
|
||||
"/console/api/workspaces/current/tool-provider/mcp",
|
||||
data=json.dumps(
|
||||
{
|
||||
"server_url": "http://example.com/mcp",
|
||||
"name": "demo",
|
||||
"icon": "😀",
|
||||
"icon_type": "emoji",
|
||||
"icon_background": "#000",
|
||||
"server_identifier": "demo-sid",
|
||||
"configuration": {"timeout": 5, "sse_read_timeout": 30},
|
||||
"headers": {},
|
||||
"authentication": {},
|
||||
}
|
||||
),
|
||||
headers=headers,
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["id"] == "provider-1"
|
||||
assert body["team_credentials"] == {"api_key": "[__HIDDEN__]"}
|
||||
assert "masked_credentials" not in body
|
||||
assert "original_credentials" not in body
|
||||
assert body["tools"]
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
"""Testcontainers integration tests for plugin_permission_required decorator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import Forbidden
|
||||
|
||||
from controllers.console.workspace import plugin_permission_required
|
||||
from models.account import (
|
||||
Tenant,
|
||||
TenantPluginDebugPermission,
|
||||
TenantPluginInstallPermission,
|
||||
TenantPluginPermission,
|
||||
TenantStatus,
|
||||
)
|
||||
|
||||
|
||||
def _create_tenant(db_session: Session) -> Tenant:
|
||||
tenant = Tenant(name="test-tenant", status=TenantStatus.NORMAL, plan="basic")
|
||||
db_session.add(tenant)
|
||||
db_session.commit()
|
||||
db_session.expire_all()
|
||||
return tenant
|
||||
|
||||
|
||||
def _create_permission(
|
||||
db_session: Session,
|
||||
tenant_id: str,
|
||||
install: TenantPluginInstallPermission = TenantPluginInstallPermission.EVERYONE,
|
||||
debug: TenantPluginDebugPermission = TenantPluginDebugPermission.EVERYONE,
|
||||
) -> TenantPluginPermission:
|
||||
perm = TenantPluginPermission(
|
||||
tenant_id=tenant_id,
|
||||
install_permission=install,
|
||||
debug_permission=debug,
|
||||
)
|
||||
db_session.add(perm)
|
||||
db_session.commit()
|
||||
db_session.expire_all()
|
||||
return perm
|
||||
|
||||
|
||||
class TestPluginPermissionRequired:
|
||||
def test_allows_without_permission(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
user = SimpleNamespace(is_admin_or_owner=False)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required()
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
assert handler() == "ok"
|
||||
|
||||
def test_install_without_permission_forbids_non_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
user = SimpleNamespace(is_admin_or_owner=False)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(install_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(Forbidden):
|
||||
handler()
|
||||
|
||||
def test_install_without_permission_allows_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
user = SimpleNamespace(is_admin_or_owner=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(install_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
assert handler() == "ok"
|
||||
|
||||
def test_debug_without_permission_allows_non_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
user = SimpleNamespace(is_admin_or_owner=False)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(debug_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
assert handler() == "ok"
|
||||
|
||||
def test_install_nobody_forbidden(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.NOBODY,
|
||||
debug=TenantPluginDebugPermission.EVERYONE,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(install_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(Forbidden):
|
||||
handler()
|
||||
|
||||
def test_install_admin_requires_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.ADMINS,
|
||||
debug=TenantPluginDebugPermission.EVERYONE,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=False)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(install_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(Forbidden):
|
||||
handler()
|
||||
|
||||
def test_install_admin_allows_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.ADMINS,
|
||||
debug=TenantPluginDebugPermission.EVERYONE,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(install_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
assert handler() == "ok"
|
||||
|
||||
def test_debug_nobody_forbidden(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.EVERYONE,
|
||||
debug=TenantPluginDebugPermission.NOBODY,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(debug_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(Forbidden):
|
||||
handler()
|
||||
|
||||
def test_debug_admin_requires_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.EVERYONE,
|
||||
debug=TenantPluginDebugPermission.ADMINS,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=False)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(debug_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(Forbidden):
|
||||
handler()
|
||||
|
||||
def test_debug_admin_allows_admin(self, db_session_with_containers: Session):
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
_create_permission(
|
||||
db_session_with_containers,
|
||||
tenant.id,
|
||||
install=TenantPluginInstallPermission.EVERYONE,
|
||||
debug=TenantPluginDebugPermission.ADMINS,
|
||||
)
|
||||
user = SimpleNamespace(is_admin_or_owner=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.workspace.current_account_with_tenant",
|
||||
return_value=(user, tenant.id),
|
||||
):
|
||||
|
||||
@plugin_permission_required(debug_required=True)
|
||||
def handler():
|
||||
return "ok"
|
||||
|
||||
assert handler() == "ok"
|
||||
Whitespace-only changes.
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections.abc import Callable, Sequence
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from faker import Faker
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from constants.oauth_bearer import TokenType
|
||||
from controllers.openapi.auth.context import Context
|
||||
from controllers.openapi.auth.loaders import PathParam, load_app
|
||||
from controllers.openapi.auth.requirements import Requirement, ResolveCaller
|
||||
from controllers.openapi.auth.subjects import subject_from_auth
|
||||
from libs.oauth_bearer import AuthContext
|
||||
from models import Account, Tenant
|
||||
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
|
||||
from tests.e2e_tests.containers.helpers import generate_valid_password
|
||||
|
||||
_CLIENT_ID = "integration-cli"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(flask_app_with_containers: Flask) -> Flask:
|
||||
return flask_app_with_containers
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_account(db_session_with_containers: Session) -> Callable[..., Account]:
|
||||
"""Factory that registers a real Account and gives it an owner workspace.
|
||||
|
||||
System feature gates are stubbed (registration / workspace creation
|
||||
allowed) exactly like the AppDslService integration tests, so this stays a
|
||||
pure account+tenant setup helper.
|
||||
"""
|
||||
|
||||
# Depend on db_session_with_containers so the app context / DB session is
|
||||
# active for the composed account and workspace services below.
|
||||
assert db_session_with_containers is not None
|
||||
|
||||
def _make(*, with_owner_tenant: bool = True) -> Account:
|
||||
fake = Faker()
|
||||
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
|
||||
mock_feature_service.is_registration_allowed.return_value = True
|
||||
account = account_fixtures.create_account(
|
||||
email=fake.email(),
|
||||
name=fake.name(),
|
||||
interface_language="en-US",
|
||||
password=generate_valid_password(fake),
|
||||
session=db_session_with_containers,
|
||||
)
|
||||
if with_owner_tenant:
|
||||
account_fixtures.create_owner_workspace(
|
||||
account, name=fake.company(), session=db_session_with_containers
|
||||
)
|
||||
return account
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
def add_tenant_for_account(
|
||||
account: Account, *, session: Session, role: str = "normal", name: str = "Second WS"
|
||||
) -> Tenant:
|
||||
"""Create an additional tenant and join ``account`` to it (real service calls)."""
|
||||
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
|
||||
mock_feature_service.is_workspace_creation_allowed.return_value = True
|
||||
tenant = account_fixtures.create_workspace(name=name, session=session)
|
||||
account_fixtures.join_workspace(tenant, account, session, role=role)
|
||||
return tenant
|
||||
|
||||
|
||||
def _account_auth(
|
||||
account: Account,
|
||||
*,
|
||||
token_id: uuid.UUID | None = None,
|
||||
client_id: str = _CLIENT_ID,
|
||||
) -> AuthContext:
|
||||
"""The ``AuthContext`` a live ``dfoa_`` token for ``account`` would carry."""
|
||||
return AuthContext(
|
||||
subject_email=account.email,
|
||||
subject_issuer=None,
|
||||
account_id=uuid.UUID(str(account.id)),
|
||||
client_id=client_id,
|
||||
token_id=token_id or uuid.uuid4(),
|
||||
token_type=TokenType.OAUTH_ACCOUNT,
|
||||
expires_at=None,
|
||||
)
|
||||
|
||||
|
||||
def context_for(
|
||||
account: Account,
|
||||
*,
|
||||
session: Session,
|
||||
view_args: dict[str, str] | None = None,
|
||||
token_id: uuid.UUID | None = None,
|
||||
requirements: Sequence[Requirement] = (),
|
||||
) -> Context:
|
||||
"""Build the ``Context`` a handler is given after the pipeline ran.
|
||||
|
||||
The subject comes from a real ``AuthContext`` through ``subject_from_auth``,
|
||||
so the helper walks the same resolution path the router does. ``view_args``
|
||||
is the route's path params — the app and the workspace are loaded from it,
|
||||
so a route carrying ``<app_id>`` needs ``{"app_id": ...}`` here.
|
||||
``token_id`` only matters to the ``/account/sessions*`` family, which reads
|
||||
it back off the subject.
|
||||
|
||||
Pass the route's context-loading requirements, such as
|
||||
``CheckWorkspaceMember``, to bind the caller to its requested workspace.
|
||||
They run alongside the pipeline's fixed ``ResolveCaller`` in rank order;
|
||||
the caller is freshly loaded and does not inherit ``account.current_tenant``.
|
||||
App routes also load their app, as ``CheckAppApiEnabled`` does before the
|
||||
handler runs. Authorization itself is covered by the auth-layer tests.
|
||||
"""
|
||||
ctx = Context(subject_from_auth(_account_auth(account, token_id=token_id)), session, view_args or {})
|
||||
if PathParam.APP_ID in ctx.view_args:
|
||||
load_app(ctx)
|
||||
for requirement in sorted((*requirements, ResolveCaller()), key=lambda item: item.rank):
|
||||
requirement.run(ctx.subject, ctx, session)
|
||||
return ctx
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.openapi.account import AccountApi
|
||||
from models import Account
|
||||
from models.account import TenantAccountRole
|
||||
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
|
||||
|
||||
|
||||
class TestAccountInfo:
|
||||
def test_returns_account_and_owner_workspace(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
owner_tenant = account.current_tenant
|
||||
assert owner_tenant is not None
|
||||
|
||||
api = AccountApi()
|
||||
with app.test_request_context("/openapi/v1/account"):
|
||||
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
|
||||
|
||||
assert result.subject_type == "account"
|
||||
assert result.subject_email == account.email
|
||||
assert result.account is not None
|
||||
assert result.account.id == account.id
|
||||
assert result.account.email == account.email
|
||||
|
||||
workspaces = {w.id: w for w in result.workspaces}
|
||||
assert set(workspaces) == {owner_tenant.id}
|
||||
assert workspaces[owner_tenant.id].role == TenantAccountRole.OWNER.value
|
||||
# No membership is flagged `current` yet, so the default falls back to
|
||||
# the only workspace the account belongs to.
|
||||
assert result.default_workspace_id == owner_tenant.id
|
||||
|
||||
def test_lists_all_joined_workspaces(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
owner_tenant = account.current_tenant
|
||||
assert owner_tenant is not None
|
||||
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
|
||||
|
||||
api = AccountApi()
|
||||
with app.test_request_context("/openapi/v1/account"):
|
||||
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
|
||||
|
||||
assert {w.id for w in result.workspaces} == {owner_tenant.id, second.id}
|
||||
roles = {w.id: w.role for w in result.workspaces}
|
||||
assert roles[owner_tenant.id] == TenantAccountRole.OWNER.value
|
||||
assert roles[second.id] == "normal"
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from constants.oauth_bearer import TokenType
|
||||
from controllers.openapi._models import SessionListQuery
|
||||
from controllers.openapi.account import (
|
||||
AccountSessionByIdApi,
|
||||
AccountSessionsApi,
|
||||
AccountSessionsSelfApi,
|
||||
)
|
||||
from models import Account
|
||||
from models.oauth import OAuthAccessToken
|
||||
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _MintResult:
|
||||
token_id: UUID
|
||||
|
||||
|
||||
def _mint_account_token(
|
||||
db_session: Session,
|
||||
account: Account,
|
||||
*,
|
||||
client_id: str = "integration-cli",
|
||||
device_label: str = "Test Device",
|
||||
) -> _MintResult:
|
||||
"""Mint a real, persisted ``dfoa_`` access token for ``account``."""
|
||||
record = OAuthAccessToken(
|
||||
subject_email=account.email,
|
||||
subject_issuer="dify:account",
|
||||
account_id=str(account.id),
|
||||
client_id=client_id,
|
||||
device_label=device_label,
|
||||
prefix=TokenType.OAUTH_ACCOUNT.prefix,
|
||||
token_hash=f"integration-{uuid4().hex}",
|
||||
expires_at=datetime.now(UTC) + timedelta(days=14),
|
||||
)
|
||||
db_session.add(record)
|
||||
db_session.commit()
|
||||
return _MintResult(token_id=UUID(str(record.id)))
|
||||
|
||||
|
||||
class TestSessionList:
|
||||
def test_lists_active_session(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
mint = _mint_account_token(db_session_with_containers, account, device_label="Laptop")
|
||||
|
||||
api = AccountSessionsApi()
|
||||
with app.test_request_context("/openapi/v1/account/sessions"):
|
||||
result = api.get.__handler__(
|
||||
api,
|
||||
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
|
||||
query=SessionListQuery(),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
row = result.data[0]
|
||||
assert row.id == str(mint.token_id)
|
||||
assert row.prefix == TokenType.OAUTH_ACCOUNT.prefix
|
||||
assert row.device_label == "Laptop"
|
||||
|
||||
def test_excludes_other_accounts_sessions(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
"""Sessions are subject-scoped: another account's token must not appear."""
|
||||
account = make_account()
|
||||
other = make_account()
|
||||
mine = _mint_account_token(db_session_with_containers, account)
|
||||
_mint_account_token(db_session_with_containers, other)
|
||||
|
||||
api = AccountSessionsApi()
|
||||
with app.test_request_context("/openapi/v1/account/sessions"):
|
||||
result = api.get.__handler__(
|
||||
api,
|
||||
context_for(account, session=db_session_with_containers, token_id=mine.token_id),
|
||||
query=SessionListQuery(),
|
||||
)
|
||||
|
||||
assert {row.id for row in result.data} == {str(mine.token_id)}
|
||||
|
||||
|
||||
class TestSessionRevoke:
|
||||
def test_revoke_self_removes_from_active_list(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
mint = _mint_account_token(db_session_with_containers, account)
|
||||
|
||||
revoke_api = AccountSessionsSelfApi()
|
||||
with app.test_request_context("/openapi/v1/account/sessions/self", method="DELETE"):
|
||||
result = revoke_api.delete.__handler__(
|
||||
revoke_api, context_for(account, session=db_session_with_containers, token_id=mint.token_id)
|
||||
)
|
||||
|
||||
assert result.status == "revoked"
|
||||
|
||||
# Revocation persisted: the real list path no longer returns it.
|
||||
list_api = AccountSessionsApi()
|
||||
with app.test_request_context("/openapi/v1/account/sessions"):
|
||||
listing = list_api.get.__handler__(
|
||||
list_api,
|
||||
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
|
||||
query=SessionListQuery(),
|
||||
)
|
||||
assert listing.total == 0
|
||||
|
||||
def test_revoke_by_id_for_own_session(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
mint = _mint_account_token(db_session_with_containers, account)
|
||||
session_id = str(mint.token_id)
|
||||
|
||||
api = AccountSessionByIdApi()
|
||||
ctx = context_for(
|
||||
account,
|
||||
session=db_session_with_containers,
|
||||
view_args={"session_id": session_id},
|
||||
token_id=mint.token_id,
|
||||
)
|
||||
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
|
||||
result = api.delete.__handler__(api, ctx, session_id)
|
||||
|
||||
assert result.status == "revoked"
|
||||
|
||||
def test_revoke_foreign_session_is_404(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
"""A token id owned by another subject must be indistinguishable from a
|
||||
missing one (404), so token ids can't be probed across subjects. The
|
||||
access service makes that call; the handler only maps it to 404."""
|
||||
owner = make_account()
|
||||
outsider = make_account()
|
||||
foreign = _mint_account_token(db_session_with_containers, owner)
|
||||
|
||||
session_id = str(foreign.token_id)
|
||||
ctx = context_for(outsider, session=db_session_with_containers, view_args={"session_id": session_id})
|
||||
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
|
||||
api = AccountSessionByIdApi()
|
||||
with pytest.raises(NotFound):
|
||||
api.delete.__handler__(api, ctx, session_id)
|
||||
@@ -0,0 +1,287 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Callable, Generator
|
||||
from typing import Protocol, cast
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from faker import Faker
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.openapi._errors import DraftNotFound
|
||||
from controllers.openapi._models import AppDslExportQuery, AppDslExportResponse, AppDslImportPayload
|
||||
from controllers.openapi.app_dsl import (
|
||||
AppDslCheckDependenciesApi,
|
||||
AppDslExportApi,
|
||||
AppDslImportApi,
|
||||
AppDslImportConfirmApi,
|
||||
)
|
||||
from machinery.context import AppRequestContext, RequestContext
|
||||
from models import Account, App
|
||||
from models.model import AppMode, AppModelConfig
|
||||
from services.app_dsl_service import CURRENT_DSL_VERSION
|
||||
from services.app_service import AppService, CreateAppParams
|
||||
from services.entities.dsl_entities import CheckDependenciesResult, Import, ImportStatus
|
||||
from services.errors.app import WorkflowNotFoundError
|
||||
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
|
||||
from tests.e2e_tests.containers.helpers import generate_valid_password
|
||||
|
||||
|
||||
class _Endpoint[T](Protocol):
|
||||
__handler__: Callable[..., T]
|
||||
|
||||
|
||||
def _workflow_yaml(*, version: str = CURRENT_DSL_VERSION, name: str = "My App") -> str:
|
||||
return yaml.safe_dump(
|
||||
{
|
||||
"version": version,
|
||||
"kind": "app",
|
||||
"app": {"name": name, "mode": "workflow"},
|
||||
"workflow": {"graph": {"nodes": []}, "features": {}},
|
||||
},
|
||||
allow_unicode=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def external_deps() -> Generator[dict[str, object]]:
|
||||
"""Stub the heavy collaborators an import/export touches (model runtime,
|
||||
workflow sync, dependency analysis, enterprise hooks) while leaving the DSL
|
||||
service and DB writes real."""
|
||||
with (
|
||||
patch("services.app_dsl_service.WorkflowService") as mock_workflow_service,
|
||||
patch("services.app_dsl_service.DependenciesAnalysisService") as mock_dependencies_service,
|
||||
patch("services.app_dsl_service.app_was_created") as mock_app_was_created,
|
||||
patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,
|
||||
patch("services.app_service.SystemFeatureService") as mock_feature_service,
|
||||
patch("services.app_service.EnterpriseService") as mock_enterprise_service,
|
||||
):
|
||||
mock_workflow_service.get_draft_workflow.return_value = None
|
||||
mock_workflow_service.get_published_workflow_by_id.return_value = None
|
||||
mock_workflow_service.return_value.get_draft_workflow.return_value = None
|
||||
mock_workflow_service.return_value.sync_draft_workflow.return_value = None
|
||||
mock_dependencies_service.generate_latest_dependencies.return_value = [] # type: ignore[assignment]
|
||||
mock_dependencies_service.get_leaked_dependencies.return_value = [] # type: ignore[assignment]
|
||||
mock_dependencies_service.generate_dependencies.return_value = [] # type: ignore[assignment]
|
||||
mock_app_was_created.send.return_value = None
|
||||
|
||||
mock_model_instance = mock_model_manager.return_value
|
||||
mock_model_instance.get_default_model_instance.return_value = None
|
||||
mock_model_instance.get_default_provider_model_name.return_value = ("openai", "gpt-3.5-turbo")
|
||||
|
||||
mock_feature_service.is_webapp_auth_enabled.return_value = False
|
||||
mock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = None
|
||||
mock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None
|
||||
|
||||
yield {"workflow_service": mock_workflow_service}
|
||||
|
||||
|
||||
def _app_and_account(db_session: Session, *, mode: str = "chat") -> tuple[App, Account]:
|
||||
fake = Faker()
|
||||
with patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service:
|
||||
mock_account_feature_service.is_registration_allowed.return_value = True
|
||||
account = account_fixtures.create_account(
|
||||
email=fake.email(),
|
||||
name=fake.name(),
|
||||
interface_language="en-US",
|
||||
password=generate_valid_password(fake),
|
||||
session=db_session,
|
||||
)
|
||||
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session)
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
app_args = CreateAppParams(
|
||||
name=fake.company(),
|
||||
description=fake.text(max_nb_chars=100),
|
||||
mode=mode, # type: ignore[arg-type]
|
||||
icon_type="emoji",
|
||||
icon="🤖",
|
||||
icon_background="#FF6B6B",
|
||||
api_rph=100,
|
||||
api_rpm=10,
|
||||
)
|
||||
app_model = AppService().create_app(tenant.id, app_args, account, session=db_session)
|
||||
return app_model, account
|
||||
|
||||
|
||||
class TestDslImport:
|
||||
def test_invalid_dsl_maps_to_400_and_persists_nothing(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
|
||||
api = AppDslImportApi()
|
||||
body = AppDslImportPayload(mode="yaml-content", yaml_content="[]") # not a mapping
|
||||
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
|
||||
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
|
||||
api,
|
||||
RequestContext("test-request", None, account.id, tenant.id),
|
||||
tenant.id,
|
||||
body=body,
|
||||
)
|
||||
|
||||
assert code == 400
|
||||
assert result.status == ImportStatus.FAILED
|
||||
# A failed import must not leave an app behind.
|
||||
assert db_session_with_containers.query(App).filter(App.tenant_id == tenant.id).count() == 0
|
||||
|
||||
def test_major_version_mismatch_maps_to_202_pending(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
|
||||
api = AppDslImportApi()
|
||||
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(version="99.0.0"))
|
||||
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
|
||||
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
|
||||
api,
|
||||
RequestContext("test-request", None, account.id, tenant.id),
|
||||
tenant.id,
|
||||
body=body,
|
||||
)
|
||||
|
||||
assert code == 202
|
||||
assert result.status == ImportStatus.PENDING
|
||||
assert result.id # a pending import id the caller can confirm with
|
||||
|
||||
def test_valid_dsl_maps_to_200_completed(
|
||||
self,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
make_account: Callable[..., Account],
|
||||
external_deps: dict[str, object],
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
|
||||
api = AppDslImportApi()
|
||||
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(name="Imported"))
|
||||
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
|
||||
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
|
||||
api,
|
||||
RequestContext("test-request", None, account.id, tenant.id),
|
||||
tenant.id,
|
||||
body=body,
|
||||
)
|
||||
|
||||
assert code == 200
|
||||
assert result.status in (ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS)
|
||||
assert result.app_id is not None
|
||||
|
||||
|
||||
class TestDslImportConfirm:
|
||||
def test_unknown_pending_import_maps_to_400(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
"""An expired/unknown import id has no Redis pending data → FAILED → 400."""
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
import_id = str(uuid4())
|
||||
|
||||
api = AppDslImportConfirmApi()
|
||||
with app.test_request_context(
|
||||
f"/openapi/v1/workspaces/{tenant.id}/apps/imports/{import_id}:confirm", method="POST"
|
||||
):
|
||||
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
|
||||
api,
|
||||
RequestContext("test-request", None, account.id, tenant.id),
|
||||
tenant.id,
|
||||
import_id,
|
||||
)
|
||||
|
||||
assert code == 400
|
||||
assert result.status == ImportStatus.FAILED
|
||||
|
||||
|
||||
class TestDslExport:
|
||||
def test_export_returns_dsl_yaml(
|
||||
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
|
||||
) -> None:
|
||||
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
|
||||
model_config = AppModelConfig(
|
||||
app_id=app_model.id,
|
||||
provider="openai",
|
||||
model_id="gpt-3.5-turbo",
|
||||
model=json.dumps({"provider": "openai", "name": "gpt-3.5-turbo", "mode": "chat", "completion_params": {}}),
|
||||
pre_prompt="You are a helpful assistant.",
|
||||
prompt_type="simple", # type: ignore[arg-type]
|
||||
created_by=account.id,
|
||||
updated_by=account.id,
|
||||
)
|
||||
model_config.id = str(uuid4())
|
||||
app_model.app_model_config_id = model_config.id
|
||||
db_session_with_containers.add(model_config)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
api = AppDslExportApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):
|
||||
response, code = cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
|
||||
api,
|
||||
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
|
||||
app_model.id,
|
||||
query=AppDslExportQuery(),
|
||||
)
|
||||
|
||||
assert code == 200
|
||||
assert isinstance(response, AppDslExportResponse)
|
||||
parsed = yaml.safe_load(response.data)
|
||||
assert parsed["kind"] == "app"
|
||||
assert parsed["app"]["name"] == app_model.name
|
||||
|
||||
def test_export_workflow_app_without_draft_maps_to_404(
|
||||
self, app: Flask, db_session_with_containers: Session
|
||||
) -> None:
|
||||
"""A workflow app with no draft workflow can't be exported → the service
|
||||
raises WorkflowNotFoundError, which the controller maps to 404 draft_not_found."""
|
||||
app_model = App(
|
||||
id=str(uuid4()),
|
||||
tenant_id=str(uuid4()),
|
||||
name="Workflow without draft",
|
||||
mode=AppMode.WORKFLOW,
|
||||
enable_api=True,
|
||||
enable_site=False,
|
||||
)
|
||||
db_session_with_containers.add(app_model)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
api = AppDslExportApi()
|
||||
with (
|
||||
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"),
|
||||
pytest.raises(DraftNotFound) as exc_info,
|
||||
):
|
||||
cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
|
||||
api,
|
||||
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
|
||||
app_model.id,
|
||||
query=AppDslExportQuery(),
|
||||
)
|
||||
|
||||
assert isinstance(exc_info.value.__cause__, WorkflowNotFoundError)
|
||||
|
||||
|
||||
class TestDslCheckDependencies:
|
||||
def test_check_dependencies_returns_result(
|
||||
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
|
||||
) -> None:
|
||||
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
|
||||
|
||||
api = AppDslCheckDependenciesApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dependencies:check"):
|
||||
result, code = cast(_Endpoint[tuple[CheckDependenciesResult, int]], api.get).__handler__(
|
||||
api,
|
||||
RequestContext("test-request", None, account.id, app_model.tenant_id),
|
||||
app_model.id,
|
||||
)
|
||||
|
||||
assert code == 200
|
||||
assert result.leaked_dependencies == []
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.openapi._errors import RunNotFound
|
||||
from controllers.openapi.app_run import AppRunStopApi
|
||||
from models import Account, App
|
||||
from services.app_service import AppService, CreateAppParams
|
||||
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
|
||||
|
||||
|
||||
def _create_app(db_session: Session, account: Account, *, name: str = "Runner") -> App:
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
params = CreateAppParams(
|
||||
name=name,
|
||||
description="",
|
||||
mode="workflow",
|
||||
icon_type="emoji",
|
||||
icon="🤖",
|
||||
icon_background="#FF6B6B",
|
||||
)
|
||||
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
|
||||
db_session.commit()
|
||||
return app_model
|
||||
|
||||
|
||||
class TestAppRunStop:
|
||||
def test_run_stop_rejects_an_unknown_run(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
app_model = _create_app(db_session_with_containers, account)
|
||||
run_id = str(uuid4())
|
||||
|
||||
api = AppRunStopApi()
|
||||
with (
|
||||
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/runs/{run_id}:stop", method="POST"),
|
||||
pytest.raises(RunNotFound),
|
||||
):
|
||||
api.post.__handler__( # pyrefly: ignore[missing-attribute]
|
||||
api,
|
||||
context_for(
|
||||
account,
|
||||
session=db_session_with_containers,
|
||||
view_args={"app_id": app_model.id, "run_id": run_id},
|
||||
),
|
||||
app_model.id,
|
||||
run_id,
|
||||
)
|
||||
@@ -0,0 +1,161 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Protocol, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from controllers.openapi._models import AppDescribeQuery, AppDescribeResponse, AppListQuery, AppListResponse
|
||||
from controllers.openapi.apps import AppDescribeApi, AppListApi
|
||||
from machinery.context import AppRequestContext, RequestContext
|
||||
from models import Account, App
|
||||
from services.app_service import AppService, CreateAppParams
|
||||
|
||||
|
||||
class _Endpoint[T](Protocol):
|
||||
__handler__: Callable[..., T]
|
||||
|
||||
|
||||
def _create_app(
|
||||
db_session: Session,
|
||||
account: Account,
|
||||
*,
|
||||
name: str,
|
||||
enable_api: bool = True,
|
||||
) -> App:
|
||||
"""Create a workflow app in the account's owner tenant.
|
||||
|
||||
Workflow mode is used because its template seeds no ``model_config``, so
|
||||
``AppService.create_app`` never reaches ``ModelManager`` — keeping the
|
||||
fixture free of model-runtime patching.
|
||||
"""
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
params = CreateAppParams(
|
||||
name=name,
|
||||
description="",
|
||||
mode="workflow",
|
||||
icon_type="emoji",
|
||||
icon="🤖",
|
||||
icon_background="#FF6B6B",
|
||||
)
|
||||
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
|
||||
# The openapi surface gate keys off ``enable_api``; flip it explicitly so
|
||||
# the test states the visibility precondition rather than relying on the
|
||||
# template default.
|
||||
app_model.enable_api = enable_api
|
||||
db_session.add(app_model)
|
||||
db_session.commit()
|
||||
return app_model
|
||||
|
||||
|
||||
class TestAppList:
|
||||
def test_lists_only_api_enabled_apps_in_workspace(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
visible = _create_app(db_session_with_containers, account, name="Visible", enable_api=True)
|
||||
_create_app(db_session_with_containers, account, name="Hidden", enable_api=False)
|
||||
|
||||
api = AppListApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}"):
|
||||
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
|
||||
api,
|
||||
RequestContext("request", None, account.id, tenant.id),
|
||||
query=AppListQuery(workspace_id=str(tenant.id)),
|
||||
)
|
||||
|
||||
# The api-disabled app is gated out, so it counts neither in `data`
|
||||
# nor in `total` (the gate is pushed into the query for stable paging).
|
||||
assert result.total == 1
|
||||
assert [row.id for row in result.data] == [visible.id]
|
||||
assert result.has_more is False
|
||||
|
||||
def test_uuid_name_filter_returns_matching_app(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
target = _create_app(db_session_with_containers, account, name="Target", enable_api=True)
|
||||
|
||||
api = AppListApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}&name={target.id}"):
|
||||
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
|
||||
api,
|
||||
RequestContext("request", None, account.id, tenant.id),
|
||||
query=AppListQuery(workspace_id=str(tenant.id), name=str(target.id)),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.data[0].id == target.id
|
||||
assert result.data[0].workspace_id == str(tenant.id)
|
||||
|
||||
def test_uuid_name_filter_for_foreign_app_returns_empty(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
"""A UUID that resolves to an app in another workspace must not leak
|
||||
across tenants — the list returns empty rather than the foreign app."""
|
||||
owner = make_account()
|
||||
outsider = make_account()
|
||||
foreign_app = _create_app(db_session_with_containers, owner, name="Foreign", enable_api=True)
|
||||
outsider_tenant = outsider.current_tenant
|
||||
assert outsider_tenant is not None
|
||||
|
||||
api = AppListApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps?workspace_id={outsider_tenant.id}&name={foreign_app.id}"):
|
||||
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
|
||||
api,
|
||||
RequestContext("request", None, outsider.id, outsider_tenant.id),
|
||||
query=AppListQuery(workspace_id=str(outsider_tenant.id), name=str(foreign_app.id)),
|
||||
)
|
||||
|
||||
assert result.total == 0
|
||||
assert result.data == []
|
||||
|
||||
|
||||
class TestAppDescribe:
|
||||
def test_describe_info_returns_metadata(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
app_model = _create_app(db_session_with_containers, account, name="Describe Me", enable_api=True)
|
||||
|
||||
api = AppDescribeApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}?fields=info"):
|
||||
result = cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
|
||||
api,
|
||||
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
|
||||
app_model.id,
|
||||
query=AppDescribeQuery(fields="info"),
|
||||
)
|
||||
|
||||
assert result.info is not None
|
||||
assert result.info.id == app_model.id
|
||||
assert result.info.name == "Describe Me"
|
||||
assert result.info.service_api_enabled is True
|
||||
# Only the requested block is materialized.
|
||||
assert result.parameters is None
|
||||
assert result.input_schema is None
|
||||
|
||||
def test_describe_unknown_app_is_404(self, app: Flask, make_account: Callable[..., Account]) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
missing_id = str(uuid4())
|
||||
|
||||
api = AppDescribeApi()
|
||||
with app.test_request_context(f"/openapi/v1/apps/{missing_id}"):
|
||||
with pytest.raises(NotFound):
|
||||
cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
|
||||
api,
|
||||
AppRequestContext(tenant_id=tenant.id, app_id=missing_id),
|
||||
missing_id,
|
||||
query=AppDescribeQuery(),
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from controllers.openapi._models import FileUploadPayload
|
||||
from controllers.openapi.auth.requirements import CheckWorkspaceMember
|
||||
from controllers.openapi.files import AppFileUploadApi
|
||||
from models import Account, App
|
||||
from services.app_service import AppService, CreateAppParams
|
||||
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
|
||||
|
||||
|
||||
def _create_app(db_session: Session, account: Account, *, name: str = "Uploader") -> App:
|
||||
"""Create a workflow app (no model_config → no ModelManager) for the upload context."""
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
params = CreateAppParams(
|
||||
name=name,
|
||||
description="",
|
||||
mode="workflow",
|
||||
icon_type="emoji",
|
||||
icon="🤖",
|
||||
icon_background="#FF6B6B",
|
||||
)
|
||||
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
|
||||
db_session.commit()
|
||||
return app_model
|
||||
|
||||
|
||||
class TestAppFileUpload:
|
||||
def test_upload_persists_and_returns_metadata(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
app_model = _create_app(db_session_with_containers, account)
|
||||
content = b"hello integration world"
|
||||
|
||||
api = AppFileUploadApi()
|
||||
body = FileUploadPayload(
|
||||
file=FileStorage(stream=BytesIO(content), filename="note.txt", content_type="text/plain")
|
||||
)
|
||||
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/files", method="POST"):
|
||||
result = vars(api.post)["__handler__"](
|
||||
api,
|
||||
context_for(
|
||||
account,
|
||||
session=db_session_with_containers,
|
||||
view_args={"app_id": app_model.id},
|
||||
requirements=(CheckWorkspaceMember(),),
|
||||
),
|
||||
app_model.id,
|
||||
body=body,
|
||||
)
|
||||
|
||||
assert result.id
|
||||
assert result.name == "note.txt"
|
||||
assert result.size == len(content)
|
||||
assert result.extension == "txt"
|
||||
assert result.mime_type == "text/plain"
|
||||
# Persisted under the caller's tenant.
|
||||
assert result.tenant_id == str(tenant.id)
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from controllers.openapi._models import WorkspaceListQuery
|
||||
from controllers.openapi.workspaces import WorkspaceByIdApi, WorkspacesApi
|
||||
from models import Account
|
||||
from models.account import TenantAccountRole
|
||||
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
|
||||
|
||||
|
||||
class TestWorkspacesList:
|
||||
def test_lists_only_members_workspaces_with_role(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
owner_tenant = account.current_tenant
|
||||
assert owner_tenant is not None
|
||||
|
||||
api = WorkspacesApi()
|
||||
with app.test_request_context("/openapi/v1/workspaces"):
|
||||
result = api.get.__handler__(
|
||||
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
|
||||
)
|
||||
|
||||
ids = {w.id for w in result.data}
|
||||
assert ids == {owner_tenant.id}
|
||||
only = result.data[0]
|
||||
assert only.role == TenantAccountRole.OWNER.value
|
||||
assert only.status == "normal"
|
||||
|
||||
def test_lists_all_joined_workspaces(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
owner_tenant = account.current_tenant
|
||||
assert owner_tenant is not None
|
||||
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
|
||||
|
||||
api = WorkspacesApi()
|
||||
with app.test_request_context("/openapi/v1/workspaces"):
|
||||
result = api.get.__handler__(
|
||||
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
|
||||
)
|
||||
|
||||
assert {w.id for w in result.data} == {owner_tenant.id, second.id}
|
||||
|
||||
|
||||
class TestWorkspaceDetail:
|
||||
def test_member_can_read_detail(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
account = make_account()
|
||||
tenant = account.current_tenant
|
||||
assert tenant is not None
|
||||
|
||||
api = WorkspaceByIdApi()
|
||||
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}"):
|
||||
detail = api.get.__handler__(
|
||||
api,
|
||||
context_for(account, session=db_session_with_containers, view_args={"workspace_id": tenant.id}),
|
||||
tenant.id,
|
||||
)
|
||||
|
||||
assert detail.id == tenant.id
|
||||
assert detail.role == TenantAccountRole.OWNER.value
|
||||
assert detail.created_at is not None
|
||||
|
||||
def test_non_member_detail_is_404_not_403(
|
||||
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
|
||||
) -> None:
|
||||
"""A workspace the caller doesn't belong to must be indistinguishable
|
||||
from a missing one (404), so IDs can't be probed across tenants."""
|
||||
owner = make_account()
|
||||
outsider = make_account()
|
||||
someone_elses_ws = owner.current_tenant
|
||||
assert someone_elses_ws is not None
|
||||
|
||||
api = WorkspaceByIdApi()
|
||||
with app.test_request_context(f"/openapi/v1/workspaces/{someone_elses_ws.id}"):
|
||||
with pytest.raises(NotFound):
|
||||
api.get.__handler__(
|
||||
api,
|
||||
context_for(
|
||||
outsider,
|
||||
session=db_session_with_containers,
|
||||
view_args={"workspace_id": someone_elses_ws.id},
|
||||
),
|
||||
someone_elses_ws.id,
|
||||
)
|
||||
Whitespace-only changes.
+638
@@ -0,0 +1,638 @@
|
||||
"""Real Service API HTTP admission, PostgreSQL, Redis and Celery publications.
|
||||
|
||||
Workers are not executed: the memory broker verifies published messages without
|
||||
calling embedding providers or vector stores. Container execution belongs to CI.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, replace
|
||||
from queue import Empty
|
||||
from typing import Literal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from celery import Celery, Task
|
||||
from celery.signals import before_task_publish
|
||||
from flask import Flask, g
|
||||
from flask_login import user_logged_in
|
||||
from kombu.simple import SimpleQueue
|
||||
from sqlalchemy import Connection, ExecutionContext, delete, event, func, select, text, update
|
||||
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
|
||||
from werkzeug.test import TestResponse
|
||||
|
||||
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
|
||||
from constants.resource_access_token import ResourceAccessTokenResourceType
|
||||
from controllers.console.wraps import _is_setup_completed
|
||||
from enums import DeploymentEdition
|
||||
from enums.account import TenantAccountRole
|
||||
from extensions.ext_application_services import ApplicationServices
|
||||
from extensions.ext_database import db
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from libs.datetime_utils import naive_utc_now
|
||||
from libs.passport import PassportService
|
||||
from libs.token import generate_csrf_token
|
||||
from machinery.context import RequestContext
|
||||
from models import Account, App, Tenant
|
||||
from models.account import AccountStatus, TenantAccountJoin, TenantStatus
|
||||
from models.enums import ApiTokenType
|
||||
from models.model import ApiToken, AppAnnotationSetting, DifySetup, EndUser, MessageAnnotation
|
||||
from repositories.annotation_reply_job_repository import (
|
||||
RedisAnnotationReplyJobRepository,
|
||||
annotation_reply_job_owner_key,
|
||||
)
|
||||
from repositories.annotation_repository import AnnotationRepository
|
||||
from services.annotation_command_service import AnnotationCommandService
|
||||
from services.annotation_reply_service import AnnotationReplyAction, AnnotationReplyService
|
||||
from services.api_token_service import ApiTokenCache
|
||||
from services.auth.resource_access_token_contracts import ResourceAccessTokenCreateResult, ResourceAccessTokenResource
|
||||
from tasks.annotation.add_annotation_to_index_task import add_annotation_to_index_task
|
||||
from tasks.annotation.delete_annotation_index_task import delete_annotation_index_task
|
||||
from tasks.annotation.disable_annotation_reply_task import disable_annotation_reply_task
|
||||
from tasks.annotation.enable_annotation_reply_task import enable_annotation_reply_task
|
||||
from tasks.annotation.update_annotation_to_index_task import update_annotation_to_index_task
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
from tests.helpers.unit.model_factories import make_account, make_app
|
||||
|
||||
_REPLY_PAYLOAD: dict[str, object] = {
|
||||
"score_threshold": 0.75,
|
||||
"embedding_provider_name": "openai",
|
||||
"embedding_model_name": "text-embedding-3-small",
|
||||
}
|
||||
_ANNOTATION_PAYLOAD: dict[str, object] = {"question": "Question", "answer": "Answer"}
|
||||
_ENDPOINTS = [
|
||||
("GET", "/annotations"),
|
||||
("POST", "/annotations"),
|
||||
("PUT", "/annotations/{id}"),
|
||||
("DELETE", "/annotations/{id}"),
|
||||
("POST", "/annotation-reply/enable"),
|
||||
("GET", "/annotation-reply/enable/status/{id}"),
|
||||
]
|
||||
type Credential = Literal["key", "resource"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Harness:
|
||||
app: Flask
|
||||
services: ApplicationServices
|
||||
account: Account
|
||||
target: App
|
||||
other: App
|
||||
foreign: App
|
||||
api_key: ApiToken
|
||||
other_key: ApiToken
|
||||
factory: sessionmaker[Session]
|
||||
redis: RedisClientWrapper
|
||||
celery: Celery
|
||||
tasks: dict[str, Task[..., None]]
|
||||
queue: str
|
||||
sessions: list[Session]
|
||||
publications: list[bool]
|
||||
logins: list[object]
|
||||
token_reads: list[str]
|
||||
|
||||
@property
|
||||
def context(self) -> RequestContext:
|
||||
return RequestContext("annotation-test", None, self.account.id, self.target.tenant_id)
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
payload: dict[str, object] | None = None,
|
||||
token: str | None = None,
|
||||
authorization: str | None = None,
|
||||
app_id: str | None = None,
|
||||
) -> TestResponse:
|
||||
headers = {
|
||||
"Authorization": authorization if authorization is not None else f"Bearer {token or self.api_key.token}"
|
||||
}
|
||||
if authorization == "":
|
||||
headers.clear()
|
||||
if app_id is not None:
|
||||
headers["X-Dify-App-ID"] = app_id
|
||||
with self.app.test_client() as client:
|
||||
response = client.open(f"/v1/apps{path}", method=method, json=payload, headers=headers)
|
||||
assert not isinstance(g.get("_login_user"), (Account, EndUser))
|
||||
with self.factory() as session:
|
||||
assert session.scalar(select(func.count()).select_from(EndUser)) == 0
|
||||
if response.status_code != 204:
|
||||
assert response.headers["Content-Type"] == "application/json"
|
||||
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
|
||||
assert self.logins == []
|
||||
return response
|
||||
|
||||
def resource_token(self, *app_ids: str) -> ResourceAccessTokenCreateResult:
|
||||
return self.services.resource_access_tokens.create(
|
||||
self.context,
|
||||
name="Annotation integration key",
|
||||
resources=tuple(
|
||||
ResourceAccessTokenResource(type=ResourceAccessTokenResourceType.APP, id=app_id)
|
||||
for app_id in app_ids or (self.target.id,)
|
||||
),
|
||||
)
|
||||
|
||||
def credential(self, kind: Credential) -> str:
|
||||
return self.api_key.token if kind == "key" else self.resource_token().token
|
||||
|
||||
def consume_task(self, name: str, expected: dict[str, object]) -> None:
|
||||
with self.celery.connection_for_read() as connection, SimpleQueue(connection, self.queue) as messages:
|
||||
message = messages.get(block=False)
|
||||
assert message.headers["task"] == self.tasks[name].name
|
||||
assert message.payload[0] == []
|
||||
assert message.payload[1] == expected
|
||||
message.ack()
|
||||
with pytest.raises(Empty):
|
||||
messages.get(block=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
|
||||
app = flask_app_with_containers
|
||||
services = app.extensions["application_services"]
|
||||
assert isinstance(services, ApplicationServices)
|
||||
redis = app.extensions["redis"]
|
||||
assert isinstance(redis, RedisClientWrapper)
|
||||
with app.app_context():
|
||||
engine = db.engine
|
||||
factory = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
workspace = Tenant(name="Service API annotation workspace")
|
||||
foreign_workspace = Tenant(name="Other annotation workspace")
|
||||
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
|
||||
account.last_active_at = naive_utc_now()
|
||||
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
|
||||
foreign = make_app(app_id=str(uuid4()), tenant_id=foreign_workspace.id)
|
||||
api_key = ApiToken(app_id=target.id, tenant_id=workspace.id, type=ApiTokenType.APP, token=f"app-{uuid4()}")
|
||||
other_key = ApiToken(app_id=other.id, tenant_id=workspace.id, type=ApiTokenType.APP, token=f"app-{uuid4()}")
|
||||
with factory.begin() as session:
|
||||
session.add_all(
|
||||
[
|
||||
workspace,
|
||||
foreign_workspace,
|
||||
account,
|
||||
target,
|
||||
other,
|
||||
foreign,
|
||||
api_key,
|
||||
other_key,
|
||||
TenantAccountJoin(
|
||||
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
|
||||
),
|
||||
DifySetup(version="test"),
|
||||
]
|
||||
)
|
||||
queue = f"service-api-annotation-{uuid4()}"
|
||||
celery = Celery(queue, broker="memory://", set_as_current=False)
|
||||
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
|
||||
tasks: dict[str, Task[..., None]] = {
|
||||
"add": celery.task(name=add_annotation_to_index_task.name, shared=False)(add_annotation_to_index_task.run),
|
||||
"update": celery.task(name=update_annotation_to_index_task.name, shared=False)(
|
||||
update_annotation_to_index_task.run
|
||||
),
|
||||
"delete": celery.task(name=delete_annotation_index_task.name, shared=False)(delete_annotation_index_task.run),
|
||||
"enable": celery.task(name=enable_annotation_reply_task.name, shared=False)(enable_annotation_reply_task.run),
|
||||
"disable": celery.task(name=disable_annotation_reply_task.name, shared=False)(
|
||||
disable_annotation_reply_task.run
|
||||
),
|
||||
}
|
||||
annotations = AnnotationRepository(session_factory=factory)
|
||||
app.extensions["application_services"] = replace(
|
||||
services,
|
||||
annotation_queries=annotations,
|
||||
annotation_commands=AnnotationCommandService(
|
||||
annotations=annotations,
|
||||
add_index=tasks["add"].delay,
|
||||
update_index=tasks["update"].delay,
|
||||
delete_index=tasks["delete"].delay,
|
||||
),
|
||||
annotation_reply=AnnotationReplyService(
|
||||
apps=annotations,
|
||||
jobs=RedisAnnotationReplyJobRepository(redis=redis),
|
||||
enable_task=tasks["enable"].delay,
|
||||
disable_task=tasks["disable"].delay,
|
||||
),
|
||||
)
|
||||
sessions: list[Session] = []
|
||||
publications: list[bool] = []
|
||||
logins: list[object] = []
|
||||
token_reads: list[str] = []
|
||||
|
||||
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
|
||||
sessions.append(session)
|
||||
|
||||
def observe_publish(**_kwargs: object) -> None:
|
||||
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
|
||||
|
||||
def observe_login(_sender: object, user: object) -> None:
|
||||
logins.append(user)
|
||||
|
||||
def observe_query(
|
||||
_connection: Connection,
|
||||
_cursor: object,
|
||||
statement: str,
|
||||
_parameters: object,
|
||||
_context: ExecutionContext,
|
||||
_executemany: bool,
|
||||
) -> None:
|
||||
if statement.lstrip().upper().startswith("SELECT") and "api_tokens" in statement:
|
||||
token_reads.append(statement)
|
||||
|
||||
event.listen(Session, "after_begin", track)
|
||||
event.listen(engine, "before_cursor_execute", observe_query)
|
||||
before_task_publish.connect(observe_publish, weak=True)
|
||||
user_logged_in.connect(observe_login, weak=True)
|
||||
_is_setup_completed.reset_success()
|
||||
try:
|
||||
with config_overrides_context(
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
|
||||
SECRET_KEY="service-api-annotation-passport-key-32-bytes",
|
||||
LOGIN_DISABLED=False,
|
||||
INIT_PASSWORD="",
|
||||
CONSOLE_API_URL="http://localhost",
|
||||
CONSOLE_WEB_URL="http://localhost",
|
||||
COOKIE_DOMAIN="",
|
||||
RBAC_ENABLED=False,
|
||||
):
|
||||
with app.app_context():
|
||||
assert _is_setup_completed()
|
||||
db.session.remove()
|
||||
yield _Harness(
|
||||
app,
|
||||
services,
|
||||
account,
|
||||
target,
|
||||
other,
|
||||
foreign,
|
||||
api_key,
|
||||
other_key,
|
||||
factory,
|
||||
redis,
|
||||
celery,
|
||||
tasks,
|
||||
queue,
|
||||
sessions,
|
||||
publications,
|
||||
logins,
|
||||
token_reads,
|
||||
)
|
||||
finally:
|
||||
app.extensions["application_services"] = services
|
||||
del observe_publish
|
||||
user_logged_in.disconnect(observe_login)
|
||||
event.remove(Session, "after_begin", track)
|
||||
event.remove(engine, "before_cursor_execute", observe_query)
|
||||
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
|
||||
messages.clear()
|
||||
celery.close()
|
||||
_is_setup_completed.reset_success()
|
||||
with app.app_context():
|
||||
db.session.remove()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("credential", ["key", "resource"])
|
||||
def test_crud_publishes_scoped_index_tasks_after_sessions_close(harness: _Harness, credential: Credential) -> None:
|
||||
token = harness.credential(credential)
|
||||
binding_id = str(uuid4())
|
||||
with harness.factory.begin() as session:
|
||||
session.add(
|
||||
AppAnnotationSetting(
|
||||
app_id=harness.target.id,
|
||||
score_threshold=0.75,
|
||||
collection_binding_id=binding_id,
|
||||
created_user_id=harness.account.id,
|
||||
updated_user_id=harness.account.id,
|
||||
)
|
||||
)
|
||||
|
||||
created = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD, token=token)
|
||||
|
||||
assert created.status_code == 201
|
||||
body = created.get_json()
|
||||
annotation_id = body["id"]
|
||||
assert str(UUID(annotation_id)) == annotation_id
|
||||
assert body == {
|
||||
"id": annotation_id,
|
||||
"question": "Question",
|
||||
"answer": "Answer",
|
||||
"hit_count": 0,
|
||||
"created_at": body["created_at"],
|
||||
}
|
||||
assert isinstance(body["created_at"], int)
|
||||
task_scope: dict[str, object] = {
|
||||
"annotation_id": annotation_id,
|
||||
"tenant_id": harness.target.tenant_id,
|
||||
"app_id": harness.target.id,
|
||||
"collection_binding_id": binding_id,
|
||||
}
|
||||
harness.consume_task("add", {**task_scope, "question": "Question"})
|
||||
listed = harness.request("GET", "/annotations", token=token)
|
||||
assert listed.status_code == 200
|
||||
assert listed.get_json() == {"data": [body], "has_more": False, "limit": 20, "total": 1, "page": 1}
|
||||
updated = harness.request(
|
||||
"PUT", f"/annotations/{annotation_id}", payload={"question": "", "answer": "Updated answer"}, token=token
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json() == {**body, "question": "", "answer": "Updated answer"}
|
||||
harness.consume_task("update", {**task_scope, "question": "Updated answer"})
|
||||
with harness.factory() as session:
|
||||
annotation = session.get(MessageAnnotation, annotation_id)
|
||||
assert annotation is not None
|
||||
assert (annotation.question, annotation.content, annotation.account_id) == (
|
||||
"",
|
||||
"Updated answer",
|
||||
harness.account.id,
|
||||
)
|
||||
|
||||
removed = harness.request("DELETE", f"/annotations/{annotation_id}", token=token)
|
||||
|
||||
assert removed.status_code == 204
|
||||
assert removed.data == b""
|
||||
harness.consume_task("delete", task_scope)
|
||||
assert harness.publications == [True, True, True]
|
||||
with harness.factory() as session:
|
||||
assert session.get(MessageAnnotation, annotation_id) is None
|
||||
assert harness.request("GET", "/annotations", token=token).get_json()["total"] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("question", "answer"), [("", ""), ("", "Answer"), ("Question", "")])
|
||||
def test_create_preserves_service_api_empty_strings(harness: _Harness, question: str, answer: str) -> None:
|
||||
response = harness.request("POST", "/annotations", payload={"question": question, "answer": answer})
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.get_json()
|
||||
assert body["question"] == question
|
||||
assert body["answer"] == answer
|
||||
with harness.factory() as session:
|
||||
annotation = session.get(MessageAnnotation, body["id"])
|
||||
assert annotation is not None
|
||||
assert (annotation.question, annotation.content, annotation.account_id) == (
|
||||
question,
|
||||
answer,
|
||||
harness.account.id,
|
||||
)
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
def test_list_scopes_annotations_and_preserves_pagination_and_literal_search(harness: _Harness) -> None:
|
||||
with harness.factory.begin() as session:
|
||||
session.add_all(
|
||||
MessageAnnotation(app_id=app_id, question=question, content="Answer", account_id=harness.account.id)
|
||||
for app_id, question in (
|
||||
(harness.target.id, "100% complete"),
|
||||
(harness.target.id, "Ordinary question"),
|
||||
(harness.other.id, "Other app 100% complete"),
|
||||
(harness.foreign.id, "Foreign workspace 100% complete"),
|
||||
)
|
||||
)
|
||||
|
||||
first = harness.request("GET", "/annotations?page=1&limit=1").get_json()
|
||||
second = harness.request("GET", "/annotations?page=2&limit=1").get_json()
|
||||
assert (first["total"], first["page"], first["limit"], first["has_more"]) == (2, 1, 1, True)
|
||||
assert (second["total"], second["page"], second["limit"], second["has_more"]) == (2, 2, 1, False)
|
||||
assert first["data"][0]["id"] != second["data"][0]["id"]
|
||||
filtered = harness.request("GET", "/annotations?keyword=%25&limit=999").get_json()
|
||||
assert (filtered["total"], filtered["limit"], filtered["has_more"]) == (1, 100, False)
|
||||
assert filtered["data"][0]["question"] == "100% complete"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["PUT", "DELETE"])
|
||||
@pytest.mark.parametrize("scope", ["app", "tenant"])
|
||||
def test_annotation_mutations_reject_other_owners(harness: _Harness, method: str, scope: str) -> None:
|
||||
annotation = MessageAnnotation(
|
||||
app_id=harness.other.id if scope == "app" else harness.foreign.id,
|
||||
question="Other question",
|
||||
content="Other answer",
|
||||
account_id=harness.account.id,
|
||||
)
|
||||
with harness.factory.begin() as session:
|
||||
session.add(annotation)
|
||||
|
||||
response = harness.request(method, f"/annotations/{annotation.id}", payload=_ANNOTATION_PAYLOAD)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["code"] == "not_found"
|
||||
assert harness.publications == []
|
||||
with harness.factory() as session:
|
||||
preserved = session.get(MessageAnnotation, annotation.id)
|
||||
assert preserved is not None
|
||||
assert (preserved.question, preserved.content) == ("Other question", "Other answer")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("method", "path"), _ENDPOINTS)
|
||||
@pytest.mark.parametrize("credential_state", ["missing", "invalid", "revoked"])
|
||||
def test_every_handler_requires_a_valid_bearer_key(
|
||||
harness: _Harness, method: str, path: str, credential_state: str
|
||||
) -> None:
|
||||
authorization = "" if credential_state == "missing" else f"Bearer app-{uuid4()}"
|
||||
if credential_state == "revoked":
|
||||
assert harness.request("GET", "/annotations").status_code == 200
|
||||
harness.services.app_api_keys.delete_key(harness.context, harness.target.id, harness.api_key.id)
|
||||
authorization = f"Bearer {harness.api_key.token}"
|
||||
|
||||
response = harness.request(
|
||||
method, path.format(id=uuid4()), payload={**_ANNOTATION_PAYLOAD, **_REPLY_PAYLOAD}, authorization=authorization
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.get_json()["code"] == "unauthorized"
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
def test_api_key_cache_hit_avoids_token_query_and_revocation_invalidates_cache(harness: _Harness) -> None:
|
||||
assert harness.request("GET", "/annotations").status_code == 200
|
||||
assert len(harness.token_reads) == 1
|
||||
cached = ApiTokenCache.get(harness.api_key.token, "app")
|
||||
assert cached is not None
|
||||
assert (cached.id, cached.app_id) == (harness.api_key.id, harness.target.id)
|
||||
|
||||
assert harness.request("GET", "/annotations").status_code == 200
|
||||
assert len(harness.token_reads) == 1
|
||||
harness.services.app_api_keys.delete_key(harness.context, harness.target.id, harness.api_key.id)
|
||||
|
||||
response = harness.request("GET", "/annotations")
|
||||
assert response.status_code == 401
|
||||
assert response.get_json()["code"] == "unauthorized"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("state", "status", "code"),
|
||||
[
|
||||
("app_missing", 403, "app_not_found"),
|
||||
("api_disabled", 403, "app_api_disabled"),
|
||||
("app_abnormal", 403, "app_abnormal_status"),
|
||||
("tenant_missing", 403, "workspace_not_found"),
|
||||
("tenant_archived", 403, "workspace_archived"),
|
||||
("owner_role", 401, "unauthorized"),
|
||||
("owner_missing", 401, "unauthorized"),
|
||||
],
|
||||
)
|
||||
def test_cached_key_rechecks_application_workspace_and_owner(
|
||||
harness: _Harness, state: str, status: int, code: str
|
||||
) -> None:
|
||||
assert harness.request("GET", "/annotations").status_code == 200
|
||||
with harness.factory.begin() as session:
|
||||
match state:
|
||||
case "app_missing":
|
||||
session.execute(delete(App).where(App.id == harness.target.id))
|
||||
case "api_disabled":
|
||||
session.execute(update(App).where(App.id == harness.target.id).values(enable_api=False))
|
||||
case "app_abnormal":
|
||||
session.execute(text("UPDATE apps SET status = 'disabled' WHERE id = :id"), {"id": harness.target.id})
|
||||
case "tenant_missing":
|
||||
session.execute(delete(Tenant).where(Tenant.id == harness.target.tenant_id))
|
||||
case "tenant_archived":
|
||||
session.execute(
|
||||
update(Tenant).where(Tenant.id == harness.target.tenant_id).values(status=TenantStatus.ARCHIVE)
|
||||
)
|
||||
case "owner_role":
|
||||
session.execute(
|
||||
update(TenantAccountJoin)
|
||||
.where(TenantAccountJoin.account_id == harness.account.id)
|
||||
.values(role=TenantAccountRole.EDITOR)
|
||||
)
|
||||
case "owner_missing":
|
||||
session.execute(delete(Account).where(Account.id == harness.account.id))
|
||||
|
||||
response = harness.request("GET", "/annotations")
|
||||
|
||||
assert response.status_code == status
|
||||
assert response.get_json()["code"] == code
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token_scope", ["matching", "legacy_missing", "foreign"])
|
||||
def test_api_key_admission_checks_token_workspace_and_preserves_legacy_keys(
|
||||
harness: _Harness, token_scope: str
|
||||
) -> None:
|
||||
tenant_id = {
|
||||
"matching": harness.target.tenant_id,
|
||||
"legacy_missing": None,
|
||||
"foreign": harness.foreign.tenant_id,
|
||||
}[token_scope]
|
||||
with harness.factory.begin() as session:
|
||||
session.execute(update(ApiToken).where(ApiToken.id == harness.api_key.id).values(tenant_id=tenant_id))
|
||||
|
||||
for _ in range(2):
|
||||
response = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD)
|
||||
if token_scope == "foreign":
|
||||
assert response.status_code == 403
|
||||
assert response.get_json()["code"] == "app_not_found"
|
||||
else:
|
||||
assert response.status_code == 201
|
||||
with harness.factory() as session:
|
||||
annotation = session.get(MessageAnnotation, response.get_json()["id"])
|
||||
assert annotation is not None
|
||||
assert (annotation.app_id, annotation.account_id) == (harness.target.id, harness.account.id)
|
||||
assert len(harness.token_reads) == 1
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
def test_api_key_admission_does_not_require_console_account_login_state(harness: _Harness) -> None:
|
||||
with harness.factory.begin() as session:
|
||||
session.execute(update(Account).where(Account.id == harness.account.id).values(status=AccountStatus.BANNED))
|
||||
session.execute(
|
||||
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(current=False)
|
||||
)
|
||||
|
||||
response = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert harness.publications == []
|
||||
|
||||
|
||||
def test_resource_token_selection_and_revocation(harness: _Harness) -> None:
|
||||
resource = harness.resource_token(harness.target.id, harness.other.id)
|
||||
missing_selection = harness.request("GET", "/annotations", token=resource.token)
|
||||
assert missing_selection.status_code == 400
|
||||
assert missing_selection.get_json()["code"] == "invalid_param"
|
||||
forbidden = harness.request("GET", "/annotations", token=resource.token, app_id=harness.foreign.id)
|
||||
assert forbidden.status_code == 403
|
||||
assert forbidden.get_json()["code"] == "forbidden"
|
||||
created = harness.request(
|
||||
"POST", "/annotations", token=resource.token, app_id=harness.other.id, payload=_ANNOTATION_PAYLOAD
|
||||
)
|
||||
assert created.status_code == 201
|
||||
assert (
|
||||
harness.request("GET", "/annotations", token=resource.token, app_id=harness.target.id).get_json()["total"] == 0
|
||||
)
|
||||
assert (
|
||||
harness.request("GET", "/annotations", token=resource.token, app_id=harness.other.id).get_json()["total"] == 1
|
||||
)
|
||||
|
||||
harness.services.resource_access_tokens.delete_relation(
|
||||
harness.context, token_id=resource.token_id, relation_id=resource.rows[0].relation_id
|
||||
)
|
||||
|
||||
assert harness.request("GET", "/annotations", token=resource.token, app_id=harness.other.id).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
@pytest.mark.parametrize("credential", ["key", "resource"])
|
||||
def test_reply_jobs_share_console_ownership_and_publish_after_sessions_close(
|
||||
harness: _Harness, action: AnnotationReplyAction, credential: Credential
|
||||
) -> None:
|
||||
token = harness.credential(credential)
|
||||
response = harness.request("POST", f"/annotation-reply/{action}", payload=_REPLY_PAYLOAD, token=token)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
job_id = body["job_id"]
|
||||
assert str(UUID(job_id)) == job_id
|
||||
assert body == {"job_id": job_id, "job_status": "waiting"}
|
||||
assert harness.redis.get(annotation_reply_job_owner_key(action=action, job_id=job_id)) == (
|
||||
f"{harness.target.tenant_id}:{harness.target.id}".encode()
|
||||
)
|
||||
expected: dict[str, object] = {"job_id": job_id, "app_id": harness.target.id, "tenant_id": harness.target.tenant_id}
|
||||
if action == "enable":
|
||||
expected.update(_REPLY_PAYLOAD, user_id=harness.account.id)
|
||||
harness.consume_task(action, expected)
|
||||
assert harness.publications == [True]
|
||||
status = harness.request("GET", f"/annotation-reply/{action}/status/{job_id}", token=token)
|
||||
assert status.status_code == 200
|
||||
expected_status = {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
|
||||
assert status.get_json() == expected_status
|
||||
|
||||
client = harness.app.test_client()
|
||||
csrf = generate_csrf_token(harness.account.id)
|
||||
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, csrf)
|
||||
console_status = client.get(
|
||||
f"/console/api/apps/{harness.target.id}/annotation-reply/{action}/status/{job_id}",
|
||||
headers={
|
||||
HEADER_NAME_CSRF_TOKEN: csrf,
|
||||
"Authorization": f"Bearer {PassportService().issue({'user_id': harness.account.id})}",
|
||||
},
|
||||
)
|
||||
assert console_status.status_code == 200
|
||||
assert console_status.get_json() == expected_status
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
@pytest.mark.parametrize("mismatch", ["app", "tenant", "action", "legacy", "missing"])
|
||||
def test_reply_status_rejects_unverifiable_ownership(
|
||||
harness: _Harness, action: AnnotationReplyAction, mismatch: str
|
||||
) -> None:
|
||||
job_id = str(uuid4())
|
||||
stored_action: AnnotationReplyAction = (
|
||||
("disable" if action == "enable" else "enable") if mismatch == "action" else action
|
||||
)
|
||||
if mismatch != "missing":
|
||||
harness.redis.set(f"{stored_action}_app_annotation_job_{job_id}", "completed")
|
||||
if mismatch not in {"legacy", "missing"}:
|
||||
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
|
||||
harness.redis.set(
|
||||
annotation_reply_job_owner_key(action=stored_action, job_id=job_id), f"{tenant_id}:{harness.target.id}"
|
||||
)
|
||||
|
||||
response = harness.request(
|
||||
"GET",
|
||||
f"/annotation-reply/{action}/status/{job_id}",
|
||||
token=harness.other_key.token if mismatch == "app" else harness.api_key.token,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["code"] == "not_found"
|
||||
assert response.get_json()["message"] == "The job does not exist."
|
||||
assert harness.publications == []
|
||||
Whitespace-only changes.
+52
@@ -0,0 +1,52 @@
|
||||
"""Container integration coverage for Service API dataset controllers."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models.account import Account
|
||||
from models.enums import TagType
|
||||
from models.model import Tag
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import create_console_account_and_tenant
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(flask_app_with_containers: Flask) -> Flask:
|
||||
return flask_app_with_containers
|
||||
|
||||
|
||||
class TestDatasetTagsApiGet:
|
||||
"""Exercise the unmocked tag query against the container database."""
|
||||
|
||||
@patch("controllers.service_api.dataset.dataset.current_user")
|
||||
def test_list_tags_from_db(
|
||||
self,
|
||||
mock_current_user: MagicMock,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
account, tenant = create_console_account_and_tenant(db_session_with_containers)
|
||||
tag = Tag(
|
||||
name="Integration Tag",
|
||||
type=TagType.KNOWLEDGE,
|
||||
created_by=account.id,
|
||||
tenant_id=tenant.id,
|
||||
)
|
||||
db_session_with_containers.add(tag)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
mock_current_user.__class__ = Account
|
||||
mock_current_user.current_tenant_id = tenant.id
|
||||
|
||||
from controllers.service_api.dataset.dataset import DatasetTagsApi
|
||||
|
||||
with app.test_request_context("/datasets/tags", method="GET"):
|
||||
response, status = DatasetTagsApi().get(_=None)
|
||||
|
||||
assert status == 200
|
||||
assert isinstance(response, list)
|
||||
assert any(item["name"] == "Integration Tag" for item in response)
|
||||
assert all(set(item) == {"id", "name", "type", "binding_count"} for item in response)
|
||||
assert all(isinstance(item["binding_count"], str) for item in response)
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
"""DB-backed integration tests for service API dataset segment endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
|
||||
from models.dataset import ChildChunk, Dataset, Document, DocumentSegment, DocumentSegmentSummary
|
||||
from models.enums import (
|
||||
ApiTokenType,
|
||||
DataSourceType,
|
||||
DocumentCreatedFrom,
|
||||
IndexingStatus,
|
||||
SegmentStatus,
|
||||
SegmentType,
|
||||
SummaryStatus,
|
||||
)
|
||||
from models.model import ApiToken
|
||||
from tests.e2e_tests.containers.controllers.console.helpers import create_console_account_and_tenant
|
||||
|
||||
|
||||
def _create_dataset_graph(db_session: Session) -> tuple[Dataset, Document, DocumentSegment]:
|
||||
account, tenant = create_console_account_and_tenant(db_session)
|
||||
dataset = Dataset(
|
||||
tenant_id=tenant.id,
|
||||
name=f"Segment Dataset {uuid4()}",
|
||||
description="Segment integration dataset",
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
indexing_technique=IndexTechniqueType.ECONOMY,
|
||||
created_by=account.id,
|
||||
permission="only_me",
|
||||
provider="vendor",
|
||||
enable_api=True,
|
||||
)
|
||||
db_session.add(dataset)
|
||||
db_session.commit()
|
||||
|
||||
document = Document(
|
||||
tenant_id=tenant.id,
|
||||
dataset_id=dataset.id,
|
||||
position=1,
|
||||
data_source_type=DataSourceType.UPLOAD_FILE,
|
||||
batch=f"batch-{uuid4()}",
|
||||
name="segment-doc.txt",
|
||||
created_from=DocumentCreatedFrom.API,
|
||||
created_by=account.id,
|
||||
enabled=True,
|
||||
archived=False,
|
||||
indexing_status=IndexingStatus.COMPLETED,
|
||||
doc_form=IndexStructureType.PARAGRAPH_INDEX,
|
||||
word_count=4,
|
||||
tokens=5,
|
||||
)
|
||||
db_session.add(document)
|
||||
db_session.commit()
|
||||
|
||||
segment = DocumentSegment(
|
||||
tenant_id=tenant.id,
|
||||
dataset_id=dataset.id,
|
||||
document_id=document.id,
|
||||
position=1,
|
||||
content="Segment content for integration",
|
||||
word_count=4,
|
||||
tokens=5,
|
||||
keywords=["segment", "integration"],
|
||||
status=SegmentStatus.COMPLETED,
|
||||
created_by=account.id,
|
||||
)
|
||||
db_session.add(segment)
|
||||
db_session.commit()
|
||||
|
||||
summary = DocumentSegmentSummary(
|
||||
dataset_id=dataset.id,
|
||||
document_id=document.id,
|
||||
chunk_id=segment.id,
|
||||
summary_content="DB summary",
|
||||
status=SummaryStatus.COMPLETED,
|
||||
)
|
||||
db_session.add(summary)
|
||||
|
||||
api_token = ApiToken(
|
||||
tenant_id=tenant.id,
|
||||
type=ApiTokenType.DATASET,
|
||||
token=f"dataset-{uuid4().hex}",
|
||||
)
|
||||
db_session.add(api_token)
|
||||
db_session.commit()
|
||||
return dataset, document, segment
|
||||
|
||||
|
||||
def _auth_headers(db_session: Session, dataset: Dataset) -> dict[str, str]:
|
||||
token = db_session.query(ApiToken).filter_by(tenant_id=dataset.tenant_id, type=ApiTokenType.DATASET).one()
|
||||
return {"Authorization": f"Bearer {token.token}"}
|
||||
|
||||
|
||||
def test_list_segments_uses_real_services_and_service_api_shape(
|
||||
test_client_with_containers: FlaskClient,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
dataset, document, segment = _create_dataset_graph(db_session_with_containers)
|
||||
segment_id = segment.id
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/v1/datasets/{dataset.id}/documents/{document.id}/segments"
|
||||
"?page=1&limit=20&status=completed&keyword=integration",
|
||||
headers=_auth_headers(db_session_with_containers, dataset),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert set(body) == {"data", "doc_form", "total", "has_more", "limit", "page"}
|
||||
assert body["doc_form"] == "text_model"
|
||||
assert body["total"] == 1
|
||||
assert "total_pages" not in body
|
||||
assert body["data"][0]["id"] == segment_id
|
||||
assert body["data"][0]["summary"] == "DB summary"
|
||||
assert body["data"][0]["attachments"] == []
|
||||
assert body["data"][0]["child_chunks"] == []
|
||||
|
||||
|
||||
def test_list_child_chunks_uses_real_segment_service(
|
||||
test_client_with_containers: FlaskClient,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
dataset, document, segment = _create_dataset_graph(db_session_with_containers)
|
||||
child_chunk = ChildChunk(
|
||||
tenant_id=dataset.tenant_id,
|
||||
dataset_id=dataset.id,
|
||||
document_id=document.id,
|
||||
segment_id=segment.id,
|
||||
position=1,
|
||||
content="Child integration content",
|
||||
word_count=3,
|
||||
type=SegmentType.CUSTOMIZED,
|
||||
created_by=document.created_by,
|
||||
)
|
||||
db_session_with_containers.add(child_chunk)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
response = test_client_with_containers.get(
|
||||
f"/v1/datasets/{dataset.id}/documents/{document.id}/segments/{segment.id}/child_chunks"
|
||||
"?page=1&limit=20&keyword=integration",
|
||||
headers=_auth_headers(db_session_with_containers, dataset),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert set(body) == {"data", "total", "total_pages", "page", "limit"}
|
||||
assert body["total"] == 1
|
||||
assert body["data"][0]["content"] == "Child integration content"
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask.testing import FlaskClient
|
||||
from sqlalchemy import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from core.app.app_config.entities import WorkflowUIBasedAppConfig
|
||||
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, WorkflowAppGenerateEntity
|
||||
from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
|
||||
from core.workflow.human_input_adapter import DeliveryMethodType
|
||||
from core.workflow.nodes.human_input.entities import (
|
||||
FormDefinition,
|
||||
SelectInputConfig,
|
||||
StringListSource,
|
||||
UserActionConfig,
|
||||
)
|
||||
from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceType
|
||||
from core.workflow.nodes.human_input.pause_reason import HumanInputRequired
|
||||
from graphon.enums import WorkflowExecutionStatus
|
||||
from graphon.runtime import RuntimeState, VariablePool
|
||||
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
|
||||
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
|
||||
from models.human_input import (
|
||||
HumanInputDelivery,
|
||||
HumanInputForm,
|
||||
HumanInputFormRecipient,
|
||||
RecipientType,
|
||||
StandaloneWebAppRecipientPayload,
|
||||
)
|
||||
from models.model import App, AppMode, CustomizeTokenStrategy, IconType, Site
|
||||
from models.workflow import WorkflowRun, WorkflowType
|
||||
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
|
||||
from services.entities.feature_entities import FeatureModel
|
||||
|
||||
|
||||
def _create_app_with_site(session: Session) -> tuple[App, Account]:
|
||||
tenant = Tenant(name="Test Tenant")
|
||||
account = Account(name="Tester", email=f"tester-{uuid4()}@example.com")
|
||||
session.add_all([tenant, account])
|
||||
session.flush()
|
||||
|
||||
session.add(
|
||||
TenantAccountJoin(
|
||||
tenant_id=tenant.id,
|
||||
account_id=account.id,
|
||||
current=True,
|
||||
role=TenantAccountRole.OWNER,
|
||||
)
|
||||
)
|
||||
|
||||
app = App(
|
||||
tenant_id=tenant.id,
|
||||
name="Test App",
|
||||
description="",
|
||||
mode=AppMode.WORKFLOW,
|
||||
icon_type=IconType.EMOJI,
|
||||
icon="app",
|
||||
icon_background="#ffffff",
|
||||
enable_site=True,
|
||||
enable_api=True,
|
||||
created_by=account.id,
|
||||
updated_by=account.id,
|
||||
)
|
||||
session.add(app)
|
||||
session.flush()
|
||||
|
||||
site = Site(
|
||||
app_id=app.id,
|
||||
title="Test Site",
|
||||
icon_type=IconType.EMOJI,
|
||||
icon="robot",
|
||||
icon_background="#ffffff",
|
||||
description="desc",
|
||||
default_language="en",
|
||||
chat_color_theme="light",
|
||||
chat_color_theme_inverted=False,
|
||||
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
|
||||
code=f"code-{uuid4().hex[:8]}",
|
||||
prompt_public=False,
|
||||
show_workflow_steps=True,
|
||||
use_icon_as_answer_icon=False,
|
||||
)
|
||||
session.add(site)
|
||||
session.flush()
|
||||
return app, account
|
||||
|
||||
|
||||
def _build_resumption_context(*, app: App, workflow_run: WorkflowRun, options: list[str]) -> WorkflowResumptionContext:
|
||||
app_config = WorkflowUIBasedAppConfig(
|
||||
tenant_id=app.tenant_id,
|
||||
app_id=app.id,
|
||||
app_mode=AppMode.WORKFLOW,
|
||||
workflow_id=workflow_run.workflow_id,
|
||||
)
|
||||
generate_entity = WorkflowAppGenerateEntity(
|
||||
user_from=UserFrom.END_USER,
|
||||
task_id="task-1",
|
||||
app_config=app_config,
|
||||
inputs={},
|
||||
files=[],
|
||||
user_id=str(uuid4()),
|
||||
stream=True,
|
||||
invoke_from=InvokeFrom.WEB_APP,
|
||||
call_depth=0,
|
||||
workflow_execution_id=workflow_run.id,
|
||||
)
|
||||
runtime_state = RuntimeState(workflow_id="test-workflow", variable_pool=VariablePool(), start_at=0.0)
|
||||
runtime_state.variable_pool.add(("start", "options"), options)
|
||||
return WorkflowResumptionContext(
|
||||
generate_entity=_WorkflowGenerateEntityWrapper(entity=generate_entity),
|
||||
serialized_graph_runtime_state=runtime_state.dumps(),
|
||||
)
|
||||
|
||||
|
||||
def test_get_human_input_form_resolves_runtime_select_options(
|
||||
db_session_with_containers: Session,
|
||||
test_client_with_containers: FlaskClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
app, account = _create_app_with_site(db_session_with_containers)
|
||||
workflow_run = WorkflowRun(
|
||||
tenant_id=app.tenant_id,
|
||||
app_id=app.id,
|
||||
workflow_id=str(uuid4()),
|
||||
type=WorkflowType.WORKFLOW,
|
||||
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
|
||||
version="v1",
|
||||
graph=None,
|
||||
inputs="{}",
|
||||
status=WorkflowExecutionStatus.RUNNING,
|
||||
outputs="{}",
|
||||
error=None,
|
||||
elapsed_time=0.0,
|
||||
total_tokens=0,
|
||||
total_steps=0,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=account.id,
|
||||
)
|
||||
workflow_run.created_at = datetime.now(UTC).replace(tzinfo=None)
|
||||
db_session_with_containers.add(workflow_run)
|
||||
db_session_with_containers.flush()
|
||||
|
||||
configured_input = SelectInputConfig(
|
||||
output_variable_name="decision",
|
||||
option_source=StringListSource(
|
||||
type=ValueSourceType.VARIABLE,
|
||||
selector=["start", "options"],
|
||||
value=["configured"],
|
||||
),
|
||||
)
|
||||
expiration_time = datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)
|
||||
form_definition = FormDefinition(
|
||||
form_content="Choose",
|
||||
rendered_content="Choose",
|
||||
inputs=[configured_input],
|
||||
user_actions=[UserActionConfig(id="approve", title="Approve")],
|
||||
expiration_time=expiration_time,
|
||||
)
|
||||
form = HumanInputForm(
|
||||
tenant_id=app.tenant_id,
|
||||
app_id=app.id,
|
||||
workflow_run_id=workflow_run.id,
|
||||
form_kind=HumanInputFormKind.RUNTIME,
|
||||
node_id="human-node",
|
||||
form_definition=form_definition.model_dump_json(),
|
||||
rendered_content="Choose",
|
||||
status=HumanInputFormStatus.WAITING,
|
||||
expiration_time=expiration_time,
|
||||
)
|
||||
db_session_with_containers.add(form)
|
||||
db_session_with_containers.flush()
|
||||
|
||||
delivery = HumanInputDelivery(
|
||||
form_id=form.id,
|
||||
delivery_method_type=DeliveryMethodType.WEBAPP,
|
||||
channel_payload="{}",
|
||||
)
|
||||
db_session_with_containers.add(delivery)
|
||||
db_session_with_containers.flush()
|
||||
|
||||
access_token = f"hitl{uuid4().hex[:18]}"
|
||||
recipient = HumanInputFormRecipient(
|
||||
form_id=form.id,
|
||||
delivery_id=delivery.id,
|
||||
recipient_type=RecipientType.STANDALONE_WEB_APP,
|
||||
recipient_payload=StandaloneWebAppRecipientPayload().model_dump_json(),
|
||||
access_token=access_token,
|
||||
)
|
||||
db_session_with_containers.add(recipient)
|
||||
db_session_with_containers.commit()
|
||||
|
||||
context = _build_resumption_context(
|
||||
app=app,
|
||||
workflow_run=workflow_run,
|
||||
options=["approve", "reject"],
|
||||
)
|
||||
reason = HumanInputRequired(
|
||||
form_id=form.id,
|
||||
form_content="Choose",
|
||||
inputs=[configured_input],
|
||||
actions=[UserActionConfig(id="approve", title="Approve")],
|
||||
node_id="human-node",
|
||||
node_title="Human Input",
|
||||
)
|
||||
engine = db_session_with_containers.get_bind()
|
||||
assert isinstance(engine, Engine)
|
||||
workflow_run_repo = DifyAPISQLAlchemyWorkflowRunRepository(
|
||||
session_maker=sessionmaker(bind=engine, expire_on_commit=False)
|
||||
)
|
||||
workflow_run_repo.create_workflow_pause(
|
||||
workflow_run_id=workflow_run.id,
|
||||
state_owner_user_id=account.id,
|
||||
state=context.dumps(),
|
||||
pause_reasons=[reason],
|
||||
)
|
||||
|
||||
def mock_get_features(tenant_id: str, exclude_vector_space: bool = False) -> FeatureModel:
|
||||
features = FeatureModel(can_replace_logo=True, webapp_copyright_enabled=True)
|
||||
return features
|
||||
|
||||
monkeypatch.setattr(
|
||||
"controllers.web.human_input_form.FeatureService.get_features",
|
||||
mock_get_features,
|
||||
)
|
||||
|
||||
response = test_client_with_containers.get(f"/api/form/human_input/{access_token}")
|
||||
|
||||
assert response.status_code == 200, response.get_data(as_text=True)
|
||||
body = json.loads(response.get_data(as_text=True))
|
||||
assert body["inputs"][0]["option_source"]["type"] == "constant"
|
||||
assert body["inputs"][0]["option_source"]["selector"] == []
|
||||
assert body["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Web login rejection with the account application service and real persistence."""
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import Unauthorized
|
||||
|
||||
from configs import dify_config
|
||||
from controllers.console import wraps
|
||||
from controllers.web.login import EmailCodeLoginSendEmailApi
|
||||
from enums import DeploymentEdition
|
||||
from models.account import Account, AccountStatus
|
||||
|
||||
|
||||
def test_email_code_login_rejects_persisted_banned_account(
|
||||
flask_app_with_containers: Flask, db_session_with_containers: Session, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
account = Account(name="Banned", email=f"banned-{uuid4()}@example.com", status=AccountStatus.BANNED)
|
||||
db_session_with_containers.add(account)
|
||||
db_session_with_containers.commit()
|
||||
monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
|
||||
monkeypatch.setattr(wraps, "_is_setup_completed", lambda: True)
|
||||
|
||||
with (
|
||||
flask_app_with_containers.test_request_context(
|
||||
"/api/email-code-login", method="POST", json={"email": account.email, "language": "en-US"}
|
||||
),
|
||||
pytest.raises(Unauthorized, match="Account is banned."),
|
||||
):
|
||||
EmailCodeLoginSendEmailApi().post()
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Testcontainers integration tests for controllers.web.site endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.web.error import WebAppNotFoundError
|
||||
from controllers.web.site import AppSiteApi, WebAppSiteResponse, WebModelConfigResponse
|
||||
from models import Tenant, TenantStatus
|
||||
from models.account import TenantCustomConfigDict
|
||||
from models.model import App, AppMode, AppModelConfig, CustomizeTokenStrategy, EndUser, Site
|
||||
from services.entities.feature_entities import FeatureModel
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(flask_app_with_containers: Flask) -> Flask:
|
||||
return flask_app_with_containers
|
||||
|
||||
|
||||
def _create_tenant(db_session: Session, *, status: TenantStatus = TenantStatus.NORMAL) -> Tenant:
|
||||
tenant = Tenant(name="test-tenant", status=status)
|
||||
db_session.add(tenant)
|
||||
db_session.commit()
|
||||
return tenant
|
||||
|
||||
|
||||
def _create_app(db_session: Session, tenant_id: str, *, enable_site: bool = True) -> App:
|
||||
app_model = App(
|
||||
tenant_id=tenant_id,
|
||||
mode=AppMode.CHAT,
|
||||
name="test-app",
|
||||
enable_site=enable_site,
|
||||
enable_api=True,
|
||||
)
|
||||
db_session.add(app_model)
|
||||
db_session.commit()
|
||||
return app_model
|
||||
|
||||
|
||||
def _create_site(db_session: Session, app_id: str) -> Site:
|
||||
site = _site_model(app_id=app_id)
|
||||
db_session.add(site)
|
||||
db_session.commit()
|
||||
return site
|
||||
|
||||
|
||||
def _end_user(tenant_id: str, app_id: str) -> EndUser:
|
||||
return EndUser(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
type="browser",
|
||||
session_id=f"session-{app_id}",
|
||||
)
|
||||
|
||||
|
||||
def _site_model(*, app_id: str) -> Site:
|
||||
return Site(
|
||||
app_id=app_id,
|
||||
title="Site",
|
||||
icon_type="emoji",
|
||||
icon="robot",
|
||||
icon_background="#fff",
|
||||
description="desc",
|
||||
input_placeholder="Ask the app",
|
||||
default_language="en",
|
||||
chat_color_theme="light",
|
||||
chat_color_theme_inverted=False,
|
||||
custom_disclaimer="",
|
||||
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
|
||||
code=f"code-{app_id[-6:]}",
|
||||
prompt_public=False,
|
||||
show_workflow_steps=True,
|
||||
use_icon_as_answer_icon=False,
|
||||
)
|
||||
|
||||
|
||||
class TestAppSiteApi:
|
||||
@patch("services.feature_service.FeatureService.get_features")
|
||||
def test_happy_path(self, mock_features: MagicMock, app: Flask, db_session_with_containers: Session) -> None:
|
||||
app.config["RESTX_MASK_HEADER"] = "X-Fields"
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
app_model = _create_app(db_session_with_containers, tenant.id)
|
||||
_create_site(db_session_with_containers, app_model.id)
|
||||
end_user = _end_user(tenant.id, app_model.id)
|
||||
mock_features.return_value = FeatureModel(can_replace_logo=False)
|
||||
|
||||
with app.test_request_context("/site"):
|
||||
result = AppSiteApi().get(app_model, end_user)
|
||||
|
||||
assert result["app_id"] == app_model.id
|
||||
assert result["end_user_id"] == end_user.id
|
||||
assert result["plan"] == "basic"
|
||||
assert result["enable_site"] is True
|
||||
assert result["mode"] == AppMode.CHAT
|
||||
|
||||
def test_missing_site_raises_not_found(self, app: Flask, db_session_with_containers: Session) -> None:
|
||||
app.config["RESTX_MASK_HEADER"] = "X-Fields"
|
||||
tenant = _create_tenant(db_session_with_containers)
|
||||
app_model = _create_app(db_session_with_containers, tenant.id)
|
||||
end_user = _end_user(tenant.id, app_model.id)
|
||||
|
||||
with app.test_request_context("/site"):
|
||||
with pytest.raises(WebAppNotFoundError):
|
||||
AppSiteApi().get(app_model, end_user)
|
||||
|
||||
def test_archived_tenant_raises_not_found(self, app: Flask, db_session_with_containers: Session) -> None:
|
||||
app.config["RESTX_MASK_HEADER"] = "X-Fields"
|
||||
tenant = _create_tenant(db_session_with_containers, status=TenantStatus.ARCHIVE)
|
||||
app_model = _create_app(db_session_with_containers, tenant.id)
|
||||
_create_site(db_session_with_containers, app_model.id)
|
||||
end_user = _end_user(tenant.id, app_model.id)
|
||||
|
||||
with app.test_request_context("/site"):
|
||||
with pytest.raises(WebAppNotFoundError):
|
||||
AppSiteApi().get(app_model, end_user)
|
||||
|
||||
|
||||
def _tenant_model(*, plan: str = "basic", custom_config: TenantCustomConfigDict | None = None) -> Tenant:
|
||||
tenant = Tenant(name="test-tenant", plan=plan)
|
||||
tenant.custom_config_dict = custom_config or {}
|
||||
return tenant
|
||||
|
||||
|
||||
def _app_model(*, tenant: Tenant, enable_site: bool = True) -> App:
|
||||
app_model = App(
|
||||
tenant_id=tenant.id,
|
||||
mode=AppMode.CHAT,
|
||||
name="test-app",
|
||||
enable_site=enable_site,
|
||||
enable_api=True,
|
||||
)
|
||||
app_model.id = "app-test"
|
||||
return app_model
|
||||
|
||||
|
||||
class TestWebAppSiteResponse:
|
||||
def test_basic_fields(self) -> None:
|
||||
tenant = _tenant_model()
|
||||
app_model = _app_model(tenant=tenant)
|
||||
response = WebAppSiteResponse.from_app_site(
|
||||
tenant=tenant,
|
||||
app_model=app_model,
|
||||
mode=AppMode.CHAT,
|
||||
site=_site_model(app_id=app_model.id),
|
||||
end_user_id="eu-1",
|
||||
features=FeatureModel(can_replace_logo=False, webapp_copyright_enabled=True),
|
||||
can_replace_logo=False,
|
||||
)
|
||||
|
||||
assert response.app_id == app_model.id
|
||||
assert response.mode == AppMode.CHAT
|
||||
assert response.end_user_id == "eu-1"
|
||||
assert response.enable_site is True
|
||||
assert response.plan == "basic"
|
||||
assert response.can_replace_logo is False
|
||||
assert response.model_config_ is None
|
||||
assert response.custom_config is None
|
||||
assert response.site.input_placeholder == "Ask the app"
|
||||
assert response.site.custom_disclaimer == ""
|
||||
|
||||
def test_nullable_site_fields_preserve_none(self) -> None:
|
||||
tenant = _tenant_model()
|
||||
app_model = _app_model(tenant=tenant)
|
||||
site = _site_model(app_id=app_model.id)
|
||||
site.chat_color_theme = None
|
||||
site.icon_type = None
|
||||
site.icon = None
|
||||
site.icon_background = None
|
||||
site.description = None
|
||||
site.copyright = None
|
||||
site.privacy_policy = None
|
||||
|
||||
response = WebAppSiteResponse.from_app_site(
|
||||
tenant=tenant,
|
||||
app_model=app_model,
|
||||
mode=AppMode.CHAT,
|
||||
site=site,
|
||||
end_user_id=None,
|
||||
features=FeatureModel(can_replace_logo=False, webapp_copyright_enabled=True),
|
||||
can_replace_logo=False,
|
||||
)
|
||||
|
||||
dumped = response.model_dump(mode="json")
|
||||
assert dumped["end_user_id"] is None
|
||||
assert dumped["site"]["chat_color_theme"] is None
|
||||
assert dumped["site"]["icon_type"] is None
|
||||
assert dumped["site"]["icon"] is None
|
||||
assert dumped["site"]["icon_background"] is None
|
||||
assert dumped["site"]["description"] is None
|
||||
assert dumped["site"]["copyright"] is None
|
||||
assert dumped["site"]["privacy_policy"] is None
|
||||
assert dumped["site"]["custom_disclaimer"] == ""
|
||||
|
||||
@patch("controllers.web.site.dify_config.FILES_URL", "https://files.example.com")
|
||||
def test_can_replace_logo_sets_custom_config(self) -> None:
|
||||
tenant = _tenant_model(
|
||||
plan="pro",
|
||||
custom_config={"remove_webapp_brand": True, "replace_webapp_logo": "enabled"},
|
||||
)
|
||||
app_model = _app_model(tenant=tenant)
|
||||
response = WebAppSiteResponse.from_app_site(
|
||||
tenant=tenant,
|
||||
app_model=app_model,
|
||||
mode=AppMode.CHAT,
|
||||
site=_site_model(app_id=app_model.id),
|
||||
end_user_id="eu-1",
|
||||
features=FeatureModel(can_replace_logo=True, webapp_copyright_enabled=True),
|
||||
can_replace_logo=True,
|
||||
)
|
||||
|
||||
assert response.can_replace_logo is True
|
||||
assert response.custom_config is not None
|
||||
assert response.custom_config.remove_webapp_brand is True
|
||||
assert response.custom_config.replace_webapp_logo is not None
|
||||
assert "webapp-logo" in response.custom_config.replace_webapp_logo
|
||||
|
||||
|
||||
class TestWebModelConfigResponse:
|
||||
def test_serializes_internal_model_config_properties_to_public_keys(self) -> None:
|
||||
model_config = AppModelConfig(
|
||||
app_id="app-test",
|
||||
opening_statement="Hello",
|
||||
suggested_questions='["Question?"]',
|
||||
suggested_questions_after_answer='{"enabled": true}',
|
||||
more_like_this='{"enabled": false}',
|
||||
model='{"provider": "openai", "name": "gpt-4o", "mode": "chat"}',
|
||||
user_input_form='[{"text-input": {"label": "Name", "variable": "name", "required": true}}]',
|
||||
pre_prompt="System prompt",
|
||||
created_by="account-1",
|
||||
updated_by="account-1",
|
||||
)
|
||||
|
||||
dumped = WebModelConfigResponse.model_validate(model_config, from_attributes=True).model_dump(mode="json")
|
||||
|
||||
assert dumped == {
|
||||
"opening_statement": "Hello",
|
||||
"suggested_questions": ["Question?"],
|
||||
"suggested_questions_after_answer": {"enabled": True},
|
||||
"more_like_this": {"enabled": False},
|
||||
"model": {"provider": "openai", "name": "gpt-4o", "mode": "chat"},
|
||||
"user_input_form": [{"text-input": {"label": "Name", "variable": "name", "required": True}}],
|
||||
"pre_prompt": "System prompt",
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
"""Testcontainers integration tests for controllers.web.wraps — JWT auth decorator and validation helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
from werkzeug.exceptions import NotFound, Unauthorized
|
||||
|
||||
from controllers.web.error import WebAppAuthAccessDeniedError, WebAppAuthRequiredError, WebAppNotFoundError
|
||||
from controllers.web.wraps import (
|
||||
_validate_user_accessibility,
|
||||
_validate_webapp_token,
|
||||
decode_jwt_token,
|
||||
)
|
||||
from models.enums import EndUserType
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("db_session_with_containers")
|
||||
|
||||
|
||||
class TestValidateWebappToken:
|
||||
def test_enterprise_enabled_and_app_auth_requires_webapp_source(self) -> None:
|
||||
decoded = {"token_source": "other"}
|
||||
with pytest.raises(WebAppAuthRequiredError):
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
|
||||
|
||||
def test_enterprise_enabled_and_app_auth_accepts_webapp_source(self) -> None:
|
||||
decoded = {"token_source": "webapp"}
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
|
||||
|
||||
def test_enterprise_enabled_and_app_auth_missing_source_raises(self) -> None:
|
||||
decoded = {}
|
||||
with pytest.raises(WebAppAuthRequiredError):
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
|
||||
|
||||
def test_public_app_rejects_webapp_source(self) -> None:
|
||||
decoded = {"token_source": "webapp"}
|
||||
with pytest.raises(Unauthorized):
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
|
||||
|
||||
def test_public_app_accepts_non_webapp_source(self) -> None:
|
||||
decoded = {"token_source": "other"}
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
|
||||
|
||||
def test_public_app_accepts_no_source(self) -> None:
|
||||
decoded = {}
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
|
||||
|
||||
def test_system_enabled_but_app_public(self) -> None:
|
||||
decoded = {"token_source": "webapp"}
|
||||
with pytest.raises(Unauthorized):
|
||||
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=True)
|
||||
|
||||
|
||||
class TestValidateUserAccessibility:
|
||||
def test_skips_when_auth_disabled(self) -> None:
|
||||
_validate_user_accessibility(
|
||||
decoded={},
|
||||
app_code="code",
|
||||
app_web_auth_enabled=False,
|
||||
system_webapp_auth_enabled=False,
|
||||
webapp_settings=None,
|
||||
)
|
||||
|
||||
def test_missing_user_id_raises(self) -> None:
|
||||
decoded = {}
|
||||
with pytest.raises(WebAppAuthRequiredError):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=SimpleNamespace(access_mode="internal"),
|
||||
)
|
||||
|
||||
def test_missing_webapp_settings_raises(self) -> None:
|
||||
decoded = {"user_id": "u1"}
|
||||
with pytest.raises(WebAppAuthRequiredError, match="settings not found"):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=None,
|
||||
)
|
||||
|
||||
def test_missing_auth_type_raises(self) -> None:
|
||||
decoded = {"user_id": "u1", "granted_at": 1}
|
||||
settings = SimpleNamespace(access_mode="private")
|
||||
with pytest.raises(WebAppAuthRequiredError, match="auth_type"):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
def test_missing_granted_at_raises(self) -> None:
|
||||
decoded = {"user_id": "u1", "auth_type": "external"}
|
||||
settings = SimpleNamespace(access_mode="sso_verified")
|
||||
with pytest.raises(WebAppAuthAccessDeniedError, match="granted_at"):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
@patch("controllers.web.wraps.EnterpriseService.get_app_sso_settings_last_update_time")
|
||||
@patch(
|
||||
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
|
||||
)
|
||||
def test_external_auth_type_checks_sso_update_time(
|
||||
self, mock_perm_check: MagicMock, mock_sso_time: MagicMock
|
||||
) -> None:
|
||||
mock_sso_time.return_value = datetime.now(UTC)
|
||||
old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())
|
||||
decoded = {"user_id": "u1", "auth_type": "external", "granted_at": old_granted}
|
||||
settings = SimpleNamespace(access_mode="sso_verified")
|
||||
with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
@patch("controllers.web.wraps.EnterpriseService.get_workspace_sso_settings_last_update_time")
|
||||
@patch(
|
||||
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
|
||||
)
|
||||
def test_internal_auth_type_checks_workspace_sso_update_time(
|
||||
self, mock_perm_check: MagicMock, mock_workspace_sso: MagicMock
|
||||
) -> None:
|
||||
mock_workspace_sso.return_value = datetime.now(UTC)
|
||||
old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())
|
||||
decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": old_granted}
|
||||
settings = SimpleNamespace(access_mode="private")
|
||||
with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
@patch("controllers.web.wraps.EnterpriseService.get_app_sso_settings_last_update_time")
|
||||
@patch(
|
||||
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
|
||||
)
|
||||
def test_external_auth_passes_when_granted_after_sso_update(
|
||||
self, mock_perm_check: MagicMock, mock_sso_time: MagicMock
|
||||
) -> None:
|
||||
mock_sso_time.return_value = datetime.now(UTC) - timedelta(hours=2)
|
||||
recent_granted = int(datetime.now(UTC).timestamp())
|
||||
decoded = {"user_id": "u1", "auth_type": "external", "granted_at": recent_granted}
|
||||
settings = SimpleNamespace(access_mode="sso_verified")
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp", return_value=False)
|
||||
@patch("services.webapp_access_query_service.WebAppAccessQueryService.get_app_id_by_code", return_value="app-id-1")
|
||||
@patch(
|
||||
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=True
|
||||
)
|
||||
def test_permission_check_denies_unauthorized_user(
|
||||
self, mock_perm: MagicMock, mock_app_id: MagicMock, mock_allowed: MagicMock
|
||||
) -> None:
|
||||
decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": int(datetime.now(UTC).timestamp())}
|
||||
settings = SimpleNamespace(access_mode="private")
|
||||
with pytest.raises(WebAppAuthAccessDeniedError):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=settings,
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("access_mode", "auth_type"),
|
||||
[
|
||||
pytest.param("private", "external", id="private-rejects-external"),
|
||||
pytest.param("private_all", "external", id="private-all-rejects-external"),
|
||||
pytest.param("sso_verified", "internal", id="sso-verified-rejects-internal"),
|
||||
],
|
||||
)
|
||||
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp")
|
||||
@patch("services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required")
|
||||
def test_auth_type_must_match_current_access_mode(
|
||||
self,
|
||||
mock_permission_check: MagicMock,
|
||||
mock_allowed: MagicMock,
|
||||
access_mode: str,
|
||||
auth_type: str,
|
||||
) -> None:
|
||||
decoded = {"user_id": "u1", "auth_type": auth_type, "granted_at": int(datetime.now(UTC).timestamp())}
|
||||
|
||||
with pytest.raises(WebAppAuthRequiredError):
|
||||
_validate_user_accessibility(
|
||||
decoded=decoded,
|
||||
app_code="code",
|
||||
app_web_auth_enabled=True,
|
||||
system_webapp_auth_enabled=True,
|
||||
webapp_settings=SimpleNamespace(access_mode=access_mode),
|
||||
)
|
||||
|
||||
mock_permission_check.assert_not_called()
|
||||
mock_allowed.assert_not_called()
|
||||
|
||||
|
||||
class TestDecodeJwtToken:
|
||||
@pytest.fixture
|
||||
def app(self, flask_app_with_containers: Flask):
|
||||
return flask_app_with_containers
|
||||
|
||||
def _create_app_site_enduser(self, db_session: Session, *, enable_site: bool = True):
|
||||
from models.model import App, AppMode, AppModelConfig, CustomizeTokenStrategy, EndUser, Site
|
||||
|
||||
tenant_id = str(uuid4())
|
||||
app_model = App(
|
||||
tenant_id=tenant_id,
|
||||
mode=AppMode.CHAT.value,
|
||||
name="test-app",
|
||||
enable_site=enable_site,
|
||||
enable_api=True,
|
||||
)
|
||||
db_session.add(app_model)
|
||||
db_session.commit()
|
||||
db_session.expire_all()
|
||||
|
||||
# The happy-path fixture represents a published public App.
|
||||
config = AppModelConfig(app_id=app_model.id)
|
||||
db_session.add(config)
|
||||
db_session.flush()
|
||||
app_model.app_model_config_id = config.id
|
||||
db_session.commit()
|
||||
|
||||
site = Site(
|
||||
app_id=app_model.id,
|
||||
title="test-site",
|
||||
default_language="en-US",
|
||||
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
|
||||
code="code1",
|
||||
)
|
||||
db_session.add(site)
|
||||
db_session.commit()
|
||||
db_session.expire_all()
|
||||
|
||||
end_user = EndUser(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_model.id,
|
||||
type=EndUserType.BROWSER,
|
||||
session_id="sess-1",
|
||||
)
|
||||
db_session.add(end_user)
|
||||
db_session.commit()
|
||||
db_session.expire_all()
|
||||
|
||||
return app_model, site, end_user
|
||||
|
||||
@patch("controllers.web.wraps._validate_user_accessibility")
|
||||
@patch("controllers.web.wraps._validate_webapp_token")
|
||||
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.get_app_access_mode_by_id")
|
||||
@patch("services.webapp_access_query_service.WebAppAccessQueryService.get_app_id_by_code")
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.PassportService")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_happy_path(
|
||||
self,
|
||||
mock_extract: MagicMock,
|
||||
mock_passport_cls: MagicMock,
|
||||
mock_features: MagicMock,
|
||||
mock_app_id: MagicMock,
|
||||
mock_access_mode: MagicMock,
|
||||
mock_validate_token: MagicMock,
|
||||
mock_validate_user: MagicMock,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers)
|
||||
|
||||
mock_extract.return_value = "jwt-token"
|
||||
mock_passport_cls.return_value.verify.return_value = {
|
||||
"app_code": site.code,
|
||||
"app_id": app_model.id,
|
||||
"end_user_id": end_user.id,
|
||||
}
|
||||
mock_features.return_value = False
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": site.code}):
|
||||
result_app, result_user = decode_jwt_token()
|
||||
|
||||
assert result_app.id == app_model.id
|
||||
assert result_user.id == end_user.id
|
||||
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_missing_token_raises_unauthorized(self, mock_extract: MagicMock, mock_features: MagicMock, app) -> None:
|
||||
mock_features.return_value = False
|
||||
mock_extract.return_value = None
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": "code1"}):
|
||||
with pytest.raises(Unauthorized):
|
||||
decode_jwt_token()
|
||||
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.PassportService")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_missing_app_raises_not_found(
|
||||
self,
|
||||
mock_extract: MagicMock,
|
||||
mock_passport_cls: MagicMock,
|
||||
mock_features: MagicMock,
|
||||
app: Flask,
|
||||
) -> None:
|
||||
non_existent_id = str(uuid4())
|
||||
mock_extract.return_value = "jwt-token"
|
||||
mock_passport_cls.return_value.verify.return_value = {
|
||||
"app_code": "code1",
|
||||
"app_id": non_existent_id,
|
||||
"end_user_id": str(uuid4()),
|
||||
}
|
||||
mock_features.return_value = False
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": "code1"}):
|
||||
with pytest.raises(WebAppNotFoundError):
|
||||
decode_jwt_token()
|
||||
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.PassportService")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_disabled_site_raises_app_not_found(
|
||||
self,
|
||||
mock_extract: MagicMock,
|
||||
mock_passport_cls: MagicMock,
|
||||
mock_features: MagicMock,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers, enable_site=False)
|
||||
|
||||
mock_extract.return_value = "jwt-token"
|
||||
mock_passport_cls.return_value.verify.return_value = {
|
||||
"app_code": site.code,
|
||||
"app_id": app_model.id,
|
||||
"end_user_id": end_user.id,
|
||||
}
|
||||
mock_features.return_value = False
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": site.code}):
|
||||
with pytest.raises(WebAppNotFoundError):
|
||||
decode_jwt_token()
|
||||
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.PassportService")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_missing_end_user_raises_not_found(
|
||||
self,
|
||||
mock_extract: MagicMock,
|
||||
mock_passport_cls: MagicMock,
|
||||
mock_features: MagicMock,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
app_model, site, _ = self._create_app_site_enduser(db_session_with_containers)
|
||||
non_existent_eu = str(uuid4())
|
||||
|
||||
mock_extract.return_value = "jwt-token"
|
||||
mock_passport_cls.return_value.verify.return_value = {
|
||||
"app_code": site.code,
|
||||
"app_id": app_model.id,
|
||||
"end_user_id": non_existent_eu,
|
||||
}
|
||||
mock_features.return_value = False
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": site.code}):
|
||||
with pytest.raises(NotFound):
|
||||
decode_jwt_token()
|
||||
|
||||
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
|
||||
@patch("controllers.web.wraps.PassportService")
|
||||
@patch("controllers.web.wraps.extract_webapp_passport")
|
||||
def test_user_id_mismatch_raises_unauthorized(
|
||||
self,
|
||||
mock_extract: MagicMock,
|
||||
mock_passport_cls: MagicMock,
|
||||
mock_features: MagicMock,
|
||||
app: Flask,
|
||||
db_session_with_containers: Session,
|
||||
) -> None:
|
||||
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers)
|
||||
|
||||
mock_extract.return_value = "jwt-token"
|
||||
mock_passport_cls.return_value.verify.return_value = {
|
||||
"app_code": site.code,
|
||||
"app_id": app_model.id,
|
||||
"end_user_id": end_user.id,
|
||||
}
|
||||
mock_features.return_value = False
|
||||
|
||||
with app.test_request_context("/", headers={"X-App-Code": site.code}):
|
||||
with pytest.raises(Unauthorized, match="expired"):
|
||||
decode_jwt_token(user_id="different-user")
|
||||
Reference in new issue
Block a user