dump-things-service/dump_things_service/main.py
Christian Monch 00b2ef84ec sec: bind server to 127.0.0.1 by default
To reduce unwanted exposure, the default
IP is now: `127.0.0.1`. This will affect
all installations that do not explicitly
define an IP address to bind to.

The changelog entry changes the version
to 7.0.0 because a service that is
started without the `--host` option
will no longer bind to all interfaces
and will therefore not be rearchable
from other machines.
2026-11-13 16:25:02 +01:00

349 lines
10 KiB
Python

from __future__ import annotations # noqa: I001 -- the patches have to be imported early
import argparse
import asyncio
import logging
import os
import sys
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from dump_things_service.abstract_config import store_config
from dump_things_service.commands.upload_config import convert_config_1_to_config_2
from dump_things_service.exceptions import ConfigError
from dump_things_service.manifest import manifest_configuration
# Perform the patching before importing any third-party libraries
from dump_things_service.patches import enabled # noqa: F401 -- side effects are required
import yaml
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi_pagination import add_pagination
from fastapi_pagination.utils import disable_installed_extensions_check
from dump_things_service import __version__
from dump_things_service.abstract_config import (
Configuration,
hash_token_representation,
read_config,
CONFIG_VERSION_1_ID,
CONFIG_VERSION_2_ID,
)
from dump_things_service.collection import check_recoverable_errors
from dump_things_service.endpoints.v0.base_endpoints import router as base_router
from dump_things_service.endpoints.v0.curated import router as curated_router
from dump_things_service.endpoints.v0.incoming import router as incoming_router
from dump_things_service.endpoints.v0.collection_endpoints import (
router as collection_router,
)
from dump_things_service.endpoints.v0.token_endpoints import (
hash_matcher,
router as token_router,
)
from dump_things_service.endpoints.v0.validate import router as validate_router
from dump_things_service.instance_state import create_instance_state, InstanceState
from dump_things_service.periodic import (
add_task_to_queue,
periodic_worker,
)
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger('dump_things_service')
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', default=8000, type=int)
parser.add_argument('--origins', action='append', default=[])
parser.add_argument(
'--admin-token-hash',
type=str,
default='',
help='The sha256 hash of an initial admin token that will allow to add or '
'remove tokens, collections, and additional admin tokens (64 '
'characters hex-digit). NOTE: an admin token in plaintext is read '
'from the environment variable `DTS_ADMIN_TOKEN` if it is set, and '
'if this option is not provided.',
)
parser.add_argument(
'-c',
'--config',
metavar='CONFIG_FILE',
help="Read the configuration from 'CONFIG_FILE' if no persisted "
'configuration is found in the data store root directory, and '
'initialize the persistent configuration and the service state with '
"the values in 'CONFIG_FILE'.",
)
parser.add_argument(
'--root-path',
default='',
help="Set the ASGI 'root_path' for applications submounted below a given URL path.",
)
parser.add_argument(
'--log-level',
default='WARNING',
help="Set the log level for the service, allowed values are 'ERROR', 'WARNING', 'INFO', 'DEBUG'. Default is 'warning'.",
)
parser.add_argument(
'--ignore-default-config-file',
action='store_true',
help='If the persisted configuration is empty, do not try to initialize it '
'from an existing default-config file, i.e., do not read the file '
'`<store>/.dumpthings.yaml`. That means the configuration be empty '
'collections and tokens are added via the API.',
)
parser.add_argument(
'--retry-interval',
type=int,
default=60,
help='Set the retry interval for recoverable errors in seconds. After the '
'retry interval, the server will try to manifest collections '
'configurations that have recoverable errors, e.g., failing URLs. '
'The default is 60 seconds.',
)
parser.add_argument(
'store',
help='The root of the data store, it should contain a global_store and token_stores.',
)
description = """
A service to store and retrieve data that is structured according to given
schemata.
Data is stored in **collections**.
Each collection has a name and an associated schema.
All data records in the collection have to adhere to the given schema.
Users store data in an incoming area and read data from a curated area and their
incoming area. There can be many incoming areas, but only one curated area.
Curators store data in an incoming area or in the curated area and read data
from any incoming area or the curated area.
For more information refer to the [README-file](https://hub.psychoinformatics.de/orinoco/dump-things-server)
of the project.
"""
arguments = parser.parse_args()
# Try to get bootstrap token from environment if an admin token hash is
# not provided via option
if not arguments.admin_token_hash:
if 'DTS_ADMIN_TOKEN' in os.environ:
arguments.admin_token_hash = hash_token_representation(
os.environ.get('DTS_ADMIN_TOKEN', ''),
)
# Validate the hash token format
elif not hash_matcher.match(arguments.admin_token_hash):
sys.stderr.write('Hashed admin token is not a 64-digits hex-number\n')
sys.stderr.flush()
sys.exit(1)
# Set the log level
numeric_level = getattr(logging, arguments.log_level.upper(), None)
if not isinstance(numeric_level, int):
logger.error(
'Invalid log level: %s, defaulting to level "WARNING"',
arguments.log_level,
)
else:
logger.setLevel(level=numeric_level)
logger.propagate = False
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(numeric_level)
formatter = logging.Formatter('%(levelname)s:dump_things_service:%(message)s')
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
store_path = Path(arguments.store).resolve()
if not store_path.exists():
logger.error('Store path does not exist: %s', str(store_path))
sys.exit(1)
disable_installed_extensions_check()
# Define the tag-order
openapi_tags = [
{'name': 'default'},
{'name': 'Read records'},
{'name': 'Store records'},
{'name': 'Validate records'},
{'name': 'Delete records'},
{'name': 'Curated area: read records'},
{'name': 'Curated area: store records'},
{'name': 'Curated area: delete records'},
{'name': 'Incoming area: read records'},
{'name': 'Incoming area: read labels'},
{'name': 'Incoming area: store records'},
{'name': 'Incoming area: delete records'},
{'name': 'Server management'},
{'name': 'Administration interface'},
]
@asynccontextmanager
async def lifespan(_app: FastAPI):
task = asyncio.create_task(periodic_worker())
yield
task.cancel()
with suppress(asyncio.CancelledError):
await task
app = FastAPI(
title='Dump Things Service',
description=description,
version=__version__,
openapi_tags=openapi_tags,
lifespan=lifespan,
)
app.include_router(curated_router)
app.include_router(incoming_router)
app.include_router(validate_router)
app.include_router(token_router)
app.include_router(collection_router)
app.include_router(base_router)
# Add CORS origins
app.add_middleware(
CORSMiddleware,
allow_origins=arguments.origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
# Add pagination
add_pagination(app)
g_instance_state = create_instance_state(
store_path=store_path,
bootstrap_token=arguments.admin_token_hash,
fastapi_app=app,
)
g_configuration = read_config(store_path)
def initialize_from_config_file(
instance_state: InstanceState,
config_file: str | Path,
) -> Configuration:
with open(config_file) as f:
config_dict = yaml.safe_load(f)
config_version = config_dict['version']
if config_version == CONFIG_VERSION_1_ID:
logger.info(
'Converting version 1 configuration at %s',
config_file,
)
config_dict = convert_config_1_to_config_2(
config_dict,
instance_state.store_path,
)
elif config_version != CONFIG_VERSION_2_ID:
msg = f'Invalid version in config file: {config_version}'
raise ValueError(msg)
return Configuration(**config_dict)
# If the configuration is empty, read the configuration from the default
# location, i.e., from `<store>/.dumpthings.yaml`, or from the configuration
# option, unless `--dont-use-old-config` is specified.
if not (
g_configuration.admin_tokens
or g_configuration.collections
or g_configuration.tokens
):
if arguments.config:
config_file = arguments.config
elif arguments.ignore_default_config_file:
config_file = None
else:
from dump_things_service import config_file_name
config_file = g_instance_state.store_path / config_file_name
if not config_file.exists():
config_file = None
if config_file:
logger.info(
'Initializing empty persisted configuration from %s',
config_file,
)
g_configuration = initialize_from_config_file(
g_instance_state,
config_file,
)
# Persist the configuration
store_config(
store_path=g_instance_state.store_path,
config=g_configuration,
)
# If there are no structures in the configuration, check for a bootstrap token.
if (
not (
g_configuration.admin_tokens
or g_configuration.collections
or g_configuration.tokens
)
and not g_instance_state.bootstrap_token
):
sys.stderr.write(
'The server has an empty configuration and requires a bootstrap '
'token (use `--admin-token-hash` or the environment variable '
'`DTS_ADMIN_TOKEN` to provide one).\n',
)
sys.stderr.flush()
sys.exit(2)
try:
manifest_configuration(
configuration=g_configuration,
instance_state=g_instance_state,
)
except ConfigError as e:
logger.exception('There were errors manifesting configuration: %s', e)
# Add a periodic task that tries to recover from recoverable errors in the
# configuration by re-manifesting the configuration.
add_task_to_queue(
interval=arguments.retry_interval,
callable_=check_recoverable_errors,
abstract_configuration=g_configuration,
instance_state=g_instance_state,
)
def main():
uvicorn.run(
app,
host=arguments.host,
port=arguments.port,
root_path=arguments.root_path,
)
if __name__ == '__main__':
main()