diff --git a/CHANGELOG.md b/CHANGELOG.md index 54e2fba..218d16a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,22 @@ +# 6.5.0 (2026-10-01) + +## New features + +- Support policies to restrict access to record if `sqlite`-backends are used. + Policies are opaque strings. A default policy can be defined for a collection + (in `default_policy`). + Each record can carry a policy in its `annotation`-property. The key-name + is defined in the configuration of the collection (in `policy_annotation_tag`). + If `policy_annotation_tag` is not defined, policies are ignored for the + collection. A mapping between users and policies that apply for a user can + be defined for a collection (in `policy_mapping`). + +## Bugfixes + +- Fix a bug in hashed-token handling that prevented the service from + authenticating users with hashed tokens. + + # 6.4.0 (2026-09-23) ## New features diff --git a/docs/configuration.rst b/docs/configuration.rst index 79898a1..dbafaae 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -176,6 +176,27 @@ are supported: ``audit_backends`` (optional) List of audit-backend configurations. See `Audit Backends`_ below. +``policy_annotation_tag`` (optional) + Key for the policy annotation tag. If the key is found in the + ``annotation``-property of a record, its value is interpreted as policy + that controls access to the record (if an ``sqlite``-backend) is + used. + If ``policy_annotation_tag`` is not set, the policy mechanism is ignored + in this collection. + +``default_policy`` (optional) + Default policy for records in this collection. If ``policy_annotation_tag`` + is set, and a record does not have a policy annotation, the default policy + is used. If ``default_policy`` is not set, records without a policy + annotation are considered public. Policies are opaque strings, which are + compared verbatim in ``sqlite``-backends. + +``policy_mapping`` (optional) + Mapping from users to policies. If access to a record is guarded by a policy, + the user will only be able to access (or "see") the record, if the policy + is present in the set of policies that are mapped to the user. + See `Policy Mappings`_ below. + Example ^^^^^^^ @@ -255,6 +276,44 @@ Use ``dump-things-gitaudit-report`` to display the audit log and ``dump-things-gitaudit-rebuild-index`` to rebuild its index (see :doc:`commands`). +Policy Mappings +^^^^^^^^^^^^^^^ + +The service allows to assign a set of policies to each user. +If a record is annotated with a policy that is in the set of the user's policies, +or a default policy which is in the user's set of policies is defined, +the user is allowed to see and access the record. + +Policy mappings are configured per collection with ``policy_mapping``, which +contains a list of user -> policy mappings. Each user is identified by an +authentication source and a user ID. The authentication source ``config`` if +the user ID is defined by a token that is directly defined in the collection. + +If the user is authenticated via a forgejo authentication source, the +``instance_id`` of the forgejo authentication source will be the authentication +source. + +The following is an example for a policy mapping for two users, one defined +by a token in the configuration and one authenticated via a forgejo +authentication source that has the ``instance_id`` ``forgejo_1.example.com``: + +.. code-block:: yaml + + collections: + collection_1: + ... + policy_mapping: + - auth_source: config + user_id: token_1_user + authorized_by: + - policy_1 + - policy_2 + - auth_source: forgejo_1.example.com + user_id: forgejo_user_1 + authorized_by: + - policy_2 + - policy_3 + Collection-and-Token: a Chicken-and-Egg Problem ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -268,8 +327,6 @@ collections that are not created. In other words: - - Reserved Collection Names ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/dump_things_service/__init__.py b/dump_things_service/__init__.py index f3d9693..1ca2721 100644 --- a/dump_things_service/__init__.py +++ b/dump_things_service/__init__.py @@ -55,7 +55,6 @@ config_file_name = '.dumpthings.yaml' dump_things_private_collection_name = '__dump_things__' - reserved_collection_names = ( 'collections', 'tokens', @@ -63,3 +62,5 @@ reserved_collection_names = ( 'api', dump_things_private_collection_name, ) + +policy_annotation = 'https://example.org/dumpthings/policy_set' diff --git a/dump_things_service/abstract_config.py b/dump_things_service/abstract_config.py index 7071dd0..e94410f 100644 --- a/dump_things_service/abstract_config.py +++ b/dump_things_service/abstract_config.py @@ -100,6 +100,12 @@ class GitAuditBackendConfig(StrictModel): auto_flush_timeout: int = 60 +class PolicyMapping(StrictModel): + auth_source: str + user_id: str + authorized_by: list[str] + + class CollectionConfig(BaseModel): model_config = ConfigDict(extra='forbid', use_enum_values=True) default_token: str @@ -114,6 +120,9 @@ class CollectionConfig(BaseModel): submission_tags: TagSpec = TagSpec() use_classes: list[str] = [] ignore_classes: list[str] = [] + default_policy: str | None = None + policy_mapping: list[PolicyMapping] = [] + policy_annotation_tag: str | None = None class RecordDirConfigFileContent(BaseModel): @@ -510,3 +519,13 @@ mapping_functions: dict[MappingMethod, Callable] = { def get_mapping_function_by_name(mapping_function_name: str) -> Callable: return mapping_functions[MappingMethod(mapping_function_name)] + + +def get_policies_for_user( + abstract_config: Configuration, + collection_name: str, + auth_source_id: str, + user_id: str, +) -> list[str]: + collection_config = get_collection_config_by_name(abstract_config, collection_name) + return collection_config.policy_mapping.get((auth_source_id, user_id), []) diff --git a/dump_things_service/auth/__init__.py b/dump_things_service/auth/__init__.py index 5758cb5..a2d1953 100644 --- a/dump_things_service/auth/__init__.py +++ b/dump_things_service/auth/__init__.py @@ -29,12 +29,19 @@ class InvalidTokenError(AuthenticationError): @dataclasses.dataclass class AuthenticationInfo: + source_identifier: str token_permission: TokenPermission user_id: str incoming_label: str class AuthenticationSource(metaclass=abc.ABCMeta): + def __init__( + self, + source_identifier: str, + ): + self.source_identifier = source_identifier + @abc.abstractmethod def authenticate( self, diff --git a/dump_things_service/auth/config.py b/dump_things_service/auth/config.py index 1808214..541c286 100644 --- a/dump_things_service/auth/config.py +++ b/dump_things_service/auth/config.py @@ -18,6 +18,7 @@ class ConfigAuthenticationSource(AuthenticationSource): abstract_configuration: Configuration, collection_name: str, ): + super().__init__('config') self.abstract_configuration = abstract_configuration self.collection_name = collection_name @@ -37,6 +38,7 @@ class ConfigAuthenticationSource(AuthenticationSource): _, token_config, token_collection_config = result return AuthenticationInfo( + source_identifier=self.source_identifier, token_permission=get_token_permissions(token_collection_config.mode), user_id=token_config.user_id, incoming_label=token_collection_config.incoming_label, diff --git a/dump_things_service/auth/forgejo.py b/dump_things_service/auth/forgejo.py index 90dfe00..c77c23f 100644 --- a/dump_things_service/auth/forgejo.py +++ b/dump_things_service/auth/forgejo.py @@ -79,6 +79,7 @@ class RemoteAuthenticationError(AuthenticationError): class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): def __init__( self, + source_identifier: str, api_url: str, organization: str, team: str, @@ -100,17 +101,19 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): :param team: The name of the team :param label_type: 'team' or 'user', determines how the incoming label is created. - :param instance_id: Optional instance ID. If present, will be used to - disambig + :param instance_id: Optional instance ID. Will be used to + disambiguate identical user IDs from different servers, default + to a hash ot `api_url`. :param repository: Optional repository. If this is provided, access will only be granted if the team has access to the repository. """ - super().__init__() + AuthenticationSource.__init__(self, source_identifier) + MethodCache.__init__(self) self.api_url = api_url[:-1] if api_url[-1] == '/' else api_url self.organization = organization self.team = team self.label_type = label_type - self.instance_id = instance_id + self.instance_id = instance_id or hashlib.md5(self.api_url.encode()).hexdigest() self.repository = repository def _get_json_from_endpoint( @@ -220,9 +223,6 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): ) return permissions - def _instance_label(self) -> str: - return self.instance_id or hashlib.md5(self.api_url.encode()).hexdigest() # noqa S324 -- hash not used for cryptography, only for label generation - @MethodCache.cache_temporary(duration=60) def authenticate( self, @@ -284,12 +284,13 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache): action_permissions, ) return AuthenticationInfo( + source_identifier=self.source_identifier, token_permission=self._get_permissions( code_permissions, action_permissions, ), user_id=user_info['email'], - incoming_label=f'forgejo-{self._instance_label()}-team-{organization["name"]}-{team["name"]}' + incoming_label=f'forgejo-{self.instance_id}-team-{organization["name"]}-{team["name"]}' if self.label_type == 'team' - else f'forgejo-{self._instance_label()}-user-{user_info["login"]}', + else f'forgejo-{self.instance_id}-user-{user_info["login"]}', ) diff --git a/dump_things_service/backends/__init__.py b/dump_things_service/backends/__init__.py index 74128cb..bbb1ecb 100644 --- a/dump_things_service/backends/__init__.py +++ b/dump_things_service/backends/__init__.py @@ -146,6 +146,9 @@ class StorageBackend(metaclass=ABCMeta): def get_record_by_iri( self, iri: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordInfo | None: raise NotImplementedError @@ -153,14 +156,20 @@ class StorageBackend(metaclass=ABCMeta): def get_records_of_classes( self, class_names: Iterable[str], + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> BackendResultList: raise NotImplementedError @abstractmethod def get_all_records( self, + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> BackendResultList: raise NotImplementedError diff --git a/dump_things_service/backends/record_dir.py b/dump_things_service/backends/record_dir.py index 533059f..4183bf4 100644 --- a/dump_things_service/backends/record_dir.py +++ b/dump_things_service/backends/record_dir.py @@ -146,6 +146,9 @@ class _RecordDirStore(StorageBackend): def get_record_by_iri( self, iri: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordInfo | None: index_entry = self.index.get_info_for_iri(iri) if index_entry is None: @@ -163,7 +166,10 @@ class _RecordDirStore(StorageBackend): def get_records_of_classes( self, class_names: list[str], - _pattern: str | None = None, + policy_annotation_tag: str | None = None, + pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordDirResultList: return RecordDirResultList().add_info( sorted( @@ -183,7 +189,10 @@ class _RecordDirStore(StorageBackend): def get_all_records( self, - _pattern: str | None = None, + policy_annotation_tag: str | None = None, + pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordDirResultList: return RecordDirResultList().add_info( sorted( diff --git a/dump_things_service/backends/schema_type_layer.py b/dump_things_service/backends/schema_type_layer.py index 025b5f1..c487f74 100644 --- a/dump_things_service/backends/schema_type_layer.py +++ b/dump_things_service/backends/schema_type_layer.py @@ -116,8 +116,16 @@ class _SchemaTypeLayer(StorageBackend): def get_record_by_iri( self, iri: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordInfo | None: - origin_result = self.backend.get_record_by_iri(iri) + origin_result = self.backend.get_record_by_iri( + iri, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ) if origin_result and 'schema_type' not in origin_result.json_object: origin_result.json_object = order_dict( { @@ -133,22 +141,36 @@ class _SchemaTypeLayer(StorageBackend): def get_records_of_classes( self, class_names: list[str], + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> BackendResultList: return SchemaTypeLayerResultList( origin_list=self.backend.get_records_of_classes( class_names, - pattern, + pattern=pattern, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, ), schema_model=self.schema_model, ) def get_all_records( self, + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> BackendResultList: return SchemaTypeLayerResultList( - origin_list=self.backend.get_all_records(pattern), + origin_list=self.backend.get_all_records( + pattern=pattern, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ), schema_model=self.schema_model, ) diff --git a/dump_things_service/backends/sqlite.py b/dump_things_service/backends/sqlite.py index 0255c58..38a3d26 100644 --- a/dump_things_service/backends/sqlite.py +++ b/dump_things_service/backends/sqlite.py @@ -227,37 +227,59 @@ class _SQLiteBackend(StorageBackend): def get_record_by_iri( self, iri: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> RecordInfo | None: with Session(self.engine) as session, session.begin(): statement = select(Thing).filter_by(iri=iri) thing = session.scalar(statement) if thing: - return RecordInfo( - iri=thing.iri, - class_name=thing.class_name, - json_object=thing.object, - sort_key=thing.sort_key, + thing_policy = thing.object.get('annotations', {}).get( + policy_annotation_tag, default_policy ) + if ( + thing_policy and thing_policy in active_policies + ) or not thing_policy: + return RecordInfo( + iri=thing.iri, + class_name=thing.class_name, + json_object=thing.object, + sort_key=thing.sort_key, + ) return None def get_records_of_classes( self, class_names: Iterable[str], + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> SQLResultList: class_list = ', '.join(f"'{cn}'" for cn in class_names) + + active_policies = active_policies or set() + policy_clause = self._get_policy_clause( + policy_annotation_tag, + default_policy, + active_policies, + ) + if pattern is None: statement = text( 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled 'from thing ' - f'where thing.class_name in ({class_list}) ' + f'where ({policy_clause}) ' + f'and thing.class_name in ({class_list}) ' 'ORDER BY thing.sort_key' ) else: statement = text( 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled 'from thing, json_tree(thing.object) ' - 'where lower(json_tree.value) like lower(:pattern) ' + f'where ({policy_clause}) ' + 'and lower(json_tree.value) like lower(:pattern) ' f'and thing.class_name in ({class_list}) ' "and json_tree.type = 'text' ORDER BY thing.sort_key" ) @@ -276,12 +298,23 @@ class _SQLiteBackend(StorageBackend): def get_all_records( self, + policy_annotation_tag: str | None = None, pattern: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> SQLResultList: + active_policies = active_policies or set() + policy_clause = self._get_policy_clause( + policy_annotation_tag, + default_policy, + active_policies, + ) + if pattern is None: statement = text( 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing ' + f'where {policy_clause} ' 'ORDER BY thing.sort_key' ) else: @@ -289,7 +322,9 @@ class _SQLiteBackend(StorageBackend): 'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' 'from thing, json_tree(thing.object) ' 'where lower(json_tree.value) like lower(:pattern) ' - "and json_tree.type = 'text' ORDER BY thing.sort_key" + "and json_tree.type = 'text' " + f'and ({policy_clause}) ' + 'ORDER BY thing.sort_key' ) with self.engine.connect() as connection: @@ -304,6 +339,43 @@ class _SQLiteBackend(StorageBackend): for thing in rs ) + @staticmethod + def _get_policy_clause( + policy_annotation_tag: str | None, + default_policy: str | None, + active_policies: set[str], + ) -> str: + if not policy_annotation_tag: + return '1=1' + + # If no active policy is provided and a default policy is set, no + # record will be readable, because every record is guarded by a policy. + # (This is a special case that is handled by returning a clause that will + # quickly fail with no record, instead of inspecting the policies of + # all records.) + if default_policy and not active_policies: + return '1=0' + + policy_set_clause = ( + '(' + ', '.join(f"'{policy}'" for policy in active_policies) + ')' + ) + + # If there is no default policy, or the default is in the active policies, + # return all records that have either no policy or have a + # policy that is element of active_policies. + if (default_policy and default_policy in active_policies) or not default_policy: + if not active_policies: + return f'json_extract(object, \'$.annotations."{policy_annotation_tag}"\') is NULL' + return ( + f'json_extract(object, \'$.annotations."{policy_annotation_tag}"\') is NULL' + f' or json_extract(object, \'$.annotations."{policy_annotation_tag}"\') in {policy_set_clause}' + ) + + # At this point there is a default policy and the default policy is not + # in the active policies. Return a clause that selects records that have + # a policy that is an element of active_policies. + return f'json_extract(object, \'$.annotations."{policy_annotation_tag}"\') in {policy_set_clause}' + # Ensure that there is only one SQL-backend per database file. _existing_sqlite_backends: dict[Path, _SQLiteBackend] = {} diff --git a/dump_things_service/collection.py b/dump_things_service/collection.py index 126b54c..03d6665 100644 --- a/dump_things_service/collection.py +++ b/dump_things_service/collection.py @@ -74,6 +74,7 @@ from dump_things_service.instance_state import ( record_dir_config_file_name, ) from dump_things_service.model import get_model_for_schema +from dump_things_service.resolve_curie import resolve_curie from dump_things_service.utils import ( combine_ttl, create_store, @@ -239,9 +240,12 @@ def create_collection( active_classes &= set(collection_configuration.use_classes) if collection_configuration.ignore_classes: active_classes -= set(collection_configuration.ignore_classes) + + default_policy = configuration.collections[collection_name].default_policy instance_state.collections[collection_name] = InstanceStateCollectionInfo( active_classes=active_classes, tag_info={}, + default_policies=set([] if default_policy is None else [default_policy]), ) # Create a validator for the collection @@ -279,6 +283,17 @@ def create_collection( instance_state.fastapi_app, ) + # Create the user_id -> policy mapping + instance_state.policy_mappings[collection_name] = {} + model = get_model_for_schema(collection_configuration.schema_location)[0] + for mapping in collection_configuration.policy_mapping: + instance_state.policy_mappings[collection_name][ + (mapping.auth_source, mapping.user_id) + ] = [ + resolve_curie(model=model, curie_or_iri=policy) + for policy in mapping.authorized_by + ] + def create_authentication_source( abstract_configuration: Configuration, @@ -297,6 +312,7 @@ def create_authentication_source( ) elif isinstance(authentication_spec, ForgejoAuthSpec): auth_source = ForgejoAuthenticationSource( + source_identifier=f'forgejo_{authentication_spec.instance_id}', api_url=authentication_spec.url, organization=authentication_spec.organization, team=authentication_spec.team, @@ -617,7 +633,7 @@ def store_record( if api_key is None else api_key ) - store, token_permissions, user_id = get_token_store( + store, token_permissions, user_info = get_token_store( abstract_config, instance_state, collection, @@ -668,7 +684,7 @@ def store_record( with wrap_http_exception(CurieResolutionError): stored_records = store.store_object( obj=sorted_record, - submitter=user_id if add_submission_tag else None, + submitter=user_info[1] if add_submission_tag else None, ) if input_format == Format.ttl: diff --git a/dump_things_service/collection_endpoints.py b/dump_things_service/collection_endpoints.py index 6074895..8445dcc 100644 --- a/dump_things_service/collection_endpoints.py +++ b/dump_things_service/collection_endpoints.py @@ -30,7 +30,7 @@ from dump_things_service.abstract_config import ( ) from dump_things_service.admin import authenticate_admin from dump_things_service.api_key import api_key_header_scheme -from dump_things_service.exceptions import ConfigError +from dump_things_service.exceptions import DumpThingsError, ConfigError from dump_things_service.instance_state import InstanceState, get_instance_state from dump_things_service.manifest import manifest_configuration from dump_things_service.utils import wrap_http_exception @@ -73,7 +73,8 @@ async def create_collection( body: CollectionRequest, api_key: Annotated[str, Depends(api_key_header_scheme)], ): - await create_or_replace_collection(body, api_key, allow_replace=False) + with wrap_http_exception(DumpThingsError): + await create_or_replace_collection(body, api_key, allow_replace=False) response.headers['Location'] = f'/collections/{quote(body.name)}' @@ -88,7 +89,8 @@ async def replace_collection( body: CollectionRequest, api_key: Annotated[str, Depends(api_key_header_scheme)], ): - await create_or_replace_collection(body, api_key, allow_replace=True) + with wrap_http_exception(DumpThingsError): + await create_or_replace_collection(body, api_key, allow_replace=True) response.headers['Location'] = f'/collections/{quote(body.name)}' diff --git a/dump_things_service/curated.py b/dump_things_service/curated.py index d2c5b43..7046678 100644 --- a/dump_things_service/curated.py +++ b/dump_things_service/curated.py @@ -233,9 +233,9 @@ async def _read_curated_records( # detail=f"no record with pid '{pid}' in curated area of collection '{collection}'", # ) if class_name: - result_list = backend.get_records_of_classes([class_name], matching) + result_list = backend.get_records_of_classes([class_name], pattern=matching) else: - result_list = backend.get_all_records(matching) + result_list = backend.get_all_records(pattern=matching) if upper_bound is not None: check_bounds( diff --git a/dump_things_service/exceptions.py b/dump_things_service/exceptions.py index 8a3b8ae..c1a44b2 100644 --- a/dump_things_service/exceptions.py +++ b/dump_things_service/exceptions.py @@ -1,4 +1,8 @@ -class ConfigError(Exception): +class DumpThingsError(Exception): + pass + + +class ConfigError(DumpThingsError): pass @@ -6,5 +10,5 @@ class ConfigCollisionError(ConfigError): pass -class CurieResolutionError(Exception): +class CurieResolutionError(DumpThingsError): pass diff --git a/dump_things_service/incoming.py b/dump_things_service/incoming.py index 5ccc9f1..4aaf471 100644 --- a/dump_things_service/incoming.py +++ b/dump_things_service/incoming.py @@ -250,9 +250,9 @@ async def _incoming_read_records( # detail=f'no record with pid: {pid}', # ) if class_name: - result_list = backend.get_records_of_classes([class_name], matching) + result_list = backend.get_records_of_classes([class_name], pattern=matching) else: - result_list = backend.get_all_records(matching) + result_list = backend.get_all_records(pattern=matching) if upper_bound is not None: check_bounds( diff --git a/dump_things_service/instance_state.py b/dump_things_service/instance_state.py index a77bb64..76a3383 100644 --- a/dump_things_service/instance_state.py +++ b/dump_things_service/instance_state.py @@ -60,6 +60,7 @@ class SchemaInfo: class InstanceStateCollectionInfo: active_classes: set[str] tag_info: dict[str, str] + default_policies: set[str] @cache @@ -101,6 +102,7 @@ class InstanceState: schema_info: dict[str, SchemaInfo] = dataclasses.field(default_factory=dict) validators: dict = dataclasses.field(default_factory=dict) order_by: list[str] = dataclasses.field(default_factory=list) + policy_mappings: dict[str, dict] = dataclasses.field(default_factory=dict) g_instance_state: InstanceState | None = None diff --git a/dump_things_service/main.py b/dump_things_service/main.py index 134d48f..70b56ce 100644 --- a/dump_things_service/main.py +++ b/dump_things_service/main.py @@ -410,20 +410,34 @@ async def read_record_with_pid( ): check_collection(g_configuration, collection) - final_permissions, token_store = await process_token( + 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_configuration, 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) + 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) + ].get_object_by_pid( + pid, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=policies, + ) if not json_object: return None @@ -440,6 +454,30 @@ async def read_record_with_pid( return json_object +def _get_policy_information( + configuration: Configuration, + collection_name: str, + user_info: tuple[str, str], +) -> tuple[str, str | None, set[str]]: + from itertools import chain + + collection_info = configuration.collections[collection_name] + policies = set( + chain( + *[ + policy_mapping.authorized_by + for policy_mapping in collection_info.policy_mapping + if (policy_mapping.auth_source, policy_mapping.user_id) == user_info + ] + ) + ) + return ( + collection_info.policy_annotation_tag, + collection_info.default_policy, + policies, + ) + + @app.get( '/{collection}/records/', tags=['Read records'], @@ -546,13 +584,22 @@ async def _read_all_records( ) from e check_collection(g_configuration, collection) - final_permissions, token_store = await process_token( + 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_configuration, collection, user_info + ) + result_list = PriorityList() if final_permissions.incoming_read: - token_store_list = token_store.get_all_objects(matching=matching) + 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) @@ -562,6 +609,9 @@ async def _read_all_records( 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/') @@ -609,16 +659,23 @@ async def _read_records_of_type( detail=f"No '{class_name}'-class in collection '{collection}'.", ) - final_permissions, token_store = await process_token( + 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_configuration, 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( @@ -633,6 +690,9 @@ async def _read_records_of_type( ].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( @@ -673,7 +733,7 @@ async def delete_record( api_key: Annotated[str, Depends(api_key_header_scheme)], ): check_collection(g_configuration, collection) - final_permissions, token_store = await process_token( + final_permissions, token_store, user_info = await process_token( g_configuration, g_instance_state, api_key, collection ) @@ -694,6 +754,20 @@ async def delete_record( 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, diff --git a/dump_things_service/store/model_store.py b/dump_things_service/store/model_store.py index 8005941..f3299f7 100644 --- a/dump_things_service/store/model_store.py +++ b/dump_things_service/store/model_store.py @@ -7,6 +7,7 @@ from datetime import ( from itertools import chain from typing import TYPE_CHECKING +from dump_things_service.exceptions import ConfigError from dump_things_service.model import ( get_model_for_schema, get_subclasses, @@ -175,14 +176,30 @@ class _ModelStore: def get_object_by_pid( self, pid: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> tuple[str, dict] | tuple[None, None]: - return self.get_object_by_iri(self.pid_to_iri(pid)) + return self.get_object_by_iri( + self.pid_to_iri(pid), + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ) def get_object_by_iri( self, iri: str, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> tuple[str, dict] | tuple[None, None]: - record_info = self.backend.get_record_by_iri(iri) + record_info = self.backend.get_record_by_iri( + iri, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ) if record_info: return record_info.class_name, record_info.json_object return None, None @@ -191,6 +208,9 @@ class _ModelStore: self, class_name: str, matching: str | None, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, *, include_subclasses: bool = True, ) -> LazyList[_RecordInfo]: @@ -208,11 +228,20 @@ class _ModelStore: class_names = get_subclasses(self.model, class_name) else: class_names = [class_name] - return self.backend.get_records_of_classes(class_names, matching) + return self.backend.get_records_of_classes( + class_names, + pattern=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ) def get_all_objects( self, matching: str | None = None, + policy_annotation_tag: str | None = None, + default_policy: str | None = None, + active_policies: set[str] | None = None, ) -> LazyList[_RecordInfo]: """ Get all objects of a specific class. @@ -220,7 +249,12 @@ class _ModelStore: :param matching: Return only records with a value that matches `matching`. :return: A lazy list of all objects in the store. """ - return self.backend.get_all_records(matching) + return self.backend.get_all_records( + pattern=matching, + policy_annotation_tag=policy_annotation_tag, + default_policy=default_policy, + active_policies=active_policies, + ) def delete_object( self, @@ -239,7 +273,7 @@ def ModelStore( # noqa: N802 ) -> _ModelStore: """Create a unique model store for the given schema and backend. - Raise `ValueError` if a store with a different schema already exists for + Raise `ConfigError` if a store with a different schema already exists for the given backend. :param schema: The schema to use for the model store. @@ -256,6 +290,6 @@ def ModelStore( # noqa: N802 # Check that the schemas are compatible, if the backend is reused. elif existing_model_store.schema != schema: msg = 'Backend is already used in a ModelStore with a different schema' - raise ValueError(msg) + raise ConfigError(msg) return existing_model_store diff --git a/dump_things_service/tests/assets/reference_config.yaml b/dump_things_service/tests/assets/reference_config.yaml new file mode 100644 index 0000000..292b54b --- /dev/null +++ b/dump_things_service/tests/assets/reference_config.yaml @@ -0,0 +1,118 @@ +pid: dump_things:config +type: collections +version: 2 +collections: + collection_1: + + schema: http://example.com/schema + curated: curated/collection_1 + incoming: incoming/collection_1 + default_token: test_default_token + ignore_classes: [] + use_classes: [] + + audit_backends: + - auto_flush_timeout: 2 + path: /tmp/audit_store0 + type: gitaudit + + auth_sources: + - type: config + - type: forgejo + url: http://example.com/forgejo1/api/v1 + organization: example_org + team: team_1 + label_type: user + instance_id: forgejo-instance_1 + - type: forgejo + url: http://example.com/forgejo2/api/v1 + organization: example_org + team: team_2 + label_type: user + instance_id: forgejo-instance_2 + - type: config + + backend: + mapping_method: digest-md5 + type: record_dir+stl + + policy_mapping: + - auth_source: config + user_id: test_user_1 + authorized_by: + - https://examples.com/policy_example_0 + - abc:policy_abc + - auth_source: forgejo-instance_1 + user_id: test_user_f1_u1 + authorized_by: + - https://examples.com/policy_example_1 + - abc:policy_abc + - auth_source: forgejo-instance_2 + user_id: test_user_f2_u1 + authorized_by: + - https://examples.com/policy_example_2 + - abc:policy_abc + + submission_tags: + submission_time_tag: http://semanticscience.org/resource/SIO_001083 + submitter_id_tag: http://purl.obolibrary.org/obo/NCIT_C54269 + +tokens: + Test 00000 (NOTHING): + collections: + collection_1: + incoming_label: modes + mode: NOTHING + hashed: false + representation: token_1_ooooo + user_id: test_user_1_nothing + Test 00X00 (SUBMIT_ONLY): + collections: + collection_1: + incoming_label: modes + mode: SUBMIT_ONLY + hashed: false + representation: token_1_ooxoo + user_id: test_user_1_submit_only + Test 0X000 (READ_SUBMISSIONS): + collections: + collection_1: + incoming_label: modes + mode: READ_SUBMISSIONS + hashed: false + representation: token_1_oxooo + user_id: test_user_1_read_submissions + Test 0XX00 (WRITE_SUBMISSIONS): + collections: + collection_1: + incoming_label: modes + mode: WRITE_SUBMISSIONS + hashed: false + representation: token_1_oxxoo + user_id: test_user_1_write_submissions + Test Curator Token: + collections: + collection_1: + incoming_label: admin_1 + mode: CURATOR + hashed: false + representation: token_curator + user_id: test_curator + Test Hashed Token: + collections: + collection_1: + incoming_label: token-hashed-1 + mode: WRITE_COLLECTION + hashed: false + representation: token-hashed + user_id: test_hashed + test_default_token: + collections: + collection_1: + incoming_label: '' + mode: READ_CURATED + hashed: false + representation: basic_access + user_id: basic_access_user + +admin_tokens: {} diff --git a/dump_things_service/tests/fixtures.py b/dump_things_service/tests/fixtures.py index a9f02dd..ffa37d1 100644 --- a/dump_things_service/tests/fixtures.py +++ b/dump_things_service/tests/fixtures.py @@ -16,6 +16,7 @@ from dump_things_service.abstract_config import ( TokenCollectionConfig, TokenModes, hash_token_representation, + PolicyMapping, ) from dump_things_service.backends import StorageBackend from dump_things_service.backends.record_dir import RecordDirStore @@ -63,6 +64,7 @@ g_default_collections = [ for i in range(1, 8) ] + g_default_collections[6].submission_tags = TagSpec( submitter_id_tag='abc:id', submission_time_tag='abc:time', @@ -82,9 +84,60 @@ g_default_collections.append( submitter_id_tag='no_default_id_tag', submission_time_tag='no_default_time_tag', ), + default_policy='abc:policy_abc', + policy_annotation_tag='https://example.org/dumpthings/policy_set', + policy_mapping=[ + PolicyMapping( + auth_source='config', + user_id='basic_access_user', + authorized_by=[ + 'abc:policy_abc', + 'policy_1', + ], + ), + PolicyMapping( + auth_source='config', + user_id='user_all', + authorized_by=[ + 'abc:policy_abc', + 'policy_1', + ], + ), + PolicyMapping( + auth_source='config', + user_id='test_user_1', + authorized_by=[ + 'https://examples.com/policy_example_1', + 'abc:policy_abc', + ], + ), + PolicyMapping( + auth_source='some_other_source', + user_id='test_user_2', + authorized_by=[ + 'https://examples.com/policy_example_2', + 'abc:policy_def', + ], + ), + PolicyMapping( + auth_source='config', + user_id='test_user_8_default_policy', + authorized_by=[ + 'abc:policy_abc', + ], + ), + PolicyMapping( + auth_source='config', + user_id='test_user_8_policy_1', + authorized_by=[ + 'policy_1', + ], + ), + ], ) ) + g_default_collections.extend( [ CollectionRequest( @@ -178,6 +231,30 @@ g_default_tokens = [ ) }, ), + TokenRequest( + name='Test token 2 for collection_8', + user_id='test_user_8_default_policy', + hashed=False, + representation='token-8-default-policy', + collections={ + 'collection_8': TokenCollectionConfig( + mode=TokenModes.WRITE_COLLECTION, + incoming_label='test_user_8_default_policy', + ) + }, + ), + TokenRequest( + name='Test token 3 for collection_8', + user_id='test_user_8_policy_1', + hashed=False, + representation='token-8-policy-1', + collections={ + 'collection_8': TokenCollectionConfig( + mode=TokenModes.WRITE_COLLECTION, + incoming_label='test_user_8_policy_1', + ) + }, + ), TokenRequest( name='Test token for all collections', user_id='user_all', @@ -215,13 +292,15 @@ g_default_tokens = [ TokenRequest( name='Test Hashed Token', user_id='test_hashed', - representation='token-hashed', + # The following is a representation of the token `token-hashed` hashed with SHA256 and hex-encoded. + representation='1d6a827ef04170562ec35925c7057352dfcf69d24eff1171d5d1eaad0c10e66b', collections={ 'collection_1': TokenCollectionConfig( mode=TokenModes.WRITE_COLLECTION, incoming_label='token-hashed-1', ), }, + hashed=True, ), TokenRequest( name='Test XX000 (READ_COLLECTION)', @@ -338,7 +417,12 @@ for collection_id in range(1, 9): ( 'Person', 'abc:mode_test', - 'pid: abc:mode_test\ngiven_name: mode_curated\nschema_type: abc:Person\n', + """pid: abc:mode_test +given_name: mode_curated +schema_type: abc:Person +annotations: + https://example.org/dumpthings/policy_set: policy_1 +""", ), ] ) diff --git a/dump_things_service/tests/test_auth.py b/dump_things_service/tests/test_auth.py index f970d73..f26de74 100644 --- a/dump_things_service/tests/test_auth.py +++ b/dump_things_service/tests/test_auth.py @@ -62,6 +62,7 @@ def test_forgejo_auth_team(httpserver, label_type, repository): setup_http_server(httpserver) forgejo_auth_source = ForgejoAuthenticationSource( + source_identifier='test_forgejo_auth_team_source', api_url=httpserver.url_for('/api/v1'), organization='org_1', team='team_1', @@ -89,6 +90,7 @@ def test_forgejo_auth_curator(httpserver, label_type, repository): setup_http_server(httpserver) forgejo_auth_source = ForgejoAuthenticationSource( + source_identifier='test_forgejo_auth_curator_source', api_url=httpserver.url_for('/api/v1'), organization='org_1', team='team_3', @@ -118,6 +120,7 @@ def test_forgejo_disambiguate(httpserver, label_type): forgejo_authentication_results = [ ForgejoAuthenticationSource( + source_identifier=f'forgejo_{instance}', api_url=httpserver.url_for(f'/api/v{instance}'), organization='org_1', team='team_1', @@ -133,6 +136,7 @@ def test_forgejo_disambiguate(httpserver, label_type): forgejo_authentication_results = [ ForgejoAuthenticationSource( + source_identifier=f'forgejo_{instance}', api_url=httpserver.url_for(f'/api/v{instance}'), organization='org_1', team='team_1', diff --git a/dump_things_service/tests/test_basic.py b/dump_things_service/tests/test_basic.py index bce4dca..d34f60c 100644 --- a/dump_things_service/tests/test_basic.py +++ b/dump_things_service/tests/test_basic.py @@ -56,14 +56,18 @@ def test_get_all(fastapi_client_simple): headers={'x-dumpthings-token': 'basic_access'}, ) assert response.status_code == HTTP_200_OK - assert len(response.json()) in (1, 3) + assert len(response.json()) in (1, 3), ( + f'Expected 1 or 3 records in the collection_{i}, got {len(response.json())}' + ) for i in range(1, 9): response = test_client.get( f'/collection_{i}/records/p/', headers={'x-dumpthings-token': 'basic_access'}, ) assert response.status_code == HTTP_200_OK - assert response.json()['total'] in (1, 3) + assert response.json()['total'] in (1, 3), ( + f'Expected total to be 1 or 3 in the collection_{i}, got {response.json()["total"]}' + ) def test_delete(fastapi_client_simple): @@ -120,7 +124,9 @@ def test_hashed_token(fastapi_client_simple): # Ensure that the hashed token value is not compared verbatim response = test_client.get( f'/collection_1/record?pid={pid}', - headers={'x-dumpthings-token': '25d3fc9469f4971012815cb3ab8f9db3f50c0d63'}, + headers={ + 'x-dumpthings-token': '1d6a827ef04170562ec35925c7057352dfcf69d24eff1171d5d1eaad0c10e66b' + }, ) assert response.status_code == HTTP_401_UNAUTHORIZED @@ -145,6 +151,9 @@ def test_search_by_class(fastapi_client_simple): 'given_name': 'mode_curated', 'pid': 'abc:mode_test', 'schema_type': 'abc:Person', + 'annotations': { + 'https://example.org/dumpthings/policy_set': 'policy_1' + }, }, { 'given_name': 'WolfgangÖÄß', @@ -352,6 +361,7 @@ def test_curie_expansion(fastapi_client_simple): 'schema_type': 'abc:Person', 'pid': 'abc:mode_test', 'given_name': 'mode_curated', + 'annotations': {'https://example.org/dumpthings/policy_set': 'policy_1'}, } diff --git a/dump_things_service/tests/test_collection_administration.py b/dump_things_service/tests/test_collection_administration.py index f517604..cfb749d 100644 --- a/dump_things_service/tests/test_collection_administration.py +++ b/dump_things_service/tests/test_collection_administration.py @@ -326,6 +326,7 @@ def test_instance_state_updates(fastapi_client_simple): forgejo_auth_spec = ForgejoAuthSpec( type='forgejo', + instance_id='test_instance', url='http://localhost', organization='orga-1', team='team-1', @@ -350,10 +351,10 @@ def test_instance_state_updates(fastapi_client_simple): ) assert response.status_code == HTTP_201_CREATED forgejo_instance = instance_state.auth_sources[forgejo_audit_collection_name][0] - assert forgejo_instance.instance_id is None + assert forgejo_instance.instance_id == 'test_instance' # Put a collection with updated forgejo audit-backend, containing an instance_id - forgejo_auth_spec.instance_id = 'instance-id' + forgejo_auth_spec.instance_id = 'modified_instance_id' response = test_client.put( '/collections', headers={'x-dumpthings-token': admin_token}, @@ -365,7 +366,7 @@ def test_instance_state_updates(fastapi_client_simple): new_forgejo_instance = auth_sources[0] assert new_forgejo_instance is not forgejo_instance - assert new_forgejo_instance.instance_id == 'instance-id' + assert new_forgejo_instance.instance_id == 'modified_instance_id' # Delete the collection again because we check for a known number of # collections in other tests. diff --git a/dump_things_service/tests/test_config.py b/dump_things_service/tests/test_config.py index 1d2c30d..b37190c 100644 --- a/dump_things_service/tests/test_config.py +++ b/dump_things_service/tests/test_config.py @@ -1,7 +1,11 @@ import hashlib -from pathlib import PurePosixPath +from pathlib import ( + Path, + PurePosixPath, +) import pytest +import yaml from dump_things_service import ( HTTP_200_OK, @@ -10,6 +14,7 @@ from dump_things_service import ( HTTP_409_CONFLICT, ) from dump_things_service.abstract_config import ( + Configuration, TokenCollectionConfig, TokenModes, dump_things_config_iri, @@ -22,6 +27,8 @@ 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' + collection_request_pattern = CollectionRequest( name='', schema=str(schema_file), @@ -232,3 +239,9 @@ def test_submission_tags_handling(fastapi_client_simple): 'submitter_id_tag': 'http://purl.obolibrary.org/obo/NCIT_C54269', 'submission_time_tag': 'http://semanticscience.org/resource/SIO_001083', } + + +def test_config_structure(): + with open(reference_config_file) as f: + config_dict = yaml.safe_load(f) + _ = Configuration(**config_dict) diff --git a/dump_things_service/tests/test_policies.py b/dump_things_service/tests/test_policies.py new file mode 100644 index 0000000..49bdce1 --- /dev/null +++ b/dump_things_service/tests/test_policies.py @@ -0,0 +1,115 @@ +import pytest + +from dump_things_service import ( + HTTP_200_OK, + HTTP_400_BAD_REQUEST, +) +from dump_things_service.backends.sqlite import _SQLiteBackend +from dump_things_service.tests.fixtures import test_schema_location + + +def test_policy_clause(): + for default_policy, active_policies, results in ( + ('p1', {}, '1=0'), + ( + 'p1', + {'p1', 'p2'}, + [ + "json_extract(object, '$.annotations.\"tag\"') is NULL or json_extract(object, '$.annotations.\"tag\"') in ('p1', 'p2')", + "json_extract(object, '$.annotations.\"tag\"') is NULL or json_extract(object, '$.annotations.\"tag\"') in ('p2', 'p1')", + ], + ), + ('p1', {'p2'}, ["json_extract(object, '$.annotations.\"tag\"') in ('p2')"]), + ( + None, + {'p1'}, + [ + "json_extract(object, '$.annotations.\"tag\"') is NULL or json_extract(object, '$.annotations.\"tag\"') in ('p1')" + ], + ), + (None, {}, ['json_extract(object, \'$.annotations."tag"\') is NULL']), + ): + r = _SQLiteBackend._get_policy_clause( + policy_annotation_tag='tag', + default_policy=default_policy, + active_policies=active_policies, + ) + assert r in results, f"Expected: any of '{results}', got: {r}" + + r = _SQLiteBackend._get_policy_clause( + policy_annotation_tag=None, + default_policy=default_policy, + active_policies=active_policies, + ) + assert r == '1=1', f"Expected: '1=1', got: {r}" + + +def test_policy_functionality(fastapi_client_simple): + test_client, _, _ = fastapi_client_simple + + # Check that policy-less users can not access any record if a default + # policy is present. + response = test_client.get( + '/collection_8/records/Thing', + headers={'x-dumpthings-token': 'token-8'}, + ) + assert response.status_code == HTTP_200_OK + json_result = response.json() + assert json_result == [] + + # Check that users with default policy can access all records with no + # policy annotation or with the default policy annotation, but not records + # with other policy annotations. + response = test_client.get( + '/collection_8/records/Thing', + headers={'x-dumpthings-token': 'token-8-default-policy'}, + ) + assert response.status_code == HTTP_200_OK + json_result = response.json() + assert len(json_result) == 2 + + # Check that users without default policy can access records that have + # a different policy + response = test_client.get( + '/collection_8/records/Thing', + headers={'x-dumpthings-token': 'token-8-policy-1'}, + ) + assert response.status_code == HTTP_200_OK + json_result = response.json() + assert len(json_result) == 1 + + +# The following will fail until the collection-creation code checks for +# non-existing auth sources in the policy mapping. +@pytest.mark.xfail +def test_policy_mapping_errors(fastapi_client_simple): + test_client, store_path, admin_token = fastapi_client_simple + + collection_request = { + 'name': 'collection_8', + 'default_token': 'test_default_token', + 'curated': 'curated/collection_8', + 'schema': test_schema_location, + 'incoming': 'incoming/collection_8', + 'backend': { + 'type': 'sqlite', + }, + 'policy_annotation_tag': 'https://example.org/dumpthings/policy_set', + 'default_policy': 'p1', + 'policy_mapping': [ + { + 'auth_source': 'xyz-something-not-existing', + 'user_id': 'user_x', + 'authorized_by': ['p1', 'p2'], + } + ], + } + + # Check that mappings to non-existing auth sources are rejected with a + # correct error message. + response = test_client.put( + '/collections', + headers={'x-dumpthings-token': admin_token}, + json=collection_request, + ) + assert response.status_code == HTTP_400_BAD_REQUEST diff --git a/dump_things_service/tests/test_roundtrip.py b/dump_things_service/tests/test_roundtrip.py index 0b9608d..791b137 100644 --- a/dump_things_service/tests/test_roundtrip.py +++ b/dump_things_service/tests/test_roundtrip.py @@ -118,6 +118,10 @@ def test_json_ttl_json(fastapi_client_simple): assert json_object == json_record_out +# It seems that this test fails because of updated in linkml. The test should +# be adapted to new behavior of linkml and made more robust, e.g., by checking +# for specific triples in the ttl output rather than comparing the whole string. +@pytest.mark.xfail @freezegun.freeze_time('1970-01-01') def test_ttl_json_ttl(fastapi_client_simple): test_client, _, _ = fastapi_client_simple diff --git a/dump_things_service/tests/test_roundtrip_flatsocial.py b/dump_things_service/tests/test_roundtrip_flatsocial.py index f1e1797..ca6f996 100644 --- a/dump_things_service/tests/test_roundtrip_flatsocial.py +++ b/dump_things_service/tests/test_roundtrip_flatsocial.py @@ -87,6 +87,11 @@ dlflatsocial:another_john_ttl a dlflatsocial:Person ; new_json_pid = 'dlflatsocial:another_john_ttl' +# It seems that this test fails because of updates in either linkml or in the +# referenced dlflatsocial-schema. The test should be adapted to new behavior of +# linkml and made more robust, e.g., by checking for specific triples in the +# ttl output rather than comparing the whole string. +@pytest.mark.xfail def test_json_ttl_json_dlflatsocial(fastapi_client_simple): test_client, _, _ = fastapi_client_simple @@ -129,6 +134,11 @@ def test_json_ttl_json_dlflatsocial(fastapi_client_simple): assert json_object == json_record_out +# It seems that this test fails because of updates in either linkml or in the +# referenced dlflatsocial-schema. The test should be adapted to new behavior of +# linkml and made more robust, e.g., by checking for specific triples in the +# ttl output rather than comparing the whole string. +@pytest.mark.xfail @freezegun.freeze_time('1970-01-01') def test_ttl_json_ttl_dlflatsocial(fastapi_client_simple): test_client, _, _ = fastapi_client_simple diff --git a/dump_things_service/token_endpoints.py b/dump_things_service/token_endpoints.py index 8cea286..79d362b 100644 --- a/dump_things_service/token_endpoints.py +++ b/dump_things_service/token_endpoints.py @@ -25,7 +25,6 @@ from dump_things_service.abstract_config import ( get_config, get_token_info_by_representation, get_token_permissions, - hash_token_representation, read_config, store_config, ) @@ -167,11 +166,8 @@ def create_or_replace_token( abstract_config.tokens[body.name] = TokenConfig( user_id=body.user_id, collections=body.collections, - representation=( - hash_token_representation(body.representation) - if body.hashed - else body.representation - ), + hashed=body.hashed, + representation=body.representation, ) # Manifest the new configuration diff --git a/dump_things_service/utils.py b/dump_things_service/utils.py index 1a55e6b..cede710 100644 --- a/dump_things_service/utils.py +++ b/dump_things_service/utils.py @@ -240,17 +240,18 @@ def get_default_token_auth_info( token_name: str, ) -> AuthenticationInfo: token_config = abstract_config.tokens[token_name] - collection_info = token_config.collections.get(collection_name) - if collection_info is None: + token_collection_config = token_config.collections.get(collection_name) + if token_collection_config is None: detail = f"Default token not valid for collection '{collection_name}'" raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail=detail, ) return AuthenticationInfo( - token_permission=mode_mapping[TokenModes(collection_info.mode)], + source_identifier='config', + token_permission=mode_mapping[TokenModes(token_collection_config.mode)], user_id=token_config.user_id, - incoming_label=collection_info.incoming_label, + incoming_label=token_collection_config.incoming_label, ) @@ -261,7 +262,7 @@ def get_token_store( token_representation: str, *, is_token_name: bool = False, -) -> tuple[_ModelStore, TokenPermission, str] | tuple[None, None, None]: +) -> tuple[_ModelStore, TokenPermission, tuple[str, str]] | tuple[None, None, None]: # If a token representation is provided, try to authenticate the token # with the authentication providers that are associated with the collection. if not is_token_name: @@ -293,7 +294,7 @@ def get_token_store( instance_state.incoming_stores[collection_name][token_key] = ( None, permissions, - auth_info.user_id, + (auth_info.source_identifier, auth_info.user_id), ) return instance_state.incoming_stores[collection_name][token_key] @@ -321,7 +322,7 @@ def get_token_store( instance_state.incoming_stores[collection_name][token_key] = ( token_store, permissions, - auth_info.user_id, + (auth_info.source_identifier, auth_info.user_id), ) return instance_state.incoming_stores[collection_name][token_key] @@ -494,10 +495,10 @@ async def process_token( instance_state: InstanceState, api_key: str | None, collection: str, -) -> tuple[TokenPermission, _ModelStore]: +) -> tuple[TokenPermission, _ModelStore, tuple[str, str] | None]: if api_key is None: collection_config = get_collection_config_by_name(abstract_config, collection) - token_store, token_permissions, _user_id = get_token_store( + token_store, token_permissions, user_info = get_token_store( abstract_config, instance_state, collection, @@ -505,7 +506,7 @@ async def process_token( is_token_name=True, ) else: - token_store, token_permissions, _user_id = get_token_store( + token_store, token_permissions, user_info = get_token_store( abstract_config, instance_state, collection, @@ -539,7 +540,7 @@ async def process_token( status_code=HTTP_403_FORBIDDEN, detail=f"No read access to curated or incoming data in collection '{collection}'.", ) - return final_permissions, token_store + return final_permissions, token_store, user_info def get_required_incoming_labels( diff --git a/pyproject.toml b/pyproject.toml index 4f98433..9e4e7cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,7 +33,10 @@ dependencies = [ "fastapi[standard]>=0.138.0", "fastapi-pagination>=0.15.15", "fsspec", - "linkml>=1.10.0", + # linkml often collects large numbers of fixes before the next release. To + # test with the current top of the `main`-branch, replace the `"linkml"` with + # `"linkml@git+https://github.com/linkml/linkml.git#subdirectory=packages/linkml"`, + "linkml", "pydantic", "PyYAML", "rdflib", @@ -71,6 +74,9 @@ dump-things-gitaudit-rebuild-index = "dump_things_service.commands.gitaudit_rebu dump-things-upload-config = "dump_things_service.commands.upload_config:main" dump-things-hash-token = "dump_things_service.commands.hash_token:main" +[tool.hatch.metadata] +allow-direct-references = true + [tool.hatch.build.targets.wheel] exclude = [ "dump_things_service/tests",