Add policy support #271

Merged
cmo merged 14 commits from policies into master 2026-10-02 06:54:55 +00:00
31 changed files with 788 additions and 76 deletions

View file

@ -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

View file

@ -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
^^^^^^^^^^^^^^^^^^^^^^^^^

View file

@ -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'

View file

@ -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), [])

View file

@ -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,

View file

@ -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,

View file

@ -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"]}',
)

View file

@ -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

View file

@ -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(

View file

@ -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,
)

View file

@ -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] = {}

View file

@ -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:

View file

@ -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)}'

View file

@ -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(

View file

@ -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

View file

@ -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(

View file

@ -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

View file

@ -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,

View file

@ -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

View file

@ -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: {}

Some files were not shown because too many files have changed in this diff Show more