Add generic endpoints and support for collection names with / #281
23 changed files with 1248 additions and 1047 deletions
24
CHANGELOG.md
24
CHANGELOG.md
|
|
@ -1,3 +1,27 @@
|
|||
# 6.6.2 (2026-10-07)
|
||||
|
||||
## New features
|
||||
|
||||
- Support generic store-endpoints and do not auto-generate endpoints. As a
|
||||
result the swagger documentation is shorter and independent of the number
|
||||
of collections or schemas. Due to the new structure, the classes that can
|
||||
be stored are no longer represented in the swagger documentation.
|
||||
|
||||
- Support collection names that contain '/'.
|
||||
|
||||
|
||||
# 6.6.1 (2026-10-06)
|
||||
|
||||
## Changes
|
||||
|
||||
- Configuration is now backward compatible with configuration from version 6.5,
|
||||
i.e., the configuration properties `default_policy`, `policy_annotation_tag`,
|
||||
and `policy_mapping` can be used in version 6.6.1 . If the property
|
||||
`policy_info_location` is set, this will be used to configure policy handling.
|
||||
In this case the properties `default_policy`, `policy_annotation_tag`,
|
||||
and `policy_mapping` will be ignored and a warning will be issued.
|
||||
|
||||
|
||||
# 6.6.0 (2026-10-01)
|
||||
|
||||
## New features
|
||||
|
|
|
|||
|
|
@ -60,7 +60,6 @@ reserved_collection_names = (
|
|||
'tokens',
|
||||
'admin_tokens',
|
||||
'api',
|
||||
'v1',
|
||||
dump_things_private_collection_name,
|
||||
)
|
||||
|
||||
policy_annotation = 'https://example.org/dumpthings/policy_set'
|
||||
|
|
|
|||
|
|
@ -128,6 +128,11 @@ class CollectionConfig(BaseModel):
|
|||
ignore_classes: list[str] = []
|
||||
policy_info_location: str | None = None
|
||||
|
||||
# The following keys are ignored
|
||||
default_policy: str | None = None
|
||||
policy_mapping: list[PolicyMapping] = []
|
||||
policy_annotation_tag: str | None = None
|
||||
|
||||
|
||||
class RecordDirConfigFileContent(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
|
@ -267,6 +272,7 @@ def read_config(
|
|||
except ValidationError as ve:
|
||||
msg = f'Faulty configuration at {config_backend.root}: {ve}'
|
||||
raise ConfigError(msg) from ve
|
||||
|
||||
return g_abstract_configuration
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -6,41 +6,14 @@ import shutil
|
|||
import fsspec
|
||||
from pathlib import Path
|
||||
|
||||
# This following lines are required for dynamic endpoint generation
|
||||
from typing import (
|
||||
Annotated, # noqa: F401 -- used by autogenerated code
|
||||
Any,
|
||||
)
|
||||
|
||||
from datalad_core.runners import (
|
||||
CommandError,
|
||||
call_git_oneline,
|
||||
)
|
||||
from fastapi import (
|
||||
Body, # noqa: F401 -- used by autogenerated code
|
||||
Depends,
|
||||
FastAPI,
|
||||
HTTPException,
|
||||
)
|
||||
from fastapi.routing import _IncludedRouter
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
TypeAdapter,
|
||||
ValidationError,
|
||||
)
|
||||
from starlette.responses import (
|
||||
JSONResponse,
|
||||
PlainTextResponse,
|
||||
)
|
||||
from pydantic import ValidationError
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_403_FORBIDDEN,
|
||||
HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
Format,
|
||||
)
|
||||
from dump_things_service import Format
|
||||
from dump_things_service.abstract_config import (
|
||||
CollectionConfig,
|
||||
ConfigAuthSpec,
|
||||
Configuration,
|
||||
ForgejoAuthSpec,
|
||||
|
|
@ -48,115 +21,28 @@ from dump_things_service.abstract_config import (
|
|||
PolicyMapping,
|
||||
RecordDirBackendConfig,
|
||||
SQLiteBackendConfig,
|
||||
check_collection,
|
||||
read_config,
|
||||
)
|
||||
from dump_things_service.api_key import (
|
||||
api_key_header_scheme,
|
||||
)
|
||||
from dump_things_service.audit.gitaudit import GitAuditBackend
|
||||
from dump_things_service.auth.config import ConfigAuthenticationSource
|
||||
from dump_things_service.auth.forgejo import ForgejoAuthenticationSource
|
||||
from dump_things_service.backends.record_dir_index import index_file_name
|
||||
from dump_things_service.converter import FormatConverter
|
||||
from dump_things_service.curated import (
|
||||
store_curated_record, # noqa: F401 -- used by autogenerated code
|
||||
)
|
||||
from dump_things_service.exceptions import (
|
||||
ConfigCollisionError,
|
||||
ConfigError,
|
||||
CurieResolutionError,
|
||||
)
|
||||
from dump_things_service.incoming import (
|
||||
store_incoming_record, # noqa: F401 -- used by autogenerated code
|
||||
)
|
||||
from dump_things_service.instance_state import (
|
||||
InstanceState,
|
||||
InstanceStateCollectionInfo,
|
||||
get_instance_state,
|
||||
get_record_dir_config,
|
||||
get_schema_info,
|
||||
record_dir_config_file_name,
|
||||
)
|
||||
from dump_things_service.model import get_model_for_schema
|
||||
from dump_things_service.utils import (
|
||||
combine_ttl,
|
||||
create_store,
|
||||
get_token_store,
|
||||
join_default_token_permissions,
|
||||
order_dict,
|
||||
var_escape,
|
||||
wrap_http_exception,
|
||||
)
|
||||
from dump_things_service.validate import (
|
||||
validate_record, # noqa: F401 -- used by autogenerated code
|
||||
)
|
||||
from dump_things_service.utils import create_store
|
||||
|
||||
|
||||
logger = logging.getLogger('dump_things_service')
|
||||
|
||||
_endpoint_template = """
|
||||
def {name}(
|
||||
data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')],
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
add_submission_tag: bool = False,
|
||||
format: Format = Format.json,
|
||||
) -> JSONResponse | PlainTextResponse:
|
||||
logger.info('{name}(%s, %s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(add_submission_tag), repr(format))
|
||||
return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key, add_submission_tag=add_submission_tag)
|
||||
"""
|
||||
|
||||
_endpoint_validate_template = """
|
||||
def {name}(
|
||||
data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')],
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
format: Format = Format.json,
|
||||
) -> JSONResponse | PlainTextResponse:
|
||||
logger.info('{name}(%s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(format))
|
||||
return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key)
|
||||
"""
|
||||
|
||||
_endpoint_curated_template = """
|
||||
def {name}(
|
||||
data: {model_var_name}.{class_name},
|
||||
author_id: str | None = None,
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
) -> JSONResponse:
|
||||
logger.info(
|
||||
'{name}(%s, %s, %s)',
|
||||
repr(data),
|
||||
repr(author_id),
|
||||
repr({model_var_name}),
|
||||
)
|
||||
return store_curated_record(
|
||||
'{collection}',
|
||||
data,
|
||||
'{class_name}',
|
||||
author_id,
|
||||
api_key,
|
||||
)
|
||||
"""
|
||||
|
||||
_endpoint_incoming_template = """
|
||||
async def {name}(
|
||||
data: {model_var_name}.{class_name},
|
||||
label: str,
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
) -> JSONResponse:
|
||||
logger.info(
|
||||
'{name}(%s, %s, %s)',
|
||||
repr(data),
|
||||
repr(label),
|
||||
repr({model_var_name}),
|
||||
)
|
||||
return await store_incoming_record(
|
||||
'{collection}',
|
||||
label,
|
||||
data,
|
||||
'{class_name}',
|
||||
api_key,
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
def create_collection(
|
||||
instance_state: InstanceState,
|
||||
|
|
@ -245,10 +131,42 @@ def create_collection(
|
|||
if collection_configuration.ignore_classes:
|
||||
active_classes -= set(collection_configuration.ignore_classes)
|
||||
|
||||
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
||||
configuration,
|
||||
collection_name,
|
||||
)
|
||||
# If external policy information is specified, load it, otherwise use
|
||||
# the policy information from the collection configuration.
|
||||
if collection_configuration.policy_info_location:
|
||||
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
||||
configuration,
|
||||
collection_name,
|
||||
)
|
||||
# If there is a local configuration, issue a warning
|
||||
if (
|
||||
collection_configuration.default_policy
|
||||
or collection_configuration.policy_mapping
|
||||
or collection_configuration.policy_annotation_tag
|
||||
):
|
||||
logger.warning(
|
||||
"Collection '%s' specifies policy information in its "
|
||||
'configuration (via `policy_annotation_tag`, `default_policy`, '
|
||||
'and `policy_mapping`) as well as in an external source (via '
|
||||
'`policy_info_location`). The policy information specified in '
|
||||
'the configuration will be ignored and the externally sourced '
|
||||
'policy information will be used.',
|
||||
collection_name,
|
||||
)
|
||||
else:
|
||||
default_policy = collection_configuration.default_policy
|
||||
policy_mapping = collection_configuration.policy_mapping
|
||||
policy_annotation_tag = collection_configuration.policy_annotation_tag
|
||||
|
||||
if not policy_annotation_tag and (default_policy or policy_mapping):
|
||||
logger.warning(
|
||||
"Collection '%s' specifies policy information in its configuration "
|
||||
'(via `default_policy` and/or `policy_mapping`) but does not specify '
|
||||
'a `policy_annotation_tag`. The policy information will be ignored '
|
||||
'and no policy enforcement will be performed.',
|
||||
collection_name,
|
||||
)
|
||||
|
||||
instance_state.collections[collection_name] = InstanceStateCollectionInfo(
|
||||
active_classes=active_classes,
|
||||
tag_info={},
|
||||
|
|
@ -283,15 +201,6 @@ def create_collection(
|
|||
)
|
||||
)
|
||||
|
||||
# Create the dynamic endpoints for record storing & validation, for
|
||||
# inbox-storing, and for curated area storing.
|
||||
create_endpoints_for_collection(
|
||||
instance_state,
|
||||
collection_name,
|
||||
collection_configuration,
|
||||
instance_state.fastapi_app,
|
||||
)
|
||||
|
||||
|
||||
def create_authentication_source(
|
||||
abstract_configuration: Configuration,
|
||||
|
|
@ -437,276 +346,6 @@ def check_git_audit_compatibility(
|
|||
return
|
||||
|
||||
|
||||
def create_endpoint(
|
||||
operation_name: str,
|
||||
operation_path: str,
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
collection_config: CollectionConfig,
|
||||
template: str,
|
||||
handler: str,
|
||||
tag_group: str,
|
||||
tag_name: str,
|
||||
app: FastAPI,
|
||||
):
|
||||
logger.info(
|
||||
'Creating %s-endpoints for collection: "%s"',
|
||||
operation_name,
|
||||
collection_name,
|
||||
)
|
||||
|
||||
instance_state.collections[collection_name].tag_info[tag_group] = tag_name
|
||||
|
||||
# TODO: get schema_info from instance_state!?
|
||||
model, _classes, model_var_name = get_model_for_schema(
|
||||
collection_config.schema_location
|
||||
)
|
||||
globals()[model_var_name] = model
|
||||
|
||||
active_classes = instance_state.collections[collection_name].active_classes
|
||||
for class_name in active_classes:
|
||||
endpoint_name = (
|
||||
f'_endpoint_{var_escape(collection_name)}_{operation_name}_{class_name}'
|
||||
)
|
||||
endpoint_source = template.format(
|
||||
name=endpoint_name,
|
||||
model_var_name=model_var_name,
|
||||
class_name=class_name,
|
||||
collection=collection_name,
|
||||
info=f"'{operation_name} {collection_name}/{class_name} objects'",
|
||||
handler=handler,
|
||||
)
|
||||
exec(endpoint_source, globals()) # noqa: S102
|
||||
|
||||
# Create an API route for the endpoint
|
||||
app.add_api_route(
|
||||
path=f'/{collection_name}/{operation_path}/{class_name}',
|
||||
endpoint=globals()[endpoint_name],
|
||||
methods=['POST'],
|
||||
name=f'{operation_name} "{class_name}" object (schema: {model.linkml_meta["id"]})',
|
||||
response_model=None,
|
||||
tags=[tag_name],
|
||||
)
|
||||
|
||||
logger.info(
|
||||
'Creation of %d %s-endpoints completed.',
|
||||
len(active_classes),
|
||||
operation_name,
|
||||
)
|
||||
|
||||
|
||||
def create_endpoints_for_collection(
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
collection_config: CollectionConfig,
|
||||
app: FastAPI,
|
||||
):
|
||||
for (
|
||||
operation_name,
|
||||
operation_path,
|
||||
template,
|
||||
handler,
|
||||
tag_group,
|
||||
tag_name,
|
||||
) in (
|
||||
(
|
||||
'store',
|
||||
'record',
|
||||
_endpoint_template,
|
||||
'store_record',
|
||||
'write',
|
||||
f'Write records to collection "{collection_name}"',
|
||||
),
|
||||
(
|
||||
'validate',
|
||||
'validate/record',
|
||||
_endpoint_validate_template,
|
||||
'validate_record',
|
||||
'validate',
|
||||
f'Validate records for collection "{collection_name}"',
|
||||
),
|
||||
(
|
||||
'curated',
|
||||
'curated/record',
|
||||
_endpoint_curated_template,
|
||||
'store_curated_record',
|
||||
'curated_write',
|
||||
f'Curated area: store records in curated area of collection "{collection_name}"',
|
||||
),
|
||||
(
|
||||
'incoming',
|
||||
'incoming/{label}/record',
|
||||
_endpoint_incoming_template,
|
||||
'store_incoming_record',
|
||||
'incoming_write',
|
||||
f'Incoming area: store records in incoming area "{{label}}" of collection "{collection_name}"',
|
||||
),
|
||||
):
|
||||
create_endpoint(
|
||||
operation_name=operation_name,
|
||||
operation_path=operation_path,
|
||||
instance_state=instance_state,
|
||||
collection_name=collection_name,
|
||||
collection_config=collection_config,
|
||||
template=template,
|
||||
handler=handler,
|
||||
tag_group=tag_group,
|
||||
tag_name=tag_name,
|
||||
app=app,
|
||||
)
|
||||
|
||||
|
||||
def delete_endpoints_for_collection(
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
):
|
||||
active_classes = instance_state.collections[collection_name].active_classes
|
||||
|
||||
for operation_path in (
|
||||
'record',
|
||||
'validate/record',
|
||||
'curated/record',
|
||||
'incoming/{label}/record',
|
||||
):
|
||||
delete_endpoint(
|
||||
collection_name=collection_name,
|
||||
active_classes=active_classes,
|
||||
operation_path=operation_path,
|
||||
app=instance_state.fastapi_app,
|
||||
)
|
||||
|
||||
|
||||
def delete_endpoint(
|
||||
collection_name: str,
|
||||
active_classes: set[str],
|
||||
operation_path: str,
|
||||
app: FastAPI,
|
||||
):
|
||||
remove_paths_set = {
|
||||
f'/{collection_name}/{operation_path}/{class_name}'
|
||||
for class_name in active_classes
|
||||
}
|
||||
|
||||
remove_indices = [
|
||||
index
|
||||
for index, api_route in enumerate(app.router.routes)
|
||||
if not isinstance(api_route, _IncludedRouter) # skip included router
|
||||
and api_route.path in remove_paths_set
|
||||
]
|
||||
for index in sorted(remove_indices, reverse=True):
|
||||
del app.router.routes[index]
|
||||
|
||||
|
||||
def store_record(
|
||||
collection: str,
|
||||
data: BaseModel | str,
|
||||
class_name: str,
|
||||
model: Any,
|
||||
input_format: Format,
|
||||
api_key: str | None = Depends(api_key_header_scheme),
|
||||
*,
|
||||
add_submission_tag: bool,
|
||||
) -> JSONResponse | PlainTextResponse:
|
||||
if input_format == Format.json and isinstance(data, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
|
||||
if input_format == Format.ttl and not isinstance(data, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
abstract_config = read_config(instance_state.store_path)
|
||||
check_collection(abstract_config, collection)
|
||||
|
||||
# Get the token permissions and extend them by the default permissions.
|
||||
# This call will also convert plaintext tokens into the hashed version of
|
||||
# the token, if the token is hashed. This is necessary because we do not
|
||||
# store the plaintext token, so all token-information is associated with
|
||||
# the hashed representation of the token.
|
||||
token_representation = (
|
||||
abstract_config.collections[collection].default_token
|
||||
if api_key is None
|
||||
else api_key
|
||||
)
|
||||
store, token_permissions, user_info = get_token_store(
|
||||
abstract_config,
|
||||
instance_state,
|
||||
collection,
|
||||
token_representation,
|
||||
is_token_name=api_key is None,
|
||||
)
|
||||
final_permissions = join_default_token_permissions(
|
||||
abstract_config,
|
||||
token_permissions,
|
||||
collection,
|
||||
)
|
||||
if not final_permissions.incoming_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f"Not authorized to submit to collection '{collection}'.",
|
||||
)
|
||||
|
||||
if input_format == Format.ttl:
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Conversion error',
|
||||
):
|
||||
json_object = FormatConverter(
|
||||
abstract_config.collections[collection].schema_location,
|
||||
input_format=Format.ttl,
|
||||
output_format=Format.json,
|
||||
).convert(data, class_name)
|
||||
with wrap_http_exception(
|
||||
ValidationError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Validation error',
|
||||
):
|
||||
record = TypeAdapter(getattr(model, class_name)).validate_python(
|
||||
json_object
|
||||
)
|
||||
else:
|
||||
record = data
|
||||
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Validation error',
|
||||
):
|
||||
instance_state.validators[collection].validate(record)
|
||||
|
||||
sorted_record = order_dict(record)
|
||||
with wrap_http_exception(CurieResolutionError):
|
||||
stored_records = store.store_object(
|
||||
obj=sorted_record,
|
||||
submitter=user_info[1] if add_submission_tag else None,
|
||||
)
|
||||
|
||||
if input_format == Format.ttl:
|
||||
format_converter = FormatConverter(
|
||||
abstract_config.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=Format.ttl,
|
||||
)
|
||||
with wrap_http_exception(ValueError, header='Conversion error'):
|
||||
return PlainTextResponse(
|
||||
combine_ttl(
|
||||
[
|
||||
format_converter.convert(
|
||||
record,
|
||||
class_name,
|
||||
)
|
||||
for class_name, record in stored_records
|
||||
]
|
||||
),
|
||||
media_type='text/turtle',
|
||||
)
|
||||
return JSONResponse([order_dict(record) for _, record in stored_records])
|
||||
|
||||
|
||||
def load_policy_info(
|
||||
abstract_configuration: Configuration,
|
||||
collection_name: str,
|
||||
|
|
|
|||
0
dump_things_service/endpoints/__init__.py
Normal file
0
dump_things_service/endpoints/__init__.py
Normal file
0
dump_things_service/endpoints/v0/__init__.py
Normal file
0
dump_things_service/endpoints/v0/__init__.py
Normal file
716
dump_things_service/endpoints/v0/base_endpoints.py
Normal file
716
dump_things_service/endpoints/v0/base_endpoints.py
Normal file
|
|
@ -0,0 +1,716 @@
|
|||
from __future__ import annotations # noqa: I001 -- the patches have to be imported early
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Annotated
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_200_OK,
|
||||
HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
)
|
||||
from dump_things_service.abstract_config import get_config
|
||||
from dump_things_service.collection import reload_policy
|
||||
from dump_things_service.instance_state import get_instance_state
|
||||
|
||||
# Perform the patching before importing any third-party libraries
|
||||
from dump_things_service.patches import enabled # noqa: F401 -- used by generated code
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
Response,
|
||||
)
|
||||
from fastapi_pagination import (
|
||||
Page,
|
||||
paginate,
|
||||
)
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
Field,
|
||||
)
|
||||
from starlette.responses import (
|
||||
JSONResponse,
|
||||
PlainTextResponse,
|
||||
RedirectResponse,
|
||||
)
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_403_FORBIDDEN,
|
||||
HTTP_404_NOT_FOUND,
|
||||
Format,
|
||||
)
|
||||
from dump_things_service import __version__
|
||||
from dump_things_service.abstract_config import (
|
||||
check_collection,
|
||||
)
|
||||
from dump_things_service.api_key import api_key_header_scheme
|
||||
from dump_things_service.converter import (
|
||||
FormatConverter,
|
||||
ConvertingList,
|
||||
)
|
||||
from dump_things_service.exceptions import (
|
||||
CurieResolutionError,
|
||||
ConfigError,
|
||||
)
|
||||
from dump_things_service.instance_state import InstanceState
|
||||
from dump_things_service.lazy_list import (
|
||||
PriorityList,
|
||||
ModifierList,
|
||||
)
|
||||
from dump_things_service.model import (
|
||||
get_subclasses,
|
||||
)
|
||||
from dump_things_service.utils import (
|
||||
authenticate_token,
|
||||
check_bounds,
|
||||
combine_ttl,
|
||||
get_token_store,
|
||||
join_default_token_permissions,
|
||||
order_dict,
|
||||
process_token,
|
||||
simple_process_token,
|
||||
wrap_http_exception,
|
||||
dict_to_base_model,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from dump_things_service.lazy_list import LazyList
|
||||
|
||||
|
||||
class MaintenanceRequest(BaseModel):
|
||||
collection: str
|
||||
active: bool
|
||||
|
||||
|
||||
class ServerCollectionResponse(BaseModel):
|
||||
name: str
|
||||
schema_location: str = Field(alias='schema')
|
||||
classes: list[str]
|
||||
|
||||
|
||||
class ServerCollectionCountedResponse(ServerCollectionResponse):
|
||||
records: int
|
||||
|
||||
|
||||
class ServerResponse(BaseModel):
|
||||
version: str
|
||||
collections: list[ServerCollectionResponse | ServerCollectionCountedResponse]
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
logger = logging.getLogger('dump_things_service')
|
||||
|
||||
|
||||
@router.get('/', response_class=RedirectResponse)
|
||||
async def root() -> RedirectResponse:
|
||||
return RedirectResponse('/docs')
|
||||
|
||||
|
||||
@router.get('/server', tags=['Server management'], name='get server information')
|
||||
async def server() -> ServerResponse:
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
return ServerResponse(
|
||||
version=__version__,
|
||||
collections=[
|
||||
ServerCollectionResponse(
|
||||
name=collection_name,
|
||||
schema=configuration.collections[collection_name].schema_location,
|
||||
classes=instance_state.schema_info[
|
||||
configuration.collections[collection_name].schema_location
|
||||
].classes,
|
||||
)
|
||||
for collection_name in configuration.collections
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/management/reload/policy_info/{collection:path}',
|
||||
tags=['Server management'],
|
||||
name='reload policy information from configured location ',
|
||||
)
|
||||
async def reload_configured_policy(
|
||||
collection: str,
|
||||
api_key: Annotated[str | None, Depends(api_key_header_scheme)],
|
||||
url: str | None = None,
|
||||
):
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
check_collection(configuration, collection)
|
||||
|
||||
final_permissions = await simple_process_token(
|
||||
configuration, instance_state, api_key, collection
|
||||
)
|
||||
|
||||
if not final_permissions.curated_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f'CURATOR token is required to reload policy information in collection {collection}.',
|
||||
)
|
||||
|
||||
if not url:
|
||||
url = configuration.collections[collection].policy_info_location
|
||||
|
||||
if not url:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f"No policy_info_location configured for collection '{collection}' and no URL provided.",
|
||||
)
|
||||
|
||||
with wrap_http_exception(ConfigError):
|
||||
reload_policy(
|
||||
abstract_configuration=configuration,
|
||||
instance_state=instance_state,
|
||||
collection_name=collection,
|
||||
override_policy_info_location=url,
|
||||
)
|
||||
return Response(status_code=HTTP_200_OK)
|
||||
|
||||
|
||||
@router.post(
|
||||
'/maintenance',
|
||||
tags=['Server management'],
|
||||
name='put a collection in maintenance mode',
|
||||
)
|
||||
async def maintenance(
|
||||
body: MaintenanceRequest,
|
||||
api_key: Annotated[str | None, Depends(api_key_header_scheme)],
|
||||
):
|
||||
if api_key is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='Token required for this operation',
|
||||
)
|
||||
|
||||
collection = body.collection
|
||||
active = body.active
|
||||
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
# Try to authenticate the token with the authentication providers that
|
||||
# are associated with the collection.
|
||||
check_collection(configuration, collection)
|
||||
auth_info = authenticate_token(instance_state, collection, api_key)
|
||||
permissions = auth_info.token_permission
|
||||
|
||||
if not (
|
||||
permissions.curated_write
|
||||
and permissions.curated_read
|
||||
and permissions.zones_access
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='Curator permissions required for this operation',
|
||||
)
|
||||
|
||||
if active:
|
||||
instance_state.maintenance_mode.add(collection)
|
||||
else:
|
||||
instance_state.maintenance_mode.remove(collection)
|
||||
|
||||
|
||||
@router.post(
|
||||
'/{collection:path}/record/{class_name}',
|
||||
tags=['Store records'],
|
||||
name='Write record of class {class_name} to collection {collection}',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {
|
||||
'application/json': {'schema': {'type': 'object'}},
|
||||
'text/turtle': {'schema': {'type': 'string'}},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
async def store_record(
|
||||
body: dict | str,
|
||||
collection: str,
|
||||
class_name: str,
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
add_submission_tag: bool = False,
|
||||
format: Format = Format.json,
|
||||
):
|
||||
logger.info(
|
||||
'store_record(%s, %s, %s, %s, %s, %s)',
|
||||
type(body),
|
||||
repr(body),
|
||||
repr(collection),
|
||||
repr(class_name),
|
||||
repr(add_submission_tag),
|
||||
repr(format),
|
||||
)
|
||||
|
||||
configuration = get_config()
|
||||
|
||||
if format == Format.json and isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
|
||||
if format == Format.ttl and not isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
check_collection(configuration, collection)
|
||||
|
||||
# Get the token permissions and extend them by the default permissions.
|
||||
# This call will also convert plaintext tokens into the hashed version of
|
||||
# the token, if the token is hashed. This is necessary because we do not
|
||||
# store the plaintext token, so all token-information is associated with
|
||||
# the hashed representation of the token.
|
||||
token_representation = (
|
||||
configuration.collections[collection].default_token
|
||||
if api_key is None
|
||||
else api_key
|
||||
)
|
||||
store, token_permissions, user_id = get_token_store(
|
||||
configuration,
|
||||
instance_state,
|
||||
collection,
|
||||
token_representation,
|
||||
is_token_name=api_key is None,
|
||||
)
|
||||
final_permissions = join_default_token_permissions(
|
||||
configuration,
|
||||
token_permissions,
|
||||
collection,
|
||||
)
|
||||
if not final_permissions.incoming_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f"Not authorized to submit to collection '{collection}'.",
|
||||
)
|
||||
|
||||
if class_name not in instance_state.collections[collection].active_classes:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"No class named '{class_name}' found in collection '{collection}'.",
|
||||
)
|
||||
|
||||
if format == Format.ttl:
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Conversion error',
|
||||
):
|
||||
json_object = FormatConverter(
|
||||
configuration.collections[collection].schema_location,
|
||||
input_format=Format.ttl,
|
||||
output_format=Format.json,
|
||||
).convert(body, class_name)
|
||||
else:
|
||||
json_object = body
|
||||
|
||||
record = dict_to_base_model(json_object, class_name, collection)
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Validation error',
|
||||
):
|
||||
instance_state.validators[collection].validate(record)
|
||||
|
||||
with wrap_http_exception(CurieResolutionError):
|
||||
stored_records = store.store_object(
|
||||
obj=record,
|
||||
submitter=user_id if add_submission_tag else None,
|
||||
)
|
||||
|
||||
if format == Format.ttl:
|
||||
format_converter = FormatConverter(
|
||||
configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=Format.ttl,
|
||||
)
|
||||
with wrap_http_exception(ValueError, header='Conversion error'):
|
||||
return PlainTextResponse(
|
||||
combine_ttl(
|
||||
[
|
||||
format_converter.convert(
|
||||
record,
|
||||
class_name,
|
||||
)
|
||||
for class_name, record in stored_records
|
||||
]
|
||||
),
|
||||
media_type='text/turtle',
|
||||
)
|
||||
return JSONResponse([order_dict(record) for _, record in stored_records])
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection:path}/record',
|
||||
tags=['Read records'],
|
||||
name='Read the record with the given PID from the given collection',
|
||||
)
|
||||
async def read_record_with_pid(
|
||||
collection: str,
|
||||
pid: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
check_collection(configuration, collection)
|
||||
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
configuration, instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
instance_state, collection, user_info
|
||||
)
|
||||
|
||||
class_name, json_object = None, None
|
||||
if final_permissions.incoming_read:
|
||||
with wrap_http_exception(CurieResolutionError, header='CURIE error:'):
|
||||
class_name, json_object = token_store.get_object_by_pid(
|
||||
pid,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
|
||||
if not json_object and final_permissions.curated_read:
|
||||
with wrap_http_exception(CurieResolutionError, header='CURIE error:'):
|
||||
class_name, json_object = instance_state.curated_stores[
|
||||
collection
|
||||
].get_object_by_pid(
|
||||
pid,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
|
||||
if not json_object:
|
||||
return None
|
||||
|
||||
if format == Format.ttl:
|
||||
converter = FormatConverter(
|
||||
schema=configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
)
|
||||
with wrap_http_exception(ValueError, header='Conversion error'):
|
||||
ttl_record = converter.convert(json_object, class_name)
|
||||
return PlainTextResponse(ttl_record, media_type='text/turtle')
|
||||
return json_object
|
||||
|
||||
|
||||
def _get_policy_information(
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
user_info: tuple[str, str],
|
||||
) -> tuple[str | None, str | None, set[str] | None]:
|
||||
from itertools import chain
|
||||
|
||||
collection_state = instance_state.collections[collection_name]
|
||||
policy_mapping = collection_state.policy_mapping
|
||||
if not policy_mapping:
|
||||
return None, None, None
|
||||
|
||||
policies = set(
|
||||
chain(
|
||||
*[
|
||||
policy_mapping.authorized_by
|
||||
for policy_mapping in policy_mapping
|
||||
if (policy_mapping.auth_source, policy_mapping.user_id) == user_info
|
||||
]
|
||||
)
|
||||
)
|
||||
return (
|
||||
collection_state.policy_annotation_tag,
|
||||
collection_state.default_policy,
|
||||
policies,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection:path}/records/',
|
||||
tags=['Read records'],
|
||||
name='Read all records from the given collection',
|
||||
)
|
||||
async def read_all_records(
|
||||
collection: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
return await _read_all_records(
|
||||
collection=collection,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
# Set an upper limit for the number of non-paginated result records to
|
||||
# keep processing time for individual requests short and avoid
|
||||
# overloading the server.
|
||||
bound=1000,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection:path}/records/p/',
|
||||
tags=['Read records'],
|
||||
name='Read all records from the given collection with pagination',
|
||||
)
|
||||
async def read_all_records_paginated(
|
||||
collection: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
) -> Page[dict | str]:
|
||||
result_list = await _read_all_records(
|
||||
collection=collection,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
bound=None,
|
||||
)
|
||||
return paginate(result_list)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection:path}/records/{class_name}',
|
||||
tags=['Read records'],
|
||||
name='Read records of the given class (or subclass) from the given collection',
|
||||
)
|
||||
async def read_records_of_type(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
return await _read_records_of_type(
|
||||
collection=collection,
|
||||
class_name=class_name,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
# Set an upper limit for the number of non-paginated result records to
|
||||
# keep processing time for individual requests short and avoid
|
||||
# overloading the server.
|
||||
bound=1000,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection:path}/records/p/{class_name}',
|
||||
tags=['Read records'],
|
||||
name='Read records of the given class (or subclass) from the given collection with pagination',
|
||||
)
|
||||
async def read_records_of_type_paginated(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
) -> Page[dict | str]:
|
||||
result_list = await _read_records_of_type(
|
||||
collection=collection,
|
||||
class_name=class_name,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
bound=None,
|
||||
)
|
||||
return paginate(result_list)
|
||||
|
||||
|
||||
async def _read_all_records(
|
||||
collection: str,
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
bound: int | None = None,
|
||||
) -> LazyList:
|
||||
def convert_to_http_exception(e: BaseException):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f'Conversion error: {e}',
|
||||
) from e
|
||||
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
check_collection(configuration, collection)
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
configuration, instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
if final_permissions.incoming_read:
|
||||
token_store_list = token_store.get_all_objects(
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(len(token_store_list), bound, collection, 'records/p/')
|
||||
result_list.add_list(token_store_list)
|
||||
|
||||
if final_permissions.curated_read:
|
||||
curated_store_list = instance_state.curated_stores[collection].get_all_objects(
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(len(curated_store_list), bound, collection, 'records/p/')
|
||||
result_list.add_list(curated_store_list)
|
||||
|
||||
# Sort the result list.
|
||||
result_list.sort(key=result_list.sort_key)
|
||||
|
||||
if format == Format.ttl:
|
||||
result_list = ConvertingList(
|
||||
result_list,
|
||||
configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
exception_handler=convert_to_http_exception,
|
||||
)
|
||||
else:
|
||||
result_list = ModifierList(
|
||||
result_list,
|
||||
lambda record_info: record_info.json_object,
|
||||
)
|
||||
return result_list
|
||||
|
||||
|
||||
async def _read_records_of_type(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
bound: int | None = None,
|
||||
) -> LazyList:
|
||||
def convert_to_http_exception(e: BaseException):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f'Conversion error: {e}',
|
||||
) from e
|
||||
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
check_collection(configuration, collection)
|
||||
schema_location = configuration.collections[collection].schema_location
|
||||
model = instance_state.schema_info[schema_location].pydantic_module_info.module
|
||||
if class_name not in instance_state.collections[collection].active_classes:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"No '{class_name}'-class in collection '{collection}'.",
|
||||
)
|
||||
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
configuration, instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
if final_permissions.incoming_read:
|
||||
for search_class_name in get_subclasses(model, class_name):
|
||||
token_store_list = token_store.get_objects_of_class(
|
||||
class_name=search_class_name,
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(
|
||||
len(token_store_list), bound, collection, f'/records/p/{class_name}'
|
||||
)
|
||||
result_list.add_list(token_store_list)
|
||||
|
||||
if final_permissions.curated_read:
|
||||
for search_class_name in get_subclasses(model, class_name):
|
||||
curated_store_list = instance_state.curated_stores[
|
||||
collection
|
||||
].get_objects_of_class(
|
||||
class_name=search_class_name,
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(
|
||||
len(curated_store_list),
|
||||
bound,
|
||||
collection,
|
||||
f'/records/p/{class_name}',
|
||||
)
|
||||
result_list.add_list(curated_store_list)
|
||||
|
||||
# Sort the result list.
|
||||
result_list.sort(key=result_list.sort_key)
|
||||
|
||||
if format == Format.ttl:
|
||||
result_list = ConvertingList(
|
||||
result_list,
|
||||
schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
exception_handler=convert_to_http_exception,
|
||||
)
|
||||
else:
|
||||
result_list = ModifierList(
|
||||
result_list,
|
||||
lambda record_info: record_info.json_object,
|
||||
)
|
||||
return result_list
|
||||
|
||||
|
||||
@router.delete(
|
||||
'/{collection:path}/record',
|
||||
tags=['Delete records'],
|
||||
name='Delete record with the given pid from the given collection',
|
||||
)
|
||||
async def delete_record(
|
||||
collection: str,
|
||||
pid: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
):
|
||||
configuration = get_config()
|
||||
instance_state = get_instance_state()
|
||||
|
||||
check_collection(configuration, collection)
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
configuration, instance_state, api_key, collection
|
||||
)
|
||||
|
||||
if not final_permissions.incoming_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f"No write access to incoming data in collection '{collection}'.",
|
||||
)
|
||||
with wrap_http_exception(Exception):
|
||||
result = token_store.delete_object(pid)
|
||||
if not result:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"Could not remove record with PID '{pid}' from the "
|
||||
'token associated incoming area of collection '
|
||||
f"'{collection}'.",
|
||||
)
|
||||
return True
|
||||
|
|
@ -4,7 +4,7 @@ from pathlib import (
|
|||
PurePosixPath,
|
||||
)
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
|
|
@ -75,7 +75,7 @@ async def create_collection(
|
|||
):
|
||||
with wrap_http_exception(DumpThingsError):
|
||||
await create_or_replace_collection(body, api_key, allow_replace=False)
|
||||
response.headers['Location'] = f'/collections/{quote(body.name)}'
|
||||
response.headers['Location'] = f'/collections/{quote_plus(body.name)}'
|
||||
|
||||
|
||||
@router.put(
|
||||
|
|
@ -91,7 +91,7 @@ async def replace_collection(
|
|||
):
|
||||
with wrap_http_exception(DumpThingsError):
|
||||
await create_or_replace_collection(body, api_key, allow_replace=True)
|
||||
response.headers['Location'] = f'/collections/{quote(body.name)}'
|
||||
response.headers['Location'] = f'/collections/{quote_plus(body.name)}'
|
||||
|
||||
|
||||
async def create_or_replace_collection(
|
||||
|
|
@ -189,7 +189,7 @@ async def get_collections(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/collections/{collection_name}',
|
||||
'/collections/{collection_name:path}',
|
||||
tags=['Administration interface'],
|
||||
name='Get existing collection by name',
|
||||
)
|
||||
|
|
@ -212,7 +212,7 @@ async def get_collection_with_name(
|
|||
|
||||
|
||||
@router.delete(
|
||||
'/collections/{collection_name}',
|
||||
'/collections/{collection_name:path}',
|
||||
tags=['Administration interface'],
|
||||
name='Delete collection with name',
|
||||
)
|
||||
|
|
@ -38,11 +38,10 @@ from dump_things_service.utils import (
|
|||
cleaned_json,
|
||||
order_dict,
|
||||
wrap_http_exception,
|
||||
dict_to_base_model,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pydantic import BaseModel
|
||||
|
||||
from dump_things_service.auth import AuthenticationInfo
|
||||
from dump_things_service.backends import StorageBackend
|
||||
from dump_things_service.lazy_list import LazyList
|
||||
|
|
@ -77,7 +76,7 @@ add_pagination(router)
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/curated/records/{class_name}',
|
||||
'/{collection:path}/curated/records/{class_name}',
|
||||
tags=['Curated area: read records'],
|
||||
name='Read all records of the given class from the curated area',
|
||||
)
|
||||
|
|
@ -106,7 +105,7 @@ async def read_curated_records_of_type(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/curated/records/p/{class_name}',
|
||||
'/{collection:path}/curated/records/p/{class_name}',
|
||||
tags=['Curated area: read records'],
|
||||
name='Read all records of the given class from the curated area with pagination',
|
||||
)
|
||||
|
|
@ -135,7 +134,7 @@ async def read_curated_records_of_type_paginated(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/curated/records/',
|
||||
'/{collection:path}/curated/records/',
|
||||
tags=['Curated area: read records'],
|
||||
name='Read all records from the curated area',
|
||||
)
|
||||
|
|
@ -155,7 +154,7 @@ async def read_curated_all_records(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/curated/records/p/',
|
||||
'/{collection:path}/curated/records/p/',
|
||||
tags=['Curated area: read records'],
|
||||
name='Read all records from the curated area with pagination',
|
||||
)
|
||||
|
|
@ -176,7 +175,7 @@ async def read_curated_all_records_paginated(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/curated/record',
|
||||
'/{collection:path}/curated/record',
|
||||
tags=['Curated area: read records'],
|
||||
name='Read the record with the given pid from the curated area',
|
||||
)
|
||||
|
|
@ -194,7 +193,7 @@ async def read_curated_record_with_pid(
|
|||
|
||||
|
||||
@router.delete(
|
||||
'/{collection}/curated/record',
|
||||
'/{collection:path}/curated/record',
|
||||
tags=['Curated area: delete records'],
|
||||
name='Delete the record with the given pid from the curated area of the given collection',
|
||||
)
|
||||
|
|
@ -302,14 +301,40 @@ def _get_store_and_backend(
|
|||
return model_store, backend, auth_info
|
||||
|
||||
|
||||
@router.post(
|
||||
'/{collection:path}/curated/record/{class_name}',
|
||||
tags=['Store record in curated area'],
|
||||
name='Curated area: store record of class {class_name} in curated area of collection {collection}',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {
|
||||
'application/json': {'schema': {'type': 'object'}},
|
||||
'text/turtle': {'schema': {'type': 'string'}},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
def store_curated_record(
|
||||
body: dict | str,
|
||||
collection: str,
|
||||
data: BaseModel,
|
||||
class_name: str,
|
||||
author_id: str | None,
|
||||
api_key: str | None,
|
||||
author_id: str | None = None,
|
||||
api_key: str | None = Depends(api_key_header_scheme),
|
||||
):
|
||||
logger.info(
|
||||
'store_curated_record(%s, %s, %s, %s, *)',
|
||||
repr(body),
|
||||
collection,
|
||||
class_name,
|
||||
repr(author_id),
|
||||
)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
data = dict_to_base_model(body, class_name, collection)
|
||||
|
||||
# Ensure convertibility to TTL, this will validate additional schema
|
||||
# constraints, e.g., prefixes.
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Annotated
|
||||
|
||||
from fastapi import (
|
||||
|
|
@ -42,22 +43,23 @@ from dump_things_service.utils import (
|
|||
get_on_disk_labels,
|
||||
order_dict,
|
||||
wrap_http_exception,
|
||||
dict_to_base_model,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pydantic import BaseModel
|
||||
|
||||
from dump_things_service.backends import StorageBackend
|
||||
from dump_things_service.lazy_list import LazyList
|
||||
from dump_things_service.store.model_store import _ModelStore
|
||||
|
||||
|
||||
logger = logging.getLogger('dump_things_service')
|
||||
|
||||
router = APIRouter()
|
||||
add_pagination(router)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/',
|
||||
'/{collection:path}/incoming/',
|
||||
tags=['Incoming area: read labels'],
|
||||
name='Get all incoming labels for the given collection',
|
||||
)
|
||||
|
|
@ -77,7 +79,7 @@ async def incoming_read_labels(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/{label}/records/{class_name}',
|
||||
'/{collection:path}/incoming/{label}/records/{class_name}',
|
||||
tags=['Incoming area: read records'],
|
||||
name='Read all records of the given class from the given incoming area',
|
||||
)
|
||||
|
|
@ -103,7 +105,7 @@ async def incoming_read_records_of_type(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/{label}/records/p/{class_name}',
|
||||
'/{collection:path}/incoming/{label}/records/p/{class_name}',
|
||||
tags=['Incoming area: read records'],
|
||||
name='Read all records of the given class from the given incoming area with pagination',
|
||||
)
|
||||
|
|
@ -143,7 +145,7 @@ def _check_collection_and_class(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/{label}/records/',
|
||||
'/{collection:path}/incoming/{label}/records/',
|
||||
tags=['Incoming area: read records'],
|
||||
name='Read all records from the given incoming area',
|
||||
)
|
||||
|
|
@ -165,7 +167,7 @@ async def incoming_read_all_records(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/{label}/records/p/',
|
||||
'/{collection:path}/incoming/{label}/records/p/',
|
||||
tags=['Incoming area: read records'],
|
||||
name='Read all records from the given incoming area with pagination',
|
||||
)
|
||||
|
|
@ -188,7 +190,7 @@ async def incoming_read_all_records_paginated(
|
|||
|
||||
|
||||
@router.get(
|
||||
'/{collection}/incoming/{label}/record',
|
||||
'/{collection:path}/incoming/{label}/record',
|
||||
tags=['Incoming area: read records'],
|
||||
name='Read the record with the given PID from the given incoming area',
|
||||
)
|
||||
|
|
@ -208,7 +210,7 @@ async def incoming_read_record_with_pid(
|
|||
|
||||
|
||||
@router.delete(
|
||||
'/{collection}/incoming/{label}/record',
|
||||
'/{collection:path}/incoming/{label}/record',
|
||||
tags=['Incoming area: delete records'],
|
||||
name='Delete the record with the given PID from the given incoming area',
|
||||
)
|
||||
|
|
@ -357,13 +359,37 @@ async def authorize_zones(
|
|||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
'/{collection:path}/incoming/{label}/record/{class_name}',
|
||||
tags=['Store record in an incoming area'],
|
||||
name='Incoming area: store a record of class {class_name} in incoming area {label} of collection {collection_name}',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {
|
||||
'application/json': {'schema': {'type': 'object'}},
|
||||
'text/turtle': {'schema': {'type': 'string'}},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
async def store_incoming_record(
|
||||
body: dict | str,
|
||||
collection: str,
|
||||
label: str,
|
||||
data: BaseModel,
|
||||
class_name: str,
|
||||
api_key: str | None,
|
||||
api_key: str | None = Depends(api_key_header_scheme),
|
||||
):
|
||||
logger.info(
|
||||
'store_incoming_record(%s, %s, %s, %s, *)',
|
||||
repr(body),
|
||||
collection,
|
||||
label,
|
||||
class_name,
|
||||
)
|
||||
|
||||
data = dict_to_base_model(body, class_name, collection)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
|
|
@ -2,7 +2,7 @@ import logging
|
|||
import re
|
||||
import secrets
|
||||
from typing import Annotated
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
|
|
@ -75,7 +75,7 @@ async def create_token(
|
|||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
) -> TokenRequest:
|
||||
token_request = create_or_replace_token(body, api_key, allow_replace=False)
|
||||
response.headers['Location'] = f'/tokens/{quote(body.name)}'
|
||||
response.headers['Location'] = f'/tokens/{quote_plus(body.name)}'
|
||||
return token_request
|
||||
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ async def replace_token(
|
|||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
) -> TokenRequest:
|
||||
token_request = create_or_replace_token(body, api_key, allow_replace=True)
|
||||
response.headers['Location'] = f'/tokens/{quote(body.name)}'
|
||||
response.headers['Location'] = f'/tokens/{quote_plus(body.name)}'
|
||||
return token_request
|
||||
|
||||
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
from typing import Any
|
||||
import logging
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
)
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
TypeAdapter,
|
||||
ValidationError,
|
||||
)
|
||||
|
|
@ -25,30 +25,57 @@ from dump_things_service.abstract_config import (
|
|||
from dump_things_service.api_key import api_key_header_scheme
|
||||
from dump_things_service.converter import FormatConverter
|
||||
from dump_things_service.instance_state import get_instance_state
|
||||
from dump_things_service.model import get_model_for_schema
|
||||
from dump_things_service.utils import (
|
||||
dict_to_base_model,
|
||||
get_token_store,
|
||||
join_default_token_permissions,
|
||||
wrap_http_exception,
|
||||
)
|
||||
|
||||
logger = logging.getLogger('dump_things_service')
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post(
|
||||
'/{collection:path}/validate/record/{class_name}',
|
||||
tags=['Validate records'],
|
||||
name='Validate record of class {class_name} for collection {collection}',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {
|
||||
'application/json': {'schema': {'type': 'object'}},
|
||||
'text/turtle': {'schema': {'type': 'string'}},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
def validate_record(
|
||||
body: dict | str,
|
||||
collection: str,
|
||||
data: BaseModel | str,
|
||||
class_name: str,
|
||||
model: Any,
|
||||
input_format: Format,
|
||||
format: Format = Format.json,
|
||||
api_key: str | None = Depends(api_key_header_scheme),
|
||||
) -> JSONResponse:
|
||||
logger.info(
|
||||
'validate_record(%s, %s, %s, %s, *)',
|
||||
repr(body),
|
||||
collection,
|
||||
repr(class_name),
|
||||
repr(format),
|
||||
)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
abstract_config = get_config()
|
||||
|
||||
if input_format == Format.json and isinstance(data, str):
|
||||
if format == Format.json and isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
|
||||
if input_format == Format.ttl and not isinstance(data, str):
|
||||
if format == Format.ttl and not isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
|
|
@ -78,7 +105,7 @@ def validate_record(
|
|||
detail=f"Not authorized to validate records for collection '{collection}'.",
|
||||
)
|
||||
|
||||
if input_format == Format.ttl:
|
||||
if format == Format.ttl:
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
|
|
@ -88,7 +115,12 @@ def validate_record(
|
|||
abstract_config.collections[collection].schema_location,
|
||||
input_format=Format.ttl,
|
||||
output_format=Format.json,
|
||||
).convert(data, class_name)
|
||||
).convert(body, class_name)
|
||||
|
||||
model = get_model_for_schema(
|
||||
abstract_config.collections[collection].schema_location
|
||||
)[0]
|
||||
|
||||
with wrap_http_exception(
|
||||
ValidationError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
|
|
@ -103,6 +135,7 @@ def validate_record(
|
|||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
header='Validation error',
|
||||
):
|
||||
instance_state.validators[collection].validate(data)
|
||||
pydantic_object = dict_to_base_model(body, class_name, collection)
|
||||
instance_state.validators[collection].validate(pydantic_object)
|
||||
|
||||
return JSONResponse(True)
|
||||
|
|
@ -5,12 +5,8 @@ import logging
|
|||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Annotated
|
||||
|
||||
from starlette.status import HTTP_200_OK
|
||||
|
||||
from dump_things_service.abstract_config import store_config
|
||||
from dump_things_service.collection import reload_policy
|
||||
from dump_things_service.commands.upload_config import convert_config_1_to_config_2
|
||||
from dump_things_service.manifest import manifest_configuration
|
||||
|
||||
|
|
@ -19,92 +15,31 @@ from dump_things_service.patches import enabled # noqa: F401 -- used by generat
|
|||
|
||||
import yaml
|
||||
import uvicorn
|
||||
from fastapi import (
|
||||
Depends,
|
||||
FastAPI,
|
||||
HTTPException,
|
||||
Response,
|
||||
)
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi_pagination import (
|
||||
Page,
|
||||
add_pagination,
|
||||
paginate,
|
||||
)
|
||||
from fastapi_pagination import add_pagination
|
||||
from fastapi_pagination.utils import disable_installed_extensions_check
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
Field,
|
||||
)
|
||||
from starlette.responses import (
|
||||
PlainTextResponse,
|
||||
RedirectResponse,
|
||||
)
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_403_FORBIDDEN,
|
||||
HTTP_404_NOT_FOUND,
|
||||
Format,
|
||||
)
|
||||
from dump_things_service import __version__
|
||||
from dump_things_service.abstract_config import (
|
||||
Configuration,
|
||||
check_collection,
|
||||
hash_token_representation,
|
||||
read_config,
|
||||
CONFIG_VERSION_1_ID,
|
||||
CONFIG_VERSION_2_ID,
|
||||
)
|
||||
from dump_things_service.api_key import api_key_header_scheme
|
||||
from dump_things_service.converter import (
|
||||
FormatConverter,
|
||||
ConvertingList,
|
||||
from dump_things_service.endpoints.v0.base_endpoints import router as base_router
|
||||
from dump_things_service.endpoints.v0.curated import router as curated_router
|
||||
from dump_things_service.endpoints.v0.incoming import router as incoming_router
|
||||
from dump_things_service.endpoints.v0.collection_endpoints import (
|
||||
router as collection_router,
|
||||
)
|
||||
from dump_things_service.curated import router as curated_router
|
||||
from dump_things_service.exceptions import CurieResolutionError, ConfigError
|
||||
from dump_things_service.incoming import router as incoming_router
|
||||
from dump_things_service.instance_state import create_instance_state, InstanceState
|
||||
from dump_things_service.lazy_list import (
|
||||
PriorityList,
|
||||
ModifierList,
|
||||
)
|
||||
from dump_things_service.model import get_subclasses
|
||||
from dump_things_service.collection_endpoints import router as collection_router
|
||||
from dump_things_service.token_endpoints import (
|
||||
from dump_things_service.endpoints.v0.token_endpoints import (
|
||||
hash_matcher,
|
||||
router as token_router,
|
||||
)
|
||||
from dump_things_service.utils import (
|
||||
authenticate_token,
|
||||
check_bounds,
|
||||
process_token,
|
||||
simple_process_token,
|
||||
wrap_http_exception,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from dump_things_service.lazy_list import LazyList
|
||||
|
||||
|
||||
class MaintenanceRequest(BaseModel):
|
||||
collection: str
|
||||
active: bool
|
||||
|
||||
|
||||
class ServerCollectionResponse(BaseModel):
|
||||
name: str
|
||||
schema_location: str = Field(alias='schema')
|
||||
classes: list[str]
|
||||
|
||||
|
||||
class ServerCollectionCountedResponse(ServerCollectionResponse):
|
||||
records: int
|
||||
|
||||
|
||||
class ServerResponse(BaseModel):
|
||||
version: str
|
||||
collections: list[ServerCollectionResponse | ServerCollectionCountedResponse]
|
||||
from dump_things_service.endpoints.v0.validate import router as validate_router
|
||||
from dump_things_service.instance_state import create_instance_state, InstanceState
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
|
|
@ -208,6 +143,12 @@ if not isinstance(numeric_level, int):
|
|||
)
|
||||
else:
|
||||
logger.setLevel(level=numeric_level)
|
||||
logger.propagate = False
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(numeric_level)
|
||||
formatter = logging.Formatter('%(levelname)s:dump_things_service:%(message)s')
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
store_path = Path(arguments.store).resolve()
|
||||
if not store_path.exists():
|
||||
|
|
@ -226,8 +167,11 @@ app = FastAPI(
|
|||
|
||||
app.include_router(curated_router)
|
||||
app.include_router(incoming_router)
|
||||
|
||||
app.include_router(validate_router)
|
||||
app.include_router(token_router)
|
||||
app.include_router(collection_router)
|
||||
app.include_router(base_router)
|
||||
|
||||
# Add CORS origins
|
||||
app.add_middleware(
|
||||
|
|
@ -340,484 +284,6 @@ g_instance_state.fastapi_app.setup()
|
|||
add_pagination(g_instance_state.fastapi_app)
|
||||
|
||||
|
||||
@app.get('/', response_class=RedirectResponse)
|
||||
async def root() -> RedirectResponse:
|
||||
return RedirectResponse('/docs')
|
||||
|
||||
|
||||
@app.get('/server', tags=['Server management'], name='get server information')
|
||||
async def server() -> ServerResponse:
|
||||
return ServerResponse(
|
||||
version=__version__,
|
||||
collections=[
|
||||
ServerCollectionResponse(
|
||||
name=collection_name,
|
||||
schema=g_configuration.collections[collection_name].schema_location,
|
||||
classes=g_instance_state.schema_info[
|
||||
g_configuration.collections[collection_name].schema_location
|
||||
].classes,
|
||||
)
|
||||
for collection_name in g_configuration.collections
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/management/reload/policy_info/{collection}',
|
||||
tags=['Server management'],
|
||||
name='reload policy information from configured location ',
|
||||
)
|
||||
async def reload_configured_policy(
|
||||
collection: str,
|
||||
api_key: Annotated[str | None, Depends(api_key_header_scheme)],
|
||||
url: str | None = None,
|
||||
):
|
||||
check_collection(g_configuration, collection)
|
||||
|
||||
final_permissions = await simple_process_token(
|
||||
g_configuration, g_instance_state, api_key, collection
|
||||
)
|
||||
|
||||
if not final_permissions.curated_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f'CURATOR token is required to reload policy information in collection {collection}.',
|
||||
)
|
||||
|
||||
if not url:
|
||||
url = g_configuration.collections[collection].policy_info_location
|
||||
|
||||
if not url:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f"No policy_info_location configured for collection '{collection}' and no URL provided.",
|
||||
)
|
||||
|
||||
with wrap_http_exception(ConfigError):
|
||||
reload_policy(
|
||||
abstract_configuration=g_configuration,
|
||||
instance_state=g_instance_state,
|
||||
collection_name=collection,
|
||||
override_policy_info_location=url,
|
||||
)
|
||||
return Response(status_code=HTTP_200_OK)
|
||||
|
||||
|
||||
@app.post(
|
||||
'/maintenance',
|
||||
tags=['Server management'],
|
||||
name='put a collection in maintenance mode',
|
||||
)
|
||||
async def maintenance(
|
||||
body: MaintenanceRequest,
|
||||
api_key: Annotated[str | None, Depends(api_key_header_scheme)],
|
||||
):
|
||||
if api_key is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='Token required for this operation',
|
||||
)
|
||||
|
||||
collection = body.collection
|
||||
active = body.active
|
||||
|
||||
# Try to authenticate the token with the authentication providers that
|
||||
# are associated with the collection.
|
||||
check_collection(g_configuration, collection)
|
||||
auth_info = authenticate_token(g_instance_state, collection, api_key)
|
||||
permissions = auth_info.token_permission
|
||||
|
||||
if not (
|
||||
permissions.curated_write
|
||||
and permissions.curated_read
|
||||
and permissions.zones_access
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='Curator permissions required for this operation',
|
||||
)
|
||||
|
||||
if active:
|
||||
g_instance_state.maintenance_mode.add(collection)
|
||||
else:
|
||||
g_instance_state.maintenance_mode.remove(collection)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/{collection}/record',
|
||||
tags=['Read records'],
|
||||
name='Read the record with the given PID from the given collection',
|
||||
)
|
||||
async def read_record_with_pid(
|
||||
collection: str,
|
||||
pid: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
check_collection(g_configuration, collection)
|
||||
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
g_configuration, g_instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
class_name, json_object = None, None
|
||||
if final_permissions.incoming_read:
|
||||
with wrap_http_exception(CurieResolutionError, header='CURIE error:'):
|
||||
class_name, json_object = token_store.get_object_by_pid(
|
||||
pid,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
|
||||
if not json_object and final_permissions.curated_read:
|
||||
with wrap_http_exception(CurieResolutionError, header='CURIE error:'):
|
||||
class_name, json_object = g_instance_state.curated_stores[
|
||||
collection
|
||||
].get_object_by_pid(
|
||||
pid,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
|
||||
if not json_object:
|
||||
return None
|
||||
|
||||
if format == Format.ttl:
|
||||
converter = FormatConverter(
|
||||
schema=g_configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
)
|
||||
with wrap_http_exception(ValueError, header='Conversion error'):
|
||||
ttl_record = converter.convert(json_object, class_name)
|
||||
return PlainTextResponse(ttl_record, media_type='text/turtle')
|
||||
return json_object
|
||||
|
||||
|
||||
def _get_policy_information(
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
user_info: tuple[str, str],
|
||||
) -> tuple[str | None, str | None, set[str] | None]:
|
||||
from itertools import chain
|
||||
|
||||
collection_state = instance_state.collections[collection_name]
|
||||
policy_mapping = collection_state.policy_mapping
|
||||
if not policy_mapping:
|
||||
return None, None, None
|
||||
|
||||
policies = set(
|
||||
chain(
|
||||
*[
|
||||
policy_mapping.authorized_by
|
||||
for policy_mapping in policy_mapping
|
||||
if (policy_mapping.auth_source, policy_mapping.user_id) == user_info
|
||||
]
|
||||
)
|
||||
)
|
||||
return (
|
||||
collection_state.policy_annotation_tag,
|
||||
collection_state.default_policy,
|
||||
policies,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/{collection}/records/',
|
||||
tags=['Read records'],
|
||||
name='Read all records from the given collection',
|
||||
)
|
||||
async def read_all_records(
|
||||
collection: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
return await _read_all_records(
|
||||
collection=collection,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
# Set an upper limit for the number of non-paginated result records to
|
||||
# keep processing time for individual requests short and avoid
|
||||
# overloading the server.
|
||||
bound=1000,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/{collection}/records/p/',
|
||||
tags=['Read records'],
|
||||
name='Read all records from the given collection with pagination',
|
||||
)
|
||||
async def read_all_records_paginated(
|
||||
collection: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
) -> Page[dict | str]:
|
||||
result_list = await _read_all_records(
|
||||
collection=collection,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
bound=None,
|
||||
)
|
||||
return paginate(result_list)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/{collection}/records/{class_name}',
|
||||
tags=['Read records'],
|
||||
name='Read records of the given class (or subclass) from the given collection',
|
||||
)
|
||||
async def read_records_of_type(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
):
|
||||
return await _read_records_of_type(
|
||||
collection=collection,
|
||||
class_name=class_name,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
# Set an upper limit for the number of non-paginated result records to
|
||||
# keep processing time for individual requests short and avoid
|
||||
# overloading the server.
|
||||
bound=1000,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
'/{collection}/records/p/{class_name}',
|
||||
tags=['Read records'],
|
||||
name='Read records of the given class (or subclass) from the given collection with pagination',
|
||||
)
|
||||
async def read_records_of_type_paginated(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
) -> Page[dict | str]:
|
||||
result_list = await _read_records_of_type(
|
||||
collection=collection,
|
||||
class_name=class_name,
|
||||
matching=matching,
|
||||
format=format,
|
||||
api_key=api_key,
|
||||
bound=None,
|
||||
)
|
||||
return paginate(result_list)
|
||||
|
||||
|
||||
async def _read_all_records(
|
||||
collection: str,
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
bound: int | None = None,
|
||||
) -> LazyList:
|
||||
def convert_to_http_exception(e: BaseException):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f'Conversion error: {e}',
|
||||
) from e
|
||||
|
||||
check_collection(g_configuration, collection)
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
g_configuration, g_instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
if final_permissions.incoming_read:
|
||||
token_store_list = token_store.get_all_objects(
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(len(token_store_list), bound, collection, 'records/p/')
|
||||
result_list.add_list(token_store_list)
|
||||
|
||||
if final_permissions.curated_read:
|
||||
curated_store_list = g_instance_state.curated_stores[
|
||||
collection
|
||||
].get_all_objects(
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(len(curated_store_list), bound, collection, 'records/p/')
|
||||
result_list.add_list(curated_store_list)
|
||||
|
||||
# Sort the result list.
|
||||
result_list.sort(key=result_list.sort_key)
|
||||
|
||||
if format == Format.ttl:
|
||||
result_list = ConvertingList(
|
||||
result_list,
|
||||
g_configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
exception_handler=convert_to_http_exception,
|
||||
)
|
||||
else:
|
||||
result_list = ModifierList(
|
||||
result_list,
|
||||
lambda record_info: record_info.json_object,
|
||||
)
|
||||
return result_list
|
||||
|
||||
|
||||
async def _read_records_of_type(
|
||||
collection: str,
|
||||
class_name: str,
|
||||
matching: str | None = None,
|
||||
format: Format = Format.json, # noqa: A002
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
bound: int | None = None,
|
||||
) -> LazyList:
|
||||
def convert_to_http_exception(e: BaseException):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail=f'Conversion error: {e}',
|
||||
) from e
|
||||
|
||||
check_collection(g_configuration, collection)
|
||||
schema_location = g_configuration.collections[collection].schema_location
|
||||
model = g_instance_state.schema_info[schema_location].pydantic_module_info.module
|
||||
if class_name not in g_instance_state.collections[collection].active_classes:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"No '{class_name}'-class in collection '{collection}'.",
|
||||
)
|
||||
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
g_configuration, g_instance_state, api_key, collection
|
||||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
if final_permissions.incoming_read:
|
||||
for search_class_name in get_subclasses(model, class_name):
|
||||
token_store_list = token_store.get_objects_of_class(
|
||||
class_name=search_class_name,
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(
|
||||
len(token_store_list), bound, collection, f'/records/p/{class_name}'
|
||||
)
|
||||
result_list.add_list(token_store_list)
|
||||
|
||||
if final_permissions.curated_read:
|
||||
for search_class_name in get_subclasses(model, class_name):
|
||||
curated_store_list = g_instance_state.curated_stores[
|
||||
collection
|
||||
].get_objects_of_class(
|
||||
class_name=search_class_name,
|
||||
matching=matching,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
default_policy=default_policy,
|
||||
active_policies=policies,
|
||||
)
|
||||
if bound:
|
||||
check_bounds(
|
||||
len(curated_store_list),
|
||||
bound,
|
||||
collection,
|
||||
f'/records/p/{class_name}',
|
||||
)
|
||||
result_list.add_list(curated_store_list)
|
||||
|
||||
# Sort the result list.
|
||||
result_list.sort(key=result_list.sort_key)
|
||||
|
||||
if format == Format.ttl:
|
||||
result_list = ConvertingList(
|
||||
result_list,
|
||||
schema_location,
|
||||
input_format=Format.json,
|
||||
output_format=format,
|
||||
exception_handler=convert_to_http_exception,
|
||||
)
|
||||
else:
|
||||
result_list = ModifierList(
|
||||
result_list,
|
||||
lambda record_info: record_info.json_object,
|
||||
)
|
||||
return result_list
|
||||
|
||||
|
||||
@app.delete(
|
||||
'/{collection}/record',
|
||||
tags=['Delete records'],
|
||||
name='Delete record with the given pid from the given collection',
|
||||
)
|
||||
async def delete_record(
|
||||
collection: str,
|
||||
pid: str,
|
||||
api_key: Annotated[str, Depends(api_key_header_scheme)],
|
||||
):
|
||||
check_collection(g_configuration, collection)
|
||||
final_permissions, token_store, user_info = await process_token(
|
||||
g_configuration, g_instance_state, api_key, collection
|
||||
)
|
||||
|
||||
if not final_permissions.incoming_write:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_403_FORBIDDEN,
|
||||
detail=f"No write access to incoming data in collection '{collection}'.",
|
||||
)
|
||||
with wrap_http_exception(Exception):
|
||||
result = token_store.delete_object(pid)
|
||||
if not result:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"Could not remove record with PID '{pid}' from the "
|
||||
'token associated incoming area of collection '
|
||||
f"'{collection}'.",
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _get_user_policies(
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
authenticator_id: str,
|
||||
user_id: str,
|
||||
) -> set[str]:
|
||||
return set(
|
||||
instance_state.policy_mappings[collection_name].get(
|
||||
(authenticator_id, user_id),
|
||||
set(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
uvicorn.run(
|
||||
app,
|
||||
|
|
|
|||
|
|
@ -7,10 +7,7 @@ from dump_things_service.abstract_config import (
|
|||
Configuration,
|
||||
TokenConfig,
|
||||
)
|
||||
from dump_things_service.collection import (
|
||||
create_collection,
|
||||
delete_endpoints_for_collection,
|
||||
)
|
||||
from dump_things_service.collection import create_collection
|
||||
from dump_things_service.instance_state import InstanceState
|
||||
|
||||
logger = logging.getLogger('dump_things_service')
|
||||
|
|
@ -31,7 +28,7 @@ openapi_tags_template: list[dict | str] = [
|
|||
'name': 'Read records',
|
||||
'description': 'Read records from the given collection',
|
||||
},
|
||||
'write',
|
||||
#'write',
|
||||
'validate',
|
||||
{
|
||||
'name': 'Delete records',
|
||||
|
|
@ -116,7 +113,6 @@ def manifest_configuration(
|
|||
# configuration (we do not delete the collection from token-objects here
|
||||
# because token-objects are all re-created below).
|
||||
for collection_name in deleted_collection_names:
|
||||
delete_endpoints_for_collection(instance_state, collection_name)
|
||||
delete_collection_from_instance_state(instance_state, collection_name)
|
||||
|
||||
# Create the internal representation objects for collections that have been
|
||||
|
|
@ -197,6 +193,7 @@ def create_openapi_tags(
|
|||
instance_state: InstanceState,
|
||||
openapi_tags_template_: list[dict | str],
|
||||
) -> list[dict]:
|
||||
return []
|
||||
# Collect tag name lists for all tag groups that we have defined.
|
||||
tag_group_info = {
|
||||
tag_group: sorted(
|
||||
|
|
|
|||
2
dump_things_service/tests/common.py
Normal file
2
dump_things_service/tests/common.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
def get_std_collection_names() -> list[str]:
|
||||
return [f'collection_{i}' for i in range(1, 9)] + ['collection/with/slash/0']
|
||||
|
|
@ -11,6 +11,7 @@ from fastapi.testclient import TestClient
|
|||
|
||||
from dump_things_service.abstract_config import (
|
||||
GitAuditBackendConfig,
|
||||
PolicyMapping,
|
||||
SQLiteBackendConfig,
|
||||
TagSpec,
|
||||
TokenCollectionConfig,
|
||||
|
|
@ -25,10 +26,12 @@ from dump_things_service.backends.sqlite import (
|
|||
from dump_things_service.backends.sqlite import (
|
||||
record_file_name as sqlite_db_filename,
|
||||
)
|
||||
from dump_things_service.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.token_endpoints import TokenRequest
|
||||
from dump_things_service.instance_state import get_mapping_function_by_name
|
||||
from dump_things_service.model import get_model_for_schema
|
||||
from dump_things_service.resolve_curie import resolve_curie
|
||||
from dump_things_service.tests.common import get_std_collection_names
|
||||
from dump_things_service.tests.create_store import (
|
||||
pid,
|
||||
pid_curated,
|
||||
|
|
@ -37,7 +40,6 @@ from dump_things_service.tests.create_store import (
|
|||
test_record_curated,
|
||||
test_record_trr,
|
||||
)
|
||||
from dump_things_service.token_endpoints import TokenRequest
|
||||
|
||||
# String representation of curated- and incoming-path
|
||||
curated = 'curated'
|
||||
|
|
@ -87,9 +89,30 @@ g_default_collections.append(
|
|||
submission_time_tag='no_default_time_tag',
|
||||
),
|
||||
policy_info_location=policy_info_file_location,
|
||||
policy_annotation_tag='abc:policy_set',
|
||||
default_policy='policy_1',
|
||||
policy_mapping=[
|
||||
PolicyMapping(
|
||||
auth_source='config',
|
||||
user_id='abc',
|
||||
authorized_by=[
|
||||
'test_user_8_policy_1',
|
||||
'test_user_8_default_policy',
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
g_default_collections.append(
|
||||
CollectionRequest(
|
||||
name='collection/with/slash/0',
|
||||
default_token='test_default_token',
|
||||
curated=PurePosixPath(f'{curated}/collection_with_slash_0'),
|
||||
schema=test_schema_location,
|
||||
incoming=PurePosixPath(f'{incoming}/collection_with_slash_0'),
|
||||
),
|
||||
)
|
||||
|
||||
g_default_collections.extend(
|
||||
[
|
||||
|
|
@ -141,6 +164,11 @@ g_default_tokens = [
|
|||
)
|
||||
for i in range(1, 3)
|
||||
},
|
||||
**{
|
||||
'collection/with/slash/0': TokenCollectionConfig(
|
||||
mode=TokenModes.READ_CURATED,
|
||||
)
|
||||
},
|
||||
},
|
||||
),
|
||||
TokenRequest(
|
||||
|
|
@ -215,11 +243,11 @@ g_default_tokens = [
|
|||
representation='token-all',
|
||||
collections={
|
||||
**{
|
||||
f'collection_{i}': TokenCollectionConfig(
|
||||
collection_name: TokenCollectionConfig(
|
||||
mode=TokenModes.WRITE_COLLECTION,
|
||||
incoming_label='token-all:user_all',
|
||||
)
|
||||
for i in range(1, 9)
|
||||
for collection_name in get_std_collection_names()
|
||||
},
|
||||
**{
|
||||
f'collection_dlflatsocial-{i}': TokenCollectionConfig(
|
||||
|
|
@ -361,10 +389,12 @@ g_default_tokens = [
|
|||
]
|
||||
|
||||
g_default_entries = {
|
||||
f'collection_{i}': [('Person', pid, test_record)] for i in range(1, 9)
|
||||
collection_name: [('Person', pid, test_record)]
|
||||
for collection_name in get_std_collection_names()
|
||||
}
|
||||
for collection_id in range(1, 9):
|
||||
g_default_entries[f'collection_{collection_id}'].extend(
|
||||
|
||||
for collection_name in get_std_collection_names():
|
||||
g_default_entries[collection_name].extend(
|
||||
[
|
||||
('Person', pid_curated, test_record_curated),
|
||||
(
|
||||
|
|
|
|||
217
dump_things_service/tests/test_backward_compatibility.py
Normal file
217
dump_things_service/tests/test_backward_compatibility.py
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import yaml
|
||||
|
||||
config_version_1 = """
|
||||
type: collections
|
||||
version: 1
|
||||
|
||||
collections:
|
||||
penguins:
|
||||
default_token: no_access
|
||||
curated: penguins/curated
|
||||
incoming: penguins/incoming-v1
|
||||
backend:
|
||||
type: sqlite
|
||||
schema: https://concepts.datalad.org/s/flat-study/unreleased.yaml
|
||||
|
||||
tokens:
|
||||
no_access:
|
||||
user_id: nobody
|
||||
collections:
|
||||
penguins:
|
||||
mode: NOTHING
|
||||
incoming_label: ''
|
||||
|
||||
token_1:
|
||||
user_id: cristian
|
||||
# The collections for which the token holds rights are defined in "collections"
|
||||
collections:
|
||||
penguins:
|
||||
mode: WRITE_COLLECTION
|
||||
incoming_label: 'cristian'
|
||||
|
||||
token_c:
|
||||
user_id: curator
|
||||
# The collections for which the token holds rights are defined in "collections"
|
||||
collections:
|
||||
penguins:
|
||||
mode: CURATOR
|
||||
incoming_label: 'curator'
|
||||
"""
|
||||
|
||||
config_version_2_inlined_only_policy = """
|
||||
pid: dump_things:config
|
||||
version: 2
|
||||
type: collections
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
curated: dfg-survey/2026/main/curated
|
||||
default_policy: policy_1
|
||||
default_token: noaccess
|
||||
incoming: dfg-survey/2026/main/inboxes
|
||||
policy_annotation_tag: abc
|
||||
policy_mapping:
|
||||
- auth_source: config
|
||||
authorized_by:
|
||||
- policy_1
|
||||
- policy_2
|
||||
- policy_3
|
||||
user_id: cmo
|
||||
- auth_source: trr379hub
|
||||
authorized_by:
|
||||
- policy_3
|
||||
- policy_4
|
||||
- policy_5
|
||||
user_id: mih
|
||||
schema: https://concepts.datalad.org/s/things/v2.yaml
|
||||
tokens:
|
||||
no_access:
|
||||
user_id: nobody
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
mode: NOTHING
|
||||
incoming_label: ''
|
||||
admin_tokens: {}
|
||||
"""
|
||||
|
||||
config_version_2_external_only_policy = """
|
||||
pid: dump_things:config
|
||||
version: 2
|
||||
type: collections
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
audit_backends: []
|
||||
auth_sources:
|
||||
- instance_id: trr379hub
|
||||
label_type: user
|
||||
organization: dfg-survey
|
||||
team: 2026-participants
|
||||
type: forgejo
|
||||
url: https://hub.trr379.de/api/v1
|
||||
backend:
|
||||
type: sqlite
|
||||
curated: dfg-survey/2026/main/curated
|
||||
policy_info_location: https://concepts.datalad.org/s/things/v2-policies.yaml
|
||||
default_token: noaccess
|
||||
ignore_classes: []
|
||||
incoming: dfg-survey/2026/main/inboxes
|
||||
schema: https://concepts.datalad.org/s/things/v2.yaml
|
||||
submission_tags:
|
||||
submission_time_tag: http://semanticscience.org/resource/SIO_001083
|
||||
submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269
|
||||
tokens:
|
||||
no_access:
|
||||
user_id: nobody
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
mode: NOTHING
|
||||
incoming_label: ''
|
||||
admin_tokens: {}
|
||||
"""
|
||||
|
||||
config_version_2_inlined_and_external_policy = """
|
||||
pid: dump_things:config
|
||||
version: 2
|
||||
type: collections
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
curated: dfg-survey/2026/main/curated
|
||||
default_policy: policy_1
|
||||
default_token: noaccess
|
||||
ignore_classes: []
|
||||
incoming: dfg-survey/2026/main/inboxes
|
||||
policy_annotation_tag: abc
|
||||
policy_mapping:
|
||||
- auth_source: config
|
||||
authorized_by:
|
||||
- policy_1
|
||||
- policy_2
|
||||
- policy_3
|
||||
user_id: cmo
|
||||
- auth_source: trr379hub
|
||||
authorized_by:
|
||||
- policy_3
|
||||
- policy_4
|
||||
- policy_5
|
||||
user_id: mih
|
||||
policy_info_location: https://concepts.datalad.org/s/things/v2-policies.yaml
|
||||
schema: https://concepts.datalad.org/s/things/v2.yaml
|
||||
submission_tags:
|
||||
submission_time_tag: http://semanticscience.org/resource/SIO_001083
|
||||
submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269
|
||||
tokens:
|
||||
tokens:
|
||||
no_access:
|
||||
user_id: nobody
|
||||
collections:
|
||||
dfg-survey-2026-main:
|
||||
mode: NOTHING
|
||||
incoming_label: ''
|
||||
admin_tokens: {}
|
||||
"""
|
||||
|
||||
config_example_1 = """
|
||||
admin_tokens: {}
|
||||
collections:
|
||||
collection-2026:
|
||||
audit_backends: []
|
||||
auth_sources:
|
||||
- instance_id: cerebra
|
||||
label_type: user
|
||||
organization: collection-2026
|
||||
repository: null
|
||||
team: collection-2026-participants
|
||||
type: forgejo
|
||||
url: https://example.com/api/v1
|
||||
- type: config
|
||||
backend:
|
||||
type: sqlite
|
||||
curated: collection-2026/main/curated
|
||||
default_token: noaccess
|
||||
ignore_classes: []
|
||||
incoming: collection-2026/main/inboxes
|
||||
schema: https://www.example.com/s/things/v2.yaml
|
||||
submission_tags:
|
||||
submission_time_tag: http://semanticscience.org/resource/SIO_001083
|
||||
submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269
|
||||
use_classes: []
|
||||
tokens:
|
||||
john_doe:
|
||||
collections:
|
||||
collection-2026:
|
||||
incoming_label: john_doe
|
||||
mode: CURATOR
|
||||
hashed: false
|
||||
representation: abcdefg
|
||||
user_id: john_doe
|
||||
noaccess:
|
||||
collections: {}
|
||||
hashed: false
|
||||
representation: abcdefg
|
||||
user_id: noaccess
|
||||
type: collections
|
||||
version: 2
|
||||
"""
|
||||
|
||||
|
||||
all_configurations = [
|
||||
config_version_1,
|
||||
config_version_2_inlined_only_policy,
|
||||
config_version_2_external_only_policy,
|
||||
config_version_2_inlined_and_external_policy,
|
||||
config_example_1,
|
||||
]
|
||||
|
||||
|
||||
# Check that old configurations can be read by the current Configuration class
|
||||
def test_config_backward_compatibility():
|
||||
from dump_things_service.abstract_config import Configuration
|
||||
from dump_things_service.commands.upload_config import convert_config_1_to_config_2
|
||||
|
||||
for config_yaml in all_configurations:
|
||||
config_dict = yaml.safe_load(config_yaml)
|
||||
if config_dict['version'] == 1:
|
||||
config_dict = convert_config_1_to_config_2(
|
||||
config_dict,
|
||||
None,
|
||||
)
|
||||
_ = Configuration(**config_dict)
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
from .common import get_std_collection_names
|
||||
from .. import (
|
||||
HTTP_200_OK,
|
||||
HTTP_400_BAD_REQUEST,
|
||||
|
|
@ -35,9 +36,9 @@ unicode_record = {
|
|||
|
||||
def test_search_by_pid(fastapi_client_simple):
|
||||
test_client, _, _ = fastapi_client_simple
|
||||
for i in range(1, 9):
|
||||
for collection_name in get_std_collection_names():
|
||||
response = test_client.get(
|
||||
f'/collection_{i}/record?pid={pid}',
|
||||
f'/{collection_name}/record?pid={pid}',
|
||||
headers={'x-dumpthings-token': 'token-all'},
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
|
@ -393,11 +394,11 @@ def test_server(fastapi_client_simple):
|
|||
'version': __version__,
|
||||
'collections': [
|
||||
{
|
||||
'name': f'collection_{i}',
|
||||
'name': collection_name,
|
||||
'schema': str(schema_file),
|
||||
'classes': test_schema_classes,
|
||||
}
|
||||
for i in range(1, 9)
|
||||
for collection_name in get_std_collection_names()
|
||||
]
|
||||
+ [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,8 +2,7 @@ from pathlib import (
|
|||
Path,
|
||||
PurePosixPath,
|
||||
)
|
||||
|
||||
from starlette.testclient import TestClient
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_200_OK,
|
||||
|
|
@ -18,12 +17,12 @@ from dump_things_service.abstract_config import (
|
|||
TokenModes,
|
||||
hash_token_representation,
|
||||
)
|
||||
from dump_things_service.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.instance_state import get_instance_state
|
||||
from dump_things_service.token_endpoints import (
|
||||
from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.token_endpoints import (
|
||||
AdminTokenRequest,
|
||||
TokenRequest,
|
||||
)
|
||||
from dump_things_service.instance_state import get_instance_state
|
||||
|
||||
# String representation of curated- and incoming-path
|
||||
curated = 'admin_test_curated'
|
||||
|
|
@ -32,7 +31,8 @@ incoming = 'admin_test_incoming'
|
|||
# Path to a local simple test schema
|
||||
test_schema_location = str((Path(__file__).parent / 'testschema.yaml').absolute())
|
||||
|
||||
new_collection_name = 'admin_test_collection'
|
||||
new_collection_name = 'admin@example.com/base/test_collection'
|
||||
|
||||
new_token_name = 'admin_test_token'
|
||||
new_token_representation = 'admin_test_token'
|
||||
new_collection_request = CollectionRequest(
|
||||
|
|
@ -64,15 +64,6 @@ new_admin_token_request = AdminTokenRequest(
|
|||
)
|
||||
|
||||
|
||||
def _name_in_openapi_paths(
|
||||
test_client: TestClient,
|
||||
name: str,
|
||||
) -> bool:
|
||||
response = test_client.get('/openapi.json')
|
||||
open_api = response.json()
|
||||
return any(name in path for path in open_api['paths'])
|
||||
|
||||
|
||||
def test_collection_adding(fastapi_client_simple):
|
||||
test_client, _, admin_token = fastapi_client_simple
|
||||
|
||||
|
|
@ -82,7 +73,6 @@ def test_collection_adding(fastapi_client_simple):
|
|||
headers={'x-dumpthings-token': admin_token},
|
||||
)
|
||||
assert response.status_code == HTTP_404_NOT_FOUND
|
||||
assert not _name_in_openapi_paths(test_client, new_collection_name)
|
||||
|
||||
# Add a new collection to the configuration
|
||||
response = test_client.post(
|
||||
|
|
@ -92,9 +82,6 @@ def test_collection_adding(fastapi_client_simple):
|
|||
)
|
||||
assert response.status_code == HTTP_201_CREATED
|
||||
|
||||
# Check that the collection endpoints exist in the open API document
|
||||
assert _name_in_openapi_paths(test_client, new_collection_name)
|
||||
|
||||
# Read back the new collection and compare it
|
||||
response = test_client.get(
|
||||
f'/collections/{new_collection_name}',
|
||||
|
|
@ -179,14 +166,12 @@ def test_collection_adding(fastapi_client_simple):
|
|||
)
|
||||
assert response.status_code == HTTP_404_NOT_FOUND
|
||||
|
||||
# Check that the openapi document is adjusted
|
||||
assert not _name_in_openapi_paths(test_client, new_collection_name)
|
||||
|
||||
|
||||
def test_collection_putting(fastapi_client_simple, tmp_path):
|
||||
test_client, _, admin_token = fastapi_client_simple
|
||||
|
||||
put_collection_name = 'test_put_collection'
|
||||
put_collection_name = 'admin@example.com/base/test_put_collection'
|
||||
url_encoded_put_collection_name = quote_plus(put_collection_name)
|
||||
put_collection_request_orig = CollectionRequest(
|
||||
name=put_collection_name,
|
||||
default_token='test_default_token',
|
||||
|
|
@ -211,11 +196,10 @@ def test_collection_putting(fastapi_client_simple, tmp_path):
|
|||
|
||||
# Check that the collection does not yet exist
|
||||
response = test_client.get(
|
||||
f'/collections/{put_collection_name}',
|
||||
f'/collections/{url_encoded_put_collection_name}',
|
||||
headers={'x-dumpthings-token': admin_token},
|
||||
)
|
||||
assert response.status_code == HTTP_404_NOT_FOUND
|
||||
assert not _name_in_openapi_paths(test_client, put_collection_name)
|
||||
|
||||
# Add the first version of the collection
|
||||
response = test_client.post(
|
||||
|
|
@ -224,13 +208,12 @@ def test_collection_putting(fastapi_client_simple, tmp_path):
|
|||
json=put_collection_request_orig.model_dump(mode='json', by_alias=True),
|
||||
)
|
||||
assert response.status_code == HTTP_201_CREATED
|
||||
assert _name_in_openapi_paths(test_client, put_collection_name)
|
||||
|
||||
audit_files = tuple(tmp_path.iterdir())
|
||||
assert len(audit_files) == 0
|
||||
|
||||
response = test_client.get(
|
||||
f'/collections/{put_collection_name}',
|
||||
f'/collections/{url_encoded_put_collection_name}',
|
||||
headers={'x-dumpthings-token': admin_token},
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
|
@ -250,7 +233,7 @@ def test_collection_putting(fastapi_client_simple, tmp_path):
|
|||
# Delete the collection again because we check for a known number of
|
||||
# collections in other tests.
|
||||
response = test_client.delete(
|
||||
f'/collections/{put_collection_name}',
|
||||
f'/collections/{url_encoded_put_collection_name}',
|
||||
headers={'x-dumpthings-token': admin_token},
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
|
@ -267,7 +250,7 @@ def test_collection_reading(fastapi_client_simple):
|
|||
assert response.status_code == HTTP_200_OK
|
||||
response_object = response.json()
|
||||
assert isinstance(response_object, list)
|
||||
assert len(response_object) == 10
|
||||
assert len(response_object) == 11
|
||||
|
||||
|
||||
def test_admin_token_management(fastapi_client_simple):
|
||||
|
|
|
|||
|
|
@ -22,10 +22,10 @@ from dump_things_service.abstract_config import (
|
|||
get_config_backends,
|
||||
read_config,
|
||||
)
|
||||
from dump_things_service.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.token_endpoints import TokenRequest
|
||||
from dump_things_service.exceptions import ConfigError
|
||||
from dump_things_service.tests import schema_file
|
||||
from dump_things_service.token_endpoints import TokenRequest
|
||||
|
||||
reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml'
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue