Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions api/controllers/service_api/dataset/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
from controllers.service_api.wraps import (
DatasetApiResource,
cloud_edition_billing_rate_limit_check,
validate_dataset_list_token,
validate_dataset_token,
)
from core.plugin.impl.model_runtime_factory import create_plugin_provider_manager
from core.rag.index_processor.constant.index_type import IndexTechniqueType
Expand Down Expand Up @@ -417,11 +419,18 @@ class DatasetBoundTagListResponse(ResponseModel):

@service_api_ns.route("/datasets")
class DatasetListApi(DatasetApiResource):
"""Resource for datasets."""
"""Read authorized datasets while retaining ordinary admission for creation."""

# Explicit handler decorators also protect Flask's automatic HEAD dispatch.
method_decorators = []

@service_api_ns.doc(
summary="List Knowledge Bases",
description="Returns a paginated list of knowledge bases. Supports filtering by keyword and tags.",
description=(
"Returns a paginated list of visible knowledge bases. A scoped knowledge API key "
"only lists its authorized knowledge bases; workspace-wide keys retain their existing visibility. "
"Supports filtering by keyword and tags within that scope."
),
tags=["Knowledge Bases"],
responses={
HTTPStatus.OK: "List of knowledge bases.",
Expand All @@ -441,6 +450,7 @@ class DatasetListApi(DatasetApiResource):
"Datasets retrieved successfully",
service_api_ns.models[DatasetListResponse.__name__],
)
@validate_dataset_list_token
@with_session(write=False)
def get(
self,
Expand Down Expand Up @@ -531,6 +541,7 @@ def get(
"Dataset created successfully",
service_api_ns.models[DatasetDetailResponse.__name__],
)
@validate_dataset_token
@cloud_edition_billing_rate_limit_check("knowledge", "dataset")
@with_session
@model_validate(DatasetCreatePayload)
Expand Down
29 changes: 24 additions & 5 deletions api/controllers/service_api/wraps.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,22 @@ def decorated(*args: P.args, **kwargs: P.kwargs):


def validate_dataset_token[R](view: Callable[..., R]) -> Callable[..., R]:
"""Admit an ordinary dataset operation without allowing scoped-key discovery."""
return _validate_dataset_token(view, list_datasets=False)


def validate_dataset_list_token[R](view: Callable[..., R]) -> Callable[..., R]:
"""Admit collection reads with a server-resolved DatasetServiceApiGrant.

The view must consume the grant as a hard query boundary before pagination.
Invalid credentials remain rejected; resource access tokens keep their existing
resolver. Restricted Dataset API keys must have at least one legacy binding;
KnowledgeFS-only keys remain forbidden on this legacy collection.
"""
return _validate_dataset_token(view, list_datasets=True)


def _validate_dataset_token[R](view: Callable[..., R], *, list_datasets: bool) -> Callable[..., R]:
view_parameters = inspect.signature(view).parameters
positional_parameters = [
parameter
Expand All @@ -363,6 +379,8 @@ def validate_dataset_token[R](view: Callable[..., R]) -> Callable[..., R]:
]
expects_bound_instance = bool(positional_parameters and positional_parameters[0].name in {"self", "cls"})
accepts_dataset_grant = "dataset_grant" in view_parameters
if list_datasets and not accepts_dataset_grant:
raise TypeError("Dataset list views must consume dataset_grant.")

@wraps(view)
def decorated(*args: object, **kwargs: object) -> R:
Expand Down Expand Up @@ -394,9 +412,9 @@ def decorated(*args: object, **kwargs: object) -> R:
# no rows -> the key can reach every dataset in its tenant (default / back-compat)
# N rows -> the key is limited to exactly those resources
# Only legacy-dataset bindings count here: a key bound solely to KnowledgeFS spaces
# is restricted but has no reachable legacy dataset, so it is rejected. A bound key
# may only call endpoints carrying one of its dataset ids; endpoints without a
# dataset id (e.g. list/create datasets) are rejected. The scope is queried per
# is restricted but has no reachable legacy dataset, so it remains forbidden.
# Collection reads accept legacy or mixed bindings and receive only legacy IDs;
# other operations still require a bound dataset id. The scope is queried per
# request (not cached) so changes take effect immediately.
# db.session is Flask-SQLAlchemy's scoped_session proxy; cast so the plain-Session
# typed helper accepts it (runtime proxies every Session method through unchanged).
Expand All @@ -407,12 +425,13 @@ def decorated(*args: object, **kwargs: object) -> R:
)
if scope is None:
raise Unauthorized("API key is no longer valid.")
if not scope.allows_dataset(str(dataset_id) if dataset_id else None):
allows_dataset_list = list_datasets and (not scope.restricted or bool(scope.dataset_ids))
if not allows_dataset_list and not scope.allows_dataset(str(dataset_id) if dataset_id else None):
raise Forbidden("The API key is not authorized to access this knowledge base.")
dataset_grant = DatasetServiceApiGrant(
token_id=str(api_token.id),
tenant_id=tenant_id,
dataset_ids=None,
dataset_ids=scope.dataset_ids if scope.restricted else None,
)

if dataset_id:
Expand Down
2 changes: 1 addition & 1 deletion api/openapi/markdown/service-openapi.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion api/repositories/knowledge/dataset_api_key_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
only honours bindings of its own kind: the legacy dataset endpoints check
``dataset_id`` bindings and the KnowledgeFS endpoints check
``control_space_id`` bindings, so a key bound solely to one kind is
rejected by the other.
rejected by the other. Legacy collection reads may list the authorized
dataset subset of a legacy or mixed key; KnowledgeFS-only keys remain
forbidden. A search with no matching authorized datasets may return an
empty list without changing the key's scope.

Shared by key management, dataset deletion, and service-API authentication.
The caller owns the transaction boundary (commit/flush).
Expand Down
Loading
Loading