Read policies from an external file and add a reload trigger endpoint. #274
9 changed files with 308 additions and 105 deletions
|
|
@ -284,7 +284,35 @@ 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
|
||||
Policy mappings are configured in an external JSON file and can be loaded on
|
||||
startup of the service or during runtime of the service. The file should contain
|
||||
a JSON-representation of an instance of
|
||||
`dump_thing_service.abstract_config.PolicyInfo` (see below for an example)
|
||||
|
||||
A default location for the policy information of a collection can be configured
|
||||
in the `policy_info_location`-property of the collection configuration. If
|
||||
the property is set to a URL, the service will try to load the policy information
|
||||
from the configured location on startup.
|
||||
|
||||
The following endpoint allows to trigger a reload of policy information from the
|
||||
configured location or from the optional parameter `url`.
|
||||
|
||||
.. code-block::
|
||||
|
||||
GET /management/reload/policy_info/{collection}?url
|
||||
|
||||
The endpoint triggers an immediate reload of a policy configuration. The new
|
||||
configuration will become effective immediately, i.e.,
|
||||
the next read request in the collection will use the new policy information.
|
||||
|
||||
The optional parameter `url` overwrites a configured `policy_info_location`-value.
|
||||
It can also be used to "attach" policy information to a collection that did
|
||||
not yet define policies. If the URL or the policy information file is invalid,
|
||||
no changes are made to the current policy information of the collection.
|
||||
|
||||
The use of the endpoint requires a CURATOR token.
|
||||
|
||||
in a collection configuration with ``policy_info_location``, 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.
|
||||
|
|
@ -297,22 +325,61 @@ 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
|
||||
.. code-block:: json
|
||||
|
||||
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
|
||||
{
|
||||
# Required to enable policy checking. The tag is the key of an
|
||||
# entry in the `annotations`-property of a record that defines the
|
||||
# policy for this record. The policy system treats the tag as
|
||||
# opaque string.
|
||||
"policy_annotation_tag": "https://example.org/dumpthings/policy_set"
|
||||
|
||||
# An optional default policy. If set, all records that do not have
|
||||
# an entry with `policy_annotation_tag`-key in their `annotations`-property
|
||||
# will be governed by the default policy. The policy system treats
|
||||
# the default policy as opaque string.
|
||||
"default_policy": "trr379:policy_inm7"
|
||||
|
||||
# An optional mapping from users to policies that apply to them.
|
||||
# Users are identified by the authentication source and the user IDs.
|
||||
# For user IDs that are defined in tokens definitions, the authentication
|
||||
# source is `config`. For users that are authenticated by an
|
||||
# forgejo-authentication source the user ID is the `instance_id`
|
||||
# of the authentication source (Note: if no instance_id is provided
|
||||
# in a forgejo-authentication source configuration, an MD5-hash of
|
||||
# the `url`-property is used. Therefore `instance_id`s should be
|
||||
# provided to simplify policy mappings definition)
|
||||
|
||||
"policy_mapping": [
|
||||
|
||||
# A user that could be authenticated by the forgejo-authentication
|
||||
# source defined above.
|
||||
{
|
||||
# `auth_source` is the `instance_id` of the forgejo-authentication
|
||||
# source defined above.
|
||||
"auth_source": "trr379hub",
|
||||
"user_id": "c.moench",
|
||||
# All policies that hold for the user are given as a list. Policies
|
||||
# are treated as opaque strings.
|
||||
"authorized_by": [
|
||||
"trr379:policy_inm7",
|
||||
"trr379:policy_psychoinformatics"
|
||||
]
|
||||
},
|
||||
|
||||
# Mapping for a user that is defined in a token configuration
|
||||
{
|
||||
# `auth_source` is `"config"` because the user is defined in
|
||||
# a token configuration.
|
||||
"auth_source": "config",
|
||||
"user_id": "token_defined_user_1",
|
||||
"authorized_by": [
|
||||
"inm7:library",
|
||||
"inm7:employees",
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
Collection-and-Token: a Chicken-and-Egg Problem
|
||||
|
|
|
|||
|
|
@ -106,6 +106,12 @@ class PolicyMapping(StrictModel):
|
|||
authorized_by: list[str]
|
||||
|
||||
|
||||
class PolicyInfo(StrictModel):
|
||||
default_policy: str | None = None
|
||||
policy_mapping: list[PolicyMapping] = []
|
||||
policy_annotation_tag: str | None = None
|
||||
|
||||
|
||||
class CollectionConfig(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', use_enum_values=True)
|
||||
default_token: str
|
||||
|
|
@ -120,9 +126,7 @@ 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
|
||||
policy_info_location: str | None = None
|
||||
|
||||
|
||||
class RecordDirConfigFileContent(BaseModel):
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
|
||||
import fsspec
|
||||
from pathlib import Path
|
||||
|
||||
# This following lines are required for dynamic endpoint generation
|
||||
|
|
@ -41,6 +44,8 @@ from dump_things_service.abstract_config import (
|
|||
ConfigAuthSpec,
|
||||
Configuration,
|
||||
ForgejoAuthSpec,
|
||||
PolicyInfo,
|
||||
PolicyMapping,
|
||||
RecordDirBackendConfig,
|
||||
SQLiteBackendConfig,
|
||||
check_collection,
|
||||
|
|
@ -74,7 +79,6 @@ 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,
|
||||
|
|
@ -241,11 +245,16 @@ def create_collection(
|
|||
if collection_configuration.ignore_classes:
|
||||
active_classes -= set(collection_configuration.ignore_classes)
|
||||
|
||||
default_policy = configuration.collections[collection_name].default_policy
|
||||
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
||||
configuration,
|
||||
collection_name,
|
||||
)
|
||||
instance_state.collections[collection_name] = InstanceStateCollectionInfo(
|
||||
active_classes=active_classes,
|
||||
tag_info={},
|
||||
default_policies=set([] if default_policy is None else [default_policy]),
|
||||
default_policy=default_policy,
|
||||
policy_mapping=policy_mapping,
|
||||
policy_annotation_tag=policy_annotation_tag,
|
||||
)
|
||||
|
||||
# Create a validator for the collection
|
||||
|
|
@ -283,9 +292,6 @@ def create_collection(
|
|||
instance_state.fastapi_app,
|
||||
)
|
||||
|
||||
# Create the user_id -> policy mapping
|
||||
instance_state.policy_mappings[collection_name] = collection_configuration.policy_mapping
|
||||
|
||||
|
||||
def create_authentication_source(
|
||||
abstract_configuration: Configuration,
|
||||
|
|
@ -699,3 +705,54 @@ def store_record(
|
|||
media_type='text/turtle',
|
||||
)
|
||||
return JSONResponse([order_dict(record) for _, record in stored_records])
|
||||
|
||||
|
||||
def load_policy_info(
|
||||
abstract_configuration: Configuration,
|
||||
collection_name: str,
|
||||
override_policy_info_location: str | None = None,
|
||||
) -> tuple[str | None, list[PolicyMapping], str | None]:
|
||||
policy_info_location = (
|
||||
override_policy_info_location
|
||||
or abstract_configuration.collections[collection_name].policy_info_location
|
||||
)
|
||||
|
||||
if not policy_info_location:
|
||||
return None, [], None
|
||||
|
||||
try:
|
||||
with fsspec.open(policy_info_location) as source:
|
||||
policy_info_json = json.load(source)
|
||||
except Exception as e:
|
||||
msg = f"Failed to load policy info from '{policy_info_location}': {e}"
|
||||
raise ConfigError(msg) from e
|
||||
|
||||
try:
|
||||
policy_info = PolicyInfo(**policy_info_json)
|
||||
except ValidationError as e:
|
||||
msg = f"Failed to load policy info from '{policy_info_location}': {e}"
|
||||
raise ConfigError(msg) from e
|
||||
|
||||
return (
|
||||
policy_info.default_policy,
|
||||
policy_info.policy_mapping,
|
||||
policy_info.policy_annotation_tag,
|
||||
)
|
||||
|
||||
|
||||
def reload_policy(
|
||||
abstract_configuration: Configuration,
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
override_policy_info_location: str | None = None,
|
||||
):
|
||||
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
||||
abstract_configuration,
|
||||
collection_name,
|
||||
override_policy_info_location,
|
||||
)
|
||||
instance_state.collections[collection_name].default_policy = default_policy
|
||||
instance_state.collections[collection_name].policy_mapping = policy_mapping
|
||||
instance_state.collections[
|
||||
collection_name
|
||||
].policy_annotation_tag = policy_annotation_tag
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ from yaml.scanner import ScannerError
|
|||
from dump_things_service import HTTP_404_NOT_FOUND
|
||||
from dump_things_service.abstract_config import (
|
||||
MappingMethod,
|
||||
PolicyMapping,
|
||||
RecordDirConfigFileContent,
|
||||
mapping_functions,
|
||||
)
|
||||
|
|
@ -60,7 +61,9 @@ class SchemaInfo:
|
|||
class InstanceStateCollectionInfo:
|
||||
active_classes: set[str]
|
||||
tag_info: dict[str, str]
|
||||
default_policies: set[str]
|
||||
default_policy: str | None
|
||||
policy_mapping: list[PolicyMapping]
|
||||
policy_annotation_tag: str | None
|
||||
|
||||
|
||||
@cache
|
||||
|
|
@ -102,7 +105,6 @@ 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
|
||||
|
|
|
|||
|
|
@ -7,7 +7,10 @@ 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
|
||||
|
||||
|
|
@ -20,6 +23,7 @@ from fastapi import (
|
|||
Depends,
|
||||
FastAPI,
|
||||
HTTPException,
|
||||
Response,
|
||||
)
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi_pagination import (
|
||||
|
|
@ -58,7 +62,7 @@ from dump_things_service.converter import (
|
|||
ConvertingList,
|
||||
)
|
||||
from dump_things_service.curated import router as curated_router
|
||||
from dump_things_service.exceptions import CurieResolutionError
|
||||
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 (
|
||||
|
|
@ -75,6 +79,7 @@ from dump_things_service.utils import (
|
|||
authenticate_token,
|
||||
check_bounds,
|
||||
process_token,
|
||||
simple_process_token,
|
||||
wrap_http_exception,
|
||||
)
|
||||
|
||||
|
|
@ -357,6 +362,47 @@ async def server() -> ServerResponse:
|
|||
)
|
||||
|
||||
|
||||
@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'],
|
||||
|
|
@ -415,7 +461,7 @@ async def read_record_with_pid(
|
|||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_configuration, collection, user_info
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
class_name, json_object = None, None
|
||||
|
|
@ -455,25 +501,29 @@ async def read_record_with_pid(
|
|||
|
||||
|
||||
def _get_policy_information(
|
||||
configuration: Configuration,
|
||||
instance_state: InstanceState,
|
||||
collection_name: str,
|
||||
user_info: tuple[str, str],
|
||||
) -> tuple[str, str | None, set[str]]:
|
||||
) -> tuple[str | None, str | None, set[str] | None]:
|
||||
from itertools import chain
|
||||
|
||||
collection_info = configuration.collections[collection_name]
|
||||
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 collection_info.policy_mapping
|
||||
for policy_mapping in policy_mapping
|
||||
if (policy_mapping.auth_source, policy_mapping.user_id) == user_info
|
||||
]
|
||||
)
|
||||
)
|
||||
return (
|
||||
collection_info.policy_annotation_tag,
|
||||
collection_info.default_policy,
|
||||
collection_state.policy_annotation_tag,
|
||||
collection_state.default_policy,
|
||||
policies,
|
||||
)
|
||||
|
||||
|
|
@ -589,7 +639,7 @@ async def _read_all_records(
|
|||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_configuration, collection, user_info
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
|
|
@ -664,7 +714,7 @@ async def _read_records_of_type(
|
|||
)
|
||||
|
||||
policy_annotation_tag, default_policy, policies = _get_policy_information(
|
||||
g_configuration, collection, user_info
|
||||
g_instance_state, collection, user_info
|
||||
)
|
||||
|
||||
result_list = PriorityList()
|
||||
|
|
|
|||
52
dump_things_service/tests/assets/policy_info.json
Normal file
52
dump_things_service/tests/assets/policy_info.json
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
{
|
||||
"default_policy": "abc:policy_abc",
|
||||
"policy_annotation_tag": "https://example.org/dumpthings/policy_set",
|
||||
"policy_mapping": [
|
||||
{
|
||||
"auth_source": "config",
|
||||
"user_id": "basic_access_user",
|
||||
"authorized_by": [
|
||||
"abc:policy_abc",
|
||||
"policy_1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"auth_source": "config",
|
||||
"user_id": "user_all",
|
||||
"authorized_by": [
|
||||
"abc:policy_abc",
|
||||
"policy_1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"auth_source": "config",
|
||||
"user_id": "test_user_1",
|
||||
"authorized_by": [
|
||||
"https://examples.com/policy_example_1",
|
||||
"abc:policy_abc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"auth_source": "some_other_source",
|
||||
"user_id": "test_user_2",
|
||||
"authorized_by": [
|
||||
"https://examples.com/policy_example_2",
|
||||
"abc:policy_def"
|
||||
]
|
||||
},
|
||||
{
|
||||
"auth_source": "config",
|
||||
"user_id": "test_user_8_default_policy",
|
||||
"authorized_by": [
|
||||
"abc:policy_abc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"auth_source": "config",
|
||||
"user_id": "test_user_8_policy_1",
|
||||
"authorized_by": [
|
||||
"policy_1"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -36,22 +36,7 @@ collections:
|
|||
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
|
||||
policy_info_location: http://example.com/policy_location.json
|
||||
|
||||
submission_tags:
|
||||
submission_time_tag: http://semanticscience.org/resource/SIO_001083
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ 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
|
||||
|
|
@ -49,6 +48,9 @@ test_schema_location = str((Path(__file__).parent / 'testschema.yaml').absolute(
|
|||
flat_social_schema_location = (
|
||||
'https://concepts.datalad.org/s/flat-social/unreleased.yaml'
|
||||
)
|
||||
policy_info_file_location = str(
|
||||
(Path(__file__).parent / 'assets' / 'policy_info.json').absolute()
|
||||
)
|
||||
|
||||
|
||||
# The test store is created empty and collections are added via the admin
|
||||
|
|
@ -84,56 +86,7 @@ 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',
|
||||
],
|
||||
),
|
||||
],
|
||||
policy_info_location=policy_info_file_location,
|
||||
)
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -543,6 +543,39 @@ async def process_token(
|
|||
return final_permissions, token_store, user_info
|
||||
|
||||
|
||||
async def simple_process_token(
|
||||
abstract_config: Configuration,
|
||||
instance_state: InstanceState,
|
||||
api_key: str | None,
|
||||
collection: str,
|
||||
) -> TokenPermission:
|
||||
if api_key is None:
|
||||
collection_config = get_collection_config_by_name(abstract_config, collection)
|
||||
token_store, token_permissions, user_info = get_token_store(
|
||||
abstract_config,
|
||||
instance_state,
|
||||
collection,
|
||||
token_representation=collection_config.default_token,
|
||||
is_token_name=True,
|
||||
)
|
||||
else:
|
||||
token_store, token_permissions, user_info = get_token_store(
|
||||
abstract_config,
|
||||
instance_state,
|
||||
collection,
|
||||
token_representation=api_key,
|
||||
is_token_name=False,
|
||||
)
|
||||
|
||||
final_permissions = join_default_token_permissions(
|
||||
abstract_config,
|
||||
token_permissions if token_permissions else TokenPermission(),
|
||||
collection,
|
||||
)
|
||||
|
||||
return final_permissions
|
||||
|
||||
|
||||
def get_required_incoming_labels(
|
||||
abstract_config: Configuration,
|
||||
collection_name: str,
|
||||
|
|
|
|||
Loading…
Reference in a new issue