Add dynamic configuration #206

Merged
cmo merged 64 commits from dynamic-configuration into master 2026-06-12 10:47:49 +00:00
64 changed files with 4630 additions and 2810 deletions

View file

@ -1,3 +1,55 @@
# 6.0.0b2 (26.4.2026)
# New feature
- Support `-c/--config`-option. If this option is provided and if the service
has an empty persistent configuration store, the configuration store and the
service configuration will be initialized from the configuration file content.
If the configuration file is `version: 1`, it will be converted to the updated
configuration format.
# 6.0.0b1 (22.5.2026)
## New features
- Allow dynamic creation and deletion of collections, tokens and
administration-tokens via the endpoints: `/collections`, `/tokens`, and
`/admin_tokens`.
- The configuration is persisted in the store of the service. An audit log
log of all configuration changes is kept.
- A new token type is introduced: admin-tokens. Admin-tokens are required to
perform the creation- and deletion-operations described above.
- The tool `dump-things-load-config` was added to manifest a configuration that
is defined in a configuration file on a running server.
- The tool `dump-things-hash-token` was added to calculate the hashed
representation of a token. This representation can be used to create a
"hashed"-token, i.e., a token that is stored in hashed format. So the plain
token is never stored in the dump-things server configuration
## Breaking changes
- Configuration structure has changed:
1. `schema` is now an attribute of a collection. It is no longer an
attribute of a sqlite-backend configuration.
2. The keys in the top-level mapping `tokens` are now token names and no
longer token representations. Token representations are now defined in
the values of the `tokens`-mapping
3. The top-level mapping `admin_tokens` was added.
- Configuration files are no longer read when the service is started. Instead
the service reads its configuration from the store, if it is present. Thw tool
(`dump-things-load-config`) can read an existing configuration
file and manifest the described configuration on a running dump-things server.
It supports pre version 6 config files and converts them to the new
configuration structure (except from hashed tokens, which cannot be
automatically converted).
# 5.6.1 (2026-03-20)
## Bugfixes
@ -47,7 +99,7 @@
supported by the collections, i.e., classes for which storage- and
validation-endpoints exist.
- Add `/maintenance`-endpoint to temporarilly lock collections for non-curator
- Add `/maintenance`-endpoint to temporarily lock collections for non-curator
access.
@ -569,7 +621,7 @@
## New features
- Factor out a Schema Type Layer (STL) from the `record_dir` backend." The STL
- Factor out a Schema Type Layer (STL) from the `record_dir` backend. The STL
can be used with every backend. It removes top-level `schema_type`-entries
from records before they are stored. It also adds the correct top-level
`schema_type`-entry to records that are read from a store. This functionality

24
LICENSE Normal file
View file

@ -0,0 +1,24 @@
things-graph-renderer, including all examples, code snippets and attached
documentation is covered by the MIT license.
The MIT License
Copyright (c) 2026- Michael Hanke <mih@ngln.eu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

181
README.md
View file

@ -47,7 +47,9 @@ The following command line parameters are supported:
- `--port <port>`: The port on which the service should accept connections (default: `8000`).
- `-c/--config <config-file>`: provide a path to the configuration file. The configuration file in `<storage root>/.dumpthings.yaml` will be ignored, if it exists at all.
- `-c/--config <config-file>`: provide a path to a configuration file (configuration file version 1).
If no dynamically managed configuration is found in the data store, the dynamically managed configuration and the service state will be initialized with the content of the configuration file.
This allows an easy transition from dump-things-servers of version 5 and lower to version 6.
- `--origins <origin>`: add a CORS origin hosts (repeat to add multiple CORS origin URLs).`
@ -55,6 +57,12 @@ The following command line parameters are supported:
- `--log-level`: set the log level for the service, allowed values are `ERROR`, `WARNING`, `INFO`, `DEBUG`. The default-level is `WARNING`.
- `--admin_token-hash <shs256 hash as 64-digit hexnumber>`: set an administrator token hash.
This plaintext token can be used to create and delete collections, tokens, and admin tokens.
This is useful to configure the service if no admin token was yet created.
**NOTE**: an admin token in plaintext is read from the environment variable `DTS_ADMIN_TOKEN` if it is set and this option is not provided.
```bash
dump-things-service /data-storage/store --host 127.0.0.1 --port 8000
```
@ -63,16 +71,18 @@ The above command runs the service on the network location `127.0.0.1:8000` and
### Configuration file
The service is configured via a configuration file that defines collections, paths for incoming and curated data for each collection, as well as token properties.
The service provides the tool `dump-things-load-config` which can load configurations from a file and manifest those configurations on a running service via the administration endpoints.
A configuration defines collections, paths for incoming and curated data for each collection, as well as token properties.
Token properties include a submitter identification and for each collection an incoming zone specifier, permissions for reading and writing of the incoming zone and permission for reading the curated data of the collection.
A "formal" definition of the configuration file is provided by the class `GlobalConfig` in the file `dumpthings-server/config.py`.
A "formal" definition of the configuration file is provided by the class `Configuration` in the file `dumpthings-server/abstract_config.py`.
Configurations are read in YAML format. The following is an example configuration file that illustrates all options:
Configurations are read in YAML format. The following is an example configuration file (version 6 and higher) that illustrates all options:
```yaml
type: collections # has to be "collections"
version: 1 # has to be 1
version: 2 # has to be 2
# All collections are listed in "collections"
collections:
@ -86,6 +96,9 @@ collections:
# client provided token.
default_token: no_access
# The schema that is used by the collection
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
# The path to the curated data of the collection. This path should contain the
# ".dumpthings.yaml"-configuration for collections that is described
# here: <https://concepts.datalad.org/dump-things-storage-v0/>.
@ -134,13 +147,24 @@ collections:
# All tokens are listed in "tokens"
tokens:
# The following entry defines the token "basic_access". This token allows read-only
# access to the two collections: "rooms_and_buildings" and "fixed_data".
# The following entry defines the token "basic_access".
basic_access:
# The representation of the token, this is the value that the user has to
# provide in the `x-dumpthings-token`-header to authenticate with this token.
representation: anonymous
# If hashed is `True`, the representation must be a 40-hexdigit number,
# representing the hash of the plain token. Setting `hashed` to `True` ensures
# that the plain-text token is not stored in the configuration store of the
# running server.
#
# The tool `dump-things-hash-token` can be used to calculate the correct hash.
hashed: False
# The value of "user_id" will be added as an annotation to each record that is
# uploaded with this token.
user_id: anonymous
user_id: anonymous_user
# The collections for which the token holds rights are defined in "collections"
collections:
@ -155,8 +179,9 @@ tokens:
# A token and collection-specific label, that defines "zones" in which incoming
# records are stored. Multiple tokens can share the same zone, for example if
# many clients with individual tokens work together to build a collection.
# (Since this token does not allow write access, "incoming_label" is ignored and
# left empty here (TODO: it should not be required in this case)).
# (Since this token does not allow write access, "incoming_label" is ignored. It
# is set to an empty string here in order to document it, but it could as well
# be omitted)
incoming_label: ''
# The rights that "basic_access" carries for the collection "fixed_data"
@ -168,6 +193,9 @@ tokens:
# The following entry defines the token "no_access". This token does not allow
# any access and is used as a default token for the collection "personal_records".
no_access:
representation: no_access
user_id: nobody
collections:
@ -175,9 +203,10 @@ tokens:
mode: NOTHING
incoming_label: ''
# The following entry defines the token "admin". It gives full access rights to
# the collection "personal_records".
admin:
# The following entry defines a token with the name "admin_token" and the plain
# representation: "admin". It gives full access rights to the collection "personal_records".
admin_token:
representation: admin
user_id: Admin
collections:
personal_records:
@ -187,6 +216,7 @@ tokens:
# The following entry defines the token "contributor_bob". It gives full access
# to "rooms_and_buildings" for a user with the id "Bob".
contributor_bob:
representation: bob
user_id: Bob
collections:
rooms_and_buildings:
@ -198,6 +228,7 @@ tokens:
# same incoming-zone, i.e. "new_rooms_and_buildings". That means they can read
# incoming records that the other one posted.
contributor_alice:
representation: alice
user_id: Alice
collections:
rooms_and_buildings:
@ -205,14 +236,17 @@ tokens:
incoming_label: new_rooms_and_buildings
# The following entry defines a hashed token because the key `hashed` is set
# to `True`. A hashed token has the structure
# `<id>-<sha256>`. It will match an incoming token if the incoming token has
# the structure `<id>-<content>` and if sha256(`<content>`) equals `<sha256>`.
# In this example, if the client presents the token `bob-hello`, he will be
# granted access because `sha256('hello')` equals
# `2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824`
bob-2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824:
# to `True`. A hashed token representation is the hex-digit representation of
# the sha-256 checksum of the plain token.
# In this example, if the client presents the token `hello`, he will be
# granted access because `dump-things-hash-token 'hello'` yields
# `90b1b286043f1b7612e423c74608f5ea2f676340507f0b67219b20d09fc4777b`, i.e.
# sha256('hello') == 90b1b286043f1b7612e423c74608f5ea2f676340507f0b67219b20d09fc4777b
# is true.
hashed_token_1:
representation: 90b1b286043f1b7612e423c74608f5ea2f676340507f0b67219b20d09fc4777b
hashed: True
user_id: Walter
collections:
rooms_and_buildings:
mode: WRITE_COLLECTION
@ -250,6 +284,7 @@ collections:
collection_with_default_record_dir+stl_backend:
# This is a collection with the default backend, i.e. `record_dir+stl` and
# the default authentication, i.e. config-based authentication.
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
default_token: anon_read
curated: collection_1/curated
@ -268,6 +303,7 @@ collections:
# example by the forgejo-instance at `https://forgejo.example.com`.
# If there is more than one authentication source, they will be tried
# in the order they are defined in the config file.
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
default_token: anon_read # We still need a default token
curated: collection_2/curated
@ -313,6 +349,7 @@ collections:
# permissions, user-id, and incoming from the config file.
collection_with_explicit_record_dir+stl_backend:
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
default_token: anon_read
curated: collection_3/curated
backend:
@ -322,6 +359,7 @@ collections:
type: record_dir+stl
collection_with_sqlite_backend:
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
default_token: anon_read
curated: collection_4/curated
backend:
@ -330,9 +368,18 @@ collections:
# that holds the URL of the schema that should
# be used in this backend.
type: sqlite
schema: https://concepts.inm7.de/s/flat-data/unreleased.yaml
```
#### Reserved names
The following collection names are reserved and must not be used:
- collections
- tokens
- admin_tokens
- __dump_things__
#### Authentication and authorization
To authenticate and authorize a user based on tokens, dumpthing-service uses
@ -683,6 +730,59 @@ A `CURATOR`-token required to access these endpoints.
Details about the curation endpoints can be found in [this issue](https://codeberg.org/datalink/dump-things-server/issues/118).
#### Administration endpoints
Operations on the endpoints described in this section require an administrator token.
If desired, use `dump-things-load-config` to read the configuration from a file and
generate respective POST-requests. `dump-things-load-config` can also be used to
generate a configuration from an old, i.e. dump-things version < 6, configuration file.
##### Collections
- `POST /collections`: create a new collection from the posted configuration object.
For a specification of the configuration object see the object `CollectionRequest` in the file `dump_things_service/collection_endpoints.py`
(Use `dump-things-load-config` to read the configuration from a file and generate respective POST-requests)
- `GET /collections`: get information about the currently existing collections.
- `GET /collections/<collection-name>`: get information about the collection with name `<collection-name>`.
- `DELETE /collections/<collection-name>`: delete the collection with the given name.
Note: deleting a collection does not delete any records or any storage dir, it just removes the
collection from the internal state of the service. Recreating it (via `POST /collections`) will make
all data reachable again through the Web-API.
##### Tokens
- `POST /tokens`: create a new token from the posted configuration object.
For a specification of the configuration object see the object `TokenRequest` in the file `dump_things_service/token_endpoints.py`
NOTE: Before a token for configuration can be generated, the collection must exist.
- `GET /tokens`: get information about the currently existing tokens.
- `GET /tokens/<token-name>`: get information about the token with name `<token-name>`.
- `DELETE /tokens/<token-name>`: delete the token with the given name.
- this endpoint (ending on `.../p/`) provides the same functionality as the endpoint `GET /<collection>/records/` (without `.../p/`) but supports result pagination. In addition to the query parameters `format` and `matching`, it supports the query parameters `page` and `size`.
##### Admin Tokens
- `POST /admin_tokens`: create a new admin token from the posted configuration object.
For a specification of the configuration object see the object `AdminTokenRequest` in the file `dump_things_service/token_endpoints.py`
Note that admin token are always stored as hashed values.
Therefore the representation in the request should be `sha256(<plain-admin-token>)`
- `GET /admin_tokens`: get information about the currently existing admin tokens.
- `GET /admin_tokens/<token-name>`: get information about the admin token with name `<token-name>`.
- `DELETE /admin_tokens/<token-name>`: delete the admin token with the given name.
### Tips & Tricks
@ -702,15 +802,16 @@ collections:
incoming: datamgt
tokens:
anon_read:
anon_read: # The name of the token (serves also as representation if no representation is defines)
user_id: anonymous
collections:
datamgt:
mode: READ_CURATED
incoming_label: ""
datamgt: # per collection token configuration; contains:
mode: READ_CURATED # - token mode
incoming_label: "" # - the label for the incoming area for this token and this collection, i.e., collection: "datamgt".
trusted-submitter-token:
user_id: trusted_submitter
representation: 00112233445566778899aabbccdd # The representation that the client has to send in an `x-dumpthings-token`-header (if not given, the token name will be the representation)
collections:
datamgt:
mode: WRITE_COLLECTION
@ -763,6 +864,36 @@ If any backend is a `record_dir+stl` backend, a schema has to be supplied via th
- `dump-things-create-merged-schema`: this command creates a new schema that statically contains all schemas that the original schema imports.
The new schema is fully self-contained and does not reference any other schemas.
- `dump-things-hash-token`: this command will generate a hash from a plain-text token that can be used with the `--admin-token-hash` option.
(one could also use the shell command `sha256sum` to generate the hash, but using `dump-things-hash-token` will ensure that the right hash algorithm is used)
### Migrate to version 6
Migration to version 6 is simple. It involves the following steps:
1. Start the version 6 service on the store that you used and provide an
administrator token
```
> dump-things-service --admin-token admin-1 <path to store>
```
2. Use `dump-things-load-config` to load the old configuration from the
configuration file that you used in the old version.
```
> export DTS_ADMIN_TOKEN=admin-1
> dump-things-load-config --send-to "https://<host-of-running-server>" --old-config <path to store>/.dumpthings.yaml
```
At this point the service should be running and be configured exactly as
before. The configuration is persisted and will be etablished next time the
service starts.
### If things go wrong
#### Delete a record manually

View file

@ -1 +1 @@
__version__ = '5.6.1'
__version__ = '6.0.0'

View file

@ -6,11 +6,14 @@ from typing import (
from starlette.status import (
HTTP_200_OK,
HTTP_201_CREATED,
HTTP_300_MULTIPLE_CHOICES,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED,
HTTP_403_FORBIDDEN,
HTTP_404_NOT_FOUND,
HTTP_406_NOT_ACCEPTABLE,
HTTP_409_CONFLICT,
HTTP_500_INTERNAL_SERVER_ERROR,
HTTP_503_SERVICE_UNAVAILABLE,
)
@ -24,11 +27,14 @@ from starlette.status import (
__all__ = [
'Format',
'HTTP_200_OK',
'HTTP_201_CREATED',
'HTTP_300_MULTIPLE_CHOICES',
'HTTP_400_BAD_REQUEST',
'HTTP_401_UNAUTHORIZED',
'HTTP_403_FORBIDDEN',
'HTTP_404_NOT_FOUND',
'HTTP_406_NOT_ACCEPTABLE',
'HTTP_409_CONFLICT',
'HTTP_413_CONTENT_TOO_LARGE',
'HTTP_422_UNPROCESSABLE_CONTENT',
'HTTP_500_INTERNAL_SERVER_ERROR',
@ -36,6 +42,7 @@ __all__ = [
'JSON',
'YAML',
'config_file_name',
'reserved_collection_names',
]
@ -48,3 +55,13 @@ JSON = Union[dict[str, Any], list[Any], str, int, float, None]
YAML = JSON
config_file_name = '.dumpthings.yaml'
dump_things_private_collection_name = '__dump_things__'
reserved_collection_names = (
'collections',
'tokens',
'admin_tokens',
dump_things_private_collection_name,
)

View file

@ -0,0 +1,497 @@
import enum
import hashlib
import logging
from functools import partial
from pathlib import (
Path,
PurePosixPath,
)
from typing import (
Callable,
Iterable,
Literal,
cast,
)
from fastapi import HTTPException
from pydantic import (
BaseModel,
ConfigDict,
Field, ValidationError,
)
from yaml.scanner import ScannerError
from dump_things_service import (
HTTP_404_NOT_FOUND,
dump_things_private_collection_name,
)
from dump_things_service.audit.gitaudit import GitAuditBackend
from dump_things_service.backends.record_dir import (
_RecordDirStore,
RecordDirStore,
)
from dump_things_service.exceptions import ConfigError
logger = logging.getLogger('dump_things_service')
g_abstract_configuration = None
dump_things_config_iri = 'dump_things:config'
dump_things_private_path = Path(dump_things_private_collection_name)
config_backend_path = dump_things_private_path / 'config_store'
config_audit_path = dump_things_private_path / 'config_audit'
config_backend = None
config_audit = None
class StrictModel(BaseModel):
model_config = ConfigDict(
extra='forbid',
use_enum_values=True,
)
class ConfigAuthSpec(BaseModel):
type: Literal['config'] = 'config'
class ForgejoAuthSpec(BaseModel):
type: Literal['forgejo']
url: str
organization: str
team: str
label_type: Literal['team', 'user']
instance_id: str | None = None
repository: str | None = None
class TagSpec(BaseModel):
submitter_id_tag: str = 'http://purl.obolibrary.org/obo/NCIT_C54269'
submission_time_tag: str = 'http://semanticscience.org/resource/SIO_001083'
class MappingMethod(enum.Enum):
digest_md5 = 'digest-md5'
digest_md5_p3 = 'digest-md5-p3'
digest_md5_p3_p3 = 'digest-md5-p3-p3'
digest_sha1 = 'digest-sha1'
digest_sha1_p3 = 'digest-sha1-p3'
digest_sha1_p3_p3 = 'digest-sha1-p3-p3'
after_last_colon = 'after-last-colon'
class RecordDirBackendConfig(StrictModel):
model_config = ConfigDict(use_enum_values=True)
type: Literal['record_dir', 'record_dir+stl']
mapping_method: str = MappingMethod.digest_md5.value
class SQLiteBackendConfig(StrictModel):
type: Literal['sqlite', 'sqlite+stl']
class GitAuditBackendConfig(StrictModel):
type: Literal['gitaudit']
path: Path
auto_flush_timeout: int = 60
class CollectionConfig(BaseModel):
model_config = ConfigDict(extra='forbid', use_enum_values=True)
default_token: str
curated: PurePosixPath
schema_location: str = Field(alias='schema')
incoming: PurePosixPath | None = None
backend: RecordDirBackendConfig | SQLiteBackendConfig = RecordDirBackendConfig(type='record_dir+stl')
auth_sources: list[ForgejoAuthSpec | ConfigAuthSpec] = [ConfigAuthSpec()]
audit_backends: list[GitAuditBackendConfig] = []
submission_tags: TagSpec = TagSpec()
use_classes: list[str] = []
ignore_classes: list[str] = []
class RecordDirConfigFileContent(BaseModel):
model_config = ConfigDict(extra='forbid')
type: Literal['records']
version: Literal[1]
schema_location: str = Field(alias='schema')
format: Literal['yaml']
idfx: MappingMethod
class TokenModes(enum.Enum):
READ_CURATED = 'READ_CURATED'
READ_COLLECTION = 'READ_COLLECTION'
WRITE_COLLECTION = 'WRITE_COLLECTION'
READ_SUBMISSIONS = 'READ_SUBMISSIONS'
WRITE_SUBMISSIONS = 'WRITE_SUBMISSIONS'
SUBMIT = 'SUBMIT'
SUBMIT_ONLY = 'SUBMIT_ONLY'
NOTHING = 'NOTHING'
CURATOR = 'CURATOR'
class TokenPermission(BaseModel):
curated_read: bool = False
incoming_read: bool = False
incoming_write: bool = False
curated_write: bool = False
zones_access: bool = False
class TokenCollectionConfig(StrictModel):
model_config = ConfigDict(extra='forbid', use_enum_values=True)
mode: TokenModes
incoming_label: str = ''
class TokenConfig(StrictModel):
user_id: str
collections: dict[str, TokenCollectionConfig]
hashed: bool = False
representation: str = ''
class AdminTokenConfig(StrictModel):
representation: str
class Configuration(StrictModel):
collections: dict[str, CollectionConfig] = {}
tokens: dict[str, TokenConfig] = {}
admin_tokens: dict[str, AdminTokenConfig] = {}
pid: str = dump_things_config_iri
mode_mapping = {
TokenModes.READ_CURATED: TokenPermission(curated_read=True),
TokenModes.READ_COLLECTION: TokenPermission(
curated_read=True,
incoming_read=True,
),
TokenModes.WRITE_COLLECTION: TokenPermission(
curated_read=True,
incoming_read=True,
incoming_write=True,
),
TokenModes.READ_SUBMISSIONS: TokenPermission(incoming_read=True),
TokenModes.WRITE_SUBMISSIONS: TokenPermission(
incoming_read=True,
incoming_write=True,
),
TokenModes.SUBMIT: TokenPermission(curated_read=True, incoming_write=True),
TokenModes.SUBMIT_ONLY: TokenPermission(incoming_write=True),
TokenModes.NOTHING: TokenPermission(),
TokenModes.CURATOR: TokenPermission(
curated_read=True,
incoming_read=True,
incoming_write=True,
curated_write=True,
zones_access=True,
),
}
def get_token_permissions(mode: str) -> TokenPermission:
return mode_mapping[TokenModes(mode)]
def get_config_backends(
store_path: Path,
) -> tuple[_RecordDirStore, GitAuditBackend]:
global config_audit
global config_backend
config_path = store_path / config_backend_path
if not config_path.exists():
config_path.mkdir(parents=True)
if config_backend is None:
config_backend = RecordDirStore(
config_path,
mapping_functions[MappingMethod.digest_md5],
'yaml'
)
audit_path = store_path / config_audit_path
if not audit_path.exists():
audit_path.mkdir(parents=True)
if config_audit is None:
config_audit = GitAuditBackend(audit_path)
return config_backend, config_audit
def read_config(
store_path: Path,
force_reload: bool = False,
) -> Configuration:
global g_abstract_configuration
if not g_abstract_configuration or force_reload:
config_backend, _ = get_config_backends(store_path)
try:
record_info = config_backend.get_record_by_iri(dump_things_config_iri)
except ScannerError as sce:
msg = f'Configuration at {config_backend.root} not readable: {sce}'
raise ConfigError(msg) from sce
try:
g_abstract_configuration = (
Configuration(**(record_info.json_object))
if record_info
else Configuration()
)
except ValidationError as ve:
msg = f'Faulty configuration at {config_backend.root}: {ve}'
raise ConfigError(msg) from ve
return g_abstract_configuration
def get_config() -> Configuration:
global g_abstract_configuration
if not g_abstract_configuration:
msg = 'Configuration not yet loaded'
raise RuntimeError(msg)
return cast(Configuration, g_abstract_configuration)
def store_config(
store_path,
config: Configuration,
):
global g_abstract_configuration
config_backend, audit_backend = get_config_backends(store_path)
json_object = config.model_dump(mode='json', exclude_none=True, by_alias=True)
json_object['pid'] = dump_things_config_iri
config_backend.add_record(
iri=dump_things_config_iri,
class_name='DumpThingsConfig',
json_object=json_object
)
audit_backend.add_record(
record=json_object,
committer_id='__dump_things_server__',
)
g_abstract_configuration = config
def tokens_for_collection(
config: Configuration,
collection: str,
) -> Iterable[TokenConfig]:
yield from (
token
for token_name, token in config.tokens.items()
if collection in token.collections
)
def check_collection(
abstract_config: Configuration,
collection: str,
):
if collection not in abstract_config.collections:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail=f"No such collection: '{collection}'.",
)
def check_label(
store_path: Path,
abstract_config: Configuration,
collection: str,
label: str,
):
from dump_things_service.utils import get_on_disk_labels
"""Check that a label exists in a collection configuration or on disk"""
if (
label not in get_config_labels(abstract_config, collection)
and label not in get_on_disk_labels(store_path, abstract_config, collection)
):
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail=f"No incoming label: '{label}' in collection: '{collection}'.",
)
def get_config_labels(
abstract_config: Configuration,
collection: str,
) -> set[str]:
check_collection(abstract_config, collection)
return {
token.collections[collection].incoming_label
for token in tokens_for_collection(abstract_config, collection)
if token.collections[collection].incoming_label
}
def get_default_token_name(
abstract_config: Configuration,
collection: str
) -> str:
check_collection(abstract_config, collection)
return abstract_config.collections[collection].default_token
def get_token_info_by_representation(
abstract_config: Configuration,
token_representation: str,
) -> tuple[str, TokenConfig] | None:
"""Get the name of the token given in `token_representation`"""
hashed_representation = hash_token_representation(token_representation)
for token_name, token_config in abstract_config.tokens.items():
if token_config.hashed:
compare_representation = hashed_representation
else:
compare_representation = token_representation
if compare_representation == token_config.representation:
return token_name, token_config
return None
def hash_token_representation(
token_representation: str,
) -> str:
return hashlib.sha256(token_representation.encode()).hexdigest()
def get_token_config_by_name(
abstract_config: Configuration,
token_name: str,
) -> TokenConfig | None:
return abstract_config.tokens.get(token_name)
def get_token_infos_for_collection(
abstract_config: Configuration,
collection_name: str,
) -> Iterable[tuple[str, TokenConfig, TokenCollectionConfig]]:
yield from {
(token_name, token_config, token_collection_config)
for token_name, token_config in abstract_config.tokens.items()
for token_collection_config in token_config.collections.get(collection_name)
if token_config is not None
}
def get_token_config_for_representation_and_collection(
abstract_config: Configuration,
collection_name: str,
token_representation: str,
) -> tuple[str, TokenConfig, TokenCollectionConfig] | None:
token_info = get_token_info_by_representation(
abstract_config=abstract_config,
token_representation=token_representation,
)
if token_info:
token_name, token_config = token_info
if collection_name in token_config.collections:
return token_name, token_config, token_config.collections[collection_name]
return None
def get_collection_config_by_name(
abstract_config: Configuration,
collection_name: str,
) -> CollectionConfig:
collection_config = abstract_config.collections.get(collection_name)
if not collection_config:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail=f"No such collection: '{collection_name}'",
)
return collection_config
def get_default_token_config(
abstract_config: Configuration,
collection: str,
) -> TokenConfig | None:
default_token_name = get_collection_config_by_name(
abstract_config,
collection,
).default_token
return get_token_config_by_name(abstract_config, default_token_name)
def get_default_token_representation(
abstract_config: Configuration,
collection: str,
) -> str | None:
default_token_config = get_default_token_config(
abstract_config,
collection,
)
return default_token_config.representation if default_token_config else None
def get_mapping_function(record_dir_backend_config: RecordDirBackendConfig):
return mapping_functions[MappingMethod(record_dir_backend_config.mapping_method)]
def get_backend_and_extension(backend_type: str) -> tuple[str, str]:
elements = backend_type.split('+')
return (elements[0], elements[1]) if len(elements) > 1 else (elements[0], '')
def get_hex_digest(hasher: Callable, data: str) -> str:
hash_context = hasher(data.encode())
return hash_context.hexdigest()
def mapping_digest_p3(
hasher: Callable,
pid: str,
suffix: str,
) -> Path:
hex_digest = get_hex_digest(hasher, pid)
return Path(hex_digest[:3]) / (hex_digest[3:] + '.' + suffix)
def mapping_digest_p3_p3(
hasher: Callable,
pid: str,
suffix: str,
) -> Path:
hex_digest = get_hex_digest(hasher, pid)
return Path(hex_digest[:3]) / hex_digest[3:6] / (hex_digest[6:] + '.' + suffix)
def mapping_digest(hasher: Callable, pid: str, suffix: str) -> Path:
hex_digest = get_hex_digest(hasher, pid)
return Path(hex_digest + '.' + suffix)
def mapping_after_last_colon(pid: str, suffix: str) -> Path:
plain_result = pid.split(':')[-1]
# Escape any colons and slashes in the pid
escaped_result = (
plain_result.replace('_', '__').replace('/', '_s').replace('.', '_d')
)
return Path(escaped_result + '.' + suffix)
mapping_functions = {
MappingMethod.digest_md5: partial(mapping_digest, hashlib.md5),
MappingMethod.digest_md5_p3: partial(mapping_digest_p3, hashlib.md5),
MappingMethod.digest_md5_p3_p3: partial(mapping_digest_p3_p3, hashlib.md5),
MappingMethod.digest_sha1: partial(mapping_digest, hashlib.sha1),
MappingMethod.digest_sha1_p3: partial(mapping_digest_p3, hashlib.sha1),
MappingMethod.digest_sha1_p3_p3: partial(mapping_digest_p3_p3, hashlib.sha1),
MappingMethod.after_last_colon: mapping_after_last_colon,
}
def get_mapping_function_by_name(mapping_function_name: str) -> Callable:
return mapping_functions[MappingMethod(mapping_function_name)]

View file

@ -0,0 +1,38 @@
import logging
from fastapi import HTTPException
from dump_things_service import HTTP_401_UNAUTHORIZED
from dump_things_service.abstract_config import (
Configuration,
hash_token_representation,
)
from dump_things_service.instance_state import InstanceState
logger = logging.getLogger('dump_things_service')
def authenticate_admin(
instance_state: InstanceState,
abstract_config: Configuration,
api_key: str,
):
if api_key:
hashed_token_representation = hash_token_representation(api_key)
if hashed_token_representation == instance_state.bootstrap_token:
logger.info('authenticate_admin: using bootstrap token')
return
for token_name, token_config in abstract_config.admin_tokens.items():
if token_config.representation == hashed_token_representation:
logger.info(
"authenticate_admin: using token '%s'",
token_name,
)
return
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail='Invalid admin token',
)

View file

@ -20,14 +20,7 @@ class AuditBackend(metaclass=ABCMeta):
:param committer_id: the ID of the user who adds the record.
:param author_id: the ID of the user who modified the record, defaults
to `committer_id` if not given.
:return: A dictionary where the keys are time stamps of the changes,
the values are tuples containing the elements:
(user_id, diff, resulting_record), where user_id is the
`user_id` that was used in `add_record`, `resulting_record` is
the YAML-representation of `record` that was given to
`add_record`, and diff is path the transfers the previous
version of the record to the version provided in `record` (in
git-diff format).
:return: None
"""
raise NotImplementedError

View file

@ -15,7 +15,7 @@ import dataclasses
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from dump_things_service.token import TokenPermission
from dump_things_service.abstract_config import TokenPermission
class AuthenticationError(Exception):

View file

@ -1,56 +1,44 @@
"""Use configuration information to fetch token permissions, ids, and incomng_label """
"""Use configuration information to fetch token permissions, ids, and incoming_label """
from dump_things_service.abstract_config import Configuration
from dump_things_service.auth import (
AuthenticationInfo,
AuthenticationSource,
InvalidTokenError,
)
from dump_things_service.config import (
InstanceConfig,
from dump_things_service.abstract_config import (
get_token_permissions,
get_token_config_for_representation_and_collection,
)
from dump_things_service.token import (
get_token_parts,
hash_token,
)
missing = {}
class ConfigAuthenticationSource(AuthenticationSource):
def __init__(
self,
instance_config: InstanceConfig,
collection: str,
abstract_configuration: Configuration,
collection_name: str,
):
self.instance_config = instance_config
self.collection = collection
self.abstract_configuration = abstract_configuration
self.collection_name = collection_name
def authenticate(
self,
token: str,
token_representation: str,
) -> AuthenticationInfo:
token = self._resolve_hashed_token(token)
token_info = self.instance_config.tokens.get(self.collection, {}).get(token, missing)
if token_info is missing:
msg = f'Token not valid for collection `{self.collection}`'
raise InvalidTokenError(msg)
return AuthenticationInfo(
token_permission=token_info['permissions'],
user_id=token_info['user_id'],
incoming_label=token_info['incoming_label'],
result = get_token_config_for_representation_and_collection(
self.abstract_configuration,
self.collection_name,
token_representation,
)
def _resolve_hashed_token(
self,
token: str
) -> str:
if not result:
msg = f'Token not valid for collection `{self.collection_name}`'
raise InvalidTokenError(msg)
try:
token_id, _ = get_token_parts(token)
if token_id in self.instance_config.hashed_tokens[self.collection]:
return hash_token(token)
except ValueError:
pass
return token
_, token_config, token_collection_config = result
return AuthenticationInfo(
token_permission=get_token_permissions(token_collection_config.mode),
user_id=token_config.user_id,
incoming_label=token_collection_config.incoming_label,
)

View file

@ -28,7 +28,7 @@ from dump_things_service.auth import (
AuthenticationSource,
InvalidTokenError,
)
from dump_things_service.config import TokenPermission
from dump_things_service.abstract_config import TokenPermission
logger = logging.getLogger('dump_things_service')

View file

@ -27,10 +27,10 @@ from dump_things_service.backends.record_dir_index import RecordDirIndex
if TYPE_CHECKING:
from collections.abc import Iterable
from types import ModuleType
__all__ = [
'_RecordDirStore',
'RecordDirStore',
]
@ -255,10 +255,3 @@ def RecordDirStore( # noqa: N802
raise ValueError(msg)
return existing_store
def _get_schema_type(
class_name: str,
schema_module: ModuleType,
) -> str:
return getattr(schema_module, class_name).class_class_curie

View file

@ -231,7 +231,10 @@ class RecordDirIndex:
self.rebuild_index(schema=schema, order_by=order_by)
self.needs_rebuild = False
def _get_class_name(self, path: Path) -> str:
def _get_class_name(
self,
path: Path,
) -> str:
"""Get the class name from the path."""
rel_path = path.absolute().relative_to(self.store_dir)
return rel_path.parts[0]

View file

@ -34,6 +34,7 @@ if TYPE_CHECKING:
__all__ = [
'_SchemaTypeLayer',
'SchemaTypeLayer',
]

View file

@ -60,6 +60,12 @@ if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
__all__ = [
'_SQLiteBackend',
'SQLiteBackend',
]
logger = logging.getLogger('dump_things_service')
old_record_file_name = '.sqlite-records.db'
@ -124,6 +130,9 @@ class _SQLiteBackend(StorageBackend):
order_by: Iterable[str] | None = None,
echo: bool = False,
) -> None:
assert db_path.is_absolute(), f'db_path not absolute {db_path}'
if db_path.exists():
assert db_path.is_file(), f'db_path not a file {db_path}'
super().__init__(order_by=order_by)
self.db_path = db_path
self.perform_file_name_conversion()

View file

@ -0,0 +1,626 @@
import logging
import os
import shutil
from pathlib import Path
from typing import Any
from datalad_core.runners import (
call_git_oneline,
CommandError,
)
from fastapi import (
Depends,
FastAPI,
HTTPException,
)
from pydantic import (
BaseModel,
TypeAdapter,
ValidationError,
)
from starlette.responses import (
JSONResponse,
PlainTextResponse,
)
from starlette.status import HTTP_401_UNAUTHORIZED
from dump_things_service import (
Format,
HTTP_400_BAD_REQUEST,
HTTP_403_FORBIDDEN,
HTTP_422_UNPROCESSABLE_CONTENT,
)
from dump_things_service.abstract_config import (
CollectionConfig,
Configuration,
ConfigAuthSpec,
ForgejoAuthSpec,
RecordDirBackendConfig,
SQLiteBackendConfig,
read_config,
check_collection,
get_default_token_representation,
)
from dump_things_service.audit.gitaudit import GitAuditBackend
from dump_things_service.auth.config import ConfigAuthenticationSource
from dump_things_service.auth.forgejo import ForgejoAuthenticationSource
from dump_things_service.backends.record_dir_index import index_file_name
from dump_things_service.backends.sqlite import record_file_name as sqlite_db_filename
from dump_things_service.instance_state import (
InstanceState,
InstanceStateCollectionInfo,
get_record_dir_config,
get_instance_state,
get_schema_info,
record_dir_config_file_name,
)
from dump_things_service.converter import FormatConverter
from dump_things_service.exceptions import (
ConfigError,
ConfigCollisionError,
CurieResolutionError,
)
from dump_things_service.model import get_model_for_schema
from dump_things_service.utils import (
combine_ttl,
create_store,
get_token_store,
join_default_token_permissions,
var_escape,
wrap_http_exception,
)
# This following lines are required for dynamic endpoint generation
from typing import Annotated # noqa 401 -- used by autogenerated code
from fastapi import Body # noqa 401 -- used by autogenerated code
from dump_things_service.api_key import api_key_header_scheme # noqa 401 -- used by autogenerated code
from dump_things_service.curated import store_curated_record # noqa 401 -- used by autogenerated code
from dump_things_service.incoming import store_incoming_record # noqa 401 -- used by autogenerated code
from dump_things_service.validate import validate_record # noqa 401 -- used by autogenerated code
logger = logging.getLogger('dump_things_service')
_endpoint_template = """
def {name}(
data: {model_var_name}.{class_name} | Annotated[str, Body(media_type='text/plain')],
api_key: str = Depends(api_key_header_scheme),
format: Format = Format.json,
) -> JSONResponse | PlainTextResponse:
logger.info('{name}(%s, %s, %s, %s)', repr(data), repr('{class_name}'), repr({model_var_name}), repr(format))
return {handler}('{collection}', data, '{class_name}', {model_var_name}, format, api_key)
"""
_endpoint_curated_template = """
def {name}(
data: {model_var_name}.{class_name},
author_id: str | None = None,
api_key: str = Depends(api_key_header_scheme),
) -> JSONResponse:
logger.info(
'{name}(%s, %s, %s)',
repr(data),
repr(author_id),
repr({model_var_name}),
)
return store_curated_record(
'{collection}',
data,
'{class_name}',
author_id,
api_key,
)
"""
_endpoint_incoming_template = """
async def {name}(
data: {model_var_name}.{class_name},
label: str,
api_key: str = Depends(api_key_header_scheme),
) -> JSONResponse:
logger.info(
'{name}(%s, %s, %s)',
repr(data),
repr(label),
repr({model_var_name}),
)
return await store_incoming_record(
'{collection}',
label,
data,
'{class_name}',
api_key,
)
"""
def create_collection(
instance_state: InstanceState,
configuration: Configuration,
collection_name: str,
):
"""Create a collection instance as specified by `collection_configuration`
Reuse existing disk structures, if they are compatible. If they are not
compatible, raise an error.
:param instance_state:
:param configuration:
:param collection_name:
:return:
"""
collection_configuration = configuration.collections[collection_name]
curated_path = Path(instance_state.store_path / collection_configuration.curated)
incoming_path = (
None
if collection_configuration.incoming is None
else Path(instance_state.store_path / collection_configuration.incoming)
)
# Check for compatibility of all existing stores before creating any
# structures on disk.
if curated_path.exists():
check_store_compatibility(
curated_path,
collection_configuration.backend,
collection_configuration.schema_location,
)
for audit_backend in collection_configuration.audit_backends:
audit_path = Path(instance_state.store_path / audit_backend.path)
if audit_path.exists():
check_git_audit_compatibility(audit_path)
# We know now that all existing structures are compatible with the
# collection specification. We record what we create in order to delete
# it in case of an error.
created_directories = []
try:
if not curated_path.exists():
curated_path.mkdir(parents=True)
created_directories.append(curated_path)
if incoming_path and not incoming_path.exists():
incoming_path.mkdir(parents=True)
created_directories.append(incoming_path)
for audit_backend in collection_configuration.audit_backends:
audit_path = Path(instance_state.store_path / audit_backend.path)
if not audit_path.exists():
audit_path.mkdir(parents=True)
created_directories.append(audit_path)
except ConfigError as e:
# Delete all directories that were created in this
for directory in created_directories:
shutil.rmtree(directory)
raise
# Create the curated store
curated_store = create_store(
abstract_configuration=configuration,
instance_state=instance_state,
collection_name=collection_name,
)
instance_state.curated_stores[collection_name] = curated_store
# Incoming stores are created on demand when a token is authenticated
instance_state.incoming_stores[collection_name] = {}
# Create the schema modules, schema view, and conversion objects
schema_location = collection_configuration.schema_location
instance_state.schema_info[schema_location] = get_schema_info(schema_location)
# Determine the active classes based on the classes defined in the schema
# and the configuration of the collection
active_classes = set(instance_state.schema_info[schema_location].classes)
if collection_configuration.use_classes:
active_classes &= set(collection_configuration.use_classes)
if collection_configuration.ignore_classes:
active_classes -= set(collection_configuration.ignore_classes)
instance_state.collections[collection_name] = InstanceStateCollectionInfo(
active_classes=active_classes,
tag_info=dict(),
)
# Create a validator for the collection
instance_state.validators[collection_name] = FormatConverter(
schema=collection_configuration.schema_location,
input_format=Format.json,
output_format=Format.ttl,
)
# Create the authentication sources
for authentication_spec in collection_configuration.auth_sources:
create_authentication_source(
configuration,
collection_name,
authentication_spec,
instance_state,
)
# Create the audit-backends
instance_state.audit_backends[collection_name] = []
for audit_backend_config in collection_configuration.audit_backends:
instance_state.audit_backends[collection_name].append(
GitAuditBackend(
path=Path(instance_state.store_path / audit_backend_config.path),
auto_flush_timeout=audit_backend_config.auto_flush_timeout,
)
)
# Create the dynamic endpoints for record storing & validation, for
# inbox-storing, and for curated area storing.
create_endpoints_for_collection(
instance_state,
collection_name,
collection_configuration,
instance_state.fastapi_app,
)
def create_authentication_source(
abstract_configuration: Configuration,
collection_name: str,
authentication_spec: ConfigAuthSpec | ForgejoAuthSpec,
instance_state: InstanceState,
):
if collection_name not in instance_state.auth_sources:
instance_state.auth_sources[collection_name] = []
auth_sources = instance_state.auth_sources[collection_name]
if isinstance(authentication_spec, ConfigAuthSpec):
auth_source = ConfigAuthenticationSource(
abstract_configuration=abstract_configuration,
collection_name=collection_name,
)
elif isinstance(authentication_spec, ForgejoAuthSpec):
auth_source = ForgejoAuthenticationSource(
api_url=authentication_spec.url,
organization=authentication_spec.organization,
team=authentication_spec.team,
label_type=authentication_spec.label_type,
instance_id=authentication_spec.instance_id,
repository=authentication_spec.repository,
)
else:
msg = f"Unsupported authentication config type: '{type(authentication_spec)}'"
raise ConfigError(msg)
auth_sources.append(auth_source)
def write_record_dir_config(
path: Path,
backend_config: RecordDirBackendConfig,
schema: str,
):
assert isinstance(backend_config, RecordDirBackendConfig)
record_dir_config_file_path = path / record_dir_config_file_name
if not record_dir_config_file_path.exists():
record_dir_config_file_path.write_text(f"""# RecordDir Config
type: records
version: 1
schema: {schema}
format: yaml
idfx: {backend_config.mapping_method}
""",
)
def check_store_compatibility(
store_path: Path,
backend_config: RecordDirBackendConfig | SQLiteBackendConfig,
schema: str,
):
"""Check if an existing store is compatible with the specs in `backend_config`
:param store_path:
:param backend_config:
:param schema:
:return:
"""
if not store_path.exists():
return
if isinstance(backend_config, RecordDirBackendConfig):
check_record_dir_compatibility(store_path, backend_config, schema)
elif isinstance(backend_config, SQLiteBackendConfig):
check_sqlite_compatibility(store_path)
else:
msg = f"Unsupported backend config type: '{type(backend_config)}'"
raise ConfigError(msg)
return
def check_record_dir_compatibility(
store_path: Path,
backend_config: RecordDirBackendConfig,
schema: str,
):
# Non-existing or empty record_dir-directories are compatible
if not store_path.exists():
return
# A record_dir-directory is considered to be empty, if it contains no
# files or only an record_dir-index file
files_in_dir = tuple(map(lambda dir_entry: dir_entry.name, os.scandir(store_path)))
if files_in_dir in ((), (index_file_name,)):
return
record_dir_config = get_record_dir_config(store_path)
if record_dir_config.schema_location != schema:
raise ConfigCollisionError(f"Existing backend uses a different schema: '{record_dir_config.schema_location}'")
stored_mapping_method = record_dir_config.idfx.value
if stored_mapping_method != backend_config.mapping_method:
msg = f"Configuration specifies mapping method '{backend_config.mapping_method}', existing backend uses mapping method: '{stored_mapping_method}'"
raise ConfigCollisionError(msg)
return
def check_sqlite_compatibility(
store_path: Path,
):
sqlite_db_path = Path(store_path / sqlite_db_filename)
if not sqlite_db_path.exists():
raise ConfigError('No sqlite database found in existing store')
return
def check_git_audit_compatibility(
audit_path: Path,
):
"""Check if an existing audit path is compatible with a git audit store
:param audit_path:
:return:
"""
# Non-existing or empty directories are valid gitaudit-locations
if not audit_path.exists():
return
if not tuple(os.scandir(audit_path)):
return
# A non-empty directory should contain bare git repository
try:
result = call_git_oneline(
['rev-parse', '--is-bare-repository'],
cwd=audit_path,
force_c_locale=True,
)
except CommandError as ce:
raise ConfigError(f'No git repository in gitaudit-path: {audit_path}') from ce
if result.strip().lower() != 'true':
raise ConfigError(f'No bare git repository in gitaudit-path: {audit_path}')
return
def create_endpoint(
operation_name: str,
operation_path: str,
instance_state: InstanceState,
collection_name: str,
collection_config: CollectionConfig,
template: str,
handler: str,
tag_group: str,
tag_name: str,
app: FastAPI,
):
logger.info(
f'Creating %s-endpoints for collection: "%s"',
operation_name,
collection_name,
)
instance_state.collections[collection_name].tag_info[tag_group] = tag_name
# TODO: get schema_info from instance_state!?
model, classes, model_var_name = get_model_for_schema(collection_config.schema_location)
globals()[model_var_name] = model
active_classes = instance_state.collections[collection_name].active_classes
for class_name in active_classes:
endpoint_name = f'_endpoint_{var_escape(collection_name)}_{operation_name}_{class_name}'
endpoint_source = template.format(
name=endpoint_name,
model_var_name=model_var_name,
class_name=class_name,
collection=collection_name,
info=f"'{operation_name} {collection_name}/{class_name} objects'",
handler=handler,
)
exec(endpoint_source, globals()) # noqa S102
# Create an API route for the endpoint
app.add_api_route(
path=f'/{collection_name}/{operation_path}/{class_name}',
endpoint=globals()[endpoint_name],
methods=['POST'],
name=f'{operation_name} "{class_name}" object (schema: {model.linkml_meta["id"]})',
response_model=None,
tags=[tag_name]
)
logger.info(
'Creation of %d %s-endpoints completed.',
len(active_classes),
operation_name,
)
def create_endpoints_for_collection(
instance_state: InstanceState,
collection_name: str,
collection_config: CollectionConfig,
app: FastAPI,
):
for (
operation_name,
operation_path,
template,
handler,
tag_group,
tag_name,
) in (
('store', 'record', _endpoint_template, 'store_record', 'write', f'Write records to collection "{collection_name}"'),
('validate', 'validate/record', _endpoint_template, 'validate_record', 'validate', f'Validate records for collection "{collection_name}"'),
('curated', 'curated/record', _endpoint_curated_template, 'store_curated_record', 'curated_write', f'Curated area: store records in curated area of collection "{collection_name}"'),
('incoming', 'incoming/{label}/record', _endpoint_incoming_template, 'store_incoming_record', 'incoming_write', f'Incoming area: store records in incoming area "{{label}}" of collection "{collection_name}"'),
):
create_endpoint(
operation_name=operation_name,
operation_path=operation_path,
instance_state=instance_state,
collection_name=collection_name,
collection_config=collection_config,
template=template,
handler=handler,
tag_group=tag_group,
tag_name=tag_name,
app=app,
)
def delete_endpoints_for_collection(
instance_state: InstanceState,
collection_name: str,
):
active_classes = instance_state.collections[collection_name].active_classes
for operation_path in (
'record',
'validate/record',
'curated/record',
'incoming/{label}/record'
):
delete_endpoint(
collection_name=collection_name,
active_classes=active_classes,
operation_path=operation_path,
app=instance_state.fastapi_app,
)
def delete_endpoint(
collection_name: str,
active_classes: set[str],
operation_path: str,
app: FastAPI,
):
remove_paths_set = set(
f'/{collection_name}/{operation_path}/{class_name}'
for class_name in active_classes
)
remove_indices = [
index
for index, api_route in enumerate(app.router.routes)
if api_route.path in remove_paths_set
]
for index in sorted(remove_indices, reverse=True):
del app.router.routes[index]
def store_record(
collection: str,
data: BaseModel | str,
class_name: str,
model: Any,
input_format: Format,
api_key: str | None = Depends(api_key_header_scheme),
) -> JSONResponse | PlainTextResponse:
if input_format == Format.json and isinstance(data, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
)
if input_format == Format.ttl and not isinstance(data, str):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
)
instance_state = get_instance_state()
abstract_config = read_config(instance_state.store_path)
check_collection(abstract_config, collection)
token_representation = get_default_token_representation(
abstract_config,
collection,
) if api_key is None else api_key
if not token_representation:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail=f'Not authorized to submit to collection "{collection}"',
)
# Get the token permissions and extend them by the default permissions.
# This call will also convert plaintext tokens into the hashed version of
# the token, if the token is hashed. This is necessary because we do not
# store the plaintext token, so all token-information is associated with
# the hashed representation of the token.
store, token_permissions, user_id = get_token_store(
abstract_config,
instance_state,
collection,
token_representation,
)
final_permissions = join_default_token_permissions(
abstract_config,
instance_state,
token_permissions,
collection,
)
if not final_permissions.incoming_write:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail=f"Not authorized to submit to collection '{collection}'.",
)
if input_format == Format.ttl:
with wrap_http_exception(ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, header='Conversion error'):
json_object = FormatConverter(
abstract_config.collections[collection].schema_location,
input_format=Format.ttl,
output_format=Format.json,
).convert(data, class_name)
with wrap_http_exception(ValidationError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, header='Validation error'):
record = TypeAdapter(getattr(model, class_name)).validate_python(json_object)
else:
record = data
with wrap_http_exception(ValueError, status_code=HTTP_422_UNPROCESSABLE_CONTENT, header='Validation error'):
instance_state.validators[collection].validate(record)
with wrap_http_exception(CurieResolutionError):
stored_records = store.store_object(obj=record, submitter=user_id)
if input_format == Format.ttl:
format_converter = FormatConverter(
abstract_config.collections[collection].schema_location,
input_format=Format.json,
output_format=Format.ttl,
)
with wrap_http_exception(ValueError, header='Conversion error'):
return PlainTextResponse(
combine_ttl(
[
format_converter.convert(
record,
class_name,
)
for class_name, record in stored_records
]
),
media_type='text/turtle',
)
return JSONResponse([record for _, record in stored_records])

View file

@ -0,0 +1,240 @@
import logging
from pathlib import (
Path,
PurePosixPath,
)
from typing import Literal
from urllib.parse import quote
from fastapi import (
APIRouter,
Depends,
HTTPException,
Response,
)
from pydantic import BaseModel
from dump_things_service import (
HTTP_201_CREATED,
HTTP_404_NOT_FOUND,
HTTP_406_NOT_ACCEPTABLE,
HTTP_409_CONFLICT,
reserved_collection_names,
)
from dump_things_service.abstract_config import (
Configuration,
CollectionConfig,
StrictModel,
store_config,
get_config, get_token_permissions,
)
from dump_things_service.admin import authenticate_admin
from dump_things_service.api_key import api_key_header_scheme
from dump_things_service.instance_state import get_instance_state, InstanceState
from dump_things_service.manifest import manifest_configuration
from dump_things_service.exceptions import ConfigError
from dump_things_service.utils import wrap_http_exception
logger = logging.getLogger('dump_things_service')
router = APIRouter()
class ConfigAuthSpec(BaseModel):
type: Literal['config'] = 'config'
class ForgejoAuthSpec(BaseModel):
type: Literal['forgejo']
url: str
organization: str
team: str
label_type: Literal['team', 'user']
repository: str | None = None
class TagSpec(BaseModel):
submitter_id_tag: str = 'http://purl.obolibrary.org/obo/NCIT_C54269'
submission_time_tag: str = 'http://semanticscience.org/resource/SIO_001083'
from pydantic import ConfigDict, Field
from dump_things_service.abstract_config import RecordDirBackendConfig, SQLiteBackendConfig, GitAuditBackendConfig
class CollectionRequest(CollectionConfig):
name: str
@router.post(
'/collections',
tags=['Administration interface'],
name='Create a new collection',
status_code=HTTP_201_CREATED,
)
async def create_collection(
response: Response,
body: CollectionRequest,
api_key: str = Depends(api_key_header_scheme),
):
instance_state = get_instance_state()
abstract_config = get_config()
# Check admin rights
authenticate_admin(instance_state, abstract_config, api_key)
# Check for existing collection name
if body.name in abstract_config.collections:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail=f"Collection with name '{body.name}' already exists.",
)
# Check for reserved collection names
if body.name in reserved_collection_names:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail=f"Collection name '{body.name}' is reserved and cannot be created.",
)
# Check for distinct directories
for directory in (body.incoming, body.curated):
if directory:
ensure_unique_directory(
abstract_config,
instance_state,
directory,
)
# Check for incoming directory if any of the tokens allows writing
validate_incoming_paths(abstract_config, body)
# Update the abstract configuration
abstract_config.collections[body.name] = body
# Manifest the abstract configuration
with wrap_http_exception(ConfigError):
manifest_configuration(abstract_config, instance_state)
# Persist the abstract configuration
store_config(
store_path=instance_state.store_path,
config=abstract_config,
)
response.headers['Location'] = f'/collections/{quote(body.name)}'
@router.get(
'/collections',
tags=['Administration interface'],
name='Get existing collections',
)
async def get_collections(
api_key: str = Depends(api_key_header_scheme),
) -> dict[str, CollectionConfig]:
instance_state = get_instance_state()
abstract_config = get_config()
# Check admin rights
authenticate_admin(instance_state, abstract_config, api_key)
return abstract_config.collections
@router.get(
'/collections/{collection_name}',
tags=['Administration interface'],
name='Get existing collection by name',
)
async def get_collection_with_name(
collection_name: str,
api_key: str = Depends(api_key_header_scheme),
) -> CollectionConfig:
instance_state = get_instance_state()
abstract_config = get_config()
# Check admin rights
authenticate_admin(instance_state, abstract_config, api_key)
if collection_name not in abstract_config.collections:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail=f"Collection with name '{collection_name}' does not exist.",
)
return abstract_config.collections[collection_name]
@router.delete(
'/collections/{collection_name}',
tags=['Administration interface'],
name='Delete collection with name',
)
async def delete_collection(
collection_name: str,
api_key: str = Depends(api_key_header_scheme),
):
instance_state = get_instance_state()
abstract_config = get_config()
# Check admin rights
authenticate_admin(instance_state, abstract_config, api_key)
if collection_name not in abstract_config.collections:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail=f"Collection with name '{collection_name}' does not exist.",
)
# Update the abstract configuration
del abstract_config.collections[collection_name]
# Manifest the abstract configuration
with wrap_http_exception(ConfigError):
manifest_configuration(abstract_config, instance_state)
# Persist the abstract configuration
store_config(
store_path=instance_state.store_path,
config=abstract_config,
)
def ensure_unique_directory(
abstract_config: Configuration,
instance_state: InstanceState,
existing_dir: PurePosixPath,
):
abs_existing_dir = (instance_state.store_path / Path(existing_dir)).absolute()
for collection_name, collection_config in abstract_config.collections.items():
for collection_dir in collection_config.curated, collection_config.incoming:
abs_collection_dir = (instance_state.store_path / Path(collection_dir)).absolute()
if abs_collection_dir == abs_existing_dir:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail=f"Directory '{collection_dir}' already used by collection '{collection_name}'.",
)
def validate_incoming_paths(
abstract_config: Configuration,
collection_request: CollectionRequest,
):
for token_name, token_info in abstract_config.tokens.items():
token_collection_info = token_info.collections.get(collection_request.name)
if token_collection_info:
token_permissions = get_token_permissions(token_collection_info.mode)
if token_permissions.incoming_write or token_permissions.zones_access:
if not collection_request.incoming:
detail = (
f"Cannot add collection '{collection_request.name}' without "
f"`incoming` path, because at least token '{token_name}' "
f" has write access to the collection"
)
raise HTTPException(
status_code=HTTP_406_NOT_ACCEPTABLE,
detail=detail,
)

View file

@ -5,15 +5,20 @@ from argparse import ArgumentParser
from collections.abc import Iterable
from pathlib import Path
from dump_things_service import config_file_name
from fastapi import FastAPI
from dump_things_service.abstract_config import (
get_config_labels,
read_config,
)
from dump_things_service.backends.schema_type_layer import _SchemaTypeLayer
from dump_things_service.backends.sqlite import _SQLiteBackend
from dump_things_service.config import get_config, process_config
from dump_things_service.exceptions import CurieResolutionError
from dump_things_service.instance_state import create_instance_state
from dump_things_service.manifest import manifest_configuration
from dump_things_service.store.model_store import _ModelStore
from dump_things_service.utils import (
create_token_store,
get_config_labels,
get_on_disk_labels,
)
@ -26,13 +31,6 @@ parser.add_argument(
'store',
help='The root directory of the store.',
)
parser.add_argument(
'-c',
'--config',
metavar='CONFIG_FILE',
help="Read the configuration from 'CONFIG_FILE' instead of looking for "
'it in the root directory of the store.',
)
def show_backend(model_store: _ModelStore):
@ -62,30 +60,41 @@ def check_pids_in_stores(
return result
def check_pids():
instance_config = get_config()
def check_pids(
store_path: Path,
):
abstract_config = read_config(store_path)
instance_state = create_instance_state(
store_path=store_path,
bootstrap_token='',
fastapi_app=FastAPI(),
)
manifest_configuration(abstract_config, instance_state)
result = 0
# Check pids in curated stores
result += check_pids_in_stores(instance_config.curated_stores.values())
result += check_pids_in_stores(instance_state.curated_stores.values())
# Check pids in incoming stores. Incoming stores can be defined in the
# configuration, or can be generated by external authentication sources.
# In the latter case, they are manifest as directories in the incoming area
# of a collection.
for collection, collection_info in instance_config.collections.items():
configured_labels = get_config_labels(instance_config, collection)
on_disk_labels = get_on_disk_labels(instance_config, collection)
for collection, collection_info in abstract_config.collections.items():
configured_labels = get_config_labels(abstract_config, collection)
on_disk_labels = get_on_disk_labels(
store_path=store_path,
abstract_config=abstract_config,
collection=collection,
)
all_labels = configured_labels.union(on_disk_labels)
token_stores = [
create_token_store(
instance_config,
abstract_config,
instance_state,
collection,
instance_config.store_path / collection_info.incoming / label
instance_state.store_path / collection_info.incoming / label
)
for label in all_labels
]
@ -96,16 +105,7 @@ def check_pids():
def main():
arguments = parser.parse_args()
store_path = Path(arguments.store).absolute()
process_config(
store_path=store_path,
config_file=Path(arguments.config or (store_path / config_file_name)),
order_by=['pid'],
globals_dict=globals(),
)
result = check_pids()
result = check_pids(Path(arguments.store).absolute())
if result > 0:
print(f'found {result} unresolvable pids', file=sys.stderr)
return 1

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